Merge branch 'maint'
[org-mode.git] / lisp / org.el
blobe59c469ffec0ec9adc9b8169da141a0bc90aa9c9
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 (load "org-loaddefs.el" t t)
83 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
84 ;; some places -- e.g. see the macro org-with-limited-levels.
86 ;; In Org buffers, the value of `outline-regexp' is that of
87 ;; `org-outline-regexp'. The only function still directly relying on
88 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
89 ;; job when `orgstruct-mode' is active.
90 (defvar org-outline-regexp "\\*+ "
91 "Regexp to match Org headlines.")
93 (defvar org-outline-regexp-bol "^\\*+ "
94 "Regexp to match Org headlines.
95 This is similar to `org-outline-regexp' but additionally makes
96 sure that we are at the beginning of the line.")
98 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
99 "Matches an headline, putting stars and text into groups.
100 Stars are put in group 1 and the trimmed body in group 2.")
102 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
103 (when (fboundp 'defvaralias)
104 (unless (boundp 'calendar-view-holidays-initially-flag)
105 (defvaralias 'calendar-view-holidays-initially-flag
106 'view-calendar-holidays-initially))
107 (unless (boundp 'calendar-view-diary-initially-flag)
108 (defvaralias 'calendar-view-diary-initially-flag
109 'view-diary-entries-initially))
110 (unless (boundp 'diary-fancy-buffer)
111 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
113 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
114 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
115 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
116 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
117 (declare-function org-at-clock-log-p "org-clock" ())
118 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
119 (declare-function org-clock-timestamps-up "org-clock" ())
120 (declare-function org-clock-timestamps-down "org-clock" ())
121 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
123 (declare-function orgtbl-mode "org-table" (&optional arg))
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-beamer-mode "org-beamer" ())
126 (declare-function org-table-edit-field "org-table" (arg))
127 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
128 (declare-function org-id-get-create "org-id" (&optional force))
129 (declare-function org-id-find-id-file "org-id" (id))
130 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
131 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
132 (declare-function org-table-align "org-table" ())
133 (declare-function org-table-paste-rectangle "org-table" ())
134 (declare-function org-table-maybe-eval-formula "org-table" ())
135 (declare-function org-table-maybe-recalculate-line "org-table" ())
137 ;; load languages based on value of `org-babel-load-languages'
138 (defvar org-babel-load-languages)
140 ;;;###autoload
141 (defun org-babel-do-load-languages (sym value)
142 "Load the languages defined in `org-babel-load-languages'."
143 (set-default sym value)
144 (mapc (lambda (pair)
145 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
146 (if active
147 (progn
148 (require (intern (concat "ob-" lang))))
149 (progn
150 (funcall 'fmakunbound
151 (intern (concat "org-babel-execute:" lang)))
152 (funcall 'fmakunbound
153 (intern (concat "org-babel-expand-body:" lang)))))))
154 org-babel-load-languages))
156 (defcustom org-babel-load-languages '((emacs-lisp . t))
157 "Languages which can be evaluated in Org-mode buffers.
158 This list can be used to load support for any of the languages
159 below, note that each language will depend on a different set of
160 system executables and/or Emacs modes. When a language is
161 \"loaded\", then code blocks in that language can be evaluated
162 with `org-babel-execute-src-block' bound by default to C-c
163 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
164 be set to remove code block evaluation from the C-c C-c
165 keybinding. By default only Emacs Lisp (which has no
166 requirements) is loaded."
167 :group 'org-babel
168 :set 'org-babel-do-load-languages
169 :version "24.1"
170 :type '(alist :tag "Babel Languages"
171 :key-type
172 (choice
173 (const :tag "Awk" awk)
174 (const :tag "C" C)
175 (const :tag "R" R)
176 (const :tag "Asymptote" asymptote)
177 (const :tag "Calc" calc)
178 (const :tag "Clojure" clojure)
179 (const :tag "CSS" css)
180 (const :tag "Ditaa" ditaa)
181 (const :tag "Dot" dot)
182 (const :tag "Emacs Lisp" emacs-lisp)
183 (const :tag "Fortran" fortran)
184 (const :tag "Gnuplot" gnuplot)
185 (const :tag "Haskell" haskell)
186 (const :tag "IO" io)
187 (const :tag "Java" java)
188 (const :tag "Javascript" js)
189 (const :tag "LaTeX" latex)
190 (const :tag "Ledger" ledger)
191 (const :tag "Lilypond" lilypond)
192 (const :tag "Lisp" lisp)
193 (const :tag "Maxima" maxima)
194 (const :tag "Matlab" matlab)
195 (const :tag "Mscgen" mscgen)
196 (const :tag "Ocaml" ocaml)
197 (const :tag "Octave" octave)
198 (const :tag "Org" org)
199 (const :tag "Perl" perl)
200 (const :tag "Pico Lisp" picolisp)
201 (const :tag "PlantUML" plantuml)
202 (const :tag "Python" python)
203 (const :tag "Ruby" ruby)
204 (const :tag "Sass" sass)
205 (const :tag "Scala" scala)
206 (const :tag "Scheme" scheme)
207 (const :tag "Screen" screen)
208 (const :tag "Shell Script" sh)
209 (const :tag "Shen" shen)
210 (const :tag "Sql" sql)
211 (const :tag "Sqlite" sqlite))
212 :value-type (boolean :tag "Activate" :value t)))
214 ;;;; Customization variables
215 (defcustom org-clone-delete-id nil
216 "Remove ID property of clones of a subtree.
217 When non-nil, clones of a subtree don't inherit the ID property.
218 Otherwise they inherit the ID property with a new unique
219 identifier."
220 :type 'boolean
221 :version "24.1"
222 :group 'org-id)
224 ;;; Version
225 (require 'org-compat)
226 (org-check-version)
228 ;;;###autoload
229 (defun org-version (&optional here full message)
230 "Show the org-mode version in the echo area.
231 With prefix argument HERE, insert it at point.
232 When FULL is non-nil, use a verbose version string.
233 When MESSAGE is non-nil, display a message with the version."
234 (interactive "P")
235 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
236 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs.el")))
237 (org-trash (or
238 (and (fboundp 'org-release) (fboundp 'org-git-version))
239 (load (concat org-dir "org-version.el")
240 'noerror 'nomessage 'nosuffix)))
241 (org-version (org-release))
242 (git-version (org-git-version))
243 (version (format "Org-mode version %s (%s @ %s)"
244 org-version
245 git-version
246 (if org-install-dir
247 (if (string= org-dir org-install-dir)
248 org-install-dir
249 (concat "mixed installation! " org-install-dir " and " org-dir))
250 "org-loaddefs.el can not be found!")))
251 (_version (if full version org-version)))
252 (if (org-called-interactively-p 'interactive)
253 (if here
254 (insert version)
255 (message version))
256 (if message (message _version))
257 _version)))
259 (defconst org-version (org-version))
261 ;;; Compatibility constants
263 ;;; The custom variables
265 (defgroup org nil
266 "Outline-based notes management and organizer."
267 :tag "Org"
268 :group 'outlines
269 :group 'calendar)
271 (defcustom org-mode-hook nil
272 "Mode hook for Org-mode, run after the mode was turned on."
273 :group 'org
274 :type 'hook)
276 (defcustom org-load-hook nil
277 "Hook that is run after org.el has been loaded."
278 :group 'org
279 :type 'hook)
281 (defcustom org-log-buffer-setup-hook nil
282 "Hook that is run after an Org log buffer is created."
283 :group 'org
284 :version "24.1"
285 :type 'hook)
287 (defvar org-modules) ; defined below
288 (defvar org-modules-loaded nil
289 "Have the modules been loaded already?")
291 (defun org-load-modules-maybe (&optional force)
292 "Load all extensions listed in `org-modules'."
293 (when (or force (not org-modules-loaded))
294 (mapc (lambda (ext)
295 (condition-case nil (require ext)
296 (error (message "Problems while trying to load feature `%s'" ext))))
297 org-modules)
298 (setq org-modules-loaded t)))
300 (defun org-set-modules (var value)
301 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
302 (set var value)
303 (when (featurep 'org)
304 (org-load-modules-maybe 'force)))
306 (when (org-bound-and-true-p org-modules)
307 (let ((a (member 'org-infojs org-modules)))
308 (and a (setcar a 'org-jsinfo))))
310 (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)
311 "Modules that should always be loaded together with org.el.
312 If a description starts with <C>, the file is not part of Emacs
313 and loading it will require that you have downloaded and properly installed
314 the org-mode distribution.
316 You can also use this system to load external packages (i.e. neither Org
317 core modules, nor modules from the CONTRIB directory). Just add symbols
318 to the end of the list. If the package is called org-xyz.el, then you need
319 to add the symbol `xyz', and the package must have a call to
321 (provide 'org-xyz)"
322 :group 'org
323 :set 'org-set-modules
324 :type
325 '(set :greedy t
326 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
327 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
328 (const :tag " crypt: Encryption of subtrees" org-crypt)
329 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
330 (const :tag " docview: Links to doc-view buffers" org-docview)
331 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
332 (const :tag " id: Global IDs for identifying entries" org-id)
333 (const :tag " info: Links to Info nodes" org-info)
334 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
335 (const :tag " habit: Track your consistency with habits" org-habit)
336 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
337 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
338 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
339 (const :tag " mew Links to Mew folders/messages" org-mew)
340 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
341 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
342 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
343 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
344 (const :tag " vm: Links to VM folders/messages" org-vm)
345 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
346 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
347 (const :tag " mouse: Additional mouse support" org-mouse)
348 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
350 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
351 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
352 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
353 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
354 (const :tag "C collector: Collect properties into tables" org-collector)
355 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
356 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
357 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
358 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
359 (const :tag "C eval: Include command output as text" org-eval)
360 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
361 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
362 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
363 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
364 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
366 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
368 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
369 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
370 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
371 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
372 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
373 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
374 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
375 (const :tag "C mtags: Support for muse-like tags" org-mtags)
376 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
377 (const :tag "C registry: A registry for Org-mode links" org-registry)
378 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
379 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
380 (const :tag "C secretary: Team management with org-mode" org-secretary)
381 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
382 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
383 (const :tag "C track: Keep up with Org-mode development" org-track)
384 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
385 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
386 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
388 (defcustom org-support-shift-select nil
389 "Non-nil means make shift-cursor commands select text when possible.
391 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
392 start selecting a region, or enlarge regions started in this way.
393 In Org-mode, in special contexts, these same keys are used for
394 other purposes, important enough to compete with shift selection.
395 Org tries to balance these needs by supporting `shift-select-mode'
396 outside these special contexts, under control of this variable.
398 The default of this variable is nil, to avoid confusing behavior. Shifted
399 cursor keys will then execute Org commands in the following contexts:
400 - on a headline, changing TODO state (left/right) and priority (up/down)
401 - on a time stamp, changing the time
402 - in a plain list item, changing the bullet type
403 - in a property definition line, switching between allowed values
404 - in the BEGIN line of a clock table (changing the time block).
405 Outside these contexts, the commands will throw an error.
407 When this variable is t and the cursor is not in a special
408 context, Org-mode will support shift-selection for making and
409 enlarging regions. To make this more effective, the bullet
410 cycling will no longer happen anywhere in an item line, but only
411 if the cursor is exactly on the bullet.
413 If you set this variable to the symbol `always', then the keys
414 will not be special in headlines, property lines, and item lines,
415 to make shift selection work there as well. If this is what you
416 want, you can use the following alternative commands: `C-c C-t'
417 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
418 can be used to switch TODO sets, `C-c -' to cycle item bullet
419 types, and properties can be edited by hand or in column view.
421 However, when the cursor is on a timestamp, shift-cursor commands
422 will still edit the time stamp - this is just too good to give up.
424 XEmacs user should have this variable set to nil, because
425 `shift-select-mode' is in Emacs 23 or later only."
426 :group 'org
427 :type '(choice
428 (const :tag "Never" nil)
429 (const :tag "When outside special context" t)
430 (const :tag "Everywhere except timestamps" always)))
432 (defcustom org-loop-over-headlines-in-active-region nil
433 "Shall some commands act upon headlines in the active region?
435 When set to `t', some commands will be performed in all headlines
436 within the active region.
438 When set to `start-level', some commands will be performed in all
439 headlines within the active region, provided that these headlines
440 are of the same level than the first one.
442 When set to a string, those commands will be performed on the
443 matching headlines within the active region. Such string must be
444 a tags/property/todo match as it is used in the agenda tags view.
446 The list of commands is: `org-schedule', `org-deadline',
447 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
448 `org-archive-to-archive-sibling'. The archiving commands skip
449 already archived entries."
450 :type '(choice (const :tag "Don't loop" nil)
451 (const :tag "All headlines in active region" t)
452 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
453 (string :tag "Tags/Property/Todo matcher"))
454 :version "24.1"
455 :group 'org-todo
456 :group 'org-archive)
458 (defgroup org-startup nil
459 "Options concerning startup of Org-mode."
460 :tag "Org Startup"
461 :group 'org)
463 (defcustom org-startup-folded t
464 "Non-nil means entering Org-mode will switch to OVERVIEW.
465 This can also be configured on a per-file basis by adding one of
466 the following lines anywhere in the buffer:
468 #+STARTUP: fold (or `overview', this is equivalent)
469 #+STARTUP: nofold (or `showall', this is equivalent)
470 #+STARTUP: content
471 #+STARTUP: showeverything"
472 :group 'org-startup
473 :type '(choice
474 (const :tag "nofold: show all" nil)
475 (const :tag "fold: overview" t)
476 (const :tag "content: all headlines" content)
477 (const :tag "show everything, even drawers" showeverything)))
479 (defcustom org-startup-truncated t
480 "Non-nil means entering Org-mode will set `truncate-lines'.
481 This is useful since some lines containing links can be very long and
482 uninteresting. Also tables look terrible when wrapped."
483 :group 'org-startup
484 :type 'boolean)
486 (defcustom org-startup-indented nil
487 "Non-nil means turn on `org-indent-mode' on startup.
488 This can also be configured on a per-file basis by adding one of
489 the following lines anywhere in the buffer:
491 #+STARTUP: indent
492 #+STARTUP: noindent"
493 :group 'org-structure
494 :type '(choice
495 (const :tag "Not" nil)
496 (const :tag "Globally (slow on startup in large files)" t)))
498 (defcustom org-use-sub-superscripts t
499 "Non-nil means interpret \"_\" and \"^\" for export.
500 When this option is turned on, you can use TeX-like syntax for sub- and
501 superscripts. Several characters after \"_\" or \"^\" will be
502 considered as a single item - so grouping with {} is normally not
503 needed. For example, the following things will be parsed as single
504 sub- or superscripts.
506 10^24 or 10^tau several digits will be considered 1 item.
507 10^-12 or 10^-tau a leading sign with digits or a word
508 x^2-y^3 will be read as x^2 - y^3, because items are
509 terminated by almost any nonword/nondigit char.
510 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
512 Still, ambiguity is possible - so when in doubt use {} to enclose the
513 sub/superscript. If you set this variable to the symbol `{}',
514 the braces are *required* in order to trigger interpretations as
515 sub/superscript. This can be helpful in documents that need \"_\"
516 frequently in plain text.
518 Not all export backends support this, but HTML does.
520 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
521 :group 'org-startup
522 :group 'org-export-translation
523 :version "24.1"
524 :type '(choice
525 (const :tag "Always interpret" t)
526 (const :tag "Only with braces" {})
527 (const :tag "Never interpret" nil)))
529 (if (fboundp 'defvaralias)
530 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
533 (defcustom org-startup-with-beamer-mode nil
534 "Non-nil means turn on `org-beamer-mode' on startup.
535 This can also be configured on a per-file basis by adding one of
536 the following lines anywhere in the buffer:
538 #+STARTUP: beamer"
539 :group 'org-startup
540 :version "24.1"
541 :type 'boolean)
543 (defcustom org-startup-align-all-tables nil
544 "Non-nil means align all tables when visiting a file.
545 This is useful when the column width in tables is forced with <N> cookies
546 in table fields. Such tables will look correct only after the first re-align.
547 This can also be configured on a per-file basis by adding one of
548 the following lines anywhere in the buffer:
549 #+STARTUP: align
550 #+STARTUP: noalign"
551 :group 'org-startup
552 :type 'boolean)
554 (defcustom org-startup-with-inline-images nil
555 "Non-nil means show inline images when loading a new Org file.
556 This can also be configured on a per-file basis by adding one of
557 the following lines anywhere in the buffer:
558 #+STARTUP: inlineimages
559 #+STARTUP: noinlineimages"
560 :group 'org-startup
561 :version "24.1"
562 :type 'boolean)
564 (defcustom org-insert-mode-line-in-empty-file nil
565 "Non-nil means insert the first line setting Org-mode in empty files.
566 When the function `org-mode' is called interactively in an empty file, this
567 normally means that the file name does not automatically trigger Org-mode.
568 To ensure that the file will always be in Org-mode in the future, a
569 line enforcing Org-mode will be inserted into the buffer, if this option
570 has been set."
571 :group 'org-startup
572 :type 'boolean)
574 (defcustom org-replace-disputed-keys nil
575 "Non-nil means use alternative key bindings for some keys.
576 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
577 These keys are also used by other packages like shift-selection-mode'
578 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
579 If you want to use Org-mode together with one of these other modes,
580 or more generally if you would like to move some Org-mode commands to
581 other keys, set this variable and configure the keys with the variable
582 `org-disputed-keys'.
584 This option is only relevant at load-time of Org-mode, and must be set
585 *before* org.el is loaded. Changing it requires a restart of Emacs to
586 become effective."
587 :group 'org-startup
588 :type 'boolean)
590 (defcustom org-use-extra-keys nil
591 "Non-nil means use extra key sequence definitions for certain commands.
592 This happens automatically if you run XEmacs or if `window-system'
593 is nil. This variable lets you do the same manually. You must
594 set it before loading org.
596 Example: on Carbon Emacs 22 running graphically, with an external
597 keyboard on a Powerbook, the default way of setting M-left might
598 not work for either Alt or ESC. Setting this variable will make
599 it work for ESC."
600 :group 'org-startup
601 :type 'boolean)
603 (if (fboundp 'defvaralias)
604 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
606 (defcustom org-disputed-keys
607 '(([(shift up)] . [(meta p)])
608 ([(shift down)] . [(meta n)])
609 ([(shift left)] . [(meta -)])
610 ([(shift right)] . [(meta +)])
611 ([(control shift right)] . [(meta shift +)])
612 ([(control shift left)] . [(meta shift -)]))
613 "Keys for which Org-mode and other modes compete.
614 This is an alist, cars are the default keys, second element specifies
615 the alternative to use when `org-replace-disputed-keys' is t.
617 Keys can be specified in any syntax supported by `define-key'.
618 The value of this option takes effect only at Org-mode's startup,
619 therefore you'll have to restart Emacs to apply it after changing."
620 :group 'org-startup
621 :type 'alist)
623 (defun org-key (key)
624 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
625 Or return the original if not disputed.
626 Also apply the translations defined in `org-xemacs-key-equivalents'."
627 (when org-replace-disputed-keys
628 (let* ((nkey (key-description key))
629 (x (org-find-if (lambda (x)
630 (equal (key-description (car x)) nkey))
631 org-disputed-keys)))
632 (setq key (if x (cdr x) key))))
633 (when (featurep 'xemacs)
634 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
635 key)
637 (defun org-find-if (predicate seq)
638 (catch 'exit
639 (while seq
640 (if (funcall predicate (car seq))
641 (throw 'exit (car seq))
642 (pop seq)))))
644 (defun org-defkey (keymap key def)
645 "Define a key, possibly translated, as returned by `org-key'."
646 (define-key keymap (org-key key) def))
648 (defcustom org-ellipsis nil
649 "The ellipsis to use in the Org-mode outline.
650 When nil, just use the standard three dots. When a string, use that instead,
651 When a face, use the standard 3 dots, but with the specified face.
652 The change affects only Org-mode (which will then use its own display table).
653 Changing this requires executing `M-x org-mode' in a buffer to become
654 effective."
655 :group 'org-startup
656 :type '(choice (const :tag "Default" nil)
657 (face :tag "Face" :value org-warning)
658 (string :tag "String" :value "...#")))
660 (defvar org-display-table nil
661 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
663 (defgroup org-keywords nil
664 "Keywords in Org-mode."
665 :tag "Org Keywords"
666 :group 'org)
668 (defcustom org-deadline-string "DEADLINE:"
669 "String to mark deadline entries.
670 A deadline is this string, followed by a time stamp. Should be a word,
671 terminated by a colon. You can insert a schedule keyword and
672 a timestamp with \\[org-deadline].
673 Changes become only effective after restarting Emacs."
674 :group 'org-keywords
675 :type 'string)
677 (defcustom org-scheduled-string "SCHEDULED:"
678 "String to mark scheduled TODO entries.
679 A schedule is this string, followed by a time stamp. Should be a word,
680 terminated by a colon. You can insert a schedule keyword and
681 a timestamp with \\[org-schedule].
682 Changes become only effective after restarting Emacs."
683 :group 'org-keywords
684 :type 'string)
686 (defcustom org-closed-string "CLOSED:"
687 "String used as the prefix for timestamps logging closing a TODO entry."
688 :group 'org-keywords
689 :type 'string)
691 (defcustom org-clock-string "CLOCK:"
692 "String used as prefix for timestamps clocking work hours on an item."
693 :group 'org-keywords
694 :type 'string)
696 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
697 org-scheduled-string "\\|"
698 org-deadline-string "\\|"
699 org-closed-string "\\|"
700 org-clock-string "\\)")
701 "Matches a line with planning or clock info.")
703 (defcustom org-comment-string "COMMENT"
704 "Entries starting with this keyword will never be exported.
705 An entry can be toggled between COMMENT and normal with
706 \\[org-toggle-comment].
707 Changes become only effective after restarting Emacs."
708 :group 'org-keywords
709 :type 'string)
711 (defcustom org-quote-string "QUOTE"
712 "Entries starting with this keyword will be exported in fixed-width font.
713 Quoting applies only to the text in the entry following the headline, and does
714 not extend beyond the next headline, even if that is lower level.
715 An entry can be toggled between QUOTE and normal with
716 \\[org-toggle-fixed-width-section]."
717 :group 'org-keywords
718 :type 'string)
720 (defconst org-repeat-re
721 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
722 "Regular expression for specifying repeated events.
723 After a match, group 1 contains the repeat expression.")
725 (defgroup org-structure nil
726 "Options concerning the general structure of Org-mode files."
727 :tag "Org Structure"
728 :group 'org)
730 (defgroup org-reveal-location nil
731 "Options about how to make context of a location visible."
732 :tag "Org Reveal Location"
733 :group 'org-structure)
735 (defconst org-context-choice
736 '(choice
737 (const :tag "Always" t)
738 (const :tag "Never" nil)
739 (repeat :greedy t :tag "Individual contexts"
740 (cons
741 (choice :tag "Context"
742 (const agenda)
743 (const org-goto)
744 (const occur-tree)
745 (const tags-tree)
746 (const link-search)
747 (const mark-goto)
748 (const bookmark-jump)
749 (const isearch)
750 (const default))
751 (boolean))))
752 "Contexts for the reveal options.")
754 (defcustom org-show-hierarchy-above '((default . t))
755 "Non-nil means show full hierarchy when revealing a location.
756 Org-mode often shows locations in an org-mode file which might have
757 been invisible before. When this is set, the hierarchy of headings
758 above the exposed location is shown.
759 Turning this off for example for sparse trees makes them very compact.
760 Instead of t, this can also be an alist specifying this option for different
761 contexts. Valid contexts are
762 agenda when exposing an entry from the agenda
763 org-goto when using the command `org-goto' on key C-c C-j
764 occur-tree when using the command `org-occur' on key C-c /
765 tags-tree when constructing a sparse tree based on tags matches
766 link-search when exposing search matches associated with a link
767 mark-goto when exposing the jump goal of a mark
768 bookmark-jump when exposing a bookmark location
769 isearch when exiting from an incremental search
770 default default for all contexts not set explicitly"
771 :group 'org-reveal-location
772 :type org-context-choice)
774 (defcustom org-show-following-heading '((default . nil))
775 "Non-nil means show following heading when revealing a location.
776 Org-mode often shows locations in an org-mode file which might have
777 been invisible before. When this is set, the heading following the
778 match is shown.
779 Turning this off for example for sparse trees makes them very compact,
780 but makes it harder to edit the location of the match. In such a case,
781 use the command \\[org-reveal] to show more context.
782 Instead of t, this can also be an alist specifying this option for different
783 contexts. See `org-show-hierarchy-above' for valid contexts."
784 :group 'org-reveal-location
785 :type org-context-choice)
787 (defcustom org-show-siblings '((default . nil) (isearch t))
788 "Non-nil means show all sibling heading when revealing a location.
789 Org-mode often shows locations in an org-mode file which might have
790 been invisible before. When this is set, the sibling of the current entry
791 heading are all made visible. If `org-show-hierarchy-above' is t,
792 the same happens on each level of the hierarchy above the current entry.
794 By default this is on for the isearch context, off for all other contexts.
795 Turning this off for example for sparse trees makes them very compact,
796 but makes it harder to edit the location of the match. In such a case,
797 use the command \\[org-reveal] to show more context.
798 Instead of t, this can also be an alist specifying this option for different
799 contexts. See `org-show-hierarchy-above' for valid contexts."
800 :group 'org-reveal-location
801 :type org-context-choice)
803 (defcustom org-show-entry-below '((default . nil))
804 "Non-nil means show the entry below a headline when revealing a location.
805 Org-mode often shows locations in an org-mode file which might have
806 been invisible before. When this is set, the text below the headline that is
807 exposed is also shown.
809 By default this is off for all contexts.
810 Instead of t, this can also be an alist specifying this option for different
811 contexts. See `org-show-hierarchy-above' for valid contexts."
812 :group 'org-reveal-location
813 :type org-context-choice)
815 (defcustom org-indirect-buffer-display 'other-window
816 "How should indirect tree buffers be displayed?
817 This applies to indirect buffers created with the commands
818 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
819 Valid values are:
820 current-window Display in the current window
821 other-window Just display in another window.
822 dedicated-frame Create one new frame, and re-use it each time.
823 new-frame Make a new frame each time. Note that in this case
824 previously-made indirect buffers are kept, and you need to
825 kill these buffers yourself."
826 :group 'org-structure
827 :group 'org-agenda-windows
828 :type '(choice
829 (const :tag "In current window" current-window)
830 (const :tag "In current frame, other window" other-window)
831 (const :tag "Each time a new frame" new-frame)
832 (const :tag "One dedicated frame" dedicated-frame)))
834 (defcustom org-use-speed-commands nil
835 "Non-nil means activate single letter commands at beginning of a headline.
836 This may also be a function to test for appropriate locations where speed
837 commands should be active."
838 :group 'org-structure
839 :type '(choice
840 (const :tag "Never" nil)
841 (const :tag "At beginning of headline stars" t)
842 (function)))
844 (defcustom org-speed-commands-user nil
845 "Alist of additional speed commands.
846 This list will be checked before `org-speed-commands-default'
847 when the variable `org-use-speed-commands' is non-nil
848 and when the cursor is at the beginning of a headline.
849 The car if each entry is a string with a single letter, which must
850 be assigned to `self-insert-command' in the global map.
851 The cdr is either a command to be called interactively, a function
852 to be called, or a form to be evaluated.
853 An entry that is just a list with a single string will be interpreted
854 as a descriptive headline that will be added when listing the speed
855 commands in the Help buffer using the `?' speed command."
856 :group 'org-structure
857 :type '(repeat :value ("k" . ignore)
858 (choice :value ("k" . ignore)
859 (list :tag "Descriptive Headline" (string :tag "Headline"))
860 (cons :tag "Letter and Command"
861 (string :tag "Command letter")
862 (choice
863 (function)
864 (sexp))))))
866 (defgroup org-cycle nil
867 "Options concerning visibility cycling in Org-mode."
868 :tag "Org Cycle"
869 :group 'org-structure)
871 (defcustom org-cycle-skip-children-state-if-no-children t
872 "Non-nil means skip CHILDREN state in entries that don't have any."
873 :group 'org-cycle
874 :type 'boolean)
876 (defcustom org-cycle-max-level nil
877 "Maximum level which should still be subject to visibility cycling.
878 Levels higher than this will, for cycling, be treated as text, not a headline.
879 When `org-odd-levels-only' is set, a value of N in this variable actually
880 means 2N-1 stars as the limiting headline.
881 When nil, cycle all levels.
882 Note that the limiting level of cycling is also influenced by
883 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
884 `org-inlinetask-min-level' is, cycling will be limited to levels one less
885 than its value."
886 :group 'org-cycle
887 :type '(choice
888 (const :tag "No limit" nil)
889 (integer :tag "Maximum level")))
891 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
892 "Names of drawers. Drawers are not opened by cycling on the headline above.
893 Drawers only open with a TAB on the drawer line itself. A drawer looks like
894 this:
895 :DRAWERNAME:
896 .....
897 :END:
898 The drawer \"PROPERTIES\" is special for capturing properties through
899 the property API.
901 Drawers can be defined on the per-file basis with a line like:
903 #+DRAWERS: HIDDEN STATE PROPERTIES"
904 :group 'org-structure
905 :group 'org-cycle
906 :type '(repeat (string :tag "Drawer Name")))
908 (defcustom org-hide-block-startup nil
909 "Non-nil means entering Org-mode will fold all blocks.
910 This can also be set in on a per-file basis with
912 #+STARTUP: hideblocks
913 #+STARTUP: showblocks"
914 :group 'org-startup
915 :group 'org-cycle
916 :type 'boolean)
918 (defcustom org-cycle-global-at-bob nil
919 "Cycle globally if cursor is at beginning of buffer and not at a headline.
920 This makes it possible to do global cycling without having to use S-TAB or
921 \\[universal-argument] TAB. For this special case to work, the first line
922 of the buffer must not be a headline -- it may be empty or some other text.
923 When used in this way, `org-cycle-hook' is disabled temporarily to make
924 sure the cursor stays at the beginning of the buffer. When this option is
925 nil, don't do anything special at the beginning of the buffer."
926 :group 'org-cycle
927 :type 'boolean)
929 (defcustom org-cycle-level-after-item/entry-creation t
930 "Non-nil means cycle entry level or item indentation in new empty entries.
932 When the cursor is at the end of an empty headline, i.e with only stars
933 and maybe a TODO keyword, TAB will then switch the entry to become a child,
934 and then all possible ancestor states, before returning to the original state.
935 This makes data entry extremely fast: M-RET to create a new headline,
936 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
938 When the cursor is at the end of an empty plain list item, one TAB will
939 make it a subitem, two or more tabs will back up to make this an item
940 higher up in the item hierarchy."
941 :group 'org-cycle
942 :type 'boolean)
944 (defcustom org-cycle-emulate-tab t
945 "Where should `org-cycle' emulate TAB.
946 nil Never
947 white Only in completely white lines
948 whitestart Only at the beginning of lines, before the first non-white char
949 t Everywhere except in headlines
950 exc-hl-bol Everywhere except at the start of a headline
951 If TAB is used in a place where it does not emulate TAB, the current subtree
952 visibility is cycled."
953 :group 'org-cycle
954 :type '(choice (const :tag "Never" nil)
955 (const :tag "Only in completely white lines" white)
956 (const :tag "Before first char in a line" whitestart)
957 (const :tag "Everywhere except in headlines" t)
958 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
961 (defcustom org-cycle-separator-lines 2
962 "Number of empty lines needed to keep an empty line between collapsed trees.
963 If you leave an empty line between the end of a subtree and the following
964 headline, this empty line is hidden when the subtree is folded.
965 Org-mode will leave (exactly) one empty line visible if the number of
966 empty lines is equal or larger to the number given in this variable.
967 So the default 2 means at least 2 empty lines after the end of a subtree
968 are needed to produce free space between a collapsed subtree and the
969 following headline.
971 If the number is negative, and the number of empty lines is at least -N,
972 all empty lines are shown.
974 Special case: when 0, never leave empty lines in collapsed view."
975 :group 'org-cycle
976 :type 'integer)
977 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
979 (defcustom org-pre-cycle-hook nil
980 "Hook that is run before visibility cycling is happening.
981 The function(s) in this hook must accept a single argument which indicates
982 the new state that will be set right after running this hook. The
983 argument is a symbol. Before a global state change, it can have the values
984 `overview', `content', or `all'. Before a local state change, it can have
985 the values `folded', `children', or `subtree'."
986 :group 'org-cycle
987 :type 'hook)
989 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
990 org-cycle-hide-drawers
991 org-cycle-hide-inline-tasks
992 org-cycle-show-empty-lines
993 org-optimize-window-after-visibility-change)
994 "Hook that is run after `org-cycle' has changed the buffer visibility.
995 The function(s) in this hook must accept a single argument which indicates
996 the new state that was set by the most recent `org-cycle' command. The
997 argument is a symbol. After a global state change, it can have the values
998 `overview', `contents', or `all'. After a local state change, it can have
999 the values `folded', `children', or `subtree'."
1000 :group 'org-cycle
1001 :type 'hook)
1003 (defgroup org-edit-structure nil
1004 "Options concerning structure editing in Org-mode."
1005 :tag "Org Edit Structure"
1006 :group 'org-structure)
1008 (defcustom org-odd-levels-only nil
1009 "Non-nil means skip even levels and only use odd levels for the outline.
1010 This has the effect that two stars are being added/taken away in
1011 promotion/demotion commands. It also influences how levels are
1012 handled by the exporters.
1013 Changing it requires restart of `font-lock-mode' to become effective
1014 for fontification also in regions already fontified.
1015 You may also set this on a per-file basis by adding one of the following
1016 lines to the buffer:
1018 #+STARTUP: odd
1019 #+STARTUP: oddeven"
1020 :group 'org-edit-structure
1021 :group 'org-appearance
1022 :type 'boolean)
1024 (defcustom org-adapt-indentation t
1025 "Non-nil means adapt indentation to outline node level.
1027 When this variable is set, Org assumes that you write outlines by
1028 indenting text in each node to align with the headline (after the stars).
1029 The following issues are influenced by this variable:
1031 - When this is set and the *entire* text in an entry is indented, the
1032 indentation is increased by one space in a demotion command, and
1033 decreased by one in a promotion command. If any line in the entry
1034 body starts with text at column 0, indentation is not changed at all.
1036 - Property drawers and planning information is inserted indented when
1037 this variable s set. When nil, they will not be indented.
1039 - TAB indents a line relative to context. The lines below a headline
1040 will be indented when this variable is set.
1042 Note that this is all about true indentation, by adding and removing
1043 space characters. See also `org-indent.el' which does level-dependent
1044 indentation in a virtual way, i.e. at display time in Emacs."
1045 :group 'org-edit-structure
1046 :type 'boolean)
1048 (defcustom org-special-ctrl-a/e nil
1049 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1051 When t, `C-a' will bring back the cursor to the beginning of the
1052 headline text, i.e. after the stars and after a possible TODO
1053 keyword. In an item, this will be the position after bullet and
1054 check-box, if any. When the cursor is already at that position,
1055 another `C-a' will bring it to the beginning of the line.
1057 `C-e' will jump to the end of the headline, ignoring the presence
1058 of tags in the headline. A second `C-e' will then jump to the
1059 true end of the line, after any tags. This also means that, when
1060 this variable is non-nil, `C-e' also will never jump beyond the
1061 end of the heading of a folded section, i.e. not after the
1062 ellipses.
1064 When set to the symbol `reversed', the first `C-a' or `C-e' works
1065 normally, going to the true line boundary first. Only a directly
1066 following, identical keypress will bring the cursor to the
1067 special positions.
1069 This may also be a cons cell where the behavior for `C-a' and
1070 `C-e' is set separately."
1071 :group 'org-edit-structure
1072 :type '(choice
1073 (const :tag "off" nil)
1074 (const :tag "on: after stars/bullet and before tags first" t)
1075 (const :tag "reversed: true line boundary first" reversed)
1076 (cons :tag "Set C-a and C-e separately"
1077 (choice :tag "Special C-a"
1078 (const :tag "off" nil)
1079 (const :tag "on: after stars/bullet first" t)
1080 (const :tag "reversed: before stars/bullet first" reversed))
1081 (choice :tag "Special C-e"
1082 (const :tag "off" nil)
1083 (const :tag "on: before tags first" t)
1084 (const :tag "reversed: after tags first" reversed)))))
1085 (if (fboundp 'defvaralias)
1086 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1088 (defcustom org-special-ctrl-k nil
1089 "Non-nil means `C-k' will behave specially in headlines.
1090 When nil, `C-k' will call the default `kill-line' command.
1091 When t, the following will happen while the cursor is in the headline:
1093 - When the cursor is at the beginning of a headline, kill the entire
1094 line and possible the folded subtree below the line.
1095 - When in the middle of the headline text, kill the headline up to the tags.
1096 - When after the headline text, kill the tags."
1097 :group 'org-edit-structure
1098 :type 'boolean)
1100 (defcustom org-ctrl-k-protect-subtree nil
1101 "Non-nil means, do not delete a hidden subtree with C-k.
1102 When set to the symbol `error', simply throw an error when C-k is
1103 used to kill (part-of) a headline that has hidden text behind it.
1104 Any other non-nil value will result in a query to the user, if it is
1105 OK to kill that hidden subtree. When nil, kill without remorse."
1106 :group 'org-edit-structure
1107 :version "24.1"
1108 :type '(choice
1109 (const :tag "Do not protect hidden subtrees" nil)
1110 (const :tag "Protect hidden subtrees with a security query" t)
1111 (const :tag "Never kill a hidden subtree with C-k" error)))
1113 (defcustom org-catch-invisible-edits nil
1114 "Check if in invisible region before inserting or deleting a character.
1115 Valid values are:
1117 nil Do not check, so just do invisible edits.
1118 error Throw an error and do nothing.
1119 show Make point visible, and do the requested edit.
1120 show-and-error Make point visible, then throw an error and abort the edit.
1121 smart Make point visible, and do insertion/deletion if it is
1122 adjacent to visible text and the change feels predictable.
1123 Never delete a previously invisible character or add in the
1124 middle or right after an invisible region. Basically, this
1125 allows insertion and backward-delete right before ellipses.
1126 FIXME: maybe in this case we should not even show?"
1127 :group 'org-edit-structure
1128 :version "24.1"
1129 :type '(choice
1130 (const :tag "Do not check" nil)
1131 (const :tag "Throw error when trying to edit" error)
1132 (const :tag "Unhide, but do not do the edit" show-and-error)
1133 (const :tag "Show invisible part and do the edit" show)
1134 (const :tag "Be smart and do the right thing" smart)))
1136 (defcustom org-yank-folded-subtrees t
1137 "Non-nil means when yanking subtrees, fold them.
1138 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1139 it starts with a heading and all other headings in it are either children
1140 or siblings, then fold all the subtrees. However, do this only if no
1141 text after the yank would be swallowed into a folded tree by this action."
1142 :group 'org-edit-structure
1143 :type 'boolean)
1145 (defcustom org-yank-adjusted-subtrees nil
1146 "Non-nil means when yanking subtrees, adjust the level.
1147 With this setting, `org-paste-subtree' is used to insert the subtree, see
1148 this function for details."
1149 :group 'org-edit-structure
1150 :type 'boolean)
1152 (defcustom org-M-RET-may-split-line '((default . t))
1153 "Non-nil means M-RET will split the line at the cursor position.
1154 When nil, it will go to the end of the line before making a
1155 new line.
1156 You may also set this option in a different way for different
1157 contexts. Valid contexts are:
1159 headline when creating a new headline
1160 item when creating a new item
1161 table in a table field
1162 default the value to be used for all contexts not explicitly
1163 customized"
1164 :group 'org-structure
1165 :group 'org-table
1166 :type '(choice
1167 (const :tag "Always" t)
1168 (const :tag "Never" nil)
1169 (repeat :greedy t :tag "Individual contexts"
1170 (cons
1171 (choice :tag "Context"
1172 (const headline)
1173 (const item)
1174 (const table)
1175 (const default))
1176 (boolean)))))
1179 (defcustom org-insert-heading-respect-content nil
1180 "Non-nil means insert new headings after the current subtree.
1181 When nil, the new heading is created directly after the current line.
1182 The commands \\[org-insert-heading-respect-content] and
1183 \\[org-insert-todo-heading-respect-content] turn this variable on
1184 for the duration of the command."
1185 :group 'org-structure
1186 :type 'boolean)
1188 (defcustom org-blank-before-new-entry '((heading . auto)
1189 (plain-list-item . auto))
1190 "Should `org-insert-heading' leave a blank line before new heading/item?
1191 The value is an alist, with `heading' and `plain-list-item' as CAR,
1192 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1193 which case Org will look at the surrounding headings/items and try to
1194 make an intelligent decision whether to insert a blank line or not.
1196 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1197 set, the setting here is ignored and no empty line is inserted, to avoid
1198 breaking the list structure."
1199 :group 'org-edit-structure
1200 :type '(list
1201 (cons (const heading)
1202 (choice (const :tag "Never" nil)
1203 (const :tag "Always" t)
1204 (const :tag "Auto" auto)))
1205 (cons (const plain-list-item)
1206 (choice (const :tag "Never" nil)
1207 (const :tag "Always" t)
1208 (const :tag "Auto" auto)))))
1210 (defcustom org-insert-heading-hook nil
1211 "Hook being run after inserting a new heading."
1212 :group 'org-edit-structure
1213 :type 'hook)
1215 (defcustom org-enable-fixed-width-editor t
1216 "Non-nil means lines starting with \":\" are treated as fixed-width.
1217 This currently only means they are never auto-wrapped.
1218 When nil, such lines will be treated like ordinary lines.
1219 See also the QUOTE keyword."
1220 :group 'org-edit-structure
1221 :type 'boolean)
1223 (defcustom org-goto-auto-isearch t
1224 "Non-nil means typing characters in `org-goto' starts incremental search."
1225 :group 'org-edit-structure
1226 :type 'boolean)
1228 (defgroup org-sparse-trees nil
1229 "Options concerning sparse trees in Org-mode."
1230 :tag "Org Sparse Trees"
1231 :group 'org-structure)
1233 (defcustom org-highlight-sparse-tree-matches t
1234 "Non-nil means highlight all matches that define a sparse tree.
1235 The highlights will automatically disappear the next time the buffer is
1236 changed by an edit command."
1237 :group 'org-sparse-trees
1238 :type 'boolean)
1240 (defcustom org-remove-highlights-with-change t
1241 "Non-nil means any change to the buffer will remove temporary highlights.
1242 Such highlights are created by `org-occur' and `org-clock-display'.
1243 When nil, `C-c C-c needs to be used to get rid of the highlights.
1244 The highlights created by `org-preview-latex-fragment' always need
1245 `C-c C-c' to be removed."
1246 :group 'org-sparse-trees
1247 :group 'org-time
1248 :type 'boolean)
1251 (defcustom org-occur-hook '(org-first-headline-recenter)
1252 "Hook that is run after `org-occur' has constructed a sparse tree.
1253 This can be used to recenter the window to show as much of the structure
1254 as possible."
1255 :group 'org-sparse-trees
1256 :type 'hook)
1258 (defgroup org-imenu-and-speedbar nil
1259 "Options concerning imenu and speedbar in Org-mode."
1260 :tag "Org Imenu and Speedbar"
1261 :group 'org-structure)
1263 (defcustom org-imenu-depth 2
1264 "The maximum level for Imenu access to Org-mode headlines.
1265 This also applied for speedbar access."
1266 :group 'org-imenu-and-speedbar
1267 :type 'integer)
1269 (defgroup org-table nil
1270 "Options concerning tables in Org-mode."
1271 :tag "Org Table"
1272 :group 'org)
1274 (defcustom org-enable-table-editor 'optimized
1275 "Non-nil means lines starting with \"|\" are handled by the table editor.
1276 When nil, such lines will be treated like ordinary lines.
1278 When equal to the symbol `optimized', the table editor will be optimized to
1279 do the following:
1280 - Automatic overwrite mode in front of whitespace in table fields.
1281 This makes the structure of the table stay in tact as long as the edited
1282 field does not exceed the column width.
1283 - Minimize the number of realigns. Normally, the table is aligned each time
1284 TAB or RET are pressed to move to another field. With optimization this
1285 happens only if changes to a field might have changed the column width.
1286 Optimization requires replacing the functions `self-insert-command',
1287 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1288 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1289 very good at guessing when a re-align will be necessary, but you can always
1290 force one with \\[org-ctrl-c-ctrl-c].
1292 If you would like to use the optimized version in Org-mode, but the
1293 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1295 This variable can be used to turn on and off the table editor during a session,
1296 but in order to toggle optimization, a restart is required.
1298 See also the variable `org-table-auto-blank-field'."
1299 :group 'org-table
1300 :type '(choice
1301 (const :tag "off" nil)
1302 (const :tag "on" t)
1303 (const :tag "on, optimized" optimized)))
1305 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1306 (version<= emacs-version "24.1"))
1307 "Non-nil means cluster self-insert commands for undo when possible.
1308 If this is set, then, like in the Emacs command loop, 20 consecutive
1309 characters will be undone together.
1310 This is configurable, because there is some impact on typing performance."
1311 :group 'org-table
1312 :type 'boolean)
1314 (defcustom org-table-tab-recognizes-table.el t
1315 "Non-nil means TAB will automatically notice a table.el table.
1316 When it sees such a table, it moves point into it and - if necessary -
1317 calls `table-recognize-table'."
1318 :group 'org-table-editing
1319 :type 'boolean)
1321 (defgroup org-link nil
1322 "Options concerning links in Org-mode."
1323 :tag "Org Link"
1324 :group 'org)
1326 (defvar org-link-abbrev-alist-local nil
1327 "Buffer-local version of `org-link-abbrev-alist', which see.
1328 The value of this is taken from the #+LINK lines.")
1329 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1331 (defcustom org-link-abbrev-alist nil
1332 "Alist of link abbreviations.
1333 The car of each element is a string, to be replaced at the start of a link.
1334 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1335 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1337 [[linkkey:tag][description]]
1339 The 'linkkey' must be a word word, starting with a letter, followed
1340 by letters, numbers, '-' or '_'.
1342 If REPLACE is a string, the tag will simply be appended to create the link.
1343 If the string contains \"%s\", the tag will be inserted there. If the string
1344 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1345 at that point (see the function `url-hexify-string'). If the string contains
1346 the specifier \"%(my-function)\", then the custom function `my-function' will
1347 be invoked: this function takes the tag as its only argument and must return
1348 a string.
1350 REPLACE may also be a function that will be called with the tag as the
1351 only argument to create the link, which should be returned as a string.
1353 See the manual for examples."
1354 :group 'org-link
1355 :type '(repeat
1356 (cons
1357 (string :tag "Protocol")
1358 (choice
1359 (string :tag "Format")
1360 (function)))))
1362 (defcustom org-descriptive-links t
1363 "Non-nil means Org will display descriptive links.
1364 E.g. [[http://orgmode.org][Org website]] will be displayed as
1365 \"Org Website\", hiding the link itself and just displaying its
1366 description. When set to `nil', Org will display the full links
1367 literally.
1369 You can interactively set the value of this variable by calling
1370 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1371 :group 'org-link
1372 :type 'boolean)
1374 (defcustom org-link-file-path-type 'adaptive
1375 "How the path name in file links should be stored.
1376 Valid values are:
1378 relative Relative to the current directory, i.e. the directory of the file
1379 into which the link is being inserted.
1380 absolute Absolute path, if possible with ~ for home directory.
1381 noabbrev Absolute path, no abbreviation of home directory.
1382 adaptive Use relative path for files in the current directory and sub-
1383 directories of it. For other files, use an absolute path."
1384 :group 'org-link
1385 :type '(choice
1386 (const relative)
1387 (const absolute)
1388 (const noabbrev)
1389 (const adaptive)))
1391 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1392 "Types of links that should be activated in Org-mode files.
1393 This is a list of symbols, each leading to the activation of a certain link
1394 type. In principle, it does not hurt to turn on most link types - there may
1395 be a small gain when turning off unused link types. The types are:
1397 bracket The recommended [[link][description]] or [[link]] links with hiding.
1398 angle Links in angular brackets that may contain whitespace like
1399 <bbdb:Carsten Dominik>.
1400 plain Plain links in normal text, no whitespace, like http://google.com.
1401 radio Text that is matched by a radio target, see manual for details.
1402 tag Tag settings in a headline (link to tag search).
1403 date Time stamps (link to calendar).
1404 footnote Footnote labels.
1406 Changing this variable requires a restart of Emacs to become effective."
1407 :group 'org-link
1408 :type '(set :greedy t
1409 (const :tag "Double bracket links" bracket)
1410 (const :tag "Angular bracket links" angle)
1411 (const :tag "Plain text links" plain)
1412 (const :tag "Radio target matches" radio)
1413 (const :tag "Tags" tag)
1414 (const :tag "Timestamps" date)
1415 (const :tag "Footnotes" footnote)))
1417 (defcustom org-make-link-description-function nil
1418 "Function to use for generating link descriptions from links.
1419 When nil, the link location will be used. This function must take
1420 two parameters: the first one is the link, the second one is the
1421 description generated by `org-insert-link'. The function should
1422 return the description to use."
1423 :group 'org-link
1424 :type 'function)
1426 (defgroup org-link-store nil
1427 "Options concerning storing links in Org-mode."
1428 :tag "Org Store Link"
1429 :group 'org-link)
1431 (defcustom org-url-hexify-p t
1432 "When non-nil, hexify URL when creating a link."
1433 :type 'boolean
1434 :version "24.3"
1435 :group 'org-link-store)
1437 (defcustom org-email-link-description-format "Email %c: %.30s"
1438 "Format of the description part of a link to an email or usenet message.
1439 The following %-escapes will be replaced by corresponding information:
1441 %F full \"From\" field
1442 %f name, taken from \"From\" field, address if no name
1443 %T full \"To\" field
1444 %t first name in \"To\" field, address if no name
1445 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1446 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1447 %s subject
1448 %d date
1449 %m message-id.
1451 You may use normal field width specification between the % and the letter.
1452 This is for example useful to limit the length of the subject.
1454 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1455 :group 'org-link-store
1456 :type 'string)
1458 (defcustom org-from-is-user-regexp
1459 (let (r1 r2)
1460 (when (and user-mail-address (not (string= user-mail-address "")))
1461 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1462 (when (and user-full-name (not (string= user-full-name "")))
1463 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1464 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1465 "Regexp matched against the \"From:\" header of an email or usenet message.
1466 It should match if the message is from the user him/herself."
1467 :group 'org-link-store
1468 :type 'regexp)
1470 (defcustom org-context-in-file-links t
1471 "Non-nil means file links from `org-store-link' contain context.
1472 A search string will be added to the file name with :: as separator and
1473 used to find the context when the link is activated by the command
1474 `org-open-at-point'. When this option is t, the entire active region
1475 will be placed in the search string of the file link. If set to a
1476 positive integer, only the first n lines of context will be stored.
1478 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1479 negates this setting for the duration of the command."
1480 :group 'org-link-store
1481 :type '(choice boolean integer))
1483 (defcustom org-keep-stored-link-after-insertion nil
1484 "Non-nil means keep link in list for entire session.
1486 The command `org-store-link' adds a link pointing to the current
1487 location to an internal list. These links accumulate during a session.
1488 The command `org-insert-link' can be used to insert links into any
1489 Org-mode file (offering completion for all stored links). When this
1490 option is nil, every link which has been inserted once using \\[org-insert-link]
1491 will be removed from the list, to make completing the unused links
1492 more efficient."
1493 :group 'org-link-store
1494 :type 'boolean)
1496 (defgroup org-link-follow nil
1497 "Options concerning following links in Org-mode."
1498 :tag "Org Follow Link"
1499 :group 'org-link)
1501 (defcustom org-link-translation-function nil
1502 "Function to translate links with different syntax to Org syntax.
1503 This can be used to translate links created for example by the Planner
1504 or emacs-wiki packages to Org syntax.
1505 The function must accept two parameters, a TYPE containing the link
1506 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1507 which is everything after the link protocol. It should return a cons
1508 with possibly modified values of type and path.
1509 Org contains a function for this, so if you set this variable to
1510 `org-translate-link-from-planner', you should be able follow many
1511 links created by planner."
1512 :group 'org-link-follow
1513 :type 'function)
1515 (defcustom org-follow-link-hook nil
1516 "Hook that is run after a link has been followed."
1517 :group 'org-link-follow
1518 :type 'hook)
1520 (defcustom org-tab-follows-link nil
1521 "Non-nil means on links TAB will follow the link.
1522 Needs to be set before org.el is loaded.
1523 This really should not be used, it does not make sense, and the
1524 implementation is bad."
1525 :group 'org-link-follow
1526 :type 'boolean)
1528 (defcustom org-return-follows-link nil
1529 "Non-nil means on links RET will follow the link."
1530 :group 'org-link-follow
1531 :type 'boolean)
1533 (defcustom org-mouse-1-follows-link
1534 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1535 "Non-nil means mouse-1 on a link will follow the link.
1536 A longer mouse click will still set point. Does not work on XEmacs.
1537 Needs to be set before org.el is loaded."
1538 :group 'org-link-follow
1539 :type 'boolean)
1541 (defcustom org-mark-ring-length 4
1542 "Number of different positions to be recorded in the ring.
1543 Changing this requires a restart of Emacs to work correctly."
1544 :group 'org-link-follow
1545 :type 'integer)
1547 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1548 "Non-nil means internal links in Org files must exactly match a headline.
1549 When nil, the link search tries to match a phrase with all words
1550 in the search text."
1551 :group 'org-link-follow
1552 :version "24.1"
1553 :type '(choice
1554 (const :tag "Use fuzzy text search" nil)
1555 (const :tag "Match only exact headline" t)
1556 (const :tag "Match exact headline or query to create it"
1557 query-to-create)))
1559 (defcustom org-link-frame-setup
1560 '((vm . vm-visit-folder-other-frame)
1561 (vm-imap . vm-visit-imap-folder-other-frame)
1562 (gnus . org-gnus-no-new-news)
1563 (file . find-file-other-window)
1564 (wl . wl-other-frame))
1565 "Setup the frame configuration for following links.
1566 When following a link with Emacs, it may often be useful to display
1567 this link in another window or frame. This variable can be used to
1568 set this up for the different types of links.
1569 For VM, use any of
1570 `vm-visit-folder'
1571 `vm-visit-folder-other-window'
1572 `vm-visit-folder-other-frame'
1573 For Gnus, use any of
1574 `gnus'
1575 `gnus-other-frame'
1576 `org-gnus-no-new-news'
1577 For FILE, use any of
1578 `find-file'
1579 `find-file-other-window'
1580 `find-file-other-frame'
1581 For Wanderlust use any of
1582 `wl'
1583 `wl-other-frame'
1584 For the calendar, use the variable `calendar-setup'.
1585 For BBDB, it is currently only possible to display the matches in
1586 another window."
1587 :group 'org-link-follow
1588 :type '(list
1589 (cons (const vm)
1590 (choice
1591 (const vm-visit-folder)
1592 (const vm-visit-folder-other-window)
1593 (const vm-visit-folder-other-frame)))
1594 (cons (const gnus)
1595 (choice
1596 (const gnus)
1597 (const gnus-other-frame)
1598 (const org-gnus-no-new-news)))
1599 (cons (const file)
1600 (choice
1601 (const find-file)
1602 (const find-file-other-window)
1603 (const find-file-other-frame)))
1604 (cons (const wl)
1605 (choice
1606 (const wl)
1607 (const wl-other-frame)))))
1609 (defcustom org-display-internal-link-with-indirect-buffer nil
1610 "Non-nil means use indirect buffer to display infile links.
1611 Activating internal links (from one location in a file to another location
1612 in the same file) normally just jumps to the location. When the link is
1613 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1614 is displayed in
1615 another window. When this option is set, the other window actually displays
1616 an indirect buffer clone of the current buffer, to avoid any visibility
1617 changes to the current buffer."
1618 :group 'org-link-follow
1619 :type 'boolean)
1621 (defcustom org-open-non-existing-files nil
1622 "Non-nil means `org-open-file' will open non-existing files.
1623 When nil, an error will be generated.
1624 This variable applies only to external applications because they
1625 might choke on non-existing files. If the link is to a file that
1626 will be opened in Emacs, the variable is ignored."
1627 :group 'org-link-follow
1628 :type 'boolean)
1630 (defcustom org-open-directory-means-index-dot-org nil
1631 "Non-nil means a link to a directory really means to index.org.
1632 When nil, following a directory link will run dired or open a finder/explorer
1633 window on that directory."
1634 :group 'org-link-follow
1635 :type 'boolean)
1637 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1638 "Function and arguments to call for following mailto links.
1639 This is a list with the first element being a Lisp function, and the
1640 remaining elements being arguments to the function. In string arguments,
1641 %a will be replaced by the address, and %s will be replaced by the subject
1642 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1643 :group 'org-link-follow
1644 :type '(choice
1645 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1646 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1647 (const :tag "message-mail" (message-mail "%a" "%s"))
1648 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1650 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1651 "Non-nil means ask for confirmation before executing shell links.
1652 Shell links can be dangerous: just think about a link
1654 [[shell:rm -rf ~/*][Google Search]]
1656 This link would show up in your Org-mode document as \"Google Search\",
1657 but really it would remove your entire home directory.
1658 Therefore we advise against setting this variable to nil.
1659 Just change it to `y-or-n-p' if you want to confirm with a
1660 single keystroke rather than having to type \"yes\"."
1661 :group 'org-link-follow
1662 :type '(choice
1663 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1664 (const :tag "with y-or-n (faster)" y-or-n-p)
1665 (const :tag "no confirmation (dangerous)" nil)))
1666 (put 'org-confirm-shell-link-function
1667 'safe-local-variable
1668 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1670 (defcustom org-confirm-shell-link-not-regexp ""
1671 "A regexp to skip confirmation for shell links."
1672 :group 'org-link-follow
1673 :version "24.1"
1674 :type 'regexp)
1676 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1677 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1678 Elisp links can be dangerous: just think about a link
1680 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1682 This link would show up in your Org-mode document as \"Google Search\",
1683 but really it would remove your entire home directory.
1684 Therefore we advise against setting this variable to nil.
1685 Just change it to `y-or-n-p' if you want to confirm with a
1686 single keystroke rather than having to type \"yes\"."
1687 :group 'org-link-follow
1688 :type '(choice
1689 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1690 (const :tag "with y-or-n (faster)" y-or-n-p)
1691 (const :tag "no confirmation (dangerous)" nil)))
1692 (put 'org-confirm-shell-link-function
1693 'safe-local-variable
1694 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1696 (defcustom org-confirm-elisp-link-not-regexp ""
1697 "A regexp to skip confirmation for Elisp links."
1698 :group 'org-link-follow
1699 :version "24.1"
1700 :type 'regexp)
1702 (defconst org-file-apps-defaults-gnu
1703 '((remote . emacs)
1704 (system . mailcap)
1705 (t . mailcap))
1706 "Default file applications on a UNIX or GNU/Linux system.
1707 See `org-file-apps'.")
1709 (defconst org-file-apps-defaults-macosx
1710 '((remote . emacs)
1711 (t . "open %s")
1712 (system . "open %s")
1713 ("ps.gz" . "gv %s")
1714 ("eps.gz" . "gv %s")
1715 ("dvi" . "xdvi %s")
1716 ("fig" . "xfig %s"))
1717 "Default file applications on a MacOS X system.
1718 The system \"open\" is known as a default, but we use X11 applications
1719 for some files for which the OS does not have a good default.
1720 See `org-file-apps'.")
1722 (defconst org-file-apps-defaults-windowsnt
1723 (list
1724 '(remote . emacs)
1725 (cons t
1726 (list (if (featurep 'xemacs)
1727 'mswindows-shell-execute
1728 'w32-shell-execute)
1729 "open" 'file))
1730 (cons 'system
1731 (list (if (featurep 'xemacs)
1732 'mswindows-shell-execute
1733 'w32-shell-execute)
1734 "open" 'file)))
1735 "Default file applications on a Windows NT system.
1736 The system \"open\" is used for most files.
1737 See `org-file-apps'.")
1739 (defcustom org-file-apps
1741 (auto-mode . emacs)
1742 ("\\.mm\\'" . default)
1743 ("\\.x?html?\\'" . default)
1744 ("\\.pdf\\'" . default)
1746 "External applications for opening `file:path' items in a document.
1747 Org-mode uses system defaults for different file types, but
1748 you can use this variable to set the application for a given file
1749 extension. The entries in this list are cons cells where the car identifies
1750 files and the cdr the corresponding command. Possible values for the
1751 file identifier are
1752 \"string\" A string as a file identifier can be interpreted in different
1753 ways, depending on its contents:
1755 - Alphanumeric characters only:
1756 Match links with this file extension.
1757 Example: (\"pdf\" . \"evince %s\")
1758 to open PDFs with evince.
1760 - Regular expression: Match links where the
1761 filename matches the regexp. If you want to
1762 use groups here, use shy groups.
1764 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1765 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1766 to open *.html and *.xhtml with firefox.
1768 - Regular expression which contains (non-shy) groups:
1769 Match links where the whole link, including \"::\", and
1770 anything after that, matches the regexp.
1771 In a custom command string, %1, %2, etc. are replaced with
1772 the parts of the link that were matched by the groups.
1773 For backwards compatibility, if a command string is given
1774 that does not use any of the group matches, this case is
1775 handled identically to the second one (i.e. match against
1776 file name only).
1777 In a custom lisp form, you can access the group matches with
1778 (match-string n link).
1780 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1781 to open [[file:document.pdf::5]] with evince at page 5.
1783 `directory' Matches a directory
1784 `remote' Matches a remote file, accessible through tramp or efs.
1785 Remote files most likely should be visited through Emacs
1786 because external applications cannot handle such paths.
1787 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1788 so all files Emacs knows how to handle. Using this with
1789 command `emacs' will open most files in Emacs. Beware that this
1790 will also open html files inside Emacs, unless you add
1791 (\"html\" . default) to the list as well.
1792 t Default for files not matched by any of the other options.
1793 `system' The system command to open files, like `open' on Windows
1794 and Mac OS X, and mailcap under GNU/Linux. This is the command
1795 that will be selected if you call `C-c C-o' with a double
1796 \\[universal-argument] \\[universal-argument] prefix.
1798 Possible values for the command are:
1799 `emacs' The file will be visited by the current Emacs process.
1800 `default' Use the default application for this file type, which is the
1801 association for t in the list, most likely in the system-specific
1802 part.
1803 This can be used to overrule an unwanted setting in the
1804 system-specific variable.
1805 `system' Use the system command for opening files, like \"open\".
1806 This command is specified by the entry whose car is `system'.
1807 Most likely, the system-specific version of this variable
1808 does define this command, but you can overrule/replace it
1809 here.
1810 string A command to be executed by a shell; %s will be replaced
1811 by the path to the file.
1812 sexp A Lisp form which will be evaluated. The file path will
1813 be available in the Lisp variable `file'.
1814 For more examples, see the system specific constants
1815 `org-file-apps-defaults-macosx'
1816 `org-file-apps-defaults-windowsnt'
1817 `org-file-apps-defaults-gnu'."
1818 :group 'org-link-follow
1819 :type '(repeat
1820 (cons (choice :value ""
1821 (string :tag "Extension")
1822 (const :tag "System command to open files" system)
1823 (const :tag "Default for unrecognized files" t)
1824 (const :tag "Remote file" remote)
1825 (const :tag "Links to a directory" directory)
1826 (const :tag "Any files that have Emacs modes"
1827 auto-mode))
1828 (choice :value ""
1829 (const :tag "Visit with Emacs" emacs)
1830 (const :tag "Use default" default)
1831 (const :tag "Use the system command" system)
1832 (string :tag "Command")
1833 (sexp :tag "Lisp form")))))
1835 (defcustom org-doi-server-url "http://dx.doi.org/"
1836 "The URL of the DOI server."
1837 :type 'string
1838 :version "24.3"
1839 :group 'org-link-follow)
1841 (defgroup org-refile nil
1842 "Options concerning refiling entries in Org-mode."
1843 :tag "Org Refile"
1844 :group 'org)
1846 (defcustom org-directory "~/org"
1847 "Directory with org files.
1848 This is just a default location to look for Org files. There is no need
1849 at all to put your files into this directory. It is only used in the
1850 following situations:
1852 1. When a capture template specifies a target file that is not an
1853 absolute path. The path will then be interpreted relative to
1854 `org-directory'
1855 2. When a capture note is filed away in an interactive way (when exiting the
1856 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1857 with `org-directory' as the default path."
1858 :group 'org-refile
1859 :group 'org-remember
1860 :group 'org-capture
1861 :type 'directory)
1863 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1864 "Default target for storing notes.
1865 Used as a fall back file for org-remember.el and org-capture.el, for
1866 templates that do not specify a target file."
1867 :group 'org-refile
1868 :group 'org-remember
1869 :group 'org-capture
1870 :type '(choice
1871 (const :tag "Default from remember-data-file" nil)
1872 file))
1874 (defcustom org-goto-interface 'outline
1875 "The default interface to be used for `org-goto'.
1876 Allowed values are:
1877 outline The interface shows an outline of the relevant file
1878 and the correct heading is found by moving through
1879 the outline or by searching with incremental search.
1880 outline-path-completion Headlines in the current buffer are offered via
1881 completion. This is the interface also used by
1882 the refile command."
1883 :group 'org-refile
1884 :type '(choice
1885 (const :tag "Outline" outline)
1886 (const :tag "Outline-path-completion" outline-path-completion)))
1888 (defcustom org-goto-max-level 5
1889 "Maximum target level when running `org-goto' with refile interface."
1890 :group 'org-refile
1891 :type 'integer)
1893 (defcustom org-reverse-note-order nil
1894 "Non-nil means store new notes at the beginning of a file or entry.
1895 When nil, new notes will be filed to the end of a file or entry.
1896 This can also be a list with cons cells of regular expressions that
1897 are matched against file names, and values."
1898 :group 'org-remember
1899 :group 'org-capture
1900 :group 'org-refile
1901 :type '(choice
1902 (const :tag "Reverse always" t)
1903 (const :tag "Reverse never" nil)
1904 (repeat :tag "By file name regexp"
1905 (cons regexp boolean))))
1907 (defcustom org-log-refile nil
1908 "Information to record when a task is refiled.
1910 Possible values are:
1912 nil Don't add anything
1913 time Add a time stamp to the task
1914 note Prompt for a note and add it with template `org-log-note-headings'
1916 This option can also be set with on a per-file-basis with
1918 #+STARTUP: nologrefile
1919 #+STARTUP: logrefile
1920 #+STARTUP: lognoterefile
1922 You can have local logging settings for a subtree by setting the LOGGING
1923 property to one or more of these keywords.
1925 When bulk-refiling from the agenda, the value `note' is forbidden and
1926 will temporarily be changed to `time'."
1927 :group 'org-refile
1928 :group 'org-progress
1929 :version "24.1"
1930 :type '(choice
1931 (const :tag "No logging" nil)
1932 (const :tag "Record timestamp" time)
1933 (const :tag "Record timestamp with note." note)))
1935 (defcustom org-refile-targets nil
1936 "Targets for refiling entries with \\[org-refile].
1937 This is a list of cons cells. Each cell contains:
1938 - a specification of the files to be considered, either a list of files,
1939 or a symbol whose function or variable value will be used to retrieve
1940 a file name or a list of file names. If you use `org-agenda-files' for
1941 that, all agenda files will be scanned for targets. Nil means consider
1942 headings in the current buffer.
1943 - A specification of how to find candidate refile targets. This may be
1944 any of:
1945 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1946 This tag has to be present in all target headlines, inheritance will
1947 not be considered.
1948 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1949 todo keyword.
1950 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1951 headlines that are refiling targets.
1952 - a cons cell (:level . N). Any headline of level N is considered a target.
1953 Note that, when `org-odd-levels-only' is set, level corresponds to
1954 order in hierarchy, not to the number of stars.
1955 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1956 Note that, when `org-odd-levels-only' is set, level corresponds to
1957 order in hierarchy, not to the number of stars.
1959 Each element of this list generates a set of possible targets.
1960 The union of these sets is presented (with completion) to
1961 the user by `org-refile'.
1963 You can set the variable `org-refile-target-verify-function' to a function
1964 to verify each headline found by the simple criteria above.
1966 When this variable is nil, all top-level headlines in the current buffer
1967 are used, equivalent to the value `((nil . (:level . 1))'."
1968 :group 'org-refile
1969 :type '(repeat
1970 (cons
1971 (choice :value org-agenda-files
1972 (const :tag "All agenda files" org-agenda-files)
1973 (const :tag "Current buffer" nil)
1974 (function) (variable) (file))
1975 (choice :tag "Identify target headline by"
1976 (cons :tag "Specific tag" (const :value :tag) (string))
1977 (cons :tag "TODO keyword" (const :value :todo) (string))
1978 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1979 (cons :tag "Level number" (const :value :level) (integer))
1980 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1982 (defcustom org-refile-target-verify-function nil
1983 "Function to verify if the headline at point should be a refile target.
1984 The function will be called without arguments, with point at the
1985 beginning of the headline. It should return t and leave point
1986 where it is if the headline is a valid target for refiling.
1988 If the target should not be selected, the function must return nil.
1989 In addition to this, it may move point to a place from where the search
1990 should be continued. For example, the function may decide that the entire
1991 subtree of the current entry should be excluded and move point to the end
1992 of the subtree."
1993 :group 'org-refile
1994 :type 'function)
1996 (defcustom org-refile-use-cache nil
1997 "Non-nil means cache refile targets to speed up the process.
1998 The cache for a particular file will be updated automatically when
1999 the buffer has been killed, or when any of the marker used for flagging
2000 refile targets no longer points at a live buffer.
2001 If you have added new entries to a buffer that might themselves be targets,
2002 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2003 find that easier, `C-u C-u C-u C-c C-w'."
2004 :group 'org-refile
2005 :version "24.1"
2006 :type 'boolean)
2008 (defcustom org-refile-use-outline-path nil
2009 "Non-nil means provide refile targets as paths.
2010 So a level 3 headline will be available as level1/level2/level3.
2012 When the value is `file', also include the file name (without directory)
2013 into the path. In this case, you can also stop the completion after
2014 the file name, to get entries inserted as top level in the file.
2016 When `full-file-path', include the full file path."
2017 :group 'org-refile
2018 :type '(choice
2019 (const :tag "Not" nil)
2020 (const :tag "Yes" t)
2021 (const :tag "Start with file name" file)
2022 (const :tag "Start with full file path" full-file-path)))
2024 (defcustom org-outline-path-complete-in-steps t
2025 "Non-nil means complete the outline path in hierarchical steps.
2026 When Org-mode uses the refile interface to select an outline path
2027 \(see variable `org-refile-use-outline-path'), the completion of
2028 the path can be done is a single go, or if can be done in steps down
2029 the headline hierarchy. Going in steps is probably the best if you
2030 do not use a special completion package like `ido' or `icicles'.
2031 However, when using these packages, going in one step can be very
2032 fast, while still showing the whole path to the entry."
2033 :group 'org-refile
2034 :type 'boolean)
2036 (defcustom org-refile-allow-creating-parent-nodes nil
2037 "Non-nil means allow to create new nodes as refile targets.
2038 New nodes are then created by adding \"/new node name\" to the completion
2039 of an existing node. When the value of this variable is `confirm',
2040 new node creation must be confirmed by the user (recommended)
2041 When nil, the completion must match an existing entry.
2043 Note that, if the new heading is not seen by the criteria
2044 listed in `org-refile-targets', multiple instances of the same
2045 heading would be created by trying again to file under the new
2046 heading."
2047 :group 'org-refile
2048 :type '(choice
2049 (const :tag "Never" nil)
2050 (const :tag "Always" t)
2051 (const :tag "Prompt for confirmation" confirm)))
2053 (defcustom org-refile-active-region-within-subtree nil
2054 "Non-nil means also refile active region within a subtree.
2056 By default `org-refile' doesn't allow refiling regions if they
2057 don't contain a set of subtrees, but it might be convenient to
2058 do so sometimes: in that case, the first line of the region is
2059 converted to a headline before refiling."
2060 :group 'org-refile
2061 :version "24.1"
2062 :type 'boolean)
2064 (defgroup org-todo nil
2065 "Options concerning TODO items in Org-mode."
2066 :tag "Org TODO"
2067 :group 'org)
2069 (defgroup org-progress nil
2070 "Options concerning Progress logging in Org-mode."
2071 :tag "Org Progress"
2072 :group 'org-time)
2074 (defvar org-todo-interpretation-widgets
2075 '((:tag "Sequence (cycling hits every state)" sequence)
2076 (:tag "Type (cycling directly to DONE)" type))
2077 "The available interpretation symbols for customizing `org-todo-keywords'.
2078 Interested libraries should add to this list.")
2080 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2081 "List of TODO entry keyword sequences and their interpretation.
2082 \\<org-mode-map>This is a list of sequences.
2084 Each sequence starts with a symbol, either `sequence' or `type',
2085 indicating if the keywords should be interpreted as a sequence of
2086 action steps, or as different types of TODO items. The first
2087 keywords are states requiring action - these states will select a headline
2088 for inclusion into the global TODO list Org-mode produces. If one of
2089 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2090 signify that no further action is necessary. If \"|\" is not found,
2091 the last keyword is treated as the only DONE state of the sequence.
2093 The command \\[org-todo] cycles an entry through these states, and one
2094 additional state where no keyword is present. For details about this
2095 cycling, see the manual.
2097 TODO keywords and interpretation can also be set on a per-file basis with
2098 the special #+SEQ_TODO and #+TYP_TODO lines.
2100 Each keyword can optionally specify a character for fast state selection
2101 \(in combination with the variable `org-use-fast-todo-selection')
2102 and specifiers for state change logging, using the same syntax that
2103 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2104 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2105 indicates to record a time stamp each time this state is selected.
2107 Each keyword may also specify if a timestamp or a note should be
2108 recorded when entering or leaving the state, by adding additional
2109 characters in the parenthesis after the keyword. This looks like this:
2110 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2111 record only the time of the state change. With X and Y being either
2112 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2113 Y when leaving the state if and only if the *target* state does not
2114 define X. You may omit any of the fast-selection key or X or /Y,
2115 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2117 For backward compatibility, this variable may also be just a list
2118 of keywords. In this case the interpretation (sequence or type) will be
2119 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2120 :group 'org-todo
2121 :group 'org-keywords
2122 :type '(choice
2123 (repeat :tag "Old syntax, just keywords"
2124 (string :tag "Keyword"))
2125 (repeat :tag "New syntax"
2126 (cons
2127 (choice
2128 :tag "Interpretation"
2129 ;;Quick and dirty way to see
2130 ;;`org-todo-interpretations'. This takes the
2131 ;;place of item arguments
2132 :convert-widget
2133 (lambda (widget)
2134 (widget-put widget
2135 :args (mapcar
2136 #'(lambda (x)
2137 (widget-convert
2138 (cons 'const x)))
2139 org-todo-interpretation-widgets))
2140 widget))
2141 (repeat
2142 (string :tag "Keyword"))))))
2144 (defvar org-todo-keywords-1 nil
2145 "All TODO and DONE keywords active in a buffer.")
2146 (make-variable-buffer-local 'org-todo-keywords-1)
2147 (defvar org-todo-keywords-for-agenda nil)
2148 (defvar org-done-keywords-for-agenda nil)
2149 (defvar org-drawers-for-agenda nil)
2150 (defvar org-todo-keyword-alist-for-agenda nil)
2151 (defvar org-tag-alist-for-agenda nil)
2152 (defvar org-agenda-contributing-files nil)
2153 (defvar org-not-done-keywords nil)
2154 (make-variable-buffer-local 'org-not-done-keywords)
2155 (defvar org-done-keywords nil)
2156 (make-variable-buffer-local 'org-done-keywords)
2157 (defvar org-todo-heads nil)
2158 (make-variable-buffer-local 'org-todo-heads)
2159 (defvar org-todo-sets nil)
2160 (make-variable-buffer-local 'org-todo-sets)
2161 (defvar org-todo-log-states nil)
2162 (make-variable-buffer-local 'org-todo-log-states)
2163 (defvar org-todo-kwd-alist nil)
2164 (make-variable-buffer-local 'org-todo-kwd-alist)
2165 (defvar org-todo-key-alist nil)
2166 (make-variable-buffer-local 'org-todo-key-alist)
2167 (defvar org-todo-key-trigger nil)
2168 (make-variable-buffer-local 'org-todo-key-trigger)
2170 (defcustom org-todo-interpretation 'sequence
2171 "Controls how TODO keywords are interpreted.
2172 This variable is in principle obsolete and is only used for
2173 backward compatibility, if the interpretation of todo keywords is
2174 not given already in `org-todo-keywords'. See that variable for
2175 more information."
2176 :group 'org-todo
2177 :group 'org-keywords
2178 :type '(choice (const sequence)
2179 (const type)))
2181 (defcustom org-use-fast-todo-selection t
2182 "Non-nil means use the fast todo selection scheme with C-c C-t.
2183 This variable describes if and under what circumstances the cycling
2184 mechanism for TODO keywords will be replaced by a single-key, direct
2185 selection scheme.
2187 When nil, fast selection is never used.
2189 When the symbol `prefix', it will be used when `org-todo' is called
2190 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2191 `C-u t' in an agenda buffer.
2193 When t, fast selection is used by default. In this case, the prefix
2194 argument forces cycling instead.
2196 In all cases, the special interface is only used if access keys have
2197 actually been assigned by the user, i.e. if keywords in the configuration
2198 are followed by a letter in parenthesis, like TODO(t)."
2199 :group 'org-todo
2200 :type '(choice
2201 (const :tag "Never" nil)
2202 (const :tag "By default" t)
2203 (const :tag "Only with C-u C-c C-t" prefix)))
2205 (defcustom org-provide-todo-statistics t
2206 "Non-nil means update todo statistics after insert and toggle.
2207 ALL-HEADLINES means update todo statistics by including headlines
2208 with no TODO keyword as well, counting them as not done.
2209 A list of TODO keywords means the same, but skip keywords that are
2210 not in this list.
2212 When this is set, todo statistics is updated in the parent of the
2213 current entry each time a todo state is changed."
2214 :group 'org-todo
2215 :type '(choice
2216 (const :tag "Yes, only for TODO entries" t)
2217 (const :tag "Yes, including all entries" 'all-headlines)
2218 (repeat :tag "Yes, for TODOs in this list"
2219 (string :tag "TODO keyword"))
2220 (other :tag "No TODO statistics" nil)))
2222 (defcustom org-hierarchical-todo-statistics t
2223 "Non-nil means TODO statistics covers just direct children.
2224 When nil, all entries in the subtree are considered.
2225 This has only an effect if `org-provide-todo-statistics' is set.
2226 To set this to nil for only a single subtree, use a COOKIE_DATA
2227 property and include the word \"recursive\" into the value."
2228 :group 'org-todo
2229 :type 'boolean)
2231 (defcustom org-after-todo-state-change-hook nil
2232 "Hook which is run after the state of a TODO item was changed.
2233 The new state (a string with a TODO keyword, or nil) is available in the
2234 Lisp variable `org-state'."
2235 :group 'org-todo
2236 :type 'hook)
2238 (defvar org-blocker-hook nil
2239 "Hook for functions that are allowed to block a state change.
2241 Each function gets as its single argument a property list, see
2242 `org-trigger-hook' for more information about this list.
2244 If any of the functions in this hook returns nil, the state change
2245 is blocked.")
2247 (defvar org-trigger-hook nil
2248 "Hook for functions that are triggered by a state change.
2250 Each function gets as its single argument a property list with at least
2251 the following elements:
2253 (:type type-of-change :position pos-at-entry-start
2254 :from old-state :to new-state)
2256 Depending on the type, more properties may be present.
2258 This mechanism is currently implemented for:
2260 TODO state changes
2261 ------------------
2262 :type todo-state-change
2263 :from previous state (keyword as a string), or nil, or a symbol
2264 'todo' or 'done', to indicate the general type of state.
2265 :to new state, like in :from")
2267 (defcustom org-enforce-todo-dependencies nil
2268 "Non-nil means undone TODO entries will block switching the parent to DONE.
2269 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2270 be blocked if any prior sibling is not yet done.
2271 Finally, if the parent is blocked because of ordered siblings of its own,
2272 the child will also be blocked."
2273 :set (lambda (var val)
2274 (set var val)
2275 (if val
2276 (add-hook 'org-blocker-hook
2277 'org-block-todo-from-children-or-siblings-or-parent)
2278 (remove-hook 'org-blocker-hook
2279 'org-block-todo-from-children-or-siblings-or-parent)))
2280 :group 'org-todo
2281 :type 'boolean)
2283 (defcustom org-enforce-todo-checkbox-dependencies nil
2284 "Non-nil means unchecked boxes will block switching the parent to DONE.
2285 When this is nil, checkboxes have no influence on switching TODO states.
2286 When non-nil, you first need to check off all check boxes before the TODO
2287 entry can be switched to DONE.
2288 This variable needs to be set before org.el is loaded, and you need to
2289 restart Emacs after a change to make the change effective. The only way
2290 to change is while Emacs is running is through the customize interface."
2291 :set (lambda (var val)
2292 (set var val)
2293 (if val
2294 (add-hook 'org-blocker-hook
2295 'org-block-todo-from-checkboxes)
2296 (remove-hook 'org-blocker-hook
2297 'org-block-todo-from-checkboxes)))
2298 :group 'org-todo
2299 :type 'boolean)
2301 (defcustom org-treat-insert-todo-heading-as-state-change nil
2302 "Non-nil means inserting a TODO heading is treated as state change.
2303 So when the command \\[org-insert-todo-heading] is used, state change
2304 logging will apply if appropriate. When nil, the new TODO item will
2305 be inserted directly, and no logging will take place."
2306 :group 'org-todo
2307 :type 'boolean)
2309 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2310 "Non-nil means switching TODO states with S-cursor counts as state change.
2311 This is the default behavior. However, setting this to nil allows a
2312 convenient way to select a TODO state and bypass any logging associated
2313 with that."
2314 :group 'org-todo
2315 :type 'boolean)
2317 (defcustom org-todo-state-tags-triggers nil
2318 "Tag changes that should be triggered by TODO state changes.
2319 This is a list. Each entry is
2321 (state-change (tag . flag) .......)
2323 State-change can be a string with a state, and empty string to indicate the
2324 state that has no TODO keyword, or it can be one of the symbols `todo'
2325 or `done', meaning any not-done or done state, respectively."
2326 :group 'org-todo
2327 :group 'org-tags
2328 :type '(repeat
2329 (cons (choice :tag "When changing to"
2330 (const :tag "Not-done state" todo)
2331 (const :tag "Done state" done)
2332 (string :tag "State"))
2333 (repeat
2334 (cons :tag "Tag action"
2335 (string :tag "Tag")
2336 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2338 (defcustom org-log-done nil
2339 "Information to record when a task moves to the DONE state.
2341 Possible values are:
2343 nil Don't add anything, just change the keyword
2344 time Add a time stamp to the task
2345 note Prompt for a note and add it with template `org-log-note-headings'
2347 This option can also be set with on a per-file-basis with
2349 #+STARTUP: nologdone
2350 #+STARTUP: logdone
2351 #+STARTUP: lognotedone
2353 You can have local logging settings for a subtree by setting the LOGGING
2354 property to one or more of these keywords."
2355 :group 'org-todo
2356 :group 'org-progress
2357 :type '(choice
2358 (const :tag "No logging" nil)
2359 (const :tag "Record CLOSED timestamp" time)
2360 (const :tag "Record CLOSED timestamp with note." note)))
2362 ;; Normalize old uses of org-log-done.
2363 (cond
2364 ((eq org-log-done t) (setq org-log-done 'time))
2365 ((and (listp org-log-done) (memq 'done org-log-done))
2366 (setq org-log-done 'note)))
2368 (defcustom org-log-reschedule nil
2369 "Information to record when the scheduling date of a tasks is modified.
2371 Possible values are:
2373 nil Don't add anything, just change the date
2374 time Add a time stamp to the task
2375 note Prompt for a note and add it with template `org-log-note-headings'
2377 This option can also be set with on a per-file-basis with
2379 #+STARTUP: nologreschedule
2380 #+STARTUP: logreschedule
2381 #+STARTUP: lognotereschedule"
2382 :group 'org-todo
2383 :group 'org-progress
2384 :type '(choice
2385 (const :tag "No logging" nil)
2386 (const :tag "Record timestamp" time)
2387 (const :tag "Record timestamp with note." note)))
2389 (defcustom org-log-redeadline nil
2390 "Information to record when the deadline date of a tasks is modified.
2392 Possible values are:
2394 nil Don't add anything, just change the date
2395 time Add a time stamp to the task
2396 note Prompt for a note and add it with template `org-log-note-headings'
2398 This option can also be set with on a per-file-basis with
2400 #+STARTUP: nologredeadline
2401 #+STARTUP: logredeadline
2402 #+STARTUP: lognoteredeadline
2404 You can have local logging settings for a subtree by setting the LOGGING
2405 property to one or more of these keywords."
2406 :group 'org-todo
2407 :group 'org-progress
2408 :type '(choice
2409 (const :tag "No logging" nil)
2410 (const :tag "Record timestamp" time)
2411 (const :tag "Record timestamp with note." note)))
2413 (defcustom org-log-note-clock-out nil
2414 "Non-nil means record a note when clocking out of an item.
2415 This can also be configured on a per-file basis by adding one of
2416 the following lines anywhere in the buffer:
2418 #+STARTUP: lognoteclock-out
2419 #+STARTUP: nolognoteclock-out"
2420 :group 'org-todo
2421 :group 'org-progress
2422 :type 'boolean)
2424 (defcustom org-log-done-with-time t
2425 "Non-nil means the CLOSED time stamp will contain date and time.
2426 When nil, only the date will be recorded."
2427 :group 'org-progress
2428 :type 'boolean)
2430 (defcustom org-log-note-headings
2431 '((done . "CLOSING NOTE %t")
2432 (state . "State %-12s from %-12S %t")
2433 (note . "Note taken on %t")
2434 (reschedule . "Rescheduled from %S on %t")
2435 (delschedule . "Not scheduled, was %S on %t")
2436 (redeadline . "New deadline from %S on %t")
2437 (deldeadline . "Removed deadline, was %S on %t")
2438 (refile . "Refiled on %t")
2439 (clock-out . ""))
2440 "Headings for notes added to entries.
2441 The value is an alist, with the car being a symbol indicating the note
2442 context, and the cdr is the heading to be used. The heading may also be the
2443 empty string.
2444 %t in the heading will be replaced by a time stamp.
2445 %T will be an active time stamp instead the default inactive one
2446 %d will be replaced by a short-format time stamp.
2447 %D will be replaced by an active short-format time stamp.
2448 %s will be replaced by the new TODO state, in double quotes.
2449 %S will be replaced by the old TODO state, in double quotes.
2450 %u will be replaced by the user name.
2451 %U will be replaced by the full user name.
2453 In fact, it is not a good idea to change the `state' entry, because
2454 agenda log mode depends on the format of these entries."
2455 :group 'org-todo
2456 :group 'org-progress
2457 :type '(list :greedy t
2458 (cons (const :tag "Heading when closing an item" done) string)
2459 (cons (const :tag
2460 "Heading when changing todo state (todo sequence only)"
2461 state) string)
2462 (cons (const :tag "Heading when just taking a note" note) string)
2463 (cons (const :tag "Heading when clocking out" clock-out) string)
2464 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2465 (cons (const :tag "Heading when rescheduling" reschedule) string)
2466 (cons (const :tag "Heading when changing deadline" redeadline) string)
2467 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2468 (cons (const :tag "Heading when refiling" refile) string)))
2470 (unless (assq 'note org-log-note-headings)
2471 (push '(note . "%t") org-log-note-headings))
2473 (defcustom org-log-into-drawer nil
2474 "Non-nil means insert state change notes and time stamps into a drawer.
2475 When nil, state changes notes will be inserted after the headline and
2476 any scheduling and clock lines, but not inside a drawer.
2478 The value of this variable should be the name of the drawer to use.
2479 LOGBOOK is proposed as the default drawer for this purpose, you can
2480 also set this to a string to define the drawer of your choice.
2482 A value of t is also allowed, representing \"LOGBOOK\".
2484 If this variable is set, `org-log-state-notes-insert-after-drawers'
2485 will be ignored.
2487 You can set the property LOG_INTO_DRAWER to overrule this setting for
2488 a subtree."
2489 :group 'org-todo
2490 :group 'org-progress
2491 :type '(choice
2492 (const :tag "Not into a drawer" nil)
2493 (const :tag "LOGBOOK" t)
2494 (string :tag "Other")))
2496 (if (fboundp 'defvaralias)
2497 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2499 (defun org-log-into-drawer ()
2500 "Return the value of `org-log-into-drawer', but let properties overrule.
2501 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2502 used instead of the default value."
2503 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2504 (cond
2505 ((or (not p) (equal p "nil")) org-log-into-drawer)
2506 ((equal p "t") "LOGBOOK")
2507 (t p))))
2509 (defcustom org-log-state-notes-insert-after-drawers nil
2510 "Non-nil means insert state change notes after any drawers in entry.
2511 Only the drawers that *immediately* follow the headline and the
2512 deadline/scheduled line are skipped.
2513 When nil, insert notes right after the heading and perhaps the line
2514 with deadline/scheduling if present.
2516 This variable will have no effect if `org-log-into-drawer' is
2517 set."
2518 :group 'org-todo
2519 :group 'org-progress
2520 :type 'boolean)
2522 (defcustom org-log-states-order-reversed t
2523 "Non-nil means the latest state note will be directly after heading.
2524 When nil, the state change notes will be ordered according to time."
2525 :group 'org-todo
2526 :group 'org-progress
2527 :type 'boolean)
2529 (defcustom org-todo-repeat-to-state nil
2530 "The TODO state to which a repeater should return the repeating task.
2531 By default this is the first task in a TODO sequence, or the previous state
2532 in a TODO_TYP set. But you can specify another task here.
2533 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2534 :group 'org-todo
2535 :version "24.1"
2536 :type '(choice (const :tag "Head of sequence" nil)
2537 (string :tag "Specific state")))
2539 (defcustom org-log-repeat 'time
2540 "Non-nil means record moving through the DONE state when triggering repeat.
2541 An auto-repeating task is immediately switched back to TODO when
2542 marked DONE. If you are not logging state changes (by adding \"@\"
2543 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2544 record a closing note, there will be no record of the task moving
2545 through DONE. This variable forces taking a note anyway.
2547 nil Don't force a record
2548 time Record a time stamp
2549 note Prompt for a note and add it with template `org-log-note-headings'
2551 This option can also be set with on a per-file-basis with
2553 #+STARTUP: nologrepeat
2554 #+STARTUP: logrepeat
2555 #+STARTUP: lognoterepeat
2557 You can have local logging settings for a subtree by setting the LOGGING
2558 property to one or more of these keywords."
2559 :group 'org-todo
2560 :group 'org-progress
2561 :type '(choice
2562 (const :tag "Don't force a record" nil)
2563 (const :tag "Force recording the DONE state" time)
2564 (const :tag "Force recording a note with the DONE state" note)))
2567 (defgroup org-priorities nil
2568 "Priorities in Org-mode."
2569 :tag "Org Priorities"
2570 :group 'org-todo)
2572 (defcustom org-enable-priority-commands t
2573 "Non-nil means priority commands are active.
2574 When nil, these commands will be disabled, so that you never accidentally
2575 set a priority."
2576 :group 'org-priorities
2577 :type 'boolean)
2579 (defcustom org-highest-priority ?A
2580 "The highest priority of TODO items. A character like ?A, ?B etc.
2581 Must have a smaller ASCII number than `org-lowest-priority'."
2582 :group 'org-priorities
2583 :type 'character)
2585 (defcustom org-lowest-priority ?C
2586 "The lowest priority of TODO items. A character like ?A, ?B etc.
2587 Must have a larger ASCII number than `org-highest-priority'."
2588 :group 'org-priorities
2589 :type 'character)
2591 (defcustom org-default-priority ?B
2592 "The default priority of TODO items.
2593 This is the priority an item gets if no explicit priority is given.
2594 When starting to cycle on an empty priority the first step in the cycle
2595 depends on `org-priority-start-cycle-with-default'. The resulting first
2596 step priority must not exceed the range from `org-highest-priority' to
2597 `org-lowest-priority' which means that `org-default-priority' has to be
2598 in this range exclusive or inclusive the range boundaries. Else the
2599 first step refuses to set the default and the second will fall back
2600 to (depending on the command used) the highest or lowest priority."
2601 :group 'org-priorities
2602 :type 'character)
2604 (defcustom org-priority-start-cycle-with-default t
2605 "Non-nil means start with default priority when starting to cycle.
2606 When this is nil, the first step in the cycle will be (depending on the
2607 command used) one higher or lower than the default priority.
2608 See also `org-default-priority'."
2609 :group 'org-priorities
2610 :type 'boolean)
2612 (defcustom org-get-priority-function nil
2613 "Function to extract the priority from a string.
2614 The string is normally the headline. If this is nil Org computes the
2615 priority from the priority cookie like [#A] in the headline. It returns
2616 an integer, increasing by 1000 for each priority level.
2617 The user can set a different function here, which should take a string
2618 as an argument and return the numeric priority."
2619 :group 'org-priorities
2620 :version "24.1"
2621 :type 'function)
2623 (defgroup org-time nil
2624 "Options concerning time stamps and deadlines in Org-mode."
2625 :tag "Org Time"
2626 :group 'org)
2628 (defcustom org-insert-labeled-timestamps-at-point nil
2629 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2630 When nil, these labeled time stamps are forces into the second line of an
2631 entry, just after the headline. When scheduling from the global TODO list,
2632 the time stamp will always be forced into the second line."
2633 :group 'org-time
2634 :type 'boolean)
2636 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2637 "Formats for `format-time-string' which are used for time stamps.
2638 It is not recommended to change this constant.")
2640 (defcustom org-time-stamp-rounding-minutes '(0 5)
2641 "Number of minutes to round time stamps to.
2642 These are two values, the first applies when first creating a time stamp.
2643 The second applies when changing it with the commands `S-up' and `S-down'.
2644 When changing the time stamp, this means that it will change in steps
2645 of N minutes, as given by the second value.
2647 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2648 numbers should be factors of 60, so for example 5, 10, 15.
2650 When this is larger than 1, you can still force an exact time stamp by using
2651 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2652 and by using a prefix arg to `S-up/down' to specify the exact number
2653 of minutes to shift."
2654 :group 'org-time
2655 :get #'(lambda (var) ; Make sure both elements are there
2656 (if (integerp (default-value var))
2657 (list (default-value var) 5)
2658 (default-value var)))
2659 :type '(list
2660 (integer :tag "when inserting times")
2661 (integer :tag "when modifying times")))
2663 ;; Normalize old customizations of this variable.
2664 (when (integerp org-time-stamp-rounding-minutes)
2665 (setq org-time-stamp-rounding-minutes
2666 (list org-time-stamp-rounding-minutes
2667 org-time-stamp-rounding-minutes)))
2669 (defcustom org-display-custom-times nil
2670 "Non-nil means overlay custom formats over all time stamps.
2671 The formats are defined through the variable `org-time-stamp-custom-formats'.
2672 To turn this on on a per-file basis, insert anywhere in the file:
2673 #+STARTUP: customtime"
2674 :group 'org-time
2675 :set 'set-default
2676 :type 'sexp)
2677 (make-variable-buffer-local 'org-display-custom-times)
2679 (defcustom org-time-stamp-custom-formats
2680 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2681 "Custom formats for time stamps. See `format-time-string' for the syntax.
2682 These are overlaid over the default ISO format if the variable
2683 `org-display-custom-times' is set. Time like %H:%M should be at the
2684 end of the second format. The custom formats are also honored by export
2685 commands, if custom time display is turned on at the time of export."
2686 :group 'org-time
2687 :type 'sexp)
2689 (defun org-time-stamp-format (&optional long inactive)
2690 "Get the right format for a time string."
2691 (let ((f (if long (cdr org-time-stamp-formats)
2692 (car org-time-stamp-formats))))
2693 (if inactive
2694 (concat "[" (substring f 1 -1) "]")
2695 f)))
2697 (defcustom org-time-clocksum-format "%d:%02d"
2698 "The format string used when creating CLOCKSUM lines.
2699 This is also used when org-mode generates a time duration."
2700 :group 'org-time
2701 :type 'string)
2703 (defcustom org-time-clocksum-use-fractional nil
2704 "If non-nil, \\[org-clock-display] uses fractional times.
2705 org-mode generates a time duration."
2706 :group 'org-time
2707 :type 'boolean)
2709 (defcustom org-time-clocksum-fractional-format "%.2f"
2710 "The format string used when creating CLOCKSUM lines, or when
2711 org-mode generates a time duration."
2712 :group 'org-time
2713 :type 'string)
2715 (defcustom org-deadline-warning-days 14
2716 "No. of days before expiration during which a deadline becomes active.
2717 This variable governs the display in sparse trees and in the agenda.
2718 When 0 or negative, it means use this number (the absolute value of it)
2719 even if a deadline has a different individual lead time specified.
2721 Custom commands can set this variable in the options section."
2722 :group 'org-time
2723 :group 'org-agenda-daily/weekly
2724 :type 'integer)
2726 (defcustom org-read-date-prefer-future t
2727 "Non-nil means assume future for incomplete date input from user.
2728 This affects the following situations:
2729 1. The user gives a month but not a year.
2730 For example, if it is April and you enter \"feb 2\", this will be read
2731 as Feb 2, *next* year. \"May 5\", however, will be this year.
2732 2. The user gives a day, but no month.
2733 For example, if today is the 15th, and you enter \"3\", Org-mode will
2734 read this as the third of *next* month. However, if you enter \"17\",
2735 it will be considered as *this* month.
2737 If you set this variable to the symbol `time', then also the following
2738 will work:
2740 3. If the user gives a time.
2741 If the time is before now, it will be interpreted as tomorrow.
2743 Currently none of this works for ISO week specifications.
2745 When this option is nil, the current day, month and year will always be
2746 used as defaults.
2748 See also `org-agenda-jump-prefer-future'."
2749 :group 'org-time
2750 :type '(choice
2751 (const :tag "Never" nil)
2752 (const :tag "Check month and day" t)
2753 (const :tag "Check month, day, and time" time)))
2755 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2756 "Should the agenda jump command prefer the future for incomplete dates?
2757 The default is to do the same as configured in `org-read-date-prefer-future'.
2758 But you can also set a deviating value here.
2759 This may t or nil, or the symbol `org-read-date-prefer-future'."
2760 :group 'org-agenda
2761 :group 'org-time
2762 :version "24.1"
2763 :type '(choice
2764 (const :tag "Use org-read-date-prefer-future"
2765 org-read-date-prefer-future)
2766 (const :tag "Never" nil)
2767 (const :tag "Always" t)))
2769 (defcustom org-read-date-force-compatible-dates t
2770 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2772 Depending on the system Emacs is running on, certain dates cannot
2773 be represented with the type used internally to represent time.
2774 Dates between 1970-1-1 and 2038-1-1 can always be represented
2775 correctly. Some systems allow for earlier dates, some for later,
2776 some for both. One way to find out it to insert any date into an
2777 Org buffer, putting the cursor on the year and hitting S-up and
2778 S-down to test the range.
2780 When this variable is set to t, the date/time prompt will not let
2781 you specify dates outside the 1970-2037 range, so it is certain that
2782 these dates will work in whatever version of Emacs you are
2783 running, and also that you can move a file from one Emacs implementation
2784 to another. WHenever Org is forcing the year for you, it will display
2785 a message and beep.
2787 When this variable is nil, Org will check if the date is
2788 representable in the specific Emacs implementation you are using.
2789 If not, it will force a year, usually the current year, and beep
2790 to remind you. Currently this setting is not recommended because
2791 the likelihood that you will open your Org files in an Emacs that
2792 has limited date range is not negligible.
2794 A workaround for this problem is to use diary sexp dates for time
2795 stamps outside of this range."
2796 :group 'org-time
2797 :version "24.1"
2798 :type 'boolean)
2800 (defcustom org-read-date-display-live t
2801 "Non-nil means display current interpretation of date prompt live.
2802 This display will be in an overlay, in the minibuffer."
2803 :group 'org-time
2804 :type 'boolean)
2806 (defcustom org-read-date-popup-calendar t
2807 "Non-nil means pop up a calendar when prompting for a date.
2808 In the calendar, the date can be selected with mouse-1. However, the
2809 minibuffer will also be active, and you can simply enter the date as well.
2810 When nil, only the minibuffer will be available."
2811 :group 'org-time
2812 :type 'boolean)
2813 (if (fboundp 'defvaralias)
2814 (defvaralias 'org-popup-calendar-for-date-prompt
2815 'org-read-date-popup-calendar))
2817 (defcustom org-read-date-minibuffer-setup-hook nil
2818 "Hook to be used to set up keys for the date/time interface.
2819 Add key definitions to `minibuffer-local-map', which will be a temporary
2820 copy."
2821 :group 'org-time
2822 :type 'hook)
2824 (defcustom org-extend-today-until 0
2825 "The hour when your day really ends. Must be an integer.
2826 This has influence for the following applications:
2827 - When switching the agenda to \"today\". It it is still earlier than
2828 the time given here, the day recognized as TODAY is actually yesterday.
2829 - When a date is read from the user and it is still before the time given
2830 here, the current date and time will be assumed to be yesterday, 23:59.
2831 Also, timestamps inserted in capture templates follow this rule.
2833 IMPORTANT: This is a feature whose implementation is and likely will
2834 remain incomplete. Really, it is only here because past midnight seems to
2835 be the favorite working time of John Wiegley :-)"
2836 :group 'org-time
2837 :type 'integer)
2839 (defcustom org-use-effective-time nil
2840 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2841 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2842 \"effective time\" of any timestamps between midnight and 8am will be
2843 23:59 of the previous day."
2844 :group 'org-time
2845 :version "24.1"
2846 :type 'boolean)
2848 (defcustom org-use-last-clock-out-time-as-effective-time nil
2849 "When non-nil, use the last clock out time for `org-todo'.
2850 Note that this option has precedence over the combined use of
2851 `org-use-effective-time' and `org-extend-today-until'."
2852 :group 'org-time
2853 ;; :version "24.3"
2854 :type 'boolean)
2856 (defcustom org-edit-timestamp-down-means-later nil
2857 "Non-nil means S-down will increase the time in a time stamp.
2858 When nil, S-up will increase."
2859 :group 'org-time
2860 :type 'boolean)
2862 (defcustom org-calendar-follow-timestamp-change t
2863 "Non-nil means make the calendar window follow timestamp changes.
2864 When a timestamp is modified and the calendar window is visible, it will be
2865 moved to the new date."
2866 :group 'org-time
2867 :type 'boolean)
2869 (defgroup org-tags nil
2870 "Options concerning tags in Org-mode."
2871 :tag "Org Tags"
2872 :group 'org)
2874 (defcustom org-tag-alist nil
2875 "List of tags allowed in Org-mode files.
2876 When this list is nil, Org-mode will base TAG input on what is already in the
2877 buffer.
2878 The value of this variable is an alist, the car of each entry must be a
2879 keyword as a string, the cdr may be a character that is used to select
2880 that tag through the fast-tag-selection interface.
2881 See the manual for details."
2882 :group 'org-tags
2883 :type '(repeat
2884 (choice
2885 (cons (string :tag "Tag name")
2886 (character :tag "Access char"))
2887 (list :tag "Start radio group"
2888 (const :startgroup)
2889 (option (string :tag "Group description")))
2890 (list :tag "End radio group"
2891 (const :endgroup)
2892 (option (string :tag "Group description")))
2893 (const :tag "New line" (:newline)))))
2895 (defcustom org-tag-persistent-alist nil
2896 "List of tags that will always appear in all Org-mode files.
2897 This is in addition to any in buffer settings or customizations
2898 of `org-tag-alist'.
2899 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2900 The value of this variable is an alist, the car of each entry must be a
2901 keyword as a string, the cdr may be a character that is used to select
2902 that tag through the fast-tag-selection interface.
2903 See the manual for details.
2904 To disable these tags on a per-file basis, insert anywhere in the file:
2905 #+STARTUP: noptag"
2906 :group 'org-tags
2907 :type '(repeat
2908 (choice
2909 (cons (string :tag "Tag name")
2910 (character :tag "Access char"))
2911 (const :tag "Start radio group" (:startgroup))
2912 (const :tag "End radio group" (:endgroup))
2913 (const :tag "New line" (:newline)))))
2915 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2916 "If non-nil, always offer completion for all tags of all agenda files.
2917 Instead of customizing this variable directly, you might want to
2918 set it locally for capture buffers, because there no list of
2919 tags in that file can be created dynamically (there are none).
2921 (add-hook 'org-capture-mode-hook
2922 (lambda ()
2923 (set (make-local-variable
2924 'org-complete-tags-always-offer-all-agenda-tags)
2925 t)))"
2926 :group 'org-tags
2927 :version "24.1"
2928 :type 'boolean)
2930 (defvar org-file-tags nil
2931 "List of tags that can be inherited by all entries in the file.
2932 The tags will be inherited if the variable `org-use-tag-inheritance'
2933 says they should be.
2934 This variable is populated from #+FILETAGS lines.")
2936 (defcustom org-use-fast-tag-selection 'auto
2937 "Non-nil means use fast tag selection scheme.
2938 This is a special interface to select and deselect tags with single keys.
2939 When nil, fast selection is never used.
2940 When the symbol `auto', fast selection is used if and only if selection
2941 characters for tags have been configured, either through the variable
2942 `org-tag-alist' or through a #+TAGS line in the buffer.
2943 When t, fast selection is always used and selection keys are assigned
2944 automatically if necessary."
2945 :group 'org-tags
2946 :type '(choice
2947 (const :tag "Always" t)
2948 (const :tag "Never" nil)
2949 (const :tag "When selection characters are configured" 'auto)))
2951 (defcustom org-fast-tag-selection-single-key nil
2952 "Non-nil means fast tag selection exits after first change.
2953 When nil, you have to press RET to exit it.
2954 During fast tag selection, you can toggle this flag with `C-c'.
2955 This variable can also have the value `expert'. In this case, the window
2956 displaying the tags menu is not even shown, until you press C-c again."
2957 :group 'org-tags
2958 :type '(choice
2959 (const :tag "No" nil)
2960 (const :tag "Yes" t)
2961 (const :tag "Expert" expert)))
2963 (defvar org-fast-tag-selection-include-todo nil
2964 "Non-nil means fast tags selection interface will also offer TODO states.
2965 This is an undocumented feature, you should not rely on it.")
2967 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2968 "The column to which tags should be indented in a headline.
2969 If this number is positive, it specifies the column. If it is negative,
2970 it means that the tags should be flushright to that column. For example,
2971 -80 works well for a normal 80 character screen.
2972 When 0, place tags directly after headline text, with only one space in
2973 between."
2974 :group 'org-tags
2975 :type 'integer)
2977 (defcustom org-auto-align-tags t
2978 "Non-nil keeps tags aligned when modifying headlines.
2979 Some operations (i.e. demoting) change the length of a headline and
2980 therefore shift the tags around. With this option turned on, after
2981 each such operation the tags are again aligned to `org-tags-column'."
2982 :group 'org-tags
2983 :type 'boolean)
2985 (defcustom org-use-tag-inheritance t
2986 "Non-nil means tags in levels apply also for sublevels.
2987 When nil, only the tags directly given in a specific line apply there.
2988 This may also be a list of tags that should be inherited, or a regexp that
2989 matches tags that should be inherited. Additional control is possible
2990 with the variable `org-tags-exclude-from-inheritance' which gives an
2991 explicit list of tags to be excluded from inheritance., even if the value of
2992 `org-use-tag-inheritance' would select it for inheritance.
2994 If this option is t, a match early-on in a tree can lead to a large
2995 number of matches in the subtree when constructing the agenda or creating
2996 a sparse tree. If you only want to see the first match in a tree during
2997 a search, check out the variable `org-tags-match-list-sublevels'."
2998 :group 'org-tags
2999 :type '(choice
3000 (const :tag "Not" nil)
3001 (const :tag "Always" t)
3002 (repeat :tag "Specific tags" (string :tag "Tag"))
3003 (regexp :tag "Tags matched by regexp")))
3005 (defcustom org-tags-exclude-from-inheritance nil
3006 "List of tags that should never be inherited.
3007 This is a way to exclude a few tags from inheritance. For way to do
3008 the opposite, to actively allow inheritance for selected tags,
3009 see the variable `org-use-tag-inheritance'."
3010 :group 'org-tags
3011 :type '(repeat (string :tag "Tag")))
3013 (defun org-tag-inherit-p (tag)
3014 "Check if TAG is one that should be inherited."
3015 (cond
3016 ((member tag org-tags-exclude-from-inheritance) nil)
3017 ((eq org-use-tag-inheritance t) t)
3018 ((not org-use-tag-inheritance) nil)
3019 ((stringp org-use-tag-inheritance)
3020 (string-match org-use-tag-inheritance tag))
3021 ((listp org-use-tag-inheritance)
3022 (member tag org-use-tag-inheritance))
3023 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3025 (defcustom org-tags-match-list-sublevels t
3026 "Non-nil means list also sublevels of headlines matching a search.
3027 This variable applies to tags/property searches, and also to stuck
3028 projects because this search is based on a tags match as well.
3030 When set to the symbol `indented', sublevels are indented with
3031 leading dots.
3033 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3034 the sublevels of a headline matching a tag search often also match
3035 the same search. Listing all of them can create very long lists.
3036 Setting this variable to nil causes subtrees of a match to be skipped.
3038 This variable is semi-obsolete and probably should always be true. It
3039 is better to limit inheritance to certain tags using the variables
3040 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3041 :group 'org-tags
3042 :type '(choice
3043 (const :tag "No, don't list them" nil)
3044 (const :tag "Yes, do list them" t)
3045 (const :tag "List them, indented with leading dots" indented)))
3047 (defcustom org-tags-sort-function nil
3048 "When set, tags are sorted using this function as a comparator."
3049 :group 'org-tags
3050 :type '(choice
3051 (const :tag "No sorting" nil)
3052 (const :tag "Alphabetical" string<)
3053 (const :tag "Reverse alphabetical" string>)
3054 (function :tag "Custom function" nil)))
3056 (defvar org-tags-history nil
3057 "History of minibuffer reads for tags.")
3058 (defvar org-last-tags-completion-table nil
3059 "The last used completion table for tags.")
3060 (defvar org-after-tags-change-hook nil
3061 "Hook that is run after the tags in a line have changed.")
3063 (defgroup org-properties nil
3064 "Options concerning properties in Org-mode."
3065 :tag "Org Properties"
3066 :group 'org)
3068 (defcustom org-property-format "%-10s %s"
3069 "How property key/value pairs should be formatted by `indent-line'.
3070 When `indent-line' hits a property definition, it will format the line
3071 according to this format, mainly to make sure that the values are
3072 lined-up with respect to each other."
3073 :group 'org-properties
3074 :type 'string)
3076 (defcustom org-properties-postprocess-alist nil
3077 "Alist of properties and functions to adjust inserted values.
3078 Elements of this alist must be of the form
3080 ([string] [function])
3082 where [string] must be a property name and [function] must be a
3083 lambda expression: this lambda expression must take one argument,
3084 the value to adjust, and return the new value as a string.
3086 For example, this element will allow the property \"Remaining\"
3087 to be updated wrt the relation between the \"Effort\" property
3088 and the clock summary:
3090 ((\"Remaining\" (lambda(value)
3091 (let ((clocksum (org-clock-sum-current-item))
3092 (effort (org-duration-string-to-minutes
3093 (org-entry-get (point) \"Effort\"))))
3094 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3095 :group 'org-properties
3096 :version "24.1"
3097 :type '(alist :key-type (string :tag "Property")
3098 :value-type (function :tag "Function")))
3100 (defcustom org-use-property-inheritance nil
3101 "Non-nil means properties apply also for sublevels.
3103 This setting is chiefly used during property searches. Turning it on can
3104 cause significant overhead when doing a search, which is why it is not
3105 on by default.
3107 When nil, only the properties directly given in the current entry count.
3108 When t, every property is inherited. The value may also be a list of
3109 properties that should have inheritance, or a regular expression matching
3110 properties that should be inherited.
3112 However, note that some special properties use inheritance under special
3113 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3114 and the properties ending in \"_ALL\" when they are used as descriptor
3115 for valid values of a property.
3117 Note for programmers:
3118 When querying an entry with `org-entry-get', you can control if inheritance
3119 should be used. By default, `org-entry-get' looks only at the local
3120 properties. You can request inheritance by setting the inherit argument
3121 to t (to force inheritance) or to `selective' (to respect the setting
3122 in this variable)."
3123 :group 'org-properties
3124 :type '(choice
3125 (const :tag "Not" nil)
3126 (const :tag "Always" t)
3127 (repeat :tag "Specific properties" (string :tag "Property"))
3128 (regexp :tag "Properties matched by regexp")))
3130 (defun org-property-inherit-p (property)
3131 "Check if PROPERTY is one that should be inherited."
3132 (cond
3133 ((eq org-use-property-inheritance t) t)
3134 ((not org-use-property-inheritance) nil)
3135 ((stringp org-use-property-inheritance)
3136 (string-match org-use-property-inheritance property))
3137 ((listp org-use-property-inheritance)
3138 (member property org-use-property-inheritance))
3139 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3141 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3142 "The default column format, if no other format has been defined.
3143 This variable can be set on the per-file basis by inserting a line
3145 #+COLUMNS: %25ITEM ....."
3146 :group 'org-properties
3147 :type 'string)
3149 (defcustom org-columns-ellipses ".."
3150 "The ellipses to be used when a field in column view is truncated.
3151 When this is the empty string, as many characters as possible are shown,
3152 but then there will be no visual indication that the field has been truncated.
3153 When this is a string of length N, the last N characters of a truncated
3154 field are replaced by this string. If the column is narrower than the
3155 ellipses string, only part of the ellipses string will be shown."
3156 :group 'org-properties
3157 :type 'string)
3159 (defcustom org-columns-modify-value-for-display-function nil
3160 "Function that modifies values for display in column view.
3161 For example, it can be used to cut out a certain part from a time stamp.
3162 The function must take 2 arguments:
3164 column-title The title of the column (*not* the property name)
3165 value The value that should be modified.
3167 The function should return the value that should be displayed,
3168 or nil if the normal value should be used."
3169 :group 'org-properties
3170 :type 'function)
3172 (defcustom org-effort-property "Effort"
3173 "The property that is being used to keep track of effort estimates.
3174 Effort estimates given in this property need to have the format H:MM."
3175 :group 'org-properties
3176 :group 'org-progress
3177 :type '(string :tag "Property"))
3179 (defconst org-global-properties-fixed
3180 '(("VISIBILITY_ALL" . "folded children content all")
3181 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3182 "List of property/value pairs that can be inherited by any entry.
3184 These are fixed values, for the preset properties. The user variable
3185 that can be used to add to this list is `org-global-properties'.
3187 The entries in this list are cons cells where the car is a property
3188 name and cdr is a string with the value. If the value represents
3189 multiple items like an \"_ALL\" property, separate the items by
3190 spaces.")
3192 (defcustom org-global-properties nil
3193 "List of property/value pairs that can be inherited by any entry.
3195 This list will be combined with the constant `org-global-properties-fixed'.
3197 The entries in this list are cons cells where the car is a property
3198 name and cdr is a string with the value.
3200 You can set buffer-local values for the same purpose in the variable
3201 `org-file-properties' this by adding lines like
3203 #+PROPERTY: NAME VALUE"
3204 :group 'org-properties
3205 :type '(repeat
3206 (cons (string :tag "Property")
3207 (string :tag "Value"))))
3209 (defvar org-file-properties nil
3210 "List of property/value pairs that can be inherited by any entry.
3211 Valid for the current buffer.
3212 This variable is populated from #+PROPERTY lines.")
3213 (make-variable-buffer-local 'org-file-properties)
3215 (defgroup org-agenda nil
3216 "Options concerning agenda views in Org-mode."
3217 :tag "Org Agenda"
3218 :group 'org)
3220 (defvar org-category nil
3221 "Variable used by org files to set a category for agenda display.
3222 Such files should use a file variable to set it, for example
3224 # -*- mode: org; org-category: \"ELisp\"
3226 or contain a special line
3228 #+CATEGORY: ELisp
3230 If the file does not specify a category, then file's base name
3231 is used instead.")
3232 (make-variable-buffer-local 'org-category)
3233 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3235 (defcustom org-agenda-files nil
3236 "The files to be used for agenda display.
3237 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3238 \\[org-remove-file]. You can also use customize to edit the list.
3240 If an entry is a directory, all files in that directory that are matched by
3241 `org-agenda-file-regexp' will be part of the file list.
3243 If the value of the variable is not a list but a single file name, then
3244 the list of agenda files is actually stored and maintained in that file, one
3245 agenda file per line. In this file paths can be given relative to
3246 `org-directory'. Tilde expansion and environment variable substitution
3247 are also made."
3248 :group 'org-agenda
3249 :type '(choice
3250 (repeat :tag "List of files and directories" file)
3251 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3253 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3254 "Regular expression to match files for `org-agenda-files'.
3255 If any element in the list in that variable contains a directory instead
3256 of a normal file, all files in that directory that are matched by this
3257 regular expression will be included."
3258 :group 'org-agenda
3259 :type 'regexp)
3261 (defcustom org-agenda-text-search-extra-files nil
3262 "List of extra files to be searched by text search commands.
3263 These files will be search in addition to the agenda files by the
3264 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3265 Note that these files will only be searched for text search commands,
3266 not for the other agenda views like todo lists, tag searches or the weekly
3267 agenda. This variable is intended to list notes and possibly archive files
3268 that should also be searched by these two commands.
3269 In fact, if the first element in the list is the symbol `agenda-archives',
3270 than all archive files of all agenda files will be added to the search
3271 scope."
3272 :group 'org-agenda
3273 :type '(set :greedy t
3274 (const :tag "Agenda Archives" agenda-archives)
3275 (repeat :inline t (file))))
3277 (if (fboundp 'defvaralias)
3278 (defvaralias 'org-agenda-multi-occur-extra-files
3279 'org-agenda-text-search-extra-files))
3281 (defcustom org-agenda-skip-unavailable-files nil
3282 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3283 A nil value means to remove them, after a query, from the list."
3284 :group 'org-agenda
3285 :type 'boolean)
3287 (defcustom org-calendar-to-agenda-key [?c]
3288 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3289 The command `org-calendar-goto-agenda' will be bound to this key. The
3290 default is the character `c' because then `c' can be used to switch back and
3291 forth between agenda and calendar."
3292 :group 'org-agenda
3293 :type 'sexp)
3295 (defcustom org-calendar-insert-diary-entry-key [?i]
3296 "The key to be installed in `calendar-mode-map' for adding diary entries.
3297 This option is irrelevant until `org-agenda-diary-file' has been configured
3298 to point to an Org-mode file. When that is the case, the command
3299 `org-agenda-diary-entry' will be bound to the key given here, by default
3300 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3301 if you want to continue doing this, you need to change this to a different
3302 key."
3303 :group 'org-agenda
3304 :type 'sexp)
3306 (defcustom org-agenda-diary-file 'diary-file
3307 "File to which to add new entries with the `i' key in agenda and calendar.
3308 When this is the symbol `diary-file', the functionality in the Emacs
3309 calendar will be used to add entries to the `diary-file'. But when this
3310 points to a file, `org-agenda-diary-entry' will be used instead."
3311 :group 'org-agenda
3312 :type '(choice
3313 (const :tag "The standard Emacs diary file" diary-file)
3314 (file :tag "Special Org file diary entries")))
3316 (eval-after-load "calendar"
3317 '(progn
3318 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3319 'org-calendar-goto-agenda)
3320 (add-hook 'calendar-mode-hook
3321 (lambda ()
3322 (unless (eq org-agenda-diary-file 'diary-file)
3323 (define-key calendar-mode-map
3324 org-calendar-insert-diary-entry-key
3325 'org-agenda-diary-entry))))))
3327 (defgroup org-latex nil
3328 "Options for embedding LaTeX code into Org-mode."
3329 :tag "Org LaTeX"
3330 :group 'org)
3332 (defcustom org-format-latex-options
3333 '(:foreground default :background default :scale 1.0
3334 :html-foreground "Black" :html-background "Transparent"
3335 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3336 "Options for creating images from LaTeX fragments.
3337 This is a property list with the following properties:
3338 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3339 `default' means use the foreground of the default face.
3340 `auto' means use the foreground from the text face.
3341 :background the background color, or \"Transparent\".
3342 `default' means use the background of the default face.
3343 `auto' means use the background from the text face.
3344 :scale a scaling factor for the size of the images, to get more pixels
3345 :html-foreground, :html-background, :html-scale
3346 the same numbers for HTML export.
3347 :matchers a list indicating which matchers should be used to
3348 find LaTeX fragments. Valid members of this list are:
3349 \"begin\" find environments
3350 \"$1\" find single characters surrounded by $.$
3351 \"$\" find math expressions surrounded by $...$
3352 \"$$\" find math expressions surrounded by $$....$$
3353 \"\\(\" find math expressions surrounded by \\(...\\)
3354 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3355 :group 'org-latex
3356 :type 'plist)
3358 (defcustom org-format-latex-signal-error t
3359 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3360 When nil, just push out a message."
3361 :group 'org-latex
3362 :version "24.1"
3363 :type 'boolean)
3365 (defcustom org-latex-to-mathml-jar-file nil
3366 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3367 Use this to specify additional executable file say a jar file.
3369 When using MathToWeb as the converter, specify the full-path to
3370 your mathtoweb.jar file."
3371 :group 'org-latex
3372 :version "24.1"
3373 :type '(choice
3374 (const :tag "None" nil)
3375 (file :tag "JAR file" :must-match t)))
3377 (defcustom org-latex-to-mathml-convert-command nil
3378 "Command to convert LaTeX fragments to MathML.
3379 Replace format-specifiers in the command as noted below and use
3380 `shell-command' to convert LaTeX to MathML.
3381 %j: Executable file in fully expanded form as specified by
3382 `org-latex-to-mathml-jar-file'.
3383 %I: Input LaTeX file in fully expanded form
3384 %o: Output MathML file
3385 This command is used by `org-create-math-formula'.
3387 When using MathToWeb as the converter, set this to
3388 \"java -jar %j -unicode -force -df %o %I\"."
3389 :group 'org-latex
3390 :version "24.1"
3391 :type '(choice
3392 (const :tag "None" nil)
3393 (string :tag "\nShell command")))
3395 (defcustom org-latex-create-formula-image-program 'dvipng
3396 "Program to convert LaTeX fragments with.
3398 dvipng Process the LaTeX fragments to dvi file, then convert
3399 dvi files to png files using dvipng.
3400 This will also include processing of non-math environments.
3401 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3402 to convert pdf files to png files"
3403 :group 'org-latex
3404 :version "24.1"
3405 :type '(choice
3406 (const :tag "dvipng" dvipng)
3407 (const :tag "imagemagick" imagemagick)))
3409 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3410 "Path to store latex preview images. A relative path here creates many
3411 directories relative to the processed org files paths. An absolute path
3412 puts all preview images at the same place."
3413 :group 'org-latex
3414 :version "24.3"
3415 :type 'string)
3417 (defun org-format-latex-mathml-available-p ()
3418 "Return t if `org-latex-to-mathml-convert-command' is usable."
3419 (save-match-data
3420 (when (and (boundp 'org-latex-to-mathml-convert-command)
3421 org-latex-to-mathml-convert-command)
3422 (let ((executable (car (split-string
3423 org-latex-to-mathml-convert-command))))
3424 (when (executable-find executable)
3425 (if (string-match
3426 "%j" org-latex-to-mathml-convert-command)
3427 (file-readable-p org-latex-to-mathml-jar-file)
3428 t))))))
3430 (defcustom org-format-latex-header "\\documentclass{article}
3431 \\usepackage[usenames]{color}
3432 \\usepackage{amsmath}
3433 \\usepackage[mathscr]{eucal}
3434 \\pagestyle{empty} % do not remove
3435 \[PACKAGES]
3436 \[DEFAULT-PACKAGES]
3437 % The settings below are copied from fullpage.sty
3438 \\setlength{\\textwidth}{\\paperwidth}
3439 \\addtolength{\\textwidth}{-3cm}
3440 \\setlength{\\oddsidemargin}{1.5cm}
3441 \\addtolength{\\oddsidemargin}{-2.54cm}
3442 \\setlength{\\evensidemargin}{\\oddsidemargin}
3443 \\setlength{\\textheight}{\\paperheight}
3444 \\addtolength{\\textheight}{-\\headheight}
3445 \\addtolength{\\textheight}{-\\headsep}
3446 \\addtolength{\\textheight}{-\\footskip}
3447 \\addtolength{\\textheight}{-3cm}
3448 \\setlength{\\topmargin}{1.5cm}
3449 \\addtolength{\\topmargin}{-2.54cm}"
3450 "The document header used for processing LaTeX fragments.
3451 It is imperative that this header make sure that no page number
3452 appears on the page. The package defined in the variables
3453 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3454 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3455 will be appended."
3456 :group 'org-latex
3457 :type 'string)
3459 (defvar org-format-latex-header-extra nil)
3461 (defun org-set-packages-alist (var val)
3462 "Set the packages alist and make sure it has 3 elements per entry."
3463 (set var (mapcar (lambda (x)
3464 (if (and (consp x) (= (length x) 2))
3465 (list (car x) (nth 1 x) t)
3467 val)))
3469 (defun org-get-packages-alist (var)
3471 "Get the packages alist and make sure it has 3 elements per entry."
3472 (mapcar (lambda (x)
3473 (if (and (consp x) (= (length x) 2))
3474 (list (car x) (nth 1 x) t)
3476 (default-value var)))
3478 ;; The following variables are defined here because is it also used
3479 ;; when formatting latex fragments. Originally it was part of the
3480 ;; LaTeX exporter, which is why the name includes "export".
3481 (defcustom org-export-latex-default-packages-alist
3482 '(("AUTO" "inputenc" t)
3483 ("T1" "fontenc" t)
3484 ("" "fixltx2e" nil)
3485 ("" "graphicx" t)
3486 ("" "longtable" nil)
3487 ("" "float" nil)
3488 ("" "wrapfig" nil)
3489 ("" "soul" t)
3490 ("" "textcomp" t)
3491 ("" "marvosym" t)
3492 ("" "wasysym" t)
3493 ("" "latexsym" t)
3494 ("" "amssymb" t)
3495 ("" "hyperref" nil)
3496 "\\tolerance=1000"
3498 "Alist of default packages to be inserted in the header.
3499 Change this only if one of the packages here causes an incompatibility
3500 with another package you are using.
3501 The packages in this list are needed by one part or another of Org-mode
3502 to function properly.
3504 - inputenc, fontenc: for basic font and character selection
3505 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3506 for interpreting the entities in `org-entities'. You can skip some of these
3507 packages if you don't use any of the symbols in it.
3508 - graphicx: for including images
3509 - float, wrapfig: for figure placement
3510 - longtable: for long tables
3511 - hyperref: for cross references
3513 Therefore you should not modify this variable unless you know what you
3514 are doing. The one reason to change it anyway is that you might be loading
3515 some other package that conflicts with one of the default packages.
3516 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3517 If SNIPPET-FLAG is t, the package also needs to be included when
3518 compiling LaTeX snippets into images for inclusion into HTML."
3519 :group 'org-export-latex
3520 :set 'org-set-packages-alist
3521 :get 'org-get-packages-alist
3522 :version "24.1"
3523 :type '(repeat
3524 (choice
3525 (list :tag "options/package pair"
3526 (string :tag "options")
3527 (string :tag "package")
3528 (boolean :tag "Snippet"))
3529 (string :tag "A line of LaTeX"))))
3531 (defcustom org-export-latex-packages-alist nil
3532 "Alist of packages to be inserted in every LaTeX header.
3533 These will be inserted after `org-export-latex-default-packages-alist'.
3534 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3535 SNIPPET-FLAG, when t, indicates that this package is also needed when
3536 turning LaTeX snippets into images for inclusion into HTML.
3537 Make sure that you only list packages here which:
3538 - you want in every file
3539 - do not conflict with the default packages in
3540 `org-export-latex-default-packages-alist'
3541 - do not conflict with the setup in `org-format-latex-header'."
3542 :group 'org-export-latex
3543 :set 'org-set-packages-alist
3544 :get 'org-get-packages-alist
3545 :type '(repeat
3546 (choice
3547 (list :tag "options/package pair"
3548 (string :tag "options")
3549 (string :tag "package")
3550 (boolean :tag "Snippet"))
3551 (string :tag "A line of LaTeX"))))
3554 (defgroup org-appearance nil
3555 "Settings for Org-mode appearance."
3556 :tag "Org Appearance"
3557 :group 'org)
3559 (defcustom org-level-color-stars-only nil
3560 "Non-nil means fontify only the stars in each headline.
3561 When nil, the entire headline is fontified.
3562 Changing it requires restart of `font-lock-mode' to become effective
3563 also in regions already fontified."
3564 :group 'org-appearance
3565 :type 'boolean)
3567 (defcustom org-hide-leading-stars nil
3568 "Non-nil means hide the first N-1 stars in a headline.
3569 This works by using the face `org-hide' for these stars. This
3570 face is white for a light background, and black for a dark
3571 background. You may have to customize the face `org-hide' to
3572 make this work.
3573 Changing it requires restart of `font-lock-mode' to become effective
3574 also in regions already fontified.
3575 You may also set this on a per-file basis by adding one of the following
3576 lines to the buffer:
3578 #+STARTUP: hidestars
3579 #+STARTUP: showstars"
3580 :group 'org-appearance
3581 :type 'boolean)
3583 (defcustom org-hidden-keywords nil
3584 "List of symbols corresponding to keywords to be hidden the org buffer.
3585 For example, a value '(title) for this list will make the document's title
3586 appear in the buffer without the initial #+TITLE: keyword."
3587 :group 'org-appearance
3588 :version "24.1"
3589 :type '(set (const :tag "#+AUTHOR" author)
3590 (const :tag "#+DATE" date)
3591 (const :tag "#+EMAIL" email)
3592 (const :tag "#+TITLE" title)))
3594 (defcustom org-custom-properties nil
3595 "List of properties (as strings) with a special meaning.
3596 The default use of these custom properties is to let the user
3597 hide them with `org-toggle-custom-properties-visibility'."
3598 :group 'org-properties
3599 :group 'org-appearance
3600 :version "24.3"
3601 :type '(repeat (string :tag "Property Name")))
3603 (defcustom org-fontify-done-headline nil
3604 "Non-nil means change the face of a headline if it is marked DONE.
3605 Normally, only the TODO/DONE keyword indicates the state of a headline.
3606 When this is non-nil, the headline after the keyword is set to the
3607 `org-headline-done' as an additional indication."
3608 :group 'org-appearance
3609 :type 'boolean)
3611 (defcustom org-fontify-emphasized-text t
3612 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3613 Changing this variable requires a restart of Emacs to take effect."
3614 :group 'org-appearance
3615 :type 'boolean)
3617 (defcustom org-fontify-whole-heading-line nil
3618 "Non-nil means fontify the whole line for headings.
3619 This is useful when setting a background color for the
3620 org-level-* faces."
3621 :group 'org-appearance
3622 :type 'boolean)
3624 (defcustom org-highlight-latex-fragments-and-specials nil
3625 "Non-nil means fontify what is treated specially by the exporters."
3626 :group 'org-appearance
3627 :type 'boolean)
3629 (defcustom org-hide-emphasis-markers nil
3630 "Non-nil mean font-lock should hide the emphasis marker characters."
3631 :group 'org-appearance
3632 :type 'boolean)
3634 (defcustom org-pretty-entities nil
3635 "Non-nil means show entities as UTF8 characters.
3636 When nil, the \\name form remains in the buffer."
3637 :group 'org-appearance
3638 :version "24.1"
3639 :type 'boolean)
3641 (defcustom org-pretty-entities-include-sub-superscripts t
3642 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3643 :group 'org-appearance
3644 :version "24.1"
3645 :type 'boolean)
3647 (defvar org-emph-re nil
3648 "Regular expression for matching emphasis.
3649 After a match, the match groups contain these elements:
3650 0 The match of the full regular expression, including the characters
3651 before and after the proper match
3652 1 The character before the proper match, or empty at beginning of line
3653 2 The proper match, including the leading and trailing markers
3654 3 The leading marker like * or /, indicating the type of highlighting
3655 4 The text between the emphasis markers, not including the markers
3656 5 The character after the match, empty at the end of a line")
3657 (defvar org-verbatim-re nil
3658 "Regular expression for matching verbatim text.")
3659 (defvar org-emphasis-regexp-components) ; defined just below
3660 (defvar org-emphasis-alist) ; defined just below
3661 (defun org-set-emph-re (var val)
3662 "Set variable and compute the emphasis regular expression."
3663 (set var val)
3664 (when (and (boundp 'org-emphasis-alist)
3665 (boundp 'org-emphasis-regexp-components)
3666 org-emphasis-alist org-emphasis-regexp-components)
3667 (let* ((e org-emphasis-regexp-components)
3668 (pre (car e))
3669 (post (nth 1 e))
3670 (border (nth 2 e))
3671 (body (nth 3 e))
3672 (nl (nth 4 e))
3673 (body1 (concat body "*?"))
3674 (markers (mapconcat 'car org-emphasis-alist ""))
3675 (vmarkers (mapconcat
3676 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3677 org-emphasis-alist "")))
3678 ;; make sure special characters appear at the right position in the class
3679 (if (string-match "\\^" markers)
3680 (setq markers (concat (replace-match "" t t markers) "^")))
3681 (if (string-match "-" markers)
3682 (setq markers (concat (replace-match "" t t markers) "-")))
3683 (if (string-match "\\^" vmarkers)
3684 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3685 (if (string-match "-" vmarkers)
3686 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3687 (if (> nl 0)
3688 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3689 (int-to-string nl) "\\}")))
3690 ;; Make the regexp
3691 (setq org-emph-re
3692 (concat "\\([" pre "]\\|^\\)"
3693 "\\("
3694 "\\([" markers "]\\)"
3695 "\\("
3696 "[^" border "]\\|"
3697 "[^" border "]"
3698 body1
3699 "[^" border "]"
3700 "\\)"
3701 "\\3\\)"
3702 "\\([" post "]\\|$\\)"))
3703 (setq org-verbatim-re
3704 (concat "\\([" pre "]\\|^\\)"
3705 "\\("
3706 "\\([" vmarkers "]\\)"
3707 "\\("
3708 "[^" border "]\\|"
3709 "[^" border "]"
3710 body1
3711 "[^" border "]"
3712 "\\)"
3713 "\\3\\)"
3714 "\\([" post "]\\|$\\)")))))
3716 (defcustom org-emphasis-regexp-components
3717 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3718 "Components used to build the regular expression for emphasis.
3719 This is a list with five entries. Terminology: In an emphasis string
3720 like \" *strong word* \", we call the initial space PREMATCH, the final
3721 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3722 and \"trong wor\" is the body. The different components in this variable
3723 specify what is allowed/forbidden in each part:
3725 pre Chars allowed as prematch. Beginning of line will be allowed too.
3726 post Chars allowed as postmatch. End of line will be allowed too.
3727 border The chars *forbidden* as border characters.
3728 body-regexp A regexp like \".\" to match a body character. Don't use
3729 non-shy groups here, and don't allow newline here.
3730 newline The maximum number of newlines allowed in an emphasis exp.
3732 Use customize to modify this, or restart Emacs after changing it."
3733 :group 'org-appearance
3734 :set 'org-set-emph-re
3735 :type '(list
3736 (sexp :tag "Allowed chars in pre ")
3737 (sexp :tag "Allowed chars in post ")
3738 (sexp :tag "Forbidden chars in border ")
3739 (sexp :tag "Regexp for body ")
3740 (integer :tag "number of newlines allowed")
3741 (option (boolean :tag "Please ignore this button"))))
3743 (defcustom org-emphasis-alist
3744 `(("*" bold "<b>" "</b>")
3745 ("/" italic "<i>" "</i>")
3746 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3747 ("=" org-code "<code>" "</code>" verbatim)
3748 ("~" org-verbatim "<code>" "</code>" verbatim)
3749 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3750 "<del>" "</del>")
3752 "Special syntax for emphasized text.
3753 Text starting and ending with a special character will be emphasized, for
3754 example *bold*, _underlined_ and /italic/. This variable sets the marker
3755 characters, the face to be used by font-lock for highlighting in Org-mode
3756 Emacs buffers, and the HTML tags to be used for this.
3757 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3758 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3759 Use customize to modify this, or restart Emacs after changing it."
3760 :group 'org-appearance
3761 :set 'org-set-emph-re
3762 :type '(repeat
3763 (list
3764 (string :tag "Marker character")
3765 (choice
3766 (face :tag "Font-lock-face")
3767 (plist :tag "Face property list"))
3768 (string :tag "HTML start tag")
3769 (string :tag "HTML end tag")
3770 (option (const verbatim)))))
3772 (defvar org-protecting-blocks
3773 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3774 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3775 This is needed for font-lock setup.")
3777 ;;; Miscellaneous options
3779 (defgroup org-completion nil
3780 "Completion in Org-mode."
3781 :tag "Org Completion"
3782 :group 'org)
3784 (defcustom org-completion-use-ido nil
3785 "Non-nil means use ido completion wherever possible.
3786 Note that `ido-mode' must be active for this variable to be relevant.
3787 If you decide to turn this variable on, you might well want to turn off
3788 `org-outline-path-complete-in-steps'.
3789 See also `org-completion-use-iswitchb'."
3790 :group 'org-completion
3791 :type 'boolean)
3793 (defcustom org-completion-use-iswitchb nil
3794 "Non-nil means use iswitchb completion wherever possible.
3795 Note that `iswitchb-mode' must be active for this variable to be relevant.
3796 If you decide to turn this variable on, you might well want to turn off
3797 `org-outline-path-complete-in-steps'.
3798 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3799 :group 'org-completion
3800 :type 'boolean)
3802 (defcustom org-completion-fallback-command 'hippie-expand
3803 "The expansion command called by \\[pcomplete] in normal context.
3804 Normal means, no org-mode-specific context."
3805 :group 'org-completion
3806 :type 'function)
3808 ;;; Functions and variables from their packages
3809 ;; Declared here to avoid compiler warnings
3811 ;; XEmacs only
3812 (defvar outline-mode-menu-heading)
3813 (defvar outline-mode-menu-show)
3814 (defvar outline-mode-menu-hide)
3815 (defvar zmacs-regions) ; XEmacs regions
3817 ;; Emacs only
3818 (defvar mark-active)
3820 ;; Various packages
3821 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3822 (declare-function calendar-forward-day "cal-move" (arg))
3823 (declare-function calendar-goto-date "cal-move" (date))
3824 (declare-function calendar-goto-today "cal-move" ())
3825 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3826 (defvar calc-embedded-close-formula)
3827 (defvar calc-embedded-open-formula)
3828 (declare-function cdlatex-tab "ext:cdlatex" ())
3829 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3830 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3831 (defvar font-lock-unfontify-region-function)
3832 (declare-function iswitchb-read-buffer "iswitchb"
3833 (prompt &optional default require-match start matches-set))
3834 (defvar iswitchb-temp-buflist)
3835 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3836 (defvar org-agenda-tags-todo-honor-ignore-options)
3837 (declare-function org-agenda-skip "org-agenda" ())
3838 (declare-function
3839 org-agenda-format-item "org-agenda"
3840 (extra txt &optional level category tags dotime noprefix remove-re habitp))
3841 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3842 (declare-function org-agenda-change-all-lines "org-agenda"
3843 (newhead hdmarker &optional fixface just-this))
3844 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3845 (declare-function org-agenda-maybe-redo "org-agenda" ())
3846 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3847 (beg end))
3848 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3849 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3850 "org-agenda" (&optional end))
3851 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3852 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3853 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3854 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3855 (declare-function org-indent-mode "org-indent" (&optional arg))
3856 (declare-function parse-time-string "parse-time" (string))
3857 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3858 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3859 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3860 (defvar remember-data-file)
3861 (defvar texmathp-why)
3862 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3863 (declare-function table--at-cell-p "table" (position &optional object at-column))
3865 (defvar w3m-current-url)
3866 (defvar w3m-current-title)
3868 (defvar org-latex-regexps)
3870 ;;; Autoload and prepare some org modules
3872 ;; Some table stuff that needs to be defined here, because it is used
3873 ;; by the functions setting up org-mode or checking for table context.
3875 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3876 "Detect an org-type or table-type table.")
3877 (defconst org-table-line-regexp "^[ \t]*|"
3878 "Detect an org-type table line.")
3879 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3880 "Detect an org-type table line.")
3881 (defconst org-table-hline-regexp "^[ \t]*|-"
3882 "Detect an org-type table hline.")
3883 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3884 "Detect a table-type table hline.")
3885 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3886 "Detect the first line outside a table when searching from within it.
3887 This works for both table types.")
3889 ;; Autoload the functions in org-table.el that are needed by functions here.
3891 (eval-and-compile
3892 (org-autoload "org-table"
3893 '(org-table-begin org-table-blank-field org-table-end)))
3895 ;;;###autoload
3896 (defun turn-on-orgtbl ()
3897 "Unconditionally turn on `orgtbl-mode'."
3898 (require 'org-table)
3899 (orgtbl-mode 1))
3901 (defun org-at-table-p (&optional table-type)
3902 "Return t if the cursor is inside an org-type table.
3903 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3904 (if org-enable-table-editor
3905 (save-excursion
3906 (beginning-of-line 1)
3907 (looking-at (if table-type org-table-any-line-regexp
3908 org-table-line-regexp)))
3909 nil))
3910 (defsubst org-table-p () (org-at-table-p))
3912 (defun org-at-table.el-p ()
3913 "Return t if and only if we are at a table.el table."
3914 (and (org-at-table-p 'any)
3915 (save-excursion
3916 (goto-char (org-table-begin 'any))
3917 (looking-at org-table1-hline-regexp))))
3918 (defun org-table-recognize-table.el ()
3919 "If there is a table.el table nearby, recognize it and move into it."
3920 (if org-table-tab-recognizes-table.el
3921 (if (org-at-table.el-p)
3922 (progn
3923 (beginning-of-line 1)
3924 (if (looking-at org-table-dataline-regexp)
3926 (if (looking-at org-table1-hline-regexp)
3927 (progn
3928 (beginning-of-line 2)
3929 (if (looking-at org-table-any-border-regexp)
3930 (beginning-of-line -1)))))
3931 (if (re-search-forward "|" (org-table-end t) t)
3932 (progn
3933 (require 'table)
3934 (if (table--at-cell-p (point))
3936 (message "recognizing table.el table...")
3937 (table-recognize-table)
3938 (message "recognizing table.el table...done")))
3939 (error "This should not happen"))
3941 nil)
3942 nil))
3944 (defun org-at-table-hline-p ()
3945 "Return t if the cursor is inside a hline in a table."
3946 (if org-enable-table-editor
3947 (save-excursion
3948 (beginning-of-line 1)
3949 (looking-at org-table-hline-regexp))
3950 nil))
3952 (defvar org-table-clean-did-remove-column nil)
3954 (defun org-table-map-tables (function &optional quietly)
3955 "Apply FUNCTION to the start of all tables in the buffer."
3956 (save-excursion
3957 (save-restriction
3958 (widen)
3959 (goto-char (point-min))
3960 (while (re-search-forward org-table-any-line-regexp nil t)
3961 (unless quietly
3962 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3963 (beginning-of-line 1)
3964 (when (and (looking-at org-table-line-regexp)
3965 ;; Exclude tables in src/example/verbatim/clocktable blocks
3966 (not (org-in-block-p '("src" "example"))))
3967 (save-excursion (funcall function))
3968 (or (looking-at org-table-line-regexp)
3969 (forward-char 1)))
3970 (re-search-forward org-table-any-border-regexp nil 1))))
3971 (unless quietly (message "Mapping tables: done")))
3973 ;; Declare and autoload functions from org-exp.el & Co
3975 (declare-function org-default-export-plist "org-exp")
3976 (declare-function org-infile-export-plist "org-exp")
3977 (declare-function org-get-current-options "org-exp")
3979 ;; Declare and autoload functions from org-agenda.el
3981 (eval-and-compile
3982 (org-autoload "org-agenda"
3983 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3985 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
3986 (declare-function org-clock-update-mode-line "org-clock" ())
3987 (declare-function org-resolve-clocks "org-clock"
3988 (&optional also-non-dangling-p prompt last-valid))
3989 (defvar org-clock-start-time)
3990 (defvar org-clock-marker (make-marker)
3991 "Marker recording the last clock-in.")
3992 (defvar org-clock-hd-marker (make-marker)
3993 "Marker recording the last clock-in, but the headline position.")
3994 (defvar org-clock-heading ""
3995 "The heading of the current clock entry.")
3996 (defun org-clock-is-active ()
3997 "Return non-nil if clock is currently running.
3998 The return value is actually the clock marker."
3999 (marker-buffer org-clock-marker))
4001 (eval-and-compile
4002 (org-autoload "org-clock" '(org-clock-remove-overlays
4003 org-clock-update-time-maybe
4004 org-clocktable-shift)))
4006 (defun org-check-running-clock ()
4007 "Check if the current buffer contains the running clock.
4008 If yes, offer to stop it and to save the buffer with the changes."
4009 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4010 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4011 (buffer-name))))
4012 (org-clock-out)
4013 (when (y-or-n-p "Save changed buffer?")
4014 (save-buffer))))
4016 (defun org-clocktable-try-shift (dir n)
4017 "Check if this line starts a clock table, if yes, shift the time block."
4018 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4019 (org-clocktable-shift dir n)))
4021 ;;;###autoload
4022 (defun org-clock-persistence-insinuate ()
4023 "Set up hooks for clock persistence."
4024 (require 'org-clock)
4025 (add-hook 'org-mode-hook 'org-clock-load)
4026 (add-hook 'kill-emacs-hook 'org-clock-save))
4028 ;; Define the variable already here, to make sure we have it.
4029 (defvar org-indent-mode nil
4030 "Non-nil if Org-Indent mode is enabled.
4031 Use the command `org-indent-mode' to change this variable.")
4033 ;; Autoload archiving code
4034 ;; The stuff that is needed for cycling and tags has to be defined here.
4036 (defgroup org-archive nil
4037 "Options concerning archiving in Org-mode."
4038 :tag "Org Archive"
4039 :group 'org-structure)
4041 (defcustom org-archive-location "%s_archive::"
4042 "The location where subtrees should be archived.
4044 The value of this variable is a string, consisting of two parts,
4045 separated by a double-colon. The first part is a filename and
4046 the second part is a headline.
4048 When the filename is omitted, archiving happens in the same file.
4049 %s in the filename will be replaced by the current file
4050 name (without the directory part). Archiving to a different file
4051 is useful to keep archived entries from contributing to the
4052 Org-mode Agenda.
4054 The archived entries will be filed as subtrees of the specified
4055 headline. When the headline is omitted, the subtrees are simply
4056 filed away at the end of the file, as top-level entries. Also in
4057 the heading you can use %s to represent the file name, this can be
4058 useful when using the same archive for a number of different files.
4060 Here are a few examples:
4061 \"%s_archive::\"
4062 If the current file is Projects.org, archive in file
4063 Projects.org_archive, as top-level trees. This is the default.
4065 \"::* Archived Tasks\"
4066 Archive in the current file, under the top-level headline
4067 \"* Archived Tasks\".
4069 \"~/org/archive.org::\"
4070 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4072 \"~/org/archive.org::* From %s\"
4073 Archive in file ~/org/archive.org (absolute path), under headlines
4074 \"From FILENAME\" where file name is the current file name.
4076 \"~/org/datetree.org::datetree/* Finished Tasks\"
4077 The \"datetree/\" string is special, signifying to archive
4078 items to the datetree. Items are placed in either the CLOSED
4079 date of the item, or the current date if there is no CLOSED date.
4080 The heading will be a subentry to the current date. There doesn't
4081 need to be a heading, but there always needs to be a slash after
4082 datetree. For example, to store archived items directly in the
4083 datetree, use \"~/org/datetree.org::datetree/\".
4085 \"basement::** Finished Tasks\"
4086 Archive in file ./basement (relative path), as level 3 trees
4087 below the level 2 heading \"** Finished Tasks\".
4089 You may set this option on a per-file basis by adding to the buffer a
4090 line like
4092 #+ARCHIVE: basement::** Finished Tasks
4094 You may also define it locally for a subtree by setting an ARCHIVE property
4095 in the entry. If such a property is found in an entry, or anywhere up
4096 the hierarchy, it will be used."
4097 :group 'org-archive
4098 :type 'string)
4100 (defcustom org-archive-tag "ARCHIVE"
4101 "The tag that marks a subtree as archived.
4102 An archived subtree does not open during visibility cycling, and does
4103 not contribute to the agenda listings.
4104 After changing this, font-lock must be restarted in the relevant buffers to
4105 get the proper fontification."
4106 :group 'org-archive
4107 :group 'org-keywords
4108 :type 'string)
4110 (defcustom org-agenda-skip-archived-trees t
4111 "Non-nil means the agenda will skip any items located in archived trees.
4112 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4113 variable is no longer recommended, you should leave it at the value t.
4114 Instead, use the key `v' to cycle the archives-mode in the agenda."
4115 :group 'org-archive
4116 :group 'org-agenda-skip
4117 :type 'boolean)
4119 (defcustom org-columns-skip-archived-trees t
4120 "Non-nil means ignore archived trees when creating column view."
4121 :group 'org-archive
4122 :group 'org-properties
4123 :type 'boolean)
4125 (defcustom org-cycle-open-archived-trees nil
4126 "Non-nil means `org-cycle' will open archived trees.
4127 An archived tree is a tree marked with the tag ARCHIVE.
4128 When nil, archived trees will stay folded. You can still open them with
4129 normal outline commands like `show-all', but not with the cycling commands."
4130 :group 'org-archive
4131 :group 'org-cycle
4132 :type 'boolean)
4134 (defcustom org-sparse-tree-open-archived-trees nil
4135 "Non-nil means sparse tree construction shows matches in archived trees.
4136 When nil, matches in these trees are highlighted, but the trees are kept in
4137 collapsed state."
4138 :group 'org-archive
4139 :group 'org-sparse-trees
4140 :type 'boolean)
4142 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4143 "The default date type when building a sparse tree.
4144 When this is nil, a date is a scheduled or a deadline timestamp.
4145 Otherwise, these types are allowed:
4147 all: all timestamps
4148 active: only active timestamps (<...>)
4149 inactive: only inactive timestamps (<...)
4150 scheduled: only scheduled timestamps
4151 deadline: only deadline timestamps"
4152 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4153 (const :tag "All timestamps" all)
4154 (const :tag "Only active timestamps" active)
4155 (const :tag "Only inactive timestamps" inactive)
4156 (const :tag "Only scheduled timestamps" scheduled)
4157 (const :tag "Only deadline timestamps" deadline))
4158 :version "24.3"
4159 :group 'org-sparse-trees)
4161 (defun org-cycle-hide-archived-subtrees (state)
4162 "Re-hide all archived subtrees after a visibility state change."
4163 (when (and (not org-cycle-open-archived-trees)
4164 (not (memq state '(overview folded))))
4165 (save-excursion
4166 (let* ((globalp (memq state '(contents all)))
4167 (beg (if globalp (point-min) (point)))
4168 (end (if globalp (point-max) (org-end-of-subtree t))))
4169 (org-hide-archived-subtrees beg end)
4170 (goto-char beg)
4171 (if (looking-at (concat ".*:" org-archive-tag ":"))
4172 (message "%s" (substitute-command-keys
4173 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4175 (defun org-force-cycle-archived ()
4176 "Cycle subtree even if it is archived."
4177 (interactive)
4178 (setq this-command 'org-cycle)
4179 (let ((org-cycle-open-archived-trees t))
4180 (call-interactively 'org-cycle)))
4182 (defun org-hide-archived-subtrees (beg end)
4183 "Re-hide all archived subtrees after a visibility state change."
4184 (save-excursion
4185 (let* ((re (concat ":" org-archive-tag ":")))
4186 (goto-char beg)
4187 (while (re-search-forward re end t)
4188 (when (org-at-heading-p)
4189 (org-flag-subtree t)
4190 (org-end-of-subtree t))))))
4192 (declare-function outline-end-of-heading "outline" ())
4193 (declare-function outline-flag-region "outline" (from to flag))
4194 (defun org-flag-subtree (flag)
4195 (save-excursion
4196 (org-back-to-heading t)
4197 (outline-end-of-heading)
4198 (outline-flag-region (point)
4199 (progn (org-end-of-subtree t) (point))
4200 flag)))
4202 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4204 (eval-and-compile
4205 (org-autoload "org-archive"
4206 '(org-add-archive-files)))
4208 ;; Autoload Column View Code
4210 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4211 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4212 (declare-function org-columns-compute "org-colview" (property))
4214 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4215 '(org-columns-number-to-string
4216 org-columns-get-format-and-top-level
4217 org-columns-compute
4218 org-columns-remove-overlays))
4220 ;; Autoload ID code
4222 (declare-function org-id-store-link "org-id")
4223 (declare-function org-id-locations-load "org-id")
4224 (declare-function org-id-locations-save "org-id")
4225 (defvar org-id-track-globally)
4226 (org-autoload "org-id"
4227 '(org-id-new
4228 org-id-copy
4229 org-id-get-with-outline-path-completion
4230 org-id-get-with-outline-drilling))
4232 ;;; Variables for pre-computed regular expressions, all buffer local
4234 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4235 "Matches first line of a hidden block.")
4236 (make-variable-buffer-local 'org-drawer-regexp)
4237 (defvar org-todo-regexp nil
4238 "Matches any of the TODO state keywords.")
4239 (make-variable-buffer-local 'org-todo-regexp)
4240 (defvar org-not-done-regexp nil
4241 "Matches any of the TODO state keywords except the last one.")
4242 (make-variable-buffer-local 'org-not-done-regexp)
4243 (defvar org-not-done-heading-regexp nil
4244 "Matches a TODO headline that is not done.")
4245 (make-variable-buffer-local 'org-not-done-regexp)
4246 (defvar org-todo-line-regexp nil
4247 "Matches a headline and puts TODO state into group 2 if present.")
4248 (make-variable-buffer-local 'org-todo-line-regexp)
4249 (defvar org-complex-heading-regexp nil
4250 "Matches a headline and puts everything into groups:
4251 group 1: the stars
4252 group 2: The todo keyword, maybe
4253 group 3: Priority cookie
4254 group 4: True headline
4255 group 5: Tags")
4256 (make-variable-buffer-local 'org-complex-heading-regexp)
4257 (defvar org-complex-heading-regexp-format nil
4258 "Printf format to make regexp to match an exact headline.
4259 This regexp will match the headline of any node which has the
4260 exact headline text that is put into the format, but may have any
4261 TODO state, priority and tags.")
4262 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4263 (defvar org-todo-line-tags-regexp nil
4264 "Matches a headline and puts TODO state into group 2 if present.
4265 Also put tags into group 4 if tags are present.")
4266 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4267 (defvar org-ds-keyword-length 12
4268 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4269 (make-variable-buffer-local 'org-ds-keyword-length)
4270 (defvar org-deadline-regexp nil
4271 "Matches the DEADLINE keyword.")
4272 (make-variable-buffer-local 'org-deadline-regexp)
4273 (defvar org-deadline-time-regexp nil
4274 "Matches the DEADLINE keyword together with a time stamp.")
4275 (make-variable-buffer-local 'org-deadline-time-regexp)
4276 (defvar org-deadline-line-regexp nil
4277 "Matches the DEADLINE keyword and the rest of the line.")
4278 (make-variable-buffer-local 'org-deadline-line-regexp)
4279 (defvar org-scheduled-regexp nil
4280 "Matches the SCHEDULED keyword.")
4281 (make-variable-buffer-local 'org-scheduled-regexp)
4282 (defvar org-scheduled-time-regexp nil
4283 "Matches the SCHEDULED keyword together with a time stamp.")
4284 (make-variable-buffer-local 'org-scheduled-time-regexp)
4285 (defvar org-closed-time-regexp nil
4286 "Matches the CLOSED keyword together with a time stamp.")
4287 (make-variable-buffer-local 'org-closed-time-regexp)
4289 (defvar org-keyword-time-regexp nil
4290 "Matches any of the 4 keywords, together with the time stamp.")
4291 (make-variable-buffer-local 'org-keyword-time-regexp)
4292 (defvar org-keyword-time-not-clock-regexp nil
4293 "Matches any of the 3 keywords, together with the time stamp.")
4294 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4295 (defvar org-maybe-keyword-time-regexp nil
4296 "Matches a timestamp, possibly preceded by a keyword.")
4297 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4298 (defvar org-all-time-keywords nil
4299 "List of time keywords.")
4300 (make-variable-buffer-local 'org-all-time-keywords)
4302 (defconst org-plain-time-of-day-regexp
4303 (concat
4304 "\\(\\<[012]?[0-9]"
4305 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4306 "\\(--?"
4307 "\\(\\<[012]?[0-9]"
4308 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4309 "\\)?")
4310 "Regular expression to match a plain time or time range.
4311 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4312 groups carry important information:
4313 0 the full match
4314 1 the first time, range or not
4315 8 the second time, if it is a range.")
4317 (defconst org-plain-time-extension-regexp
4318 (concat
4319 "\\(\\<[012]?[0-9]"
4320 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4321 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4322 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4323 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4324 groups carry important information:
4325 0 the full match
4326 7 hours of duration
4327 9 minutes of duration")
4329 (defconst org-stamp-time-of-day-regexp
4330 (concat
4331 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4332 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4333 "\\(--?"
4334 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4335 "Regular expression to match a timestamp time or time range.
4336 After a match, the following groups carry important information:
4337 0 the full match
4338 1 date plus weekday, for back referencing to make sure both times are on the same day
4339 2 the first time, range or not
4340 4 the second time, if it is a range.")
4342 (defconst org-startup-options
4343 '(("fold" org-startup-folded t)
4344 ("overview" org-startup-folded t)
4345 ("nofold" org-startup-folded nil)
4346 ("showall" org-startup-folded nil)
4347 ("showeverything" org-startup-folded showeverything)
4348 ("content" org-startup-folded content)
4349 ("indent" org-startup-indented t)
4350 ("noindent" org-startup-indented nil)
4351 ("hidestars" org-hide-leading-stars t)
4352 ("showstars" org-hide-leading-stars nil)
4353 ("odd" org-odd-levels-only t)
4354 ("oddeven" org-odd-levels-only nil)
4355 ("align" org-startup-align-all-tables t)
4356 ("noalign" org-startup-align-all-tables nil)
4357 ("inlineimages" org-startup-with-inline-images t)
4358 ("noinlineimages" org-startup-with-inline-images nil)
4359 ("customtime" org-display-custom-times t)
4360 ("logdone" org-log-done time)
4361 ("lognotedone" org-log-done note)
4362 ("nologdone" org-log-done nil)
4363 ("lognoteclock-out" org-log-note-clock-out t)
4364 ("nolognoteclock-out" org-log-note-clock-out nil)
4365 ("logrepeat" org-log-repeat state)
4366 ("lognoterepeat" org-log-repeat note)
4367 ("nologrepeat" org-log-repeat nil)
4368 ("logreschedule" org-log-reschedule time)
4369 ("lognotereschedule" org-log-reschedule note)
4370 ("nologreschedule" org-log-reschedule nil)
4371 ("logredeadline" org-log-redeadline time)
4372 ("lognoteredeadline" org-log-redeadline note)
4373 ("nologredeadline" org-log-redeadline nil)
4374 ("logrefile" org-log-refile time)
4375 ("lognoterefile" org-log-refile note)
4376 ("nologrefile" org-log-refile nil)
4377 ("fninline" org-footnote-define-inline t)
4378 ("nofninline" org-footnote-define-inline nil)
4379 ("fnlocal" org-footnote-section nil)
4380 ("fnauto" org-footnote-auto-label t)
4381 ("fnprompt" org-footnote-auto-label nil)
4382 ("fnconfirm" org-footnote-auto-label confirm)
4383 ("fnplain" org-footnote-auto-label plain)
4384 ("fnadjust" org-footnote-auto-adjust t)
4385 ("nofnadjust" org-footnote-auto-adjust nil)
4386 ("constcgs" constants-unit-system cgs)
4387 ("constSI" constants-unit-system SI)
4388 ("noptag" org-tag-persistent-alist nil)
4389 ("hideblocks" org-hide-block-startup t)
4390 ("nohideblocks" org-hide-block-startup nil)
4391 ("beamer" org-startup-with-beamer-mode t)
4392 ("entitiespretty" org-pretty-entities t)
4393 ("entitiesplain" org-pretty-entities nil))
4394 "Variable associated with STARTUP options for org-mode.
4395 Each element is a list of three items: the startup options (as written
4396 in the #+STARTUP line), the corresponding variable, and the value to set
4397 this variable to if the option is found. An optional forth element PUSH
4398 means to push this value onto the list in the variable.")
4400 (defun org-update-property-plist (key val props)
4401 "Update PROPS with KEY and VAL."
4402 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4403 (key (if appending (substring key 0 (- (length key) 1)) key))
4404 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4405 (previous (cdr (assoc key props))))
4406 (if appending
4407 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4408 (cons (cons key val) remainder))))
4410 (defconst org-block-regexp
4411 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4412 "Regular expression for hiding blocks.")
4413 (defconst org-heading-keyword-regexp-format
4414 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4415 "Printf format for a regexp matching an headline with some keyword.
4416 This regexp will match the headline of any node which has the
4417 exact keyword that is put into the format. The keyword isn't in
4418 any group by default, but the stars and the body are.")
4419 (defconst org-heading-keyword-maybe-regexp-format
4420 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4421 "Printf format for a regexp matching an headline, possibly with some keyword.
4422 This regexp can match any headline with the specified keyword, or
4423 without a keyword. The keyword isn't in any group by default,
4424 but the stars and the body are.")
4426 (defun org-set-regexps-and-options ()
4427 "Precompute regular expressions for current buffer."
4428 (when (derived-mode-p 'org-mode)
4429 (org-set-local 'org-todo-kwd-alist nil)
4430 (org-set-local 'org-todo-key-alist nil)
4431 (org-set-local 'org-todo-key-trigger nil)
4432 (org-set-local 'org-todo-keywords-1 nil)
4433 (org-set-local 'org-done-keywords nil)
4434 (org-set-local 'org-todo-heads nil)
4435 (org-set-local 'org-todo-sets nil)
4436 (org-set-local 'org-todo-log-states nil)
4437 (org-set-local 'org-file-properties nil)
4438 (org-set-local 'org-file-tags nil)
4439 (let ((re (org-make-options-regexp
4440 '("CATEGORY" "TODO" "COLUMNS"
4441 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4442 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4443 "OPTIONS")
4444 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4445 (splitre "[ \t]+")
4446 (scripts org-use-sub-superscripts)
4447 kwds kws0 kwsa key log value cat arch tags const links hw dws
4448 tail sep kws1 prio props ftags drawers beamer-p
4449 ext-setup-or-nil setup-contents (start 0))
4450 (save-excursion
4451 (save-restriction
4452 (widen)
4453 (goto-char (point-min))
4454 (while (or (and ext-setup-or-nil
4455 (string-match re ext-setup-or-nil start)
4456 (setq start (match-end 0)))
4457 (and (setq ext-setup-or-nil nil start 0)
4458 (re-search-forward re nil t)))
4459 (setq key (upcase (match-string 1 ext-setup-or-nil))
4460 value (org-match-string-no-properties 2 ext-setup-or-nil))
4461 (if (stringp value) (setq value (org-trim value)))
4462 (cond
4463 ((equal key "CATEGORY")
4464 (setq cat value))
4465 ((member key '("SEQ_TODO" "TODO"))
4466 (push (cons 'sequence (org-split-string value splitre)) kwds))
4467 ((equal key "TYP_TODO")
4468 (push (cons 'type (org-split-string value splitre)) kwds))
4469 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4470 ;; general TODO-like setup
4471 (push (cons (intern (downcase (match-string 1 key)))
4472 (org-split-string value splitre)) kwds))
4473 ((equal key "TAGS")
4474 (setq tags (append tags (if tags '("\\n") nil)
4475 (org-split-string value splitre))))
4476 ((equal key "COLUMNS")
4477 (org-set-local 'org-columns-default-format value))
4478 ((equal key "LINK")
4479 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4480 (push (cons (match-string 1 value)
4481 (org-trim (match-string 2 value)))
4482 links)))
4483 ((equal key "PRIORITIES")
4484 (setq prio (org-split-string value " +")))
4485 ((equal key "PROPERTY")
4486 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4487 (setq props (org-update-property-plist (match-string 1 value)
4488 (match-string 2 value)
4489 props))))
4490 ((equal key "FILETAGS")
4491 (when (string-match "\\S-" value)
4492 (setq ftags
4493 (append
4494 ftags
4495 (apply 'append
4496 (mapcar (lambda (x) (org-split-string x ":"))
4497 (org-split-string value)))))))
4498 ((equal key "DRAWERS")
4499 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4500 ((equal key "CONSTANTS")
4501 (setq const (append const (org-split-string value splitre))))
4502 ((equal key "STARTUP")
4503 (let ((opts (org-split-string value splitre))
4504 l var val)
4505 (while (setq l (pop opts))
4506 (when (setq l (assoc l org-startup-options))
4507 (setq var (nth 1 l) val (nth 2 l))
4508 (if (not (nth 3 l))
4509 (set (make-local-variable var) val)
4510 (if (not (listp (symbol-value var)))
4511 (set (make-local-variable var) nil))
4512 (set (make-local-variable var) (symbol-value var))
4513 (add-to-list var val))))))
4514 ((equal key "ARCHIVE")
4515 (setq arch value)
4516 (remove-text-properties 0 (length arch)
4517 '(face t fontified t) arch))
4518 ((equal key "LATEX_CLASS")
4519 (setq beamer-p (equal value "beamer")))
4520 ((equal key "OPTIONS")
4521 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4522 (setq scripts (read (match-string 2 value)))))
4523 ((equal key "SETUPFILE")
4524 (setq setup-contents (org-file-contents
4525 (expand-file-name
4526 (org-remove-double-quotes value))
4527 'noerror))
4528 (if (not ext-setup-or-nil)
4529 (setq ext-setup-or-nil setup-contents start 0)
4530 (setq ext-setup-or-nil
4531 (concat (substring ext-setup-or-nil 0 start)
4532 "\n" setup-contents "\n"
4533 (substring ext-setup-or-nil start)))))))
4534 ;; search for property blocks
4535 (goto-char (point-min))
4536 (while (re-search-forward org-block-regexp nil t)
4537 (when (equal "PROPERTY" (upcase (match-string 1)))
4538 (setq value (replace-regexp-in-string
4539 "[\n\r]" " " (match-string 4)))
4540 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4541 (setq props (org-update-property-plist (match-string 1 value)
4542 (match-string 2 value)
4543 props)))))))
4544 (org-set-local 'org-use-sub-superscripts scripts)
4545 (when cat
4546 (org-set-local 'org-category (intern cat))
4547 (push (cons "CATEGORY" cat) props))
4548 (when prio
4549 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4550 (setq prio (mapcar 'string-to-char prio))
4551 (org-set-local 'org-highest-priority (nth 0 prio))
4552 (org-set-local 'org-lowest-priority (nth 1 prio))
4553 (org-set-local 'org-default-priority (nth 2 prio)))
4554 (and props (org-set-local 'org-file-properties (nreverse props)))
4555 (and ftags (org-set-local 'org-file-tags
4556 (mapcar 'org-add-prop-inherited ftags)))
4557 (and drawers (org-set-local 'org-drawers drawers))
4558 (and arch (org-set-local 'org-archive-location arch))
4559 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4560 ;; Process the TODO keywords
4561 (unless kwds
4562 ;; Use the global values as if they had been given locally.
4563 (setq kwds (default-value 'org-todo-keywords))
4564 (if (stringp (car kwds))
4565 (setq kwds (list (cons org-todo-interpretation
4566 (default-value 'org-todo-keywords)))))
4567 (setq kwds (reverse kwds)))
4568 (setq kwds (nreverse kwds))
4569 (let (inter kws kw)
4570 (while (setq kws (pop kwds))
4571 (let ((kws (or
4572 (run-hook-with-args-until-success
4573 'org-todo-setup-filter-hook kws)
4574 kws)))
4575 (setq inter (pop kws) sep (member "|" kws)
4576 kws0 (delete "|" (copy-sequence kws))
4577 kwsa nil
4578 kws1 (mapcar
4579 (lambda (x)
4580 ;; 1 2
4581 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4582 (progn
4583 (setq kw (match-string 1 x)
4584 key (and (match-end 2) (match-string 2 x))
4585 log (org-extract-log-state-settings x))
4586 (push (cons kw (and key (string-to-char key))) kwsa)
4587 (and log (push log org-todo-log-states))
4589 (error "Invalid TODO keyword %s" x)))
4590 kws0)
4591 kwsa (if kwsa (append '((:startgroup))
4592 (nreverse kwsa)
4593 '((:endgroup))))
4594 hw (car kws1)
4595 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4596 tail (list inter hw (car dws) (org-last dws))))
4597 (add-to-list 'org-todo-heads hw 'append)
4598 (push kws1 org-todo-sets)
4599 (setq org-done-keywords (append org-done-keywords dws nil))
4600 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4601 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4602 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4603 (setq org-todo-sets (nreverse org-todo-sets)
4604 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4605 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4606 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4607 ;; Process the constants
4608 (when const
4609 (let (e cst)
4610 (while (setq e (pop const))
4611 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4612 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4613 (setq org-table-formula-constants-local cst)))
4615 ;; Process the tags.
4616 (when tags
4617 (let (e tgs)
4618 (while (setq e (pop tags))
4619 (cond
4620 ((equal e "{") (push '(:startgroup) tgs))
4621 ((equal e "}") (push '(:endgroup) tgs))
4622 ((equal e "\\n") (push '(:newline) tgs))
4623 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4624 (push (cons (match-string 1 e)
4625 (string-to-char (match-string 2 e)))
4626 tgs))
4627 (t (push (list e) tgs))))
4628 (org-set-local 'org-tag-alist nil)
4629 (while (setq e (pop tgs))
4630 (or (and (stringp (car e))
4631 (assoc (car e) org-tag-alist))
4632 (push e org-tag-alist)))))
4634 ;; Compute the regular expressions and other local variables.
4635 ;; Using `org-outline-regexp-bol' would complicate them much,
4636 ;; because of the fixed white space at the end of that string.
4637 (if (not org-done-keywords)
4638 (setq org-done-keywords (and org-todo-keywords-1
4639 (list (org-last org-todo-keywords-1)))))
4640 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4641 (length org-scheduled-string)
4642 (length org-clock-string)
4643 (length org-closed-string)))
4644 org-drawer-regexp
4645 (concat "^[ \t]*:\\("
4646 (mapconcat 'regexp-quote org-drawers "\\|")
4647 "\\):[ \t]*$")
4648 org-not-done-keywords
4649 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4650 org-todo-regexp
4651 (concat "\\("
4652 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4653 "\\)")
4654 org-not-done-regexp
4655 (concat "\\("
4656 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4657 "\\)")
4658 org-not-done-heading-regexp
4659 (format org-heading-keyword-regexp-format org-not-done-regexp)
4660 org-todo-line-regexp
4661 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4662 org-complex-heading-regexp
4663 (concat "^\\(\\*+\\)"
4664 "\\(?: +" org-todo-regexp "\\)?"
4665 "\\(?: +\\(\\[#.\\]\\)\\)?"
4666 "\\(?: +\\(.*?\\)\\)??"
4667 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4668 "[ \t]*$")
4669 org-complex-heading-regexp-format
4670 (concat "^\\(\\*+\\)"
4671 "\\(?: +" org-todo-regexp "\\)?"
4672 "\\(?: +\\(\\[#.\\]\\)\\)?"
4673 "\\(?: +"
4674 ;; Stats cookies can be stuck to body.
4675 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4676 "\\(%s\\)"
4677 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4678 "\\)"
4679 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4680 "[ \t]*$")
4681 org-todo-line-tags-regexp
4682 (concat "^\\(\\*+\\)"
4683 "\\(?: +" org-todo-regexp "\\)?"
4684 "\\(?: +\\(.*?\\)\\)??"
4685 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4686 "[ \t]*$")
4687 org-deadline-regexp (concat "\\<" org-deadline-string)
4688 org-deadline-time-regexp
4689 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4690 org-deadline-line-regexp
4691 (concat "\\<\\(" org-deadline-string "\\).*")
4692 org-scheduled-regexp
4693 (concat "\\<" org-scheduled-string)
4694 org-scheduled-time-regexp
4695 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4696 org-closed-time-regexp
4697 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4698 org-keyword-time-regexp
4699 (concat "\\<\\(" org-scheduled-string
4700 "\\|" org-deadline-string
4701 "\\|" org-closed-string
4702 "\\|" org-clock-string "\\)"
4703 " *[[<]\\([^]>]+\\)[]>]")
4704 org-keyword-time-not-clock-regexp
4705 (concat "\\<\\(" org-scheduled-string
4706 "\\|" org-deadline-string
4707 "\\|" org-closed-string
4708 "\\)"
4709 " *[[<]\\([^]>]+\\)[]>]")
4710 org-maybe-keyword-time-regexp
4711 (concat "\\(\\<\\(" org-scheduled-string
4712 "\\|" org-deadline-string
4713 "\\|" org-closed-string
4714 "\\|" org-clock-string "\\)\\)?"
4715 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4716 org-all-time-keywords
4717 (mapcar (lambda (w) (substring w 0 -1))
4718 (list org-scheduled-string org-deadline-string
4719 org-clock-string org-closed-string))
4721 (org-compute-latex-and-specials-regexp)
4722 (org-set-font-lock-defaults))))
4724 (defun org-file-contents (file &optional noerror)
4725 "Return the contents of FILE, as a string."
4726 (if (or (not file)
4727 (not (file-readable-p file)))
4728 (if noerror
4729 (progn
4730 (message "Cannot read file \"%s\"" file)
4731 (ding) (sit-for 2)
4733 (error "Cannot read file \"%s\"" file))
4734 (with-temp-buffer
4735 (insert-file-contents file)
4736 (buffer-string))))
4738 (defun org-extract-log-state-settings (x)
4739 "Extract the log state setting from a TODO keyword string.
4740 This will extract info from a string like \"WAIT(w@/!)\"."
4741 (let (kw key log1 log2)
4742 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4743 (setq kw (match-string 1 x)
4744 key (and (match-end 2) (match-string 2 x))
4745 log1 (and (match-end 3) (match-string 3 x))
4746 log2 (and (match-end 4) (match-string 4 x)))
4747 (and (or log1 log2)
4748 (list kw
4749 (and log1 (if (equal log1 "!") 'time 'note))
4750 (and log2 (if (equal log2 "!") 'time 'note)))))))
4752 (defun org-remove-keyword-keys (list)
4753 "Remove a pair of parenthesis at the end of each string in LIST."
4754 (mapcar (lambda (x)
4755 (if (string-match "(.*)$" x)
4756 (substring x 0 (match-beginning 0))
4758 list))
4760 (defun org-assign-fast-keys (alist)
4761 "Assign fast keys to a keyword-key alist.
4762 Respect keys that are already there."
4763 (let (new e (alt ?0))
4764 (while (setq e (pop alist))
4765 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4766 (cdr e)) ;; Key already assigned.
4767 (push e new)
4768 (let ((clist (string-to-list (downcase (car e))))
4769 (used (append new alist)))
4770 (when (= (car clist) ?@)
4771 (pop clist))
4772 (while (and clist (rassoc (car clist) used))
4773 (pop clist))
4774 (unless clist
4775 (while (rassoc alt used)
4776 (incf alt)))
4777 (push (cons (car e) (or (car clist) alt)) new))))
4778 (nreverse new)))
4780 ;;; Some variables used in various places
4782 (defvar org-window-configuration nil
4783 "Used in various places to store a window configuration.")
4784 (defvar org-selected-window nil
4785 "Used in various places to store a window configuration.")
4786 (defvar org-finish-function nil
4787 "Function to be called when `C-c C-c' is used.
4788 This is for getting out of special buffers like capture.")
4791 ;; FIXME: Occasionally check by commenting these, to make sure
4792 ;; no other functions uses these, forgetting to let-bind them.
4793 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4794 (defvar org-last-state)
4795 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4797 ;; Defined somewhere in this file, but used before definition.
4798 (defvar org-entities) ;; defined in org-entities.el
4799 (defvar org-struct-menu)
4800 (defvar org-org-menu)
4801 (defvar org-tbl-menu)
4803 ;;;; Define the Org-mode
4805 ;; We use a before-change function to check if a table might need
4806 ;; an update.
4807 (defvar org-table-may-need-update t
4808 "Indicates that a table might need an update.
4809 This variable is set by `org-before-change-function'.
4810 `org-table-align' sets it back to nil.")
4811 (defun org-before-change-function (beg end)
4812 "Every change indicates that a table might need an update."
4813 (setq org-table-may-need-update t))
4814 (defvar org-mode-map)
4815 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4816 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4817 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4818 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4819 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4820 (defvar org-table-buffer-is-an nil)
4822 (defvar bidi-paragraph-direction)
4823 (defvar buffer-face-mode-face)
4825 (require 'outline)
4826 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4827 (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"))
4828 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4830 ;; Other stuff we need.
4831 (require 'time-date)
4832 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4833 (require 'easymenu)
4834 (require 'overlay)
4836 (require 'org-macs)
4837 (require 'org-entities)
4838 ;; (require 'org-compat) moved higher up in the file before it is first used
4839 (require 'org-faces)
4840 (require 'org-list)
4841 (require 'org-pcomplete)
4842 (require 'org-src)
4843 (require 'org-footnote)
4845 ;; babel
4846 (require 'ob)
4847 (require 'ob-table)
4848 (require 'ob-lob)
4849 (require 'ob-ref)
4850 (require 'ob-tangle)
4851 (require 'ob-comint)
4852 (require 'ob-keys)
4854 ;;;###autoload
4855 (define-derived-mode org-mode outline-mode "Org"
4856 "Outline-based notes management and organizer, alias
4857 \"Carsten's outline-mode for keeping track of everything.\"
4859 Org-mode develops organizational tasks around a NOTES file which
4860 contains information about projects as plain text. Org-mode is
4861 implemented on top of outline-mode, which is ideal to keep the content
4862 of large files well structured. It supports ToDo items, deadlines and
4863 time stamps, which magically appear in the diary listing of the Emacs
4864 calendar. Tables are easily created with a built-in table editor.
4865 Plain text URL-like links connect to websites, emails (VM), Usenet
4866 messages (Gnus), BBDB entries, and any files related to the project.
4867 For printing and sharing of notes, an Org-mode file (or a part of it)
4868 can be exported as a structured ASCII or HTML file.
4870 The following commands are available:
4872 \\{org-mode-map}"
4874 ;; Get rid of Outline menus, they are not needed
4875 ;; Need to do this here because define-derived-mode sets up
4876 ;; the keymap so late. Still, it is a waste to call this each time
4877 ;; we switch another buffer into org-mode.
4878 (if (featurep 'xemacs)
4879 (when (boundp 'outline-mode-menu-heading)
4880 ;; Assume this is Greg's port, it uses easymenu
4881 (easy-menu-remove outline-mode-menu-heading)
4882 (easy-menu-remove outline-mode-menu-show)
4883 (easy-menu-remove outline-mode-menu-hide))
4884 (define-key org-mode-map [menu-bar headings] 'undefined)
4885 (define-key org-mode-map [menu-bar hide] 'undefined)
4886 (define-key org-mode-map [menu-bar show] 'undefined))
4888 (org-load-modules-maybe)
4889 (easy-menu-add org-org-menu)
4890 (easy-menu-add org-tbl-menu)
4891 (org-install-agenda-files-menu)
4892 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4893 (add-to-invisibility-spec '(org-cwidth))
4894 (add-to-invisibility-spec '(org-hide-block . t))
4895 (when (featurep 'xemacs)
4896 (org-set-local 'line-move-ignore-invisible t))
4897 (org-set-local 'outline-regexp org-outline-regexp)
4898 (org-set-local 'outline-level 'org-outline-level)
4899 (setq bidi-paragraph-direction 'left-to-right)
4900 (when (and org-ellipsis
4901 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4902 (fboundp 'make-glyph-code))
4903 (unless org-display-table
4904 (setq org-display-table (make-display-table)))
4905 (set-display-table-slot
4906 org-display-table 4
4907 (vconcat (mapcar
4908 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4909 org-ellipsis)))
4910 (if (stringp org-ellipsis) org-ellipsis "..."))))
4911 (setq buffer-display-table org-display-table))
4912 (org-set-regexps-and-options)
4913 (when (and org-tag-faces (not org-tags-special-faces-re))
4914 ;; tag faces set outside customize.... force initialization.
4915 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4916 ;; Calc embedded
4917 (org-set-local 'calc-embedded-open-mode "# ")
4918 (modify-syntax-entry ?@ "w")
4919 (modify-syntax-entry ?\" "\"")
4920 (if org-startup-truncated (setq truncate-lines t))
4921 (org-set-local 'font-lock-unfontify-region-function
4922 'org-unfontify-region)
4923 ;; Activate before-change-function
4924 (org-set-local 'org-table-may-need-update t)
4925 (org-add-hook 'before-change-functions 'org-before-change-function nil
4926 'local)
4927 ;; Check for running clock before killing a buffer
4928 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4929 ;; Initialize macros templates.
4930 (org-macro-initialize-templates)
4931 ;; Initialize radio targets.
4932 (org-update-radio-target-regexp)
4933 ;; Indentation.
4934 (org-set-local 'indent-line-function 'org-indent-line)
4935 (org-set-local 'indent-region-function 'org-indent-region)
4936 ;; Filling and auto-filling.
4937 (org-setup-filling)
4938 ;; Comments.
4939 (org-setup-comments-handling)
4940 ;; Beginning/end of defun
4941 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
4942 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
4943 ;; Next error for sparse trees
4944 (org-set-local 'next-error-function 'org-occur-next-match)
4945 ;; Make sure dependence stuff works reliably, even for users who set it
4946 ;; too late :-(
4947 (if org-enforce-todo-dependencies
4948 (add-hook 'org-blocker-hook
4949 'org-block-todo-from-children-or-siblings-or-parent)
4950 (remove-hook 'org-blocker-hook
4951 'org-block-todo-from-children-or-siblings-or-parent))
4952 (if org-enforce-todo-checkbox-dependencies
4953 (add-hook 'org-blocker-hook
4954 'org-block-todo-from-checkboxes)
4955 (remove-hook 'org-blocker-hook
4956 'org-block-todo-from-checkboxes))
4958 ;; Align options lines
4959 (org-set-local
4960 'align-mode-rules-list
4961 '((org-in-buffer-settings
4962 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4963 (modes . '(org-mode)))))
4965 ;; Imenu
4966 (org-set-local 'imenu-create-index-function
4967 'org-imenu-get-tree)
4969 ;; Make isearch reveal context
4970 (if (or (featurep 'xemacs)
4971 (not (boundp 'outline-isearch-open-invisible-function)))
4972 ;; Emacs 21 and XEmacs make use of the hook
4973 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4974 ;; Emacs 22 deals with this through a special variable
4975 (org-set-local 'outline-isearch-open-invisible-function
4976 (lambda (&rest ignore) (org-show-context 'isearch))))
4978 ;; Turn on org-beamer-mode?
4979 (and org-startup-with-beamer-mode (org-beamer-mode))
4981 ;; Setup the pcomplete hooks
4982 (set (make-local-variable 'pcomplete-command-completion-function)
4983 'org-pcomplete-initial)
4984 (set (make-local-variable 'pcomplete-command-name-function)
4985 'org-command-at-point)
4986 (set (make-local-variable 'pcomplete-default-completion-function)
4987 'ignore)
4988 (set (make-local-variable 'pcomplete-parse-arguments-function)
4989 'org-parse-arguments)
4990 (set (make-local-variable 'pcomplete-termination-string) "")
4991 (when (>= emacs-major-version 23)
4992 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
4994 ;; If empty file that did not turn on org-mode automatically, make it to.
4995 (if (and org-insert-mode-line-in-empty-file
4996 (org-called-interactively-p 'any)
4997 (= (point-min) (point-max)))
4998 (insert "# -*- mode: org -*-\n\n"))
4999 (unless org-inhibit-startup
5000 (when org-startup-align-all-tables
5001 (let ((bmp (buffer-modified-p)))
5002 (org-table-map-tables 'org-table-align 'quietly)
5003 (set-buffer-modified-p bmp)))
5004 (when org-startup-with-inline-images
5005 (org-display-inline-images))
5006 (when org-startup-indented
5007 (require 'org-indent)
5008 (org-indent-mode 1))
5009 (unless org-inhibit-startup-visibility-stuff
5010 (org-set-startup-visibility)))
5011 ;; Try to set org-hide correctly
5012 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5014 (when (fboundp 'abbrev-table-put)
5015 (abbrev-table-put org-mode-abbrev-table
5016 :parents (list text-mode-abbrev-table)))
5018 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5021 (defun org-find-invisible-foreground ()
5022 (let ((candidates (remove
5023 "unspecified-bg"
5024 (list
5025 (face-background 'default)
5026 (face-background 'org-default)
5027 (cdr (assoc 'background-color default-frame-alist))
5028 (cdr (assoc 'background-color initial-frame-alist))
5029 (cdr (assoc 'background-color window-system-default-frame-alist))
5030 (face-foreground 'org-hide)))))
5031 (car (remove nil candidates))))
5033 (defun org-current-time ()
5034 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5035 (if (> (car org-time-stamp-rounding-minutes) 1)
5036 (let ((r (car org-time-stamp-rounding-minutes))
5037 (time (decode-time)))
5038 (apply 'encode-time
5039 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5040 (nthcdr 2 time))))
5041 (current-time)))
5043 (defun org-today ()
5044 "Return today date, considering `org-extend-today-until'."
5045 (time-to-days
5046 (time-subtract (current-time)
5047 (list 0 (* 3600 org-extend-today-until) 0))))
5049 ;;;; Font-Lock stuff, including the activators
5051 (defvar org-mouse-map (make-sparse-keymap))
5052 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5053 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5054 (when org-mouse-1-follows-link
5055 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5056 (when org-tab-follows-link
5057 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5058 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5060 (require 'font-lock)
5062 (defconst org-non-link-chars "]\t\n\r<>")
5063 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5064 "shell" "elisp" "doi" "message"))
5065 (defvar org-link-types-re nil
5066 "Matches a link that has a url-like prefix like \"http:\"")
5067 (defvar org-link-re-with-space nil
5068 "Matches a link with spaces, optional angular brackets around it.")
5069 (defvar org-link-re-with-space2 nil
5070 "Matches a link with spaces, optional angular brackets around it.")
5071 (defvar org-link-re-with-space3 nil
5072 "Matches a link with spaces, only for internal part in bracket links.")
5073 (defvar org-angle-link-re nil
5074 "Matches link with angular brackets, spaces are allowed.")
5075 (defvar org-plain-link-re nil
5076 "Matches plain link, without spaces.")
5077 (defvar org-bracket-link-regexp nil
5078 "Matches a link in double brackets.")
5079 (defvar org-bracket-link-analytic-regexp nil
5080 "Regular expression used to analyze links.
5081 Here is what the match groups contain after a match:
5082 1: http:
5083 2: http
5084 3: path
5085 4: [desc]
5086 5: desc")
5087 (defvar org-bracket-link-analytic-regexp++ nil
5088 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5089 (defvar org-any-link-re nil
5090 "Regular expression matching any link.")
5092 (defcustom org-match-sexp-depth 3
5093 "Number of stacked braces for sub/superscript matching.
5094 This has to be set before loading org.el to be effective."
5095 :group 'org-export-translation ; ??????????????????????????/
5096 :type 'integer)
5098 (defun org-create-multibrace-regexp (left right n)
5099 "Create a regular expression which will match a balanced sexp.
5100 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5101 as single character strings.
5102 The regexp returned will match the entire expression including the
5103 delimiters. It will also define a single group which contains the
5104 match except for the outermost delimiters. The maximum depth of
5105 stacked delimiters is N. Escaping delimiters is not possible."
5106 (let* ((nothing (concat "[^" left right "]*?"))
5107 (or "\\|")
5108 (re nothing)
5109 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5110 (while (> n 1)
5111 (setq n (1- n)
5112 re (concat re or next)
5113 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5114 (concat left "\\(" re "\\)" right)))
5116 (defvar org-match-substring-regexp
5117 (concat
5118 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5119 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5120 "\\|"
5121 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5122 "\\|"
5123 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5124 "The regular expression matching a sub- or superscript.")
5126 (defvar org-match-substring-with-braces-regexp
5127 (concat
5128 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5129 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5130 "\\)")
5131 "The regular expression matching a sub- or superscript, forcing braces.")
5133 (defun org-make-link-regexps ()
5134 "Update the link regular expressions.
5135 This should be called after the variable `org-link-types' has changed."
5136 (setq org-link-types-re
5137 (concat
5138 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5139 org-link-re-with-space
5140 (concat
5141 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5142 "\\([^" org-non-link-chars " ]"
5143 "[^" org-non-link-chars "]*"
5144 "[^" org-non-link-chars " ]\\)>?")
5145 org-link-re-with-space2
5146 (concat
5147 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5148 "\\([^" org-non-link-chars " ]"
5149 "[^\t\n\r]*"
5150 "[^" org-non-link-chars " ]\\)>?")
5151 org-link-re-with-space3
5152 (concat
5153 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5154 "\\([^" org-non-link-chars " ]"
5155 "[^\t\n\r]*\\)")
5156 org-angle-link-re
5157 (concat
5158 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5159 "\\([^" org-non-link-chars " ]"
5160 "[^" org-non-link-chars "]*"
5161 "\\)>")
5162 org-plain-link-re
5163 (concat
5164 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5165 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5166 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5167 org-bracket-link-regexp
5168 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5169 org-bracket-link-analytic-regexp
5170 (concat
5171 "\\[\\["
5172 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5173 "\\([^]]+\\)"
5174 "\\]"
5175 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5176 "\\]")
5177 org-bracket-link-analytic-regexp++
5178 (concat
5179 "\\[\\["
5180 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5181 "\\([^]]+\\)"
5182 "\\]"
5183 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5184 "\\]")
5185 org-any-link-re
5186 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5187 org-angle-link-re "\\)\\|\\("
5188 org-plain-link-re "\\)")))
5190 (org-make-link-regexps)
5192 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5193 "Regular expression for fast time stamp matching.")
5194 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5195 "Regular expression for fast time stamp matching.")
5196 (defconst org-ts-regexp0
5197 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5198 "Regular expression matching time strings for analysis.
5199 This one does not require the space after the date, so it can be used
5200 on a string that terminates immediately after the date.")
5201 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5202 "Regular expression matching time strings for analysis.")
5203 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5204 "Regular expression matching time stamps, with groups.")
5205 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5206 "Regular expression matching time stamps (also [..]), with groups.")
5207 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5208 "Regular expression matching a time stamp range.")
5209 (defconst org-tr-regexp-both
5210 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5211 "Regular expression matching a time stamp range.")
5212 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5213 org-ts-regexp "\\)?")
5214 "Regular expression matching a time stamp or time stamp range.")
5215 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5216 org-ts-regexp-both "\\)?")
5217 "Regular expression matching a time stamp or time stamp range.
5218 The time stamps may be either active or inactive.")
5220 (defvar org-emph-face nil)
5222 (defun org-do-emphasis-faces (limit)
5223 "Run through the buffer and add overlays to emphasized strings."
5224 (let (rtn a)
5225 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5226 (if (not (= (char-after (match-beginning 3))
5227 (char-after (match-beginning 4))))
5228 (progn
5229 (setq rtn t)
5230 (setq a (assoc (match-string 3) org-emphasis-alist))
5231 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5232 'face
5233 (nth 1 a))
5234 (and (nth 4 a)
5235 (org-remove-flyspell-overlays-in
5236 (match-beginning 0) (match-end 0)))
5237 (add-text-properties (match-beginning 2) (match-end 2)
5238 '(font-lock-multiline t org-emphasis t))
5239 (when org-hide-emphasis-markers
5240 (add-text-properties (match-end 4) (match-beginning 5)
5241 '(invisible org-link))
5242 (add-text-properties (match-beginning 3) (match-end 3)
5243 '(invisible org-link)))))
5244 (backward-char 1))
5245 rtn))
5247 (defun org-emphasize (&optional char)
5248 "Insert or change an emphasis, i.e. a font like bold or italic.
5249 If there is an active region, change that region to a new emphasis.
5250 If there is no region, just insert the marker characters and position
5251 the cursor between them.
5252 CHAR should be either the marker character, or the first character of the
5253 HTML tag associated with that emphasis. If CHAR is a space, the means
5254 to remove the emphasis of the selected region.
5255 If char is not given (for example in an interactive call) it
5256 will be prompted for."
5257 (interactive)
5258 (let ((eal org-emphasis-alist) e det
5259 (erc org-emphasis-regexp-components)
5260 (prompt "")
5261 (string "") beg end move tag c s)
5262 (if (org-region-active-p)
5263 (setq beg (region-beginning) end (region-end)
5264 string (buffer-substring beg end))
5265 (setq move t))
5267 (while (setq e (pop eal))
5268 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5269 c (aref tag 0))
5270 (push (cons c (string-to-char (car e))) det)
5271 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5272 (substring tag 1)))))
5273 (setq det (nreverse det))
5274 (unless char
5275 (message "%s" (concat "Emphasis marker or tag:" prompt))
5276 (setq char (read-char-exclusive)))
5277 (setq char (or (cdr (assoc char det)) char))
5278 (if (equal char ?\ )
5279 (setq s "" move nil)
5280 (unless (assoc (char-to-string char) org-emphasis-alist)
5281 (error "No such emphasis marker: \"%c\"" char))
5282 (setq s (char-to-string char)))
5283 (while (and (> (length string) 1)
5284 (equal (substring string 0 1) (substring string -1))
5285 (assoc (substring string 0 1) org-emphasis-alist))
5286 (setq string (substring string 1 -1)))
5287 (setq string (concat s string s))
5288 (if beg (delete-region beg end))
5289 (unless (or (bolp)
5290 (string-match (concat "[" (nth 0 erc) "\n]")
5291 (char-to-string (char-before (point)))))
5292 (insert " "))
5293 (unless (or (eobp)
5294 (string-match (concat "[" (nth 1 erc) "\n]")
5295 (char-to-string (char-after (point)))))
5296 (insert " ") (backward-char 1))
5297 (insert string)
5298 (and move (backward-char 1))))
5300 (defconst org-nonsticky-props
5301 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5303 (defsubst org-rear-nonsticky-at (pos)
5304 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5306 (defun org-activate-plain-links (limit)
5307 "Run through the buffer and add overlays to links."
5308 (catch 'exit
5309 (let (f hl)
5310 (when (re-search-forward (concat org-plain-link-re) limit t)
5311 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5312 (setq f (get-text-property (match-beginning 0) 'face))
5313 (setq hl (org-match-string-no-properties 0))
5314 (if (or (eq f 'org-tag)
5315 (and (listp f) (memq 'org-tag f)))
5317 (add-text-properties (match-beginning 0) (match-end 0)
5318 (list 'mouse-face 'highlight
5319 'face 'org-link
5320 'htmlize-link `(:uri ,hl)
5321 'keymap org-mouse-map))
5322 (org-rear-nonsticky-at (match-end 0)))
5323 t))))
5325 (defun org-activate-code (limit)
5326 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5327 (progn
5328 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5329 (remove-text-properties (match-beginning 0) (match-end 0)
5330 '(display t invisible t intangible t))
5331 t)))
5333 (defcustom org-src-fontify-natively nil
5334 "When non-nil, fontify code in code blocks."
5335 :type 'boolean
5336 :version "24.1"
5337 :group 'org-appearance
5338 :group 'org-babel)
5340 (defcustom org-allow-promoting-top-level-subtree nil
5341 "When non-nil, allow promoting a top level subtree.
5342 The leading star of the top level headline will be replaced
5343 by a #."
5344 :type 'boolean
5345 :version "24.1"
5346 :group 'org-appearance)
5348 (defun org-fontify-meta-lines-and-blocks (limit)
5349 (condition-case nil
5350 (org-fontify-meta-lines-and-blocks-1 limit)
5351 (error (message "org-mode fontification error"))))
5353 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5354 "Fontify #+ lines and blocks, in the correct ways."
5355 (let ((case-fold-search t))
5356 (if (re-search-forward
5357 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5358 limit t)
5359 (let ((beg (match-beginning 0))
5360 (block-start (match-end 0))
5361 (block-end nil)
5362 (lang (match-string 7))
5363 (beg1 (line-beginning-position 2))
5364 (dc1 (downcase (match-string 2)))
5365 (dc3 (downcase (match-string 3)))
5366 end end1 quoting block-type ovl)
5367 (cond
5368 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5369 ;; a single line of backend-specific content
5370 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5371 (remove-text-properties (match-beginning 0) (match-end 0)
5372 '(display t invisible t intangible t))
5373 (add-text-properties (match-beginning 1) (match-end 3)
5374 '(font-lock-fontified t face org-meta-line))
5375 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5376 '(font-lock-fontified t face org-block))
5377 ; for backend-specific code
5379 ((and (match-end 4) (equal dc3 "+begin"))
5380 ;; Truly a block
5381 (setq block-type (downcase (match-string 5))
5382 quoting (member block-type org-protecting-blocks))
5383 (when (re-search-forward
5384 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5385 nil t) ;; on purpose, we look further than LIMIT
5386 (setq end (min (point-max) (match-end 0))
5387 end1 (min (point-max) (1- (match-beginning 0))))
5388 (setq block-end (match-beginning 0))
5389 (when quoting
5390 (remove-text-properties beg end
5391 '(display t invisible t intangible t)))
5392 (add-text-properties
5393 beg end
5394 '(font-lock-fontified t font-lock-multiline t))
5395 (add-text-properties beg beg1 '(face org-meta-line))
5396 (add-text-properties end1 (min (point-max) (1+ end))
5397 '(face org-meta-line)) ; for end_src
5398 (cond
5399 ((and lang (not (string= lang "")) org-src-fontify-natively)
5400 (org-src-font-lock-fontify-block lang block-start block-end)
5401 ;; remove old background overlays
5402 (mapc (lambda (ov)
5403 (if (eq (overlay-get ov 'face) 'org-block-background)
5404 (delete-overlay ov)))
5405 (overlays-at (/ (+ beg1 block-end) 2)))
5406 ;; add a background overlay
5407 (setq ovl (make-overlay beg1 block-end))
5408 (overlay-put ovl 'face 'org-block-background)
5409 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5410 (quoting
5411 (add-text-properties beg1 (min (point-max) (1+ end1))
5412 '(face org-block))) ; end of source block
5413 ((not org-fontify-quote-and-verse-blocks))
5414 ((string= block-type "quote")
5415 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5416 ((string= block-type "verse")
5417 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5418 (add-text-properties beg beg1 '(face org-block-begin-line))
5419 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5420 '(face org-block-end-line))
5422 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5423 (add-text-properties
5424 beg (match-end 3)
5425 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5426 '(font-lock-fontified t invisible t)
5427 '(font-lock-fontified t face org-document-info-keyword)))
5428 (add-text-properties
5429 (match-beginning 6) (match-end 6)
5430 (if (string-equal dc1 "+title:")
5431 '(font-lock-fontified t face org-document-title)
5432 '(font-lock-fontified t face org-document-info))))
5433 ((or (equal dc1 "+results")
5434 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5435 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5436 "+call:" "+header:" "+headers:" "+name:"))
5437 (and (match-end 4) (equal dc3 "+attr")))
5438 (add-text-properties
5439 beg (match-end 0)
5440 '(font-lock-fontified t face org-meta-line))
5442 ((member dc3 '(" " ""))
5443 (add-text-properties
5444 beg (match-end 0)
5445 '(font-lock-fontified t face font-lock-comment-face)))
5446 ((not (member (char-after beg) '(?\ ?\t)))
5447 ;; just any other in-buffer setting, but not indented
5448 (add-text-properties
5449 beg (match-end 0)
5450 '(font-lock-fontified t face org-meta-line))
5452 (t nil))))))
5454 (defun org-activate-angle-links (limit)
5455 "Run through the buffer and add overlays to links."
5456 (if (re-search-forward org-angle-link-re limit t)
5457 (progn
5458 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5459 (add-text-properties (match-beginning 0) (match-end 0)
5460 (list 'mouse-face 'highlight
5461 'keymap org-mouse-map))
5462 (org-rear-nonsticky-at (match-end 0))
5463 t)))
5465 (defun org-activate-footnote-links (limit)
5466 "Run through the buffer and add overlays to footnotes."
5467 (let ((fn (org-footnote-next-reference-or-definition limit)))
5468 (when fn
5469 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5470 (org-remove-flyspell-overlays-in beg end)
5471 (add-text-properties beg end
5472 (list 'mouse-face 'highlight
5473 'keymap org-mouse-map
5474 'help-echo
5475 (if (= (point-at-bol) beg)
5476 "Footnote definition"
5477 "Footnote reference")
5478 'font-lock-fontified t
5479 'font-lock-multiline t
5480 'face 'org-footnote))))))
5482 (defun org-activate-bracket-links (limit)
5483 "Run through the buffer and add overlays to bracketed links."
5484 (if (re-search-forward org-bracket-link-regexp limit t)
5485 (let* ((hl (org-match-string-no-properties 1))
5486 (help (concat "LINK: " hl))
5487 ;; FIXME: Above we should remove the escapes. But that
5488 ;; requires another match, protecting match data, a lot
5489 ;; of overhead for font-lock.
5490 (ip (org-maybe-intangible
5491 (list 'invisible 'org-link
5492 'keymap org-mouse-map 'mouse-face 'highlight
5493 'font-lock-multiline t 'help-echo help
5494 'htmlize-link `(:uri ,hl))))
5495 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5496 'font-lock-multiline t 'help-echo help
5497 'htmlize-link `(:uri ,hl))))
5498 ;; We need to remove the invisible property here. Table narrowing
5499 ;; may have made some of this invisible.
5500 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5501 (remove-text-properties (match-beginning 0) (match-end 0)
5502 '(invisible nil))
5503 (if (match-end 3)
5504 (progn
5505 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5506 (org-rear-nonsticky-at (match-beginning 3))
5507 (add-text-properties (match-beginning 3) (match-end 3) vp)
5508 (org-rear-nonsticky-at (match-end 3))
5509 (add-text-properties (match-end 3) (match-end 0) ip)
5510 (org-rear-nonsticky-at (match-end 0)))
5511 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5512 (org-rear-nonsticky-at (match-beginning 1))
5513 (add-text-properties (match-beginning 1) (match-end 1) vp)
5514 (org-rear-nonsticky-at (match-end 1))
5515 (add-text-properties (match-end 1) (match-end 0) ip)
5516 (org-rear-nonsticky-at (match-end 0)))
5517 t)))
5519 (defun org-activate-dates (limit)
5520 "Run through the buffer and add overlays to dates."
5521 (if (re-search-forward org-tsr-regexp-both limit t)
5522 (progn
5523 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5524 (add-text-properties (match-beginning 0) (match-end 0)
5525 (list 'mouse-face 'highlight
5526 'keymap org-mouse-map))
5527 (org-rear-nonsticky-at (match-end 0))
5528 (when org-display-custom-times
5529 (if (match-end 3)
5530 (org-display-custom-time (match-beginning 3) (match-end 3)))
5531 (org-display-custom-time (match-beginning 1) (match-end 1)))
5532 t)))
5534 (defvar org-target-link-regexp nil
5535 "Regular expression matching radio targets in plain text.")
5536 (make-variable-buffer-local 'org-target-link-regexp)
5537 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5538 "Regular expression matching a link target.")
5539 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5540 "Regular expression matching a radio target.")
5541 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5542 "Regular expression matching any target.")
5544 (defun org-activate-target-links (limit)
5545 "Run through the buffer and add overlays to target matches."
5546 (when org-target-link-regexp
5547 (let ((case-fold-search t))
5548 (if (re-search-forward org-target-link-regexp limit t)
5549 (progn
5550 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5551 (add-text-properties (match-beginning 0) (match-end 0)
5552 (list 'mouse-face 'highlight
5553 'keymap org-mouse-map
5554 'help-echo "Radio target link"
5555 'org-linked-text t))
5556 (org-rear-nonsticky-at (match-end 0))
5557 t)))))
5559 (defun org-update-radio-target-regexp ()
5560 "Find all radio targets in this file and update the regular expression."
5561 (interactive)
5562 (when (memq 'radio org-activate-links)
5563 (setq org-target-link-regexp
5564 (org-make-target-link-regexp (org-all-targets 'radio)))
5565 (org-restart-font-lock)))
5567 (defun org-hide-wide-columns (limit)
5568 (let (s e)
5569 (setq s (text-property-any (point) (or limit (point-max))
5570 'org-cwidth t))
5571 (when s
5572 (setq e (next-single-property-change s 'org-cwidth))
5573 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5574 (goto-char e)
5575 t)))
5577 (defvar org-latex-and-specials-regexp nil
5578 "Regular expression for highlighting export special stuff.")
5579 (defvar org-match-substring-regexp)
5580 (defvar org-match-substring-with-braces-regexp)
5582 ;; This should be with the exporter code, but we also use if for font-locking
5583 (defconst org-export-html-special-string-regexps
5584 '(("\\\\-" . "&shy;")
5585 ("---\\([^-]\\)" . "&mdash;\\1")
5586 ("--\\([^-]\\)" . "&ndash;\\1")
5587 ("\\.\\.\\." . "&hellip;"))
5588 "Regular expressions for special string conversion.")
5591 (defun org-compute-latex-and-specials-regexp ()
5592 "Compute regular expression for stuff treated specially by exporters."
5593 (if (not org-highlight-latex-fragments-and-specials)
5594 (org-set-local 'org-latex-and-specials-regexp nil)
5595 (require 'org-exp)
5596 (let*
5597 ((matchers (plist-get org-format-latex-options :matchers))
5598 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5599 org-latex-regexps)))
5600 (org-export-allow-BIND nil)
5601 (options (org-combine-plists (org-default-export-plist)
5602 (org-infile-export-plist)))
5603 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5604 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5605 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5606 (org-export-html-expand (plist-get options :expand-quoted-html))
5607 (org-export-with-special-strings (plist-get options :special-strings))
5608 (re-sub
5609 (cond
5610 ((equal org-export-with-sub-superscripts '{})
5611 (list org-match-substring-with-braces-regexp))
5612 (org-export-with-sub-superscripts
5613 (list org-match-substring-regexp))))
5614 (re-latex
5615 (if org-export-with-LaTeX-fragments
5616 (mapcar (lambda (x) (nth 1 x)) latexs)))
5617 (re-macros
5618 (if org-export-with-TeX-macros
5619 (list (concat "\\\\"
5620 (regexp-opt
5621 (append
5623 (delq nil
5624 (mapcar 'car-safe
5625 (append org-entities-user
5626 org-entities)))
5627 (if (boundp 'org-latex-entities)
5628 (mapcar (lambda (x)
5629 (or (car-safe x) x))
5630 org-latex-entities)
5631 nil))
5632 'words))) ; FIXME
5634 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5635 (re-special (if org-export-with-special-strings
5636 (mapcar (lambda (x) (car x))
5637 org-export-html-special-string-regexps)))
5638 (re-rest
5639 (delq nil
5640 (list
5641 (if org-export-html-expand "@<[^>\n]+>")
5642 ))))
5643 (org-set-local
5644 'org-latex-and-specials-regexp
5645 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5646 re-rest) "\\|")))))
5648 (defun org-do-latex-and-special-faces (limit)
5649 "Run through the buffer and add overlays to links."
5650 (when org-latex-and-specials-regexp
5651 (let (rtn d)
5652 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5653 limit t))
5654 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5655 'face))
5656 '(org-code org-verbatim underline)))
5657 (progn
5658 (setq rtn t
5659 d (cond ((member (char-after (1+ (match-beginning 0)))
5660 '(?_ ?^)) 1)
5661 (t 0)))
5662 (font-lock-prepend-text-property
5663 (+ d (match-beginning 0)) (match-end 0)
5664 'face 'org-latex-and-export-specials)
5665 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5666 '(font-lock-multiline t)))))
5667 rtn)))
5669 (defun org-restart-font-lock ()
5670 "Restart `font-lock-mode', to force refontification."
5671 (when (and (boundp 'font-lock-mode) font-lock-mode)
5672 (font-lock-mode -1)
5673 (font-lock-mode 1)))
5675 (defun org-all-targets (&optional radio)
5676 "Return a list of all targets in this file.
5677 With optional argument RADIO, only find radio targets."
5678 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5679 rtn)
5680 (save-excursion
5681 (goto-char (point-min))
5682 (while (re-search-forward re nil t)
5683 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5684 rtn)))
5686 (defun org-make-target-link-regexp (targets)
5687 "Make regular expression matching all strings in TARGETS.
5688 The regular expression finds the targets also if there is a line break
5689 between words."
5690 (and targets
5691 (concat
5692 "\\<\\("
5693 (mapconcat
5694 (lambda (x)
5695 (setq x (regexp-quote x))
5696 (while (string-match " +" x)
5697 (setq x (replace-match "\\s-+" t t x)))
5699 targets
5700 "\\|")
5701 "\\)\\>")))
5703 (defun org-activate-tags (limit)
5704 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5705 (progn
5706 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5707 (add-text-properties (match-beginning 1) (match-end 1)
5708 (list 'mouse-face 'highlight
5709 'keymap org-mouse-map))
5710 (org-rear-nonsticky-at (match-end 1))
5711 t)))
5713 (defun org-outline-level ()
5714 "Compute the outline level of the heading at point.
5715 If this is called at a normal headline, the level is the number of stars.
5716 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5717 (save-excursion
5718 (if (not (condition-case nil
5719 (org-back-to-heading t)
5720 (error nil)))
5722 (looking-at org-outline-regexp)
5723 (1- (- (match-end 0) (match-beginning 0))))))
5725 (defvar org-font-lock-keywords nil)
5727 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5728 "Regular expression matching a property line.")
5730 (defvar org-font-lock-hook nil
5731 "Functions to be called for special font lock stuff.")
5733 (defvar org-font-lock-set-keywords-hook nil
5734 "Functions that can manipulate `org-font-lock-extra-keywords'.
5735 This is called after `org-font-lock-extra-keywords' is defined, but before
5736 it is installed to be used by font lock. This can be useful if something
5737 needs to be inserted at a specific position in the font-lock sequence.")
5739 (defun org-font-lock-hook (limit)
5740 "Run `org-font-lock-hook' within LIMIT."
5741 (run-hook-with-args 'org-font-lock-hook limit))
5743 (defun org-set-font-lock-defaults ()
5744 "Set font lock defaults for the current buffer."
5745 (let* ((em org-fontify-emphasized-text)
5746 (lk org-activate-links)
5747 (org-font-lock-extra-keywords
5748 (list
5749 ;; Call the hook
5750 '(org-font-lock-hook)
5751 ;; Headlines
5752 `(,(if org-fontify-whole-heading-line
5753 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5754 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5755 (1 (org-get-level-face 1))
5756 (2 (org-get-level-face 2))
5757 (3 (org-get-level-face 3)))
5758 ;; Table lines
5759 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5760 (1 'org-table t))
5761 ;; Table internals
5762 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5763 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5764 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5765 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5766 ;; Drawers
5767 (list org-drawer-regexp '(0 'org-special-keyword t))
5768 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5769 ;; Properties
5770 (list org-property-re
5771 '(1 'org-special-keyword t)
5772 '(3 'org-property-value t))
5773 ;; Links
5774 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5775 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5776 (if (memq 'plain lk) '(org-activate-plain-links))
5777 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5778 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5779 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5780 (if (memq 'footnote lk) '(org-activate-footnote-links))
5781 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5782 '(org-hide-wide-columns (0 nil append))
5783 ;; TODO keyword
5784 (list (format org-heading-keyword-regexp-format
5785 org-todo-regexp)
5786 '(2 (org-get-todo-face 2) t))
5787 ;; DONE
5788 (if org-fontify-done-headline
5789 (list (format org-heading-keyword-regexp-format
5790 (concat
5791 "\\(?:"
5792 (mapconcat 'regexp-quote org-done-keywords "\\|")
5793 "\\)"))
5794 '(2 'org-headline-done t))
5795 nil)
5796 ;; Priorities
5797 '(org-font-lock-add-priority-faces)
5798 ;; Tags
5799 '(org-font-lock-add-tag-faces)
5800 ;; Special keywords
5801 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5802 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5803 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5804 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5805 ;; Emphasis
5806 (if em
5807 (if (featurep 'xemacs)
5808 '(org-do-emphasis-faces (0 nil append))
5809 '(org-do-emphasis-faces)))
5810 ;; Checkboxes
5811 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5812 1 'org-checkbox prepend)
5813 (if (cdr (assq 'checkbox org-list-automatic-rules))
5814 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5815 (0 (org-get-checkbox-statistics-face) t)))
5816 ;; Description list items
5817 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5818 1 'org-list-dt prepend)
5819 ;; ARCHIVEd headings
5820 (list (concat
5821 org-outline-regexp-bol
5822 "\\(.*:" org-archive-tag ":.*\\)")
5823 '(1 'org-archived prepend))
5824 ;; Specials
5825 '(org-do-latex-and-special-faces)
5826 '(org-fontify-entities)
5827 '(org-raise-scripts)
5828 ;; Code
5829 '(org-activate-code (1 'org-code t))
5830 ;; COMMENT
5831 (list (format org-heading-keyword-regexp-format
5832 (concat "\\("
5833 org-comment-string "\\|" org-quote-string
5834 "\\)"))
5835 '(2 'org-special-keyword t))
5836 ;; Blocks and meta lines
5837 '(org-fontify-meta-lines-and-blocks)
5839 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5840 (run-hooks 'org-font-lock-set-keywords-hook)
5841 ;; Now set the full font-lock-keywords
5842 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5843 (org-set-local 'font-lock-defaults
5844 '(org-font-lock-keywords t nil nil backward-paragraph))
5845 (kill-local-variable 'font-lock-keywords) nil))
5847 (defun org-toggle-pretty-entities ()
5848 "Toggle the composition display of entities as UTF8 characters."
5849 (interactive)
5850 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5851 (org-restart-font-lock)
5852 (if org-pretty-entities
5853 (message "Entities are displayed as UTF8 characters")
5854 (save-restriction
5855 (widen)
5856 (org-decompose-region (point-min) (point-max))
5857 (message "Entities are displayed plain"))))
5859 (defvar org-custom-properties-overlays nil
5860 "List of overlays used for custom properties.")
5861 (make-variable-buffer-local 'org-custom-properties-overlays)
5863 (defun org-toggle-custom-properties-visibility ()
5864 "Display or hide properties in `org-custom-properties'."
5865 (interactive)
5866 (if org-custom-properties-overlays
5867 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5868 (setq org-custom-properties-overlays nil))
5869 (unless (not org-custom-properties)
5870 (save-excursion
5871 (save-restriction
5872 (widen)
5873 (goto-char (point-min))
5874 (while (re-search-forward org-property-re nil t)
5875 (mapc (lambda(p)
5876 (when (equal p (substring (match-string 1) 1 -1))
5877 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5878 (overlay-put o 'invisible t)
5879 (overlay-put o 'org-custom-property t)
5880 (push o org-custom-properties-overlays))))
5881 org-custom-properties)))))))
5883 (defun org-fontify-entities (limit)
5884 "Find an entity to fontify."
5885 (let (ee)
5886 (when org-pretty-entities
5887 (catch 'match
5888 (while (re-search-forward
5889 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5890 limit t)
5891 (if (and (not (org-in-indented-comment-line))
5892 (setq ee (org-entity-get (match-string 1)))
5893 (= (length (nth 6 ee)) 1))
5894 (let*
5895 ((end (if (equal (match-string 2) "{}")
5896 (match-end 2)
5897 (match-end 1))))
5898 (add-text-properties
5899 (match-beginning 0) end
5900 (list 'font-lock-fontified t))
5901 (compose-region (match-beginning 0) end
5902 (nth 6 ee) nil)
5903 (backward-char 1)
5904 (throw 'match t))))
5905 nil))))
5907 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5908 "Fontify string S like in Org-mode."
5909 (with-temp-buffer
5910 (insert s)
5911 (let ((org-odd-levels-only odd-levels))
5912 (org-mode)
5913 (font-lock-fontify-buffer)
5914 (buffer-string))))
5916 (defvar org-m nil)
5917 (defvar org-l nil)
5918 (defvar org-f nil)
5919 (defun org-get-level-face (n)
5920 "Get the right face for match N in font-lock matching of headlines."
5921 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5922 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5923 (if org-cycle-level-faces
5924 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5925 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5926 (cond
5927 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5928 ((eq n 2) org-f)
5929 (t (if org-level-color-stars-only nil org-f))))
5932 (defun org-get-todo-face (kwd)
5933 "Get the right face for a TODO keyword KWD.
5934 If KWD is a number, get the corresponding match group."
5935 (if (numberp kwd) (setq kwd (match-string kwd)))
5936 (or (org-face-from-face-or-color
5937 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5938 (and (member kwd org-done-keywords) 'org-done)
5939 'org-todo))
5941 (defun org-face-from-face-or-color (context inherit face-or-color)
5942 "Create a face list that inherits INHERIT, but sets the foreground color.
5943 When FACE-OR-COLOR is not a string, just return it."
5944 (if (stringp face-or-color)
5945 (list :inherit inherit
5946 (cdr (assoc context org-faces-easy-properties))
5947 face-or-color)
5948 face-or-color))
5950 (defun org-font-lock-add-tag-faces (limit)
5951 "Add the special tag faces."
5952 (when (and org-tag-faces org-tags-special-faces-re)
5953 (while (re-search-forward org-tags-special-faces-re limit t)
5954 (add-text-properties (match-beginning 1) (match-end 1)
5955 (list 'face (org-get-tag-face 1)
5956 'font-lock-fontified t))
5957 (backward-char 1))))
5959 (defun org-font-lock-add-priority-faces (limit)
5960 "Add the special priority faces."
5961 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5962 (when (save-match-data (org-at-heading-p))
5963 (add-text-properties
5964 (match-beginning 0) (match-end 0)
5965 (list 'face (or (org-face-from-face-or-color
5966 'priority 'org-special-keyword
5967 (cdr (assoc (char-after (match-beginning 1))
5968 org-priority-faces)))
5969 'org-special-keyword)
5970 'font-lock-fontified t)))))
5972 (defun org-get-tag-face (kwd)
5973 "Get the right face for a TODO keyword KWD.
5974 If KWD is a number, get the corresponding match group."
5975 (if (numberp kwd) (setq kwd (match-string kwd)))
5976 (or (org-face-from-face-or-color
5977 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5978 'org-tag))
5980 (defun org-unfontify-region (beg end &optional maybe_loudly)
5981 "Remove fontification and activation overlays from links."
5982 (font-lock-default-unfontify-region beg end)
5983 (let* ((buffer-undo-list t)
5984 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5985 (inhibit-modification-hooks t)
5986 deactivate-mark buffer-file-name buffer-file-truename)
5987 (org-decompose-region beg end)
5988 (remove-text-properties beg end
5989 '(mouse-face t keymap t org-linked-text t
5990 invisible t intangible t
5991 org-no-flyspell t org-emphasis t))
5992 (org-remove-font-lock-display-properties beg end)))
5994 (defconst org-script-display '(((raise -0.3) (height 0.7))
5995 ((raise 0.3) (height 0.7))
5996 ((raise -0.5))
5997 ((raise 0.5)))
5998 "Display properties for showing superscripts and subscripts.")
6000 (defun org-remove-font-lock-display-properties (beg end)
6001 "Remove specific display properties that have been added by font lock.
6002 The will remove the raise properties that are used to show superscripts
6003 and subscripts."
6004 (let (next prop)
6005 (while (< beg end)
6006 (setq next (next-single-property-change beg 'display nil end)
6007 prop (get-text-property beg 'display))
6008 (if (member prop org-script-display)
6009 (put-text-property beg next 'display nil))
6010 (setq beg next))))
6012 (defun org-raise-scripts (limit)
6013 "Add raise properties to sub/superscripts."
6014 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6015 (if (re-search-forward
6016 (if (eq org-use-sub-superscripts t)
6017 org-match-substring-regexp
6018 org-match-substring-with-braces-regexp)
6019 limit t)
6020 (let* ((pos (point)) table-p comment-p
6021 (mpos (match-beginning 3))
6022 (emph-p (get-text-property mpos 'org-emphasis))
6023 (link-p (get-text-property mpos 'mouse-face))
6024 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6025 (goto-char (point-at-bol))
6026 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6027 comment-p (org-looking-at-p "[ \t]*#"))
6028 (goto-char pos)
6029 ;; FIXME: Should we go back one character here, for a_b^c
6030 ;; (goto-char (1- pos)) ;????????????????????
6031 (if (or comment-p emph-p link-p keyw-p)
6033 (put-text-property (match-beginning 3) (match-end 0)
6034 'display
6035 (if (equal (char-after (match-beginning 2)) ?^)
6036 (nth (if table-p 3 1) org-script-display)
6037 (nth (if table-p 2 0) org-script-display)))
6038 (add-text-properties (match-beginning 2) (match-end 2)
6039 (list 'invisible t
6040 'org-dwidth t 'org-dwidth-n 1))
6041 (if (and (eq (char-after (match-beginning 3)) ?{)
6042 (eq (char-before (match-end 3)) ?}))
6043 (progn
6044 (add-text-properties
6045 (match-beginning 3) (1+ (match-beginning 3))
6046 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6047 (add-text-properties
6048 (1- (match-end 3)) (match-end 3)
6049 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6050 t)))))
6052 ;;;; Visibility cycling, including org-goto and indirect buffer
6054 ;;; Cycling
6056 (defvar org-cycle-global-status nil)
6057 (make-variable-buffer-local 'org-cycle-global-status)
6058 (defvar org-cycle-subtree-status nil)
6059 (make-variable-buffer-local 'org-cycle-subtree-status)
6061 (defvar org-inlinetask-min-level)
6063 ;;;###autoload
6064 (defun org-cycle (&optional arg)
6065 "TAB-action and visibility cycling for Org-mode.
6067 This is the command invoked in Org-mode by the TAB key. Its main purpose
6068 is outline visibility cycling, but it also invokes other actions
6069 in special contexts.
6071 - When this function is called with a prefix argument, rotate the entire
6072 buffer through 3 states (global cycling)
6073 1. OVERVIEW: Show only top-level headlines.
6074 2. CONTENTS: Show all headlines of all levels, but no body text.
6075 3. SHOW ALL: Show everything.
6076 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6077 determined by the variable `org-startup-folded', and by any VISIBILITY
6078 properties in the buffer.
6079 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6080 including any drawers.
6082 - When inside a table, re-align the table and move to the next field.
6084 - When point is at the beginning of a headline, rotate the subtree started
6085 by this line through 3 different states (local cycling)
6086 1. FOLDED: Only the main headline is shown.
6087 2. CHILDREN: The main headline and the direct children are shown.
6088 From this state, you can move to one of the children
6089 and zoom in further.
6090 3. SUBTREE: Show the entire subtree, including body text.
6091 If there is no subtree, switch directly from CHILDREN to FOLDED.
6093 - When point is at the beginning of an empty headline and the variable
6094 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6095 of the headline by demoting and promoting it to likely levels. This
6096 speeds up creation document structure by pressing TAB once or several
6097 times right after creating a new headline.
6099 - When there is a numeric prefix, go up to a heading with level ARG, do
6100 a `show-subtree' and return to the previous cursor position. If ARG
6101 is negative, go up that many levels.
6103 - When point is not at the beginning of a headline, execute the global
6104 binding for TAB, which is re-indenting the line. See the option
6105 `org-cycle-emulate-tab' for details.
6107 - Special case: if point is at the beginning of the buffer and there is
6108 no headline in line 1, this function will act as if called with prefix arg
6109 (C-u TAB, same as S-TAB) also when called without prefix arg.
6110 But only if also the variable `org-cycle-global-at-bob' is t."
6111 (interactive "P")
6112 (org-load-modules-maybe)
6113 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6114 (and org-cycle-level-after-item/entry-creation
6115 (or (org-cycle-level)
6116 (org-cycle-item-indentation))))
6117 (let* ((limit-level
6118 (or org-cycle-max-level
6119 (and (boundp 'org-inlinetask-min-level)
6120 org-inlinetask-min-level
6121 (1- org-inlinetask-min-level))))
6122 (nstars (and limit-level
6123 (if org-odd-levels-only
6124 (and limit-level (1- (* limit-level 2)))
6125 limit-level)))
6126 (org-outline-regexp
6127 (if (not (derived-mode-p 'org-mode))
6128 outline-regexp
6129 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6130 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6131 (not (looking-at org-outline-regexp))))
6132 (org-cycle-hook
6133 (if bob-special
6134 (delq 'org-optimize-window-after-visibility-change
6135 (copy-sequence org-cycle-hook))
6136 org-cycle-hook))
6137 (pos (point)))
6139 (if (or bob-special (equal arg '(4)))
6140 ;; special case: use global cycling
6141 (setq arg t))
6143 (cond
6145 ((equal arg '(16))
6146 (setq last-command 'dummy)
6147 (org-set-startup-visibility)
6148 (message "Startup visibility, plus VISIBILITY properties"))
6150 ((equal arg '(64))
6151 (show-all)
6152 (message "Entire buffer visible, including drawers"))
6154 ;; Table: enter it or move to the next field.
6155 ((org-at-table-p 'any)
6156 (if (org-at-table.el-p)
6157 (message "Use C-c ' to edit table.el tables")
6158 (if arg (org-table-edit-field t)
6159 (org-table-justify-field-maybe)
6160 (call-interactively 'org-table-next-field))))
6162 ((run-hook-with-args-until-success
6163 'org-tab-after-check-for-table-hook))
6165 ;; Global cycling: delegate to `org-cycle-internal-global'.
6166 ((eq arg t) (org-cycle-internal-global))
6168 ;; Drawers: delegate to `org-flag-drawer'.
6169 ((and org-drawers org-drawer-regexp
6170 (save-excursion
6171 (beginning-of-line 1)
6172 (looking-at org-drawer-regexp)))
6173 (org-flag-drawer ; toggle block visibility
6174 (not (get-char-property (match-end 0) 'invisible))))
6176 ;; Show-subtree, ARG levels up from here.
6177 ((integerp arg)
6178 (save-excursion
6179 (org-back-to-heading)
6180 (outline-up-heading (if (< arg 0) (- arg)
6181 (- (funcall outline-level) arg)))
6182 (org-show-subtree)))
6184 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6185 ((and (featurep 'org-inlinetask)
6186 (org-inlinetask-at-task-p)
6187 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6188 (org-inlinetask-toggle-visibility))
6190 ((org-try-cdlatex-tab))
6192 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6193 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6194 (save-excursion (beginning-of-line 1)
6195 (looking-at org-outline-regexp)))
6196 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6197 (org-cycle-internal-local))
6199 ;; From there: TAB emulation and template completion.
6200 (buffer-read-only (org-back-to-heading))
6202 ((run-hook-with-args-until-success
6203 'org-tab-after-check-for-cycling-hook))
6205 ((org-try-structure-completion))
6207 ((run-hook-with-args-until-success
6208 'org-tab-before-tab-emulation-hook))
6210 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6211 (or (not (bolp))
6212 (not (looking-at org-outline-regexp))))
6213 (call-interactively (global-key-binding "\t")))
6215 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6216 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6217 (or (and (eq org-cycle-emulate-tab 'white)
6218 (= (match-end 0) (point-at-eol)))
6219 (and (eq org-cycle-emulate-tab 'whitestart)
6220 (>= (match-end 0) pos))))
6222 (eq org-cycle-emulate-tab t))
6223 (call-interactively (global-key-binding "\t")))
6225 (t (save-excursion
6226 (org-back-to-heading)
6227 (org-cycle)))))))
6229 (defun org-cycle-internal-global ()
6230 "Do the global cycling action."
6231 ;; Hack to avoid display of messages for .org attachments in Gnus
6232 (let ((ga (string-match "\\*fontification" (buffer-name))))
6233 (cond
6234 ((and (eq last-command this-command)
6235 (eq org-cycle-global-status 'overview))
6236 ;; We just created the overview - now do table of contents
6237 ;; This can be slow in very large buffers, so indicate action
6238 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6239 (unless ga (message "CONTENTS..."))
6240 (org-content)
6241 (unless ga (message "CONTENTS...done"))
6242 (setq org-cycle-global-status 'contents)
6243 (run-hook-with-args 'org-cycle-hook 'contents))
6245 ((and (eq last-command this-command)
6246 (eq org-cycle-global-status 'contents))
6247 ;; We just showed the table of contents - now show everything
6248 (run-hook-with-args 'org-pre-cycle-hook 'all)
6249 (show-all)
6250 (unless ga (message "SHOW ALL"))
6251 (setq org-cycle-global-status 'all)
6252 (run-hook-with-args 'org-cycle-hook 'all))
6255 ;; Default action: go to overview
6256 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6257 (org-overview)
6258 (unless ga (message "OVERVIEW"))
6259 (setq org-cycle-global-status 'overview)
6260 (run-hook-with-args 'org-cycle-hook 'overview)))))
6262 (defun org-cycle-internal-local ()
6263 "Do the local cycling action."
6264 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6265 ;; First, determine end of headline (EOH), end of subtree or item
6266 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6267 (save-excursion
6268 (if (org-at-item-p)
6269 (progn
6270 (beginning-of-line)
6271 (setq struct (org-list-struct))
6272 (setq eoh (point-at-eol))
6273 (setq eos (org-list-get-item-end-before-blank (point) struct))
6274 (setq has-children (org-list-has-child-p (point) struct)))
6275 (org-back-to-heading)
6276 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6277 (setq eos (save-excursion
6278 (org-end-of-subtree t)
6279 (unless (eobp)
6280 (skip-chars-forward " \t\n"))
6281 (if (eobp) (point) (1- (point)))))
6282 (setq has-children
6283 (or (save-excursion
6284 (let ((level (funcall outline-level)))
6285 (outline-next-heading)
6286 (and (org-at-heading-p t)
6287 (> (funcall outline-level) level))))
6288 (save-excursion
6289 (org-list-search-forward (org-item-beginning-re) eos t)))))
6290 ;; Determine end invisible part of buffer (EOL)
6291 (beginning-of-line 2)
6292 ;; XEmacs doesn't have `next-single-char-property-change'
6293 (if (featurep 'xemacs)
6294 (while (and (not (eobp)) ;; this is like `next-line'
6295 (get-char-property (1- (point)) 'invisible))
6296 (beginning-of-line 2))
6297 (while (and (not (eobp)) ;; this is like `next-line'
6298 (get-char-property (1- (point)) 'invisible))
6299 (goto-char (next-single-char-property-change (point) 'invisible))
6300 (and (eolp) (beginning-of-line 2))))
6301 (setq eol (point)))
6302 ;; Find out what to do next and set `this-command'
6303 (cond
6304 ((= eos eoh)
6305 ;; Nothing is hidden behind this heading
6306 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6307 (message "EMPTY ENTRY")
6308 (setq org-cycle-subtree-status nil)
6309 (save-excursion
6310 (goto-char eos)
6311 (outline-next-heading)
6312 (if (outline-invisible-p) (org-flag-heading nil))))
6313 ((and (or (>= eol eos)
6314 (not (string-match "\\S-" (buffer-substring eol eos))))
6315 (or has-children
6316 (not (setq children-skipped
6317 org-cycle-skip-children-state-if-no-children))))
6318 ;; Entire subtree is hidden in one line: children view
6319 (run-hook-with-args 'org-pre-cycle-hook 'children)
6320 (if (org-at-item-p)
6321 (org-list-set-item-visibility (point-at-bol) struct 'children)
6322 (org-show-entry)
6323 (org-with-limited-levels (show-children))
6324 ;; FIXME: This slows down the func way too much.
6325 ;; How keep drawers hidden in subtree anyway?
6326 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6327 ;; (org-cycle-hide-drawers 'subtree))
6329 ;; Fold every list in subtree to top-level items.
6330 (when (eq org-cycle-include-plain-lists 'integrate)
6331 (save-excursion
6332 (org-back-to-heading)
6333 (while (org-list-search-forward (org-item-beginning-re) eos t)
6334 (beginning-of-line 1)
6335 (let* ((struct (org-list-struct))
6336 (prevs (org-list-prevs-alist struct))
6337 (end (org-list-get-bottom-point struct)))
6338 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6339 (org-list-get-all-items (point) struct prevs))
6340 (goto-char end))))))
6341 (message "CHILDREN")
6342 (save-excursion
6343 (goto-char eos)
6344 (outline-next-heading)
6345 (if (outline-invisible-p) (org-flag-heading nil)))
6346 (setq org-cycle-subtree-status 'children)
6347 (run-hook-with-args 'org-cycle-hook 'children))
6348 ((or children-skipped
6349 (and (eq last-command this-command)
6350 (eq org-cycle-subtree-status 'children)))
6351 ;; We just showed the children, or no children are there,
6352 ;; now show everything.
6353 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6354 (outline-flag-region eoh eos nil)
6355 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6356 (setq org-cycle-subtree-status 'subtree)
6357 (run-hook-with-args 'org-cycle-hook 'subtree))
6359 ;; Default action: hide the subtree.
6360 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6361 (outline-flag-region eoh eos t)
6362 (message "FOLDED")
6363 (setq org-cycle-subtree-status 'folded)
6364 (run-hook-with-args 'org-cycle-hook 'folded)))))
6366 ;;;###autoload
6367 (defun org-global-cycle (&optional arg)
6368 "Cycle the global visibility. For details see `org-cycle'.
6369 With \\[universal-argument] prefix arg, switch to startup visibility.
6370 With a numeric prefix, show all headlines up to that level."
6371 (interactive "P")
6372 (let ((org-cycle-include-plain-lists
6373 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6374 (cond
6375 ((integerp arg)
6376 (show-all)
6377 (hide-sublevels arg)
6378 (setq org-cycle-global-status 'contents))
6379 ((equal arg '(4))
6380 (org-set-startup-visibility)
6381 (message "Startup visibility, plus VISIBILITY properties."))
6383 (org-cycle '(4))))))
6385 (defun org-set-startup-visibility ()
6386 "Set the visibility required by startup options and properties."
6387 (cond
6388 ((eq org-startup-folded t)
6389 (org-cycle '(4)))
6390 ((eq org-startup-folded 'content)
6391 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6392 (org-cycle '(4)) (org-cycle '(4)))))
6393 (unless (eq org-startup-folded 'showeverything)
6394 (if org-hide-block-startup (org-hide-block-all))
6395 (org-set-visibility-according-to-property 'no-cleanup)
6396 (org-cycle-hide-archived-subtrees 'all)
6397 (org-cycle-hide-drawers 'all)
6398 (org-cycle-show-empty-lines t)))
6400 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6401 "Switch subtree visibilities according to :VISIBILITY: property."
6402 (interactive)
6403 (let (org-show-entry-below state)
6404 (save-excursion
6405 (goto-char (point-min))
6406 (while (re-search-forward
6407 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6408 nil t)
6409 (setq state (match-string 1))
6410 (save-excursion
6411 (org-back-to-heading t)
6412 (hide-subtree)
6413 (org-reveal)
6414 (cond
6415 ((equal state '("fold" "folded"))
6416 (hide-subtree))
6417 ((equal state "children")
6418 (org-show-hidden-entry)
6419 (show-children))
6420 ((equal state "content")
6421 (save-excursion
6422 (save-restriction
6423 (org-narrow-to-subtree)
6424 (org-content))))
6425 ((member state '("all" "showall"))
6426 (show-subtree)))))
6427 (unless no-cleanup
6428 (org-cycle-hide-archived-subtrees 'all)
6429 (org-cycle-hide-drawers 'all)
6430 (org-cycle-show-empty-lines 'all)))))
6432 ;; This function uses outline-regexp instead of the more fundamental
6433 ;; org-outline-regexp so that org-cycle-global works outside of Org
6434 ;; buffers, where outline-regexp is needed.
6435 (defun org-overview ()
6436 "Switch to overview mode, showing only top-level headlines.
6437 Really, this shows all headlines with level equal or greater than the level
6438 of the first headline in the buffer. This is important, because if the
6439 first headline is not level one, then (hide-sublevels 1) gives confusing
6440 results."
6441 (interactive)
6442 (let ((level (save-excursion
6443 (goto-char (point-min))
6444 (if (re-search-forward (concat "^" outline-regexp) nil t)
6445 (progn
6446 (goto-char (match-beginning 0))
6447 (funcall outline-level))))))
6448 (and level (hide-sublevels level))))
6450 (defun org-content (&optional arg)
6451 "Show all headlines in the buffer, like a table of contents.
6452 With numerical argument N, show content up to level N."
6453 (interactive "P")
6454 (save-excursion
6455 ;; Visit all headings and show their offspring
6456 (and (integerp arg) (org-overview))
6457 (goto-char (point-max))
6458 (catch 'exit
6459 (while (and (progn (condition-case nil
6460 (outline-previous-visible-heading 1)
6461 (error (goto-char (point-min))))
6463 (looking-at org-outline-regexp))
6464 (if (integerp arg)
6465 (show-children (1- arg))
6466 (show-branches))
6467 (if (bobp) (throw 'exit nil))))))
6470 (defun org-optimize-window-after-visibility-change (state)
6471 "Adjust the window after a change in outline visibility.
6472 This function is the default value of the hook `org-cycle-hook'."
6473 (when (get-buffer-window (current-buffer))
6474 (cond
6475 ((eq state 'content) nil)
6476 ((eq state 'all) nil)
6477 ((eq state 'folded) nil)
6478 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6479 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6481 (defun org-remove-empty-overlays-at (pos)
6482 "Remove outline overlays that do not contain non-white stuff."
6483 (mapc
6484 (lambda (o)
6485 (and (eq 'outline (overlay-get o 'invisible))
6486 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6487 (overlay-end o))))
6488 (delete-overlay o)))
6489 (overlays-at pos)))
6491 (defun org-clean-visibility-after-subtree-move ()
6492 "Fix visibility issues after moving a subtree."
6493 ;; First, find a reasonable region to look at:
6494 ;; Start two siblings above, end three below
6495 (let* ((beg (save-excursion
6496 (and (org-get-last-sibling)
6497 (org-get-last-sibling))
6498 (point)))
6499 (end (save-excursion
6500 (and (org-get-next-sibling)
6501 (org-get-next-sibling)
6502 (org-get-next-sibling))
6503 (if (org-at-heading-p)
6504 (point-at-eol)
6505 (point))))
6506 (level (looking-at "\\*+"))
6507 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6508 (save-excursion
6509 (save-restriction
6510 (narrow-to-region beg end)
6511 (when re
6512 ;; Properly fold already folded siblings
6513 (goto-char (point-min))
6514 (while (re-search-forward re nil t)
6515 (if (and (not (outline-invisible-p))
6516 (save-excursion
6517 (goto-char (point-at-eol)) (outline-invisible-p)))
6518 (hide-entry))))
6519 (org-cycle-show-empty-lines 'overview)
6520 (org-cycle-hide-drawers 'overview)))))
6522 (defun org-cycle-show-empty-lines (state)
6523 "Show empty lines above all visible headlines.
6524 The region to be covered depends on STATE when called through
6525 `org-cycle-hook'. Lisp program can use t for STATE to get the
6526 entire buffer covered. Note that an empty line is only shown if there
6527 are at least `org-cycle-separator-lines' empty lines before the headline."
6528 (when (not (= org-cycle-separator-lines 0))
6529 (save-excursion
6530 (let* ((n (abs org-cycle-separator-lines))
6531 (re (cond
6532 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6533 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6534 (t (let ((ns (number-to-string (- n 2))))
6535 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6536 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6537 beg end b e)
6538 (cond
6539 ((memq state '(overview contents t))
6540 (setq beg (point-min) end (point-max)))
6541 ((memq state '(children folded))
6542 (setq beg (point) end (progn (org-end-of-subtree t t)
6543 (beginning-of-line 2)
6544 (point)))))
6545 (when beg
6546 (goto-char beg)
6547 (while (re-search-forward re end t)
6548 (unless (get-char-property (match-end 1) 'invisible)
6549 (setq e (match-end 1))
6550 (if (< org-cycle-separator-lines 0)
6551 (setq b (save-excursion
6552 (goto-char (match-beginning 0))
6553 (org-back-over-empty-lines)
6554 (if (save-excursion
6555 (goto-char (max (point-min) (1- (point))))
6556 (org-at-heading-p))
6557 (1- (point))
6558 (point))))
6559 (setq b (match-beginning 1)))
6560 (outline-flag-region b e nil)))))))
6561 ;; Never hide empty lines at the end of the file.
6562 (save-excursion
6563 (goto-char (point-max))
6564 (outline-previous-heading)
6565 (outline-end-of-heading)
6566 (if (and (looking-at "[ \t\n]+")
6567 (= (match-end 0) (point-max)))
6568 (outline-flag-region (point) (match-end 0) nil))))
6570 (defun org-show-empty-lines-in-parent ()
6571 "Move to the parent and re-show empty lines before visible headlines."
6572 (save-excursion
6573 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6574 (org-cycle-show-empty-lines context))))
6576 (defun org-files-list ()
6577 "Return `org-agenda-files' list, plus all open org-mode files.
6578 This is useful for operations that need to scan all of a user's
6579 open and agenda-wise Org files."
6580 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6581 (dolist (buf (buffer-list))
6582 (with-current-buffer buf
6583 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6584 (let ((file (expand-file-name (buffer-file-name))))
6585 (unless (member file files)
6586 (push file files))))))
6587 files))
6589 (defsubst org-entry-beginning-position ()
6590 "Return the beginning position of the current entry."
6591 (save-excursion (outline-back-to-heading t) (point)))
6593 (defsubst org-entry-end-position ()
6594 "Return the end position of the current entry."
6595 (save-excursion (outline-next-heading) (point)))
6597 (defun org-cycle-hide-drawers (state)
6598 "Re-hide all drawers after a visibility state change."
6599 (when (and (derived-mode-p 'org-mode)
6600 (not (memq state '(overview folded contents))))
6601 (save-excursion
6602 (let* ((globalp (memq state '(contents all)))
6603 (beg (if globalp (point-min) (point)))
6604 (end (if globalp (point-max)
6605 (if (eq state 'children)
6606 (save-excursion (outline-next-heading) (point))
6607 (org-end-of-subtree t)))))
6608 (goto-char beg)
6609 (while (re-search-forward org-drawer-regexp end t)
6610 (org-flag-drawer t))))))
6612 (defun org-cycle-hide-inline-tasks (state)
6613 "Re-hide inline task when switching to 'contents visibility state."
6614 (when (and (eq state 'contents)
6615 (boundp 'org-inlinetask-min-level)
6616 org-inlinetask-min-level)
6617 (hide-sublevels (1- org-inlinetask-min-level))))
6619 (defun org-flag-drawer (flag)
6620 "When FLAG is non-nil, hide the drawer we are within.
6621 Otherwise make it visible."
6622 (save-excursion
6623 (beginning-of-line 1)
6624 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6625 (let ((b (match-end 0)))
6626 (if (re-search-forward
6627 "^[ \t]*:END:"
6628 (save-excursion (outline-next-heading) (point)) t)
6629 (outline-flag-region b (point-at-eol) flag)
6630 (error ":END: line missing at position %s" b))))))
6632 (defun org-subtree-end-visible-p ()
6633 "Is the end of the current subtree visible?"
6634 (pos-visible-in-window-p
6635 (save-excursion (org-end-of-subtree t) (point))))
6637 (defun org-first-headline-recenter (&optional N)
6638 "Move cursor to the first headline and recenter the headline.
6639 Optional argument N means put the headline into the Nth line of the window."
6640 (goto-char (point-min))
6641 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6642 (beginning-of-line)
6643 (recenter (prefix-numeric-value N))))
6645 ;;; Saving and restoring visibility
6647 (defun org-outline-overlay-data (&optional use-markers)
6648 "Return a list of the locations of all outline overlays.
6649 These are overlays with the `invisible' property value `outline'.
6650 The return value is a list of cons cells, with start and stop
6651 positions for each overlay.
6652 If USE-MARKERS is set, return the positions as markers."
6653 (let (beg end)
6654 (save-excursion
6655 (save-restriction
6656 (widen)
6657 (delq nil
6658 (mapcar (lambda (o)
6659 (when (eq (overlay-get o 'invisible) 'outline)
6660 (setq beg (overlay-start o)
6661 end (overlay-end o))
6662 (and beg end (> end beg)
6663 (if use-markers
6664 (cons (move-marker (make-marker) beg)
6665 (move-marker (make-marker) end))
6666 (cons beg end)))))
6667 (overlays-in (point-min) (point-max))))))))
6669 (defun org-set-outline-overlay-data (data)
6670 "Create visibility overlays for all positions in DATA.
6671 DATA should have been made by `org-outline-overlay-data'."
6672 (let (o)
6673 (save-excursion
6674 (save-restriction
6675 (widen)
6676 (show-all)
6677 (mapc (lambda (c)
6678 (outline-flag-region (car c) (cdr c) t))
6679 data)))))
6681 ;;; Folding of blocks
6683 (defvar org-hide-block-overlays nil
6684 "Overlays hiding blocks.")
6685 (make-variable-buffer-local 'org-hide-block-overlays)
6687 (defun org-block-map (function &optional start end)
6688 "Call FUNCTION at the head of all source blocks in the current buffer.
6689 Optional arguments START and END can be used to limit the range."
6690 (let ((start (or start (point-min)))
6691 (end (or end (point-max))))
6692 (save-excursion
6693 (goto-char start)
6694 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6695 (save-excursion
6696 (save-match-data
6697 (goto-char (match-beginning 0))
6698 (funcall function)))))))
6700 (defun org-hide-block-toggle-all ()
6701 "Toggle the visibility of all blocks in the current buffer."
6702 (org-block-map #'org-hide-block-toggle))
6704 (defun org-hide-block-all ()
6705 "Fold all blocks in the current buffer."
6706 (interactive)
6707 (org-show-block-all)
6708 (org-block-map #'org-hide-block-toggle-maybe))
6710 (defun org-show-block-all ()
6711 "Unfold all blocks in the current buffer."
6712 (interactive)
6713 (mapc 'delete-overlay org-hide-block-overlays)
6714 (setq org-hide-block-overlays nil))
6716 (defun org-hide-block-toggle-maybe ()
6717 "Toggle visibility of block at point."
6718 (interactive)
6719 (let ((case-fold-search t))
6720 (if (save-excursion
6721 (beginning-of-line 1)
6722 (looking-at org-block-regexp))
6723 (progn (org-hide-block-toggle)
6724 t) ;; to signal that we took action
6725 nil))) ;; to signal that we did not
6727 (defun org-hide-block-toggle (&optional force)
6728 "Toggle the visibility of the current block."
6729 (interactive)
6730 (save-excursion
6731 (beginning-of-line)
6732 (if (re-search-forward org-block-regexp nil t)
6733 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6734 (end (match-end 0)) ;; end of entire body
6736 (if (memq t (mapcar (lambda (overlay)
6737 (eq (overlay-get overlay 'invisible)
6738 'org-hide-block))
6739 (overlays-at start)))
6740 (if (or (not force) (eq force 'off))
6741 (mapc (lambda (ov)
6742 (when (member ov org-hide-block-overlays)
6743 (setq org-hide-block-overlays
6744 (delq ov org-hide-block-overlays)))
6745 (when (eq (overlay-get ov 'invisible)
6746 'org-hide-block)
6747 (delete-overlay ov)))
6748 (overlays-at start)))
6749 (setq ov (make-overlay start end))
6750 (overlay-put ov 'invisible 'org-hide-block)
6751 ;; make the block accessible to isearch
6752 (overlay-put
6753 ov 'isearch-open-invisible
6754 (lambda (ov)
6755 (when (member ov org-hide-block-overlays)
6756 (setq org-hide-block-overlays
6757 (delq ov org-hide-block-overlays)))
6758 (when (eq (overlay-get ov 'invisible)
6759 'org-hide-block)
6760 (delete-overlay ov))))
6761 (push ov org-hide-block-overlays)))
6762 (error "Not looking at a source block"))))
6764 ;; org-tab-after-check-for-cycling-hook
6765 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6766 ;; Remove overlays when changing major mode
6767 (add-hook 'org-mode-hook
6768 (lambda () (org-add-hook 'change-major-mode-hook
6769 'org-show-block-all 'append 'local)))
6771 ;;; Org-goto
6773 (defvar org-goto-window-configuration nil)
6774 (defvar org-goto-marker nil)
6775 (defvar org-goto-map
6776 (let ((map (make-sparse-keymap)))
6777 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6778 (while (setq cmd (pop cmds))
6779 (substitute-key-definition cmd cmd map global-map)))
6780 (suppress-keymap map)
6781 (org-defkey map "\C-m" 'org-goto-ret)
6782 (org-defkey map [(return)] 'org-goto-ret)
6783 (org-defkey map [(left)] 'org-goto-left)
6784 (org-defkey map [(right)] 'org-goto-right)
6785 (org-defkey map [(control ?g)] 'org-goto-quit)
6786 (org-defkey map "\C-i" 'org-cycle)
6787 (org-defkey map [(tab)] 'org-cycle)
6788 (org-defkey map [(down)] 'outline-next-visible-heading)
6789 (org-defkey map [(up)] 'outline-previous-visible-heading)
6790 (if org-goto-auto-isearch
6791 (if (fboundp 'define-key-after)
6792 (define-key-after map [t] 'org-goto-local-auto-isearch)
6793 nil)
6794 (org-defkey map "q" 'org-goto-quit)
6795 (org-defkey map "n" 'outline-next-visible-heading)
6796 (org-defkey map "p" 'outline-previous-visible-heading)
6797 (org-defkey map "f" 'outline-forward-same-level)
6798 (org-defkey map "b" 'outline-backward-same-level)
6799 (org-defkey map "u" 'outline-up-heading))
6800 (org-defkey map "/" 'org-occur)
6801 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6802 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6803 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6804 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6805 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6806 map))
6808 (defconst org-goto-help
6809 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6810 RET=jump to location [Q]uit and return to previous location
6811 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6813 (defvar org-goto-start-pos) ; dynamically scoped parameter
6815 ;; FIXME: Docstring does not mention both interfaces
6816 (defun org-goto (&optional alternative-interface)
6817 "Look up a different location in the current file, keeping current visibility.
6819 When you want look-up or go to a different location in a
6820 document, the fastest way is often to fold the entire buffer and
6821 then dive into the tree. This method has the disadvantage, that
6822 the previous location will be folded, which may not be what you
6823 want.
6825 This command works around this by showing a copy of the current
6826 buffer in an indirect buffer, in overview mode. You can dive
6827 into the tree in that copy, use org-occur and incremental search
6828 to find a location. When pressing RET or `Q', the command
6829 returns to the original buffer in which the visibility is still
6830 unchanged. After RET it will also jump to the location selected
6831 in the indirect buffer and expose the headline hierarchy above.
6833 With a prefix argument, use the alternative interface: e.g. if
6834 `org-goto-interface' is 'outline use 'outline-path-completion."
6835 (interactive "P")
6836 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6837 (org-refile-use-outline-path t)
6838 (org-refile-target-verify-function nil)
6839 (interface
6840 (if (not alternative-interface)
6841 org-goto-interface
6842 (if (eq org-goto-interface 'outline)
6843 'outline-path-completion
6844 'outline)))
6845 (org-goto-start-pos (point))
6846 (selected-point
6847 (if (eq interface 'outline)
6848 (car (org-get-location (current-buffer) org-goto-help))
6849 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6850 (org-refile-check-position pa)
6851 (nth 3 pa)))))
6852 (if selected-point
6853 (progn
6854 (org-mark-ring-push org-goto-start-pos)
6855 (goto-char selected-point)
6856 (if (or (outline-invisible-p) (org-invisible-p2))
6857 (org-show-context 'org-goto)))
6858 (message "Quit"))))
6860 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6861 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6862 (defvar org-goto-local-auto-isearch-map) ; defined below
6864 (defun org-get-location (buf help)
6865 "Let the user select a location in the Org-mode buffer BUF.
6866 This function uses a recursive edit. It returns the selected position
6867 or nil."
6868 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6869 (isearch-hide-immediately nil)
6870 (isearch-search-fun-function
6871 (lambda () 'org-goto-local-search-headings))
6872 (org-goto-selected-point org-goto-exit-command)
6873 (pop-up-frames nil)
6874 (special-display-buffer-names nil)
6875 (special-display-regexps nil)
6876 (special-display-function nil))
6877 (save-excursion
6878 (save-window-excursion
6879 (delete-other-windows)
6880 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6881 (org-pop-to-buffer-same-window
6882 (condition-case nil
6883 (make-indirect-buffer (current-buffer) "*org-goto*")
6884 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6885 (with-output-to-temp-buffer "*Help*"
6886 (princ help))
6887 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6888 (setq buffer-read-only nil)
6889 (let ((org-startup-truncated t)
6890 (org-startup-folded nil)
6891 (org-startup-align-all-tables nil))
6892 (org-mode)
6893 (org-overview))
6894 (setq buffer-read-only t)
6895 (if (and (boundp 'org-goto-start-pos)
6896 (integer-or-marker-p org-goto-start-pos))
6897 (let ((org-show-hierarchy-above t)
6898 (org-show-siblings t)
6899 (org-show-following-heading t))
6900 (goto-char org-goto-start-pos)
6901 (and (outline-invisible-p) (org-show-context)))
6902 (goto-char (point-min)))
6903 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6904 (message "Select location and press RET")
6905 (use-local-map org-goto-map)
6906 (recursive-edit)
6908 (kill-buffer "*org-goto*")
6909 (cons org-goto-selected-point org-goto-exit-command)))
6911 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6912 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6913 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6914 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6916 (defun org-goto-local-search-headings (string bound noerror)
6917 "Search and make sure that any matches are in headlines."
6918 (catch 'return
6919 (while (if isearch-forward
6920 (search-forward string bound noerror)
6921 (search-backward string bound noerror))
6922 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6923 (and (member :headline context)
6924 (not (member :tags context))))
6925 (throw 'return (point))))))
6927 (defun org-goto-local-auto-isearch ()
6928 "Start isearch."
6929 (interactive)
6930 (goto-char (point-min))
6931 (let ((keys (this-command-keys)))
6932 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6933 (isearch-mode t)
6934 (isearch-process-search-char (string-to-char keys)))))
6936 (defun org-goto-ret (&optional arg)
6937 "Finish `org-goto' by going to the new location."
6938 (interactive "P")
6939 (setq org-goto-selected-point (point)
6940 org-goto-exit-command 'return)
6941 (throw 'exit nil))
6943 (defun org-goto-left ()
6944 "Finish `org-goto' by going to the new location."
6945 (interactive)
6946 (if (org-at-heading-p)
6947 (progn
6948 (beginning-of-line 1)
6949 (setq org-goto-selected-point (point)
6950 org-goto-exit-command 'left)
6951 (throw 'exit nil))
6952 (error "Not on a heading")))
6954 (defun org-goto-right ()
6955 "Finish `org-goto' by going to the new location."
6956 (interactive)
6957 (if (org-at-heading-p)
6958 (progn
6959 (setq org-goto-selected-point (point)
6960 org-goto-exit-command 'right)
6961 (throw 'exit nil))
6962 (error "Not on a heading")))
6964 (defun org-goto-quit ()
6965 "Finish `org-goto' without cursor motion."
6966 (interactive)
6967 (setq org-goto-selected-point nil)
6968 (setq org-goto-exit-command 'quit)
6969 (throw 'exit nil))
6971 ;;; Indirect buffer display of subtrees
6973 (defvar org-indirect-dedicated-frame nil
6974 "This is the frame being used for indirect tree display.")
6975 (defvar org-last-indirect-buffer nil)
6977 (defun org-tree-to-indirect-buffer (&optional arg)
6978 "Create indirect buffer and narrow it to current subtree.
6979 With a numerical prefix ARG, go up to this level and then take that tree.
6980 If ARG is negative, go up that many levels.
6982 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6983 indirect buffer previously made with this command, to avoid proliferation of
6984 indirect buffers. However, when you call the command with a \
6985 \\[universal-argument] prefix, or
6986 when `org-indirect-buffer-display' is `new-frame', the last buffer
6987 is kept so that you can work with several indirect buffers at the same time.
6988 If `org-indirect-buffer-display' is `dedicated-frame', the \
6989 \\[universal-argument] prefix also
6990 requests that a new frame be made for the new buffer, so that the dedicated
6991 frame is not changed."
6992 (interactive "P")
6993 (let ((cbuf (current-buffer))
6994 (cwin (selected-window))
6995 (pos (point))
6996 beg end level heading ibuf)
6997 (save-excursion
6998 (org-back-to-heading t)
6999 (when (numberp arg)
7000 (setq level (org-outline-level))
7001 (if (< arg 0) (setq arg (+ level arg)))
7002 (while (> (setq level (org-outline-level)) arg)
7003 (org-up-heading-safe)))
7004 (setq beg (point)
7005 heading (org-get-heading))
7006 (org-end-of-subtree t t)
7007 (if (org-at-heading-p) (backward-char 1))
7008 (setq end (point)))
7009 (if (and (buffer-live-p org-last-indirect-buffer)
7010 (not (eq org-indirect-buffer-display 'new-frame))
7011 (not arg))
7012 (kill-buffer org-last-indirect-buffer))
7013 (setq ibuf (org-get-indirect-buffer cbuf)
7014 org-last-indirect-buffer ibuf)
7015 (cond
7016 ((or (eq org-indirect-buffer-display 'new-frame)
7017 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7018 (select-frame (make-frame))
7019 (delete-other-windows)
7020 (org-pop-to-buffer-same-window ibuf)
7021 (org-set-frame-title heading))
7022 ((eq org-indirect-buffer-display 'dedicated-frame)
7023 (raise-frame
7024 (select-frame (or (and org-indirect-dedicated-frame
7025 (frame-live-p org-indirect-dedicated-frame)
7026 org-indirect-dedicated-frame)
7027 (setq org-indirect-dedicated-frame (make-frame)))))
7028 (delete-other-windows)
7029 (org-pop-to-buffer-same-window ibuf)
7030 (org-set-frame-title (concat "Indirect: " heading)))
7031 ((eq org-indirect-buffer-display 'current-window)
7032 (org-pop-to-buffer-same-window ibuf))
7033 ((eq org-indirect-buffer-display 'other-window)
7034 (pop-to-buffer ibuf))
7035 (t (error "Invalid value")))
7036 (if (featurep 'xemacs)
7037 (save-excursion (org-mode) (turn-on-font-lock)))
7038 (narrow-to-region beg end)
7039 (show-all)
7040 (goto-char pos)
7041 (run-hook-with-args 'org-cycle-hook 'all)
7042 (and (window-live-p cwin) (select-window cwin))))
7044 (defun org-get-indirect-buffer (&optional buffer)
7045 (setq buffer (or buffer (current-buffer)))
7046 (let ((n 1) (base (buffer-name buffer)) bname)
7047 (while (buffer-live-p
7048 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7049 (setq n (1+ n)))
7050 (condition-case nil
7051 (make-indirect-buffer buffer bname 'clone)
7052 (error (make-indirect-buffer buffer bname)))))
7054 (defun org-set-frame-title (title)
7055 "Set the title of the current frame to the string TITLE."
7056 ;; FIXME: how to name a single frame in XEmacs???
7057 (unless (featurep 'xemacs)
7058 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7060 ;;;; Structure editing
7062 ;;; Inserting headlines
7064 (defun org-previous-line-empty-p ()
7065 (save-excursion
7066 (and (not (bobp))
7067 (or (beginning-of-line 0) t)
7068 (save-match-data
7069 (looking-at "[ \t]*$")))))
7071 (defun org-insert-heading (&optional force-heading invisible-ok)
7072 "Insert a new heading or item with same depth at point.
7073 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7074 If point is at the beginning of a headline, insert a sibling before the
7075 current headline. If point is not at the beginning, split the line,
7076 create the new headline with the text in the current line after point
7077 \(but see also the variable `org-M-RET-may-split-line').
7079 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7080 This is important for non-interactive uses of the command."
7081 (interactive "P")
7082 (if (or (= (buffer-size) 0)
7083 (and (not (save-excursion
7084 (and (ignore-errors (org-back-to-heading invisible-ok))
7085 (org-at-heading-p))))
7086 (or force-heading (not (org-in-item-p)))))
7087 (progn
7088 (insert "\n* ")
7089 (run-hooks 'org-insert-heading-hook))
7090 (when (or force-heading (not (org-insert-item)))
7091 (let* ((empty-line-p nil)
7092 (level nil)
7093 (on-heading (org-at-heading-p))
7094 (head (save-excursion
7095 (condition-case nil
7096 (progn
7097 (org-back-to-heading invisible-ok)
7098 (when (and (not on-heading)
7099 (featurep 'org-inlinetask)
7100 (integerp org-inlinetask-min-level)
7101 (>= (length (match-string 0))
7102 org-inlinetask-min-level))
7103 ;; Find a heading level before the inline task
7104 (while (and (setq level (org-up-heading-safe))
7105 (>= level org-inlinetask-min-level)))
7106 (if (org-at-heading-p)
7107 (org-back-to-heading invisible-ok)
7108 (error "This should not happen")))
7109 (setq empty-line-p (org-previous-line-empty-p))
7110 (match-string 0))
7111 (error "*"))))
7112 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7113 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7114 pos hide-previous previous-pos)
7115 (cond
7116 ((and (org-at-heading-p) (bolp)
7117 (or (bobp)
7118 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7119 ;; insert before the current line
7120 (open-line (if blank 2 1)))
7121 ((and (bolp)
7122 (not org-insert-heading-respect-content)
7123 (or (bobp)
7124 (save-excursion
7125 (backward-char 1) (not (outline-invisible-p)))))
7126 ;; insert right here
7127 nil)
7129 ;; somewhere in the line
7130 (save-excursion
7131 (setq previous-pos (point-at-bol))
7132 (end-of-line)
7133 (setq hide-previous (outline-invisible-p)))
7134 (and org-insert-heading-respect-content (org-show-subtree))
7135 (let ((split
7136 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7137 (save-excursion
7138 (let ((p (point)))
7139 (goto-char (point-at-bol))
7140 (and (looking-at org-complex-heading-regexp)
7141 (match-beginning 4)
7142 (> p (match-beginning 4)))))))
7143 tags pos)
7144 (cond
7145 (org-insert-heading-respect-content
7146 (org-end-of-subtree nil t)
7147 (when (featurep 'org-inlinetask)
7148 (while (and (not (eobp))
7149 (looking-at "\\(\\*+\\)[ \t]+")
7150 (>= (length (match-string 1))
7151 org-inlinetask-min-level))
7152 (org-end-of-subtree nil t)))
7153 (or (bolp) (newline))
7154 (or (org-previous-line-empty-p)
7155 (and blank (newline)))
7156 (open-line 1))
7157 ((org-at-heading-p)
7158 (when hide-previous
7159 (show-children)
7160 (org-show-entry))
7161 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7162 (setq tags (and (match-end 2) (match-string 2)))
7163 (and (match-end 1)
7164 (delete-region (match-beginning 1) (match-end 1)))
7165 (setq pos (point-at-bol))
7166 (or split (end-of-line 1))
7167 (delete-horizontal-space)
7168 (if (string-match "\\`\\*+\\'"
7169 (buffer-substring (point-at-bol) (point)))
7170 (insert " "))
7171 (newline (if blank 2 1))
7172 (when tags
7173 (save-excursion
7174 (goto-char pos)
7175 (end-of-line 1)
7176 (insert " " tags)
7177 (org-set-tags nil 'align))))
7179 (or split (end-of-line 1))
7180 (newline (if blank 2 1)))))))
7181 (insert head) (just-one-space)
7182 (setq pos (point))
7183 (end-of-line 1)
7184 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7185 (when (and org-insert-heading-respect-content hide-previous)
7186 (save-excursion
7187 (goto-char previous-pos)
7188 (hide-subtree)))
7189 (run-hooks 'org-insert-heading-hook)))))
7191 (defun org-get-heading (&optional no-tags no-todo)
7192 "Return the heading of the current entry, without the stars.
7193 When NO-TAGS is non-nil, don't include tags.
7194 When NO-TODO is non-nil, don't include TODO keywords."
7195 (save-excursion
7196 (org-back-to-heading t)
7197 (cond
7198 ((and no-tags no-todo)
7199 (looking-at org-complex-heading-regexp)
7200 (match-string 4))
7201 (no-tags
7202 (looking-at (concat org-outline-regexp
7203 "\\(.*?\\)"
7204 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7205 (match-string 1))
7206 (no-todo
7207 (looking-at org-todo-line-regexp)
7208 (match-string 3))
7209 (t (looking-at org-heading-regexp)
7210 (match-string 2)))))
7212 (defun org-heading-components ()
7213 "Return the components of the current heading.
7214 This is a list with the following elements:
7215 - the level as an integer
7216 - the reduced level, different if `org-odd-levels-only' is set.
7217 - the TODO keyword, or nil
7218 - the priority character, like ?A, or nil if no priority is given
7219 - the headline text itself, or the tags string if no headline text
7220 - the tags string, or nil."
7221 (save-excursion
7222 (org-back-to-heading t)
7223 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7224 (list (length (match-string 1))
7225 (org-reduced-level (length (match-string 1)))
7226 (org-match-string-no-properties 2)
7227 (and (match-end 3) (aref (match-string 3) 2))
7228 (org-match-string-no-properties 4)
7229 (org-match-string-no-properties 5)))))
7231 (defun org-get-entry ()
7232 "Get the entry text, after heading, entire subtree."
7233 (save-excursion
7234 (org-back-to-heading t)
7235 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7237 (defun org-insert-heading-after-current ()
7238 "Insert a new heading with same level as current, after current subtree."
7239 (interactive)
7240 (org-back-to-heading)
7241 (org-insert-heading)
7242 (org-move-subtree-down)
7243 (end-of-line 1))
7245 (defun org-insert-heading-respect-content ()
7246 (interactive)
7247 (let ((org-insert-heading-respect-content t))
7248 (org-insert-heading t)))
7250 (defun org-insert-todo-heading-respect-content (&optional force-state)
7251 (interactive "P")
7252 (let ((org-insert-heading-respect-content t))
7253 (org-insert-todo-heading force-state t)))
7255 (defun org-insert-todo-heading (arg &optional force-heading)
7256 "Insert a new heading with the same level and TODO state as current heading.
7257 If the heading has no TODO state, or if the state is DONE, use the first
7258 state (TODO by default). Also with prefix arg, force first state."
7259 (interactive "P")
7260 (when (or force-heading (not (org-insert-item 'checkbox)))
7261 (org-insert-heading force-heading)
7262 (save-excursion
7263 (org-back-to-heading)
7264 (outline-previous-heading)
7265 (looking-at org-todo-line-regexp))
7266 (let*
7267 ((new-mark-x
7268 (if (or arg
7269 (not (match-beginning 2))
7270 (member (match-string 2) org-done-keywords))
7271 (car org-todo-keywords-1)
7272 (match-string 2)))
7273 (new-mark
7275 (run-hook-with-args-until-success
7276 'org-todo-get-default-hook new-mark-x nil)
7277 new-mark-x)))
7278 (beginning-of-line 1)
7279 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7280 (if org-treat-insert-todo-heading-as-state-change
7281 (org-todo new-mark)
7282 (insert new-mark " "))))
7283 (when org-provide-todo-statistics
7284 (org-update-parent-todo-statistics))))
7286 (defun org-insert-subheading (arg)
7287 "Insert a new subheading and demote it.
7288 Works for outline headings and for plain lists alike."
7289 (interactive "P")
7290 (org-insert-heading arg)
7291 (cond
7292 ((org-at-heading-p) (org-do-demote))
7293 ((org-at-item-p) (org-indent-item))))
7295 (defun org-insert-todo-subheading (arg)
7296 "Insert a new subheading with TODO keyword or checkbox and demote it.
7297 Works for outline headings and for plain lists alike."
7298 (interactive "P")
7299 (org-insert-todo-heading arg)
7300 (cond
7301 ((org-at-heading-p) (org-do-demote))
7302 ((org-at-item-p) (org-indent-item))))
7304 ;;; Promotion and Demotion
7306 (defvar org-after-demote-entry-hook nil
7307 "Hook run after an entry has been demoted.
7308 The cursor will be at the beginning of the entry.
7309 When a subtree is being demoted, the hook will be called for each node.")
7311 (defvar org-after-promote-entry-hook nil
7312 "Hook run after an entry has been promoted.
7313 The cursor will be at the beginning of the entry.
7314 When a subtree is being promoted, the hook will be called for each node.")
7316 (defun org-promote-subtree ()
7317 "Promote the entire subtree.
7318 See also `org-promote'."
7319 (interactive)
7320 (save-excursion
7321 (org-with-limited-levels (org-map-tree 'org-promote)))
7322 (org-fix-position-after-promote))
7324 (defun org-demote-subtree ()
7325 "Demote the entire subtree. See `org-demote'.
7326 See also `org-promote'."
7327 (interactive)
7328 (save-excursion
7329 (org-with-limited-levels (org-map-tree 'org-demote)))
7330 (org-fix-position-after-promote))
7333 (defun org-do-promote ()
7334 "Promote the current heading higher up the tree.
7335 If the region is active in `transient-mark-mode', promote all headings
7336 in the region."
7337 (interactive)
7338 (save-excursion
7339 (if (org-region-active-p)
7340 (org-map-region 'org-promote (region-beginning) (region-end))
7341 (org-promote)))
7342 (org-fix-position-after-promote))
7344 (defun org-do-demote ()
7345 "Demote the current heading lower down the tree.
7346 If the region is active in `transient-mark-mode', demote all headings
7347 in the region."
7348 (interactive)
7349 (save-excursion
7350 (if (org-region-active-p)
7351 (org-map-region 'org-demote (region-beginning) (region-end))
7352 (org-demote)))
7353 (org-fix-position-after-promote))
7355 (defun org-fix-position-after-promote ()
7356 "Make sure that after pro/demotion cursor position is right."
7357 (let ((pos (point)))
7358 (when (save-excursion
7359 (beginning-of-line 1)
7360 (looking-at org-todo-line-regexp)
7361 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7362 (cond ((eobp) (insert " "))
7363 ((eolp) (insert " "))
7364 ((equal (char-after) ?\ ) (forward-char 1))))))
7366 (defun org-current-level ()
7367 "Return the level of the current entry, or nil if before the first headline.
7368 The level is the number of stars at the beginning of the headline."
7369 (save-excursion
7370 (org-with-limited-levels
7371 (if (ignore-errors (org-back-to-heading t))
7372 (funcall outline-level)))))
7374 (defun org-get-previous-line-level ()
7375 "Return the outline depth of the last headline before the current line.
7376 Returns 0 for the first headline in the buffer, and nil if before the
7377 first headline."
7378 (let ((current-level (org-current-level))
7379 (prev-level (when (> (line-number-at-pos) 1)
7380 (save-excursion
7381 (beginning-of-line 0)
7382 (org-current-level)))))
7383 (cond ((null current-level) nil) ; Before first headline
7384 ((null prev-level) 0) ; At first headline
7385 (prev-level))))
7387 (defun org-reduced-level (l)
7388 "Compute the effective level of a heading.
7389 This takes into account the setting of `org-odd-levels-only'."
7390 (cond
7391 ((zerop l) 0)
7392 (org-odd-levels-only (1+ (floor (/ l 2))))
7393 (t l)))
7395 (defun org-level-increment ()
7396 "Return the number of stars that will be added or removed at a
7397 time to headlines when structure editing, based on the value of
7398 `org-odd-levels-only'."
7399 (if org-odd-levels-only 2 1))
7401 (defun org-get-valid-level (level &optional change)
7402 "Rectify a level change under the influence of `org-odd-levels-only'
7403 LEVEL is a current level, CHANGE is by how much the level should be
7404 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7405 even level numbers will become the next higher odd number."
7406 (if org-odd-levels-only
7407 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7408 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7409 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7410 (max 1 (+ level (or change 0)))))
7412 (if (boundp 'define-obsolete-function-alias)
7413 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7414 (define-obsolete-function-alias 'org-get-legal-level
7415 'org-get-valid-level)
7416 (define-obsolete-function-alias 'org-get-legal-level
7417 'org-get-valid-level "23.1")))
7419 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7420 ;; ̀org-with-limited-levels'
7421 (defun org-promote ()
7422 "Promote the current heading higher up the tree.
7423 If the region is active in `transient-mark-mode', promote all headings
7424 in the region."
7425 (org-back-to-heading t)
7426 (let* ((level (save-match-data (funcall outline-level)))
7427 (after-change-functions (remove 'flyspell-after-change-function
7428 after-change-functions))
7429 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7430 (diff (abs (- level (length up-head) -1))))
7431 (cond ((and (= level 1) org-called-with-limited-levels
7432 org-allow-promoting-top-level-subtree)
7433 (replace-match "# " nil t))
7434 ((= level 1)
7435 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7436 (t (replace-match up-head nil t)))
7437 ;; Fixup tag positioning
7438 (unless (= level 1)
7439 (and org-auto-align-tags (org-set-tags nil t))
7440 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7441 (run-hooks 'org-after-promote-entry-hook)))
7443 (defun org-demote ()
7444 "Demote the current heading lower down the tree.
7445 If the region is active in `transient-mark-mode', demote all headings
7446 in the region."
7447 (org-back-to-heading t)
7448 (let* ((level (save-match-data (funcall outline-level)))
7449 (after-change-functions (remove 'flyspell-after-change-function
7450 after-change-functions))
7451 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7452 (diff (abs (- level (length down-head) -1))))
7453 (replace-match down-head nil t)
7454 ;; Fixup tag positioning
7455 (and org-auto-align-tags (org-set-tags nil t))
7456 (if org-adapt-indentation (org-fixup-indentation diff))
7457 (run-hooks 'org-after-demote-entry-hook)))
7459 (defun org-cycle-level ()
7460 "Cycle the level of an empty headline through possible states.
7461 This goes first to child, then to parent, level, then up the hierarchy.
7462 After top level, it switches back to sibling level."
7463 (interactive)
7464 (let ((org-adapt-indentation nil))
7465 (when (org-point-at-end-of-empty-headline)
7466 (setq this-command 'org-cycle-level) ; Only needed for caching
7467 (let ((cur-level (org-current-level))
7468 (prev-level (org-get-previous-line-level)))
7469 (cond
7470 ;; If first headline in file, promote to top-level.
7471 ((= prev-level 0)
7472 (loop repeat (/ (- cur-level 1) (org-level-increment))
7473 do (org-do-promote)))
7474 ;; If same level as prev, demote one.
7475 ((= prev-level cur-level)
7476 (org-do-demote))
7477 ;; If parent is top-level, promote to top level if not already.
7478 ((= prev-level 1)
7479 (loop repeat (/ (- cur-level 1) (org-level-increment))
7480 do (org-do-promote)))
7481 ;; If top-level, return to prev-level.
7482 ((= cur-level 1)
7483 (loop repeat (/ (- prev-level 1) (org-level-increment))
7484 do (org-do-demote)))
7485 ;; If less than prev-level, promote one.
7486 ((< cur-level prev-level)
7487 (org-do-promote))
7488 ;; If deeper than prev-level, promote until higher than
7489 ;; prev-level.
7490 ((> cur-level prev-level)
7491 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7492 do (org-do-promote))))
7493 t))))
7495 (defun org-map-tree (fun)
7496 "Call FUN for every heading underneath the current one."
7497 (org-back-to-heading)
7498 (let ((level (funcall outline-level)))
7499 (save-excursion
7500 (funcall fun)
7501 (while (and (progn
7502 (outline-next-heading)
7503 (> (funcall outline-level) level))
7504 (not (eobp)))
7505 (funcall fun)))))
7507 (defun org-map-region (fun beg end)
7508 "Call FUN for every heading between BEG and END."
7509 (let ((org-ignore-region t))
7510 (save-excursion
7511 (setq end (copy-marker end))
7512 (goto-char beg)
7513 (if (and (re-search-forward org-outline-regexp-bol nil t)
7514 (< (point) end))
7515 (funcall fun))
7516 (while (and (progn
7517 (outline-next-heading)
7518 (< (point) end))
7519 (not (eobp)))
7520 (funcall fun)))))
7522 (defvar org-property-end-re) ; silence byte-compiler
7523 (defun org-fixup-indentation (diff)
7524 "Change the indentation in the current entry by DIFF.
7525 However, if any line in the current entry has no indentation, or if it
7526 would end up with no indentation after the change, nothing at all is done."
7527 (save-excursion
7528 (let ((end (save-excursion (outline-next-heading)
7529 (point-marker)))
7530 (prohibit (if (> diff 0)
7531 "^\\S-"
7532 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7533 col)
7534 (unless (save-excursion (end-of-line 1)
7535 (re-search-forward prohibit end t))
7536 (while (and (< (point) end)
7537 (re-search-forward "^[ \t]+" end t))
7538 (goto-char (match-end 0))
7539 (setq col (current-column))
7540 (if (< diff 0) (replace-match ""))
7541 (org-indent-to-column (+ diff col))))
7542 (move-marker end nil))))
7544 (defun org-convert-to-odd-levels ()
7545 "Convert an org-mode file with all levels allowed to one with odd levels.
7546 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7547 level 5 etc."
7548 (interactive)
7549 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7550 (let ((outline-level 'org-outline-level)
7551 (org-odd-levels-only nil) n)
7552 (save-excursion
7553 (goto-char (point-min))
7554 (while (re-search-forward "^\\*\\*+ " nil t)
7555 (setq n (- (length (match-string 0)) 2))
7556 (while (>= (setq n (1- n)) 0)
7557 (org-demote))
7558 (end-of-line 1))))))
7560 (defun org-convert-to-oddeven-levels ()
7561 "Convert an org-mode file with only odd levels to one with odd/even levels.
7562 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7563 file contains a section with an even level, conversion would
7564 destroy the structure of the file. An error is signaled in this
7565 case."
7566 (interactive)
7567 (goto-char (point-min))
7568 ;; First check if there are no even levels
7569 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7570 (org-show-context t)
7571 (error "Not all levels are odd in this file. Conversion not possible"))
7572 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7573 (let ((outline-regexp org-outline-regexp)
7574 (outline-level 'org-outline-level)
7575 (org-odd-levels-only nil) n)
7576 (save-excursion
7577 (goto-char (point-min))
7578 (while (re-search-forward "^\\*\\*+ " nil t)
7579 (setq n (/ (1- (length (match-string 0))) 2))
7580 (while (>= (setq n (1- n)) 0)
7581 (org-promote))
7582 (end-of-line 1))))))
7584 (defun org-tr-level (n)
7585 "Make N odd if required."
7586 (if org-odd-levels-only (1+ (/ n 2)) n))
7588 ;;; Vertical tree motion, cutting and pasting of subtrees
7590 (defun org-move-subtree-up (&optional arg)
7591 "Move the current subtree up past ARG headlines of the same level."
7592 (interactive "p")
7593 (org-move-subtree-down (- (prefix-numeric-value arg))))
7595 (defun org-move-subtree-down (&optional arg)
7596 "Move the current subtree down past ARG headlines of the same level."
7597 (interactive "p")
7598 (setq arg (prefix-numeric-value arg))
7599 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7600 'org-get-last-sibling))
7601 (ins-point (make-marker))
7602 (cnt (abs arg))
7603 (col (current-column))
7604 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7605 ;; Select the tree
7606 (org-back-to-heading)
7607 (setq beg0 (point))
7608 (save-excursion
7609 (setq ne-beg (org-back-over-empty-lines))
7610 (setq beg (point)))
7611 (save-match-data
7612 (save-excursion (outline-end-of-heading)
7613 (setq folded (outline-invisible-p)))
7614 (outline-end-of-subtree))
7615 (outline-next-heading)
7616 (setq ne-end (org-back-over-empty-lines))
7617 (setq end (point))
7618 (goto-char beg0)
7619 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7620 ;; include less whitespace
7621 (save-excursion
7622 (goto-char beg)
7623 (forward-line (- ne-beg ne-end))
7624 (setq beg (point))))
7625 ;; Find insertion point, with error handling
7626 (while (> cnt 0)
7627 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7628 (progn (goto-char beg0)
7629 (error "Cannot move past superior level or buffer limit")))
7630 (setq cnt (1- cnt)))
7631 (if (> arg 0)
7632 ;; Moving forward - still need to move over subtree
7633 (progn (org-end-of-subtree t t)
7634 (save-excursion
7635 (org-back-over-empty-lines)
7636 (or (bolp) (newline)))))
7637 (setq ne-ins (org-back-over-empty-lines))
7638 (move-marker ins-point (point))
7639 (setq txt (buffer-substring beg end))
7640 (org-save-markers-in-region beg end)
7641 (delete-region beg end)
7642 (org-remove-empty-overlays-at beg)
7643 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7644 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7645 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7646 (let ((bbb (point)))
7647 (insert-before-markers txt)
7648 (org-reinstall-markers-in-region bbb)
7649 (move-marker ins-point bbb))
7650 (or (bolp) (insert "\n"))
7651 (setq ins-end (point))
7652 (goto-char ins-point)
7653 (org-skip-whitespace)
7654 (when (and (< arg 0)
7655 (org-first-sibling-p)
7656 (> ne-ins ne-beg))
7657 ;; Move whitespace back to beginning
7658 (save-excursion
7659 (goto-char ins-end)
7660 (let ((kill-whole-line t))
7661 (kill-line (- ne-ins ne-beg)) (point)))
7662 (insert (make-string (- ne-ins ne-beg) ?\n)))
7663 (move-marker ins-point nil)
7664 (if folded
7665 (hide-subtree)
7666 (org-show-entry)
7667 (show-children)
7668 (org-cycle-hide-drawers 'children))
7669 (org-clean-visibility-after-subtree-move)
7670 ;; move back to the initial column we were at
7671 (move-to-column col)))
7673 (defvar org-subtree-clip ""
7674 "Clipboard for cut and paste of subtrees.
7675 This is actually only a copy of the kill, because we use the normal kill
7676 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7678 (defvar org-subtree-clip-folded nil
7679 "Was the last copied subtree folded?
7680 This is used to fold the tree back after pasting.")
7682 (defun org-cut-subtree (&optional n)
7683 "Cut the current subtree into the clipboard.
7684 With prefix arg N, cut this many sequential subtrees.
7685 This is a short-hand for marking the subtree and then cutting it."
7686 (interactive "p")
7687 (org-copy-subtree n 'cut))
7689 (defun org-copy-subtree (&optional n cut force-store-markers)
7690 "Cut the current subtree into the clipboard.
7691 With prefix arg N, cut this many sequential subtrees.
7692 This is a short-hand for marking the subtree and then copying it.
7693 If CUT is non-nil, actually cut the subtree.
7694 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7695 of some markers in the region, even if CUT is non-nil. This is
7696 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7697 (interactive "p")
7698 (let (beg end folded (beg0 (point)))
7699 (if (org-called-interactively-p 'any)
7700 (org-back-to-heading nil) ; take what looks like a subtree
7701 (org-back-to-heading t)) ; take what is really there
7702 (org-back-over-empty-lines)
7703 (setq beg (point))
7704 (skip-chars-forward " \t\r\n")
7705 (save-match-data
7706 (save-excursion (outline-end-of-heading)
7707 (setq folded (outline-invisible-p)))
7708 (condition-case nil
7709 (org-forward-heading-same-level (1- n) t)
7710 (error nil))
7711 (org-end-of-subtree t t))
7712 (org-back-over-empty-lines)
7713 (setq end (point))
7714 (goto-char beg0)
7715 (when (> end beg)
7716 (setq org-subtree-clip-folded folded)
7717 (when (or cut force-store-markers)
7718 (org-save-markers-in-region beg end))
7719 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7720 (setq org-subtree-clip (current-kill 0))
7721 (message "%s: Subtree(s) with %d characters"
7722 (if cut "Cut" "Copied")
7723 (length org-subtree-clip)))))
7725 (defun org-paste-subtree (&optional level tree for-yank)
7726 "Paste the clipboard as a subtree, with modification of headline level.
7727 The entire subtree is promoted or demoted in order to match a new headline
7728 level.
7730 If the cursor is at the beginning of a headline, the same level as
7731 that headline is used to paste the tree
7733 If not, the new level is derived from the *visible* headings
7734 before and after the insertion point, and taken to be the inferior headline
7735 level of the two. So if the previous visible heading is level 3 and the
7736 next is level 4 (or vice versa), level 4 will be used for insertion.
7737 This makes sure that the subtree remains an independent subtree and does
7738 not swallow low level entries.
7740 You can also force a different level, either by using a numeric prefix
7741 argument, or by inserting the heading marker by hand. For example, if the
7742 cursor is after \"*****\", then the tree will be shifted to level 5.
7744 If optional TREE is given, use this text instead of the kill ring.
7746 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7747 move back over whitespace before inserting, and move point to the end of
7748 the inserted text when done."
7749 (interactive "P")
7750 (setq tree (or tree (and kill-ring (current-kill 0))))
7751 (unless (org-kill-is-subtree-p tree)
7752 (error "%s"
7753 (substitute-command-keys
7754 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7755 (org-with-limited-levels
7756 (let* ((visp (not (outline-invisible-p)))
7757 (txt tree)
7758 (^re_ "\\(\\*+\\)[ \t]*")
7759 (old-level (if (string-match org-outline-regexp-bol txt)
7760 (- (match-end 0) (match-beginning 0) 1)
7761 -1))
7762 (force-level (cond (level (prefix-numeric-value level))
7763 ((and (looking-at "[ \t]*$")
7764 (string-match
7765 "^\\*+$" (buffer-substring
7766 (point-at-bol) (point))))
7767 (- (match-end 1) (match-beginning 1)))
7768 ((and (bolp)
7769 (looking-at org-outline-regexp))
7770 (- (match-end 0) (point) 1))))
7771 (previous-level (save-excursion
7772 (condition-case nil
7773 (progn
7774 (outline-previous-visible-heading 1)
7775 (if (looking-at ^re_)
7776 (- (match-end 0) (match-beginning 0) 1)
7778 (error 1))))
7779 (next-level (save-excursion
7780 (condition-case nil
7781 (progn
7782 (or (looking-at org-outline-regexp)
7783 (outline-next-visible-heading 1))
7784 (if (looking-at ^re_)
7785 (- (match-end 0) (match-beginning 0) 1)
7787 (error 1))))
7788 (new-level (or force-level (max previous-level next-level)))
7789 (shift (if (or (= old-level -1)
7790 (= new-level -1)
7791 (= old-level new-level))
7793 (- new-level old-level)))
7794 (delta (if (> shift 0) -1 1))
7795 (func (if (> shift 0) 'org-demote 'org-promote))
7796 (org-odd-levels-only nil)
7797 beg end newend)
7798 ;; Remove the forced level indicator
7799 (if force-level
7800 (delete-region (point-at-bol) (point)))
7801 ;; Paste
7802 (beginning-of-line (if (bolp) 1 2))
7803 (unless for-yank (org-back-over-empty-lines))
7804 (setq beg (point))
7805 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7806 (insert-before-markers txt)
7807 (unless (string-match "\n\\'" txt) (insert "\n"))
7808 (setq newend (point))
7809 (org-reinstall-markers-in-region beg)
7810 (setq end (point))
7811 (goto-char beg)
7812 (skip-chars-forward " \t\n\r")
7813 (setq beg (point))
7814 (if (and (outline-invisible-p) visp)
7815 (save-excursion (outline-show-heading)))
7816 ;; Shift if necessary
7817 (unless (= shift 0)
7818 (save-restriction
7819 (narrow-to-region beg end)
7820 (while (not (= shift 0))
7821 (org-map-region func (point-min) (point-max))
7822 (setq shift (+ delta shift)))
7823 (goto-char (point-min))
7824 (setq newend (point-max))))
7825 (when (or (org-called-interactively-p 'interactive) for-yank)
7826 (message "Clipboard pasted as level %d subtree" new-level))
7827 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7828 kill-ring
7829 (eq org-subtree-clip (current-kill 0))
7830 org-subtree-clip-folded)
7831 ;; The tree was folded before it was killed/copied
7832 (hide-subtree))
7833 (and for-yank (goto-char newend)))))
7835 (defun org-kill-is-subtree-p (&optional txt)
7836 "Check if the current kill is an outline subtree, or a set of trees.
7837 Returns nil if kill does not start with a headline, or if the first
7838 headline level is not the largest headline level in the tree.
7839 So this will actually accept several entries of equal levels as well,
7840 which is OK for `org-paste-subtree'.
7841 If optional TXT is given, check this string instead of the current kill."
7842 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7843 (re (org-get-limited-outline-regexp))
7844 (^re (concat "^" re))
7845 (start-level (and kill
7846 (string-match
7847 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7848 kill)
7849 (- (match-end 2) (match-beginning 2) 1)))
7850 (start (1+ (or (match-beginning 2) -1))))
7851 (if (not start-level)
7852 (progn
7853 nil) ;; does not even start with a heading
7854 (catch 'exit
7855 (while (setq start (string-match ^re kill (1+ start)))
7856 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7857 (throw 'exit nil)))
7858 t))))
7860 (defvar org-markers-to-move nil
7861 "Markers that should be moved with a cut-and-paste operation.
7862 Those markers are stored together with their positions relative to
7863 the start of the region.")
7865 (defun org-save-markers-in-region (beg end)
7866 "Check markers in region.
7867 If these markers are between BEG and END, record their position relative
7868 to BEG, so that after moving the block of text, we can put the markers back
7869 into place.
7870 This function gets called just before an entry or tree gets cut from the
7871 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7872 called immediately, to move the markers with the entries."
7873 (setq org-markers-to-move nil)
7874 (when (featurep 'org-clock)
7875 (org-clock-save-markers-for-cut-and-paste beg end))
7876 (when (featurep 'org-agenda)
7877 (org-agenda-save-markers-for-cut-and-paste beg end)))
7879 (defun org-check-and-save-marker (marker beg end)
7880 "Check if MARKER is between BEG and END.
7881 If yes, remember the marker and the distance to BEG."
7882 (when (and (marker-buffer marker)
7883 (equal (marker-buffer marker) (current-buffer)))
7884 (if (and (>= marker beg) (< marker end))
7885 (push (cons marker (- marker beg)) org-markers-to-move))))
7887 (defun org-reinstall-markers-in-region (beg)
7888 "Move all remembered markers to their position relative to BEG."
7889 (mapc (lambda (x)
7890 (move-marker (car x) (+ beg (cdr x))))
7891 org-markers-to-move)
7892 (setq org-markers-to-move nil))
7894 (defun org-narrow-to-subtree ()
7895 "Narrow buffer to the current subtree."
7896 (interactive)
7897 (save-excursion
7898 (save-match-data
7899 (org-with-limited-levels
7900 (narrow-to-region
7901 (progn (org-back-to-heading t) (point))
7902 (progn (org-end-of-subtree t t)
7903 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7904 (point)))))))
7906 (defun org-narrow-to-block ()
7907 "Narrow buffer to the current block."
7908 (interactive)
7909 (let* ((case-fold-search t)
7910 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7911 "^[ \t]*#\\+end_.*")))
7912 (if blockp
7913 (narrow-to-region (car blockp) (cdr blockp))
7914 (error "Not in a block"))))
7916 (eval-when-compile
7917 (defvar org-property-drawer-re))
7919 (defvar org-property-start-re) ;; defined below
7920 (defun org-clone-subtree-with-time-shift (n &optional shift)
7921 "Clone the task (subtree) at point N times.
7922 The clones will be inserted as siblings.
7924 In interactive use, the user will be prompted for the number of
7925 clones to be produced, and for a time SHIFT, which may be a
7926 repeater as used in time stamps, for example `+3d'.
7928 When a valid repeater is given and the entry contains any time
7929 stamps, the clones will become a sequence in time, with time
7930 stamps in the subtree shifted for each clone produced. If SHIFT
7931 is nil or the empty string, time stamps will be left alone. The
7932 ID property of the original subtree is removed.
7934 If the original subtree did contain time stamps with a repeater,
7935 the following will happen:
7936 - the repeater will be removed in each clone
7937 - an additional clone will be produced, with the current, unshifted
7938 date(s) in the entry.
7939 - the original entry will be placed *after* all the clones, with
7940 repeater intact.
7941 - the start days in the repeater in the original entry will be shifted
7942 to past the last clone.
7943 In this way you can spell out a number of instances of a repeating task,
7944 and still retain the repeater to cover future instances of the task."
7945 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7946 (let (beg end template task idprop
7947 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7948 (drawer-re org-drawer-regexp))
7949 (if (not (and (integerp n) (> n 0)))
7950 (error "Invalid number of replications %s" n))
7951 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7952 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
7953 shift)))
7954 (error "Invalid shift specification %s" shift))
7955 (when doshift
7956 (setq shift-n (string-to-number (match-string 1 shift))
7957 shift-what (cdr (assoc (match-string 2 shift)
7958 '(("d" . day) ("w" . week)
7959 ("m" . month) ("y" . year))))))
7960 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7961 (setq nmin 1 nmax n)
7962 (org-back-to-heading t)
7963 (setq beg (point))
7964 (setq idprop (org-entry-get nil "ID"))
7965 (org-end-of-subtree t t)
7966 (or (bolp) (insert "\n"))
7967 (setq end (point))
7968 (setq template (buffer-substring beg end))
7969 (when (and doshift
7970 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
7971 (delete-region beg end)
7972 (setq end beg)
7973 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7974 (goto-char end)
7975 (loop for n from nmin to nmax do
7976 ;; prepare clone
7977 (with-temp-buffer
7978 (insert template)
7979 (org-mode)
7980 (goto-char (point-min))
7981 (org-show-subtree)
7982 (and idprop (if org-clone-delete-id
7983 (org-entry-delete nil "ID")
7984 (org-id-get-create t)))
7985 (unless (= n 0)
7986 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7987 (kill-whole-line))
7988 (goto-char (point-min))
7989 (while (re-search-forward drawer-re nil t)
7990 (mapc (lambda (d)
7991 (org-remove-empty-drawer-at d (point))) org-drawers)))
7992 (goto-char (point-min))
7993 (when doshift
7994 (while (re-search-forward org-ts-regexp-both nil t)
7995 (org-timestamp-change (* n shift-n) shift-what))
7996 (unless (= n n-no-remove)
7997 (goto-char (point-min))
7998 (while (re-search-forward org-ts-regexp nil t)
7999 (save-excursion
8000 (goto-char (match-beginning 0))
8001 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8002 (delete-region (match-beginning 1) (match-end 1)))))))
8003 (setq task (buffer-string)))
8004 (insert task))
8005 (goto-char beg)))
8007 ;;; Outline Sorting
8009 (defun org-sort (with-case)
8010 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8011 Optional argument WITH-CASE means sort case-sensitively."
8012 (interactive "P")
8013 (cond
8014 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8015 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8017 (org-call-with-arg 'org-sort-entries with-case))))
8019 (defun org-sort-remove-invisible (s)
8020 (remove-text-properties 0 (length s) org-rm-props s)
8021 (while (string-match org-bracket-link-regexp s)
8022 (setq s (replace-match (if (match-end 2)
8023 (match-string 3 s)
8024 (match-string 1 s)) t t s)))
8027 (defvar org-priority-regexp) ; defined later in the file
8029 (defvar org-after-sorting-entries-or-items-hook nil
8030 "Hook that is run after a bunch of entries or items have been sorted.
8031 When children are sorted, the cursor is in the parent line when this
8032 hook gets called. When a region or a plain list is sorted, the cursor
8033 will be in the first entry of the sorted region/list.")
8035 (defun org-sort-entries
8036 (&optional with-case sorting-type getkey-func compare-func property)
8037 "Sort entries on a certain level of an outline tree.
8038 If there is an active region, the entries in the region are sorted.
8039 Else, if the cursor is before the first entry, sort the top-level items.
8040 Else, the children of the entry at point are sorted.
8042 Sorting can be alphabetically, numerically, by date/time as given by
8043 a time stamp, by a property or by priority.
8045 The command prompts for the sorting type unless it has been given to the
8046 function through the SORTING-TYPE argument, which needs to be a character,
8047 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8048 precise meaning of each character:
8050 n Numerically, by converting the beginning of the entry/item to a number.
8051 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8052 t By date/time, either the first active time stamp in the entry, or, if
8053 none exist, by the first inactive one.
8054 s By the scheduled date/time.
8055 d By deadline date/time.
8056 c By creation time, which is assumed to be the first inactive time stamp
8057 at the beginning of a line.
8058 p By priority according to the cookie.
8059 r By the value of a property.
8061 Capital letters will reverse the sort order.
8063 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8064 called with point at the beginning of the record. It must return either
8065 a string or a number that should serve as the sorting key for that record.
8067 Comparing entries ignores case by default. However, with an optional argument
8068 WITH-CASE, the sorting considers case as well."
8069 (interactive "P")
8070 (let ((case-func (if with-case 'identity 'downcase))
8071 start beg end stars re re2
8072 txt what tmp)
8073 ;; Find beginning and end of region to sort
8074 (cond
8075 ((org-region-active-p)
8076 ;; we will sort the region
8077 (setq end (region-end)
8078 what "region")
8079 (goto-char (region-beginning))
8080 (if (not (org-at-heading-p)) (outline-next-heading))
8081 (setq start (point)))
8082 ((or (org-at-heading-p)
8083 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8084 ;; we will sort the children of the current headline
8085 (org-back-to-heading)
8086 (setq start (point)
8087 end (progn (org-end-of-subtree t t)
8088 (or (bolp) (insert "\n"))
8089 (org-back-over-empty-lines)
8090 (point))
8091 what "children")
8092 (goto-char start)
8093 (show-subtree)
8094 (outline-next-heading))
8096 ;; we will sort the top-level entries in this file
8097 (goto-char (point-min))
8098 (or (org-at-heading-p) (outline-next-heading))
8099 (setq start (point))
8100 (goto-char (point-max))
8101 (beginning-of-line 1)
8102 (when (looking-at ".*?\\S-")
8103 ;; File ends in a non-white line
8104 (end-of-line 1)
8105 (insert "\n"))
8106 (setq end (point-max))
8107 (setq what "top-level")
8108 (goto-char start)
8109 (show-all)))
8111 (setq beg (point))
8112 (if (>= beg end) (error "Nothing to sort"))
8114 (looking-at "\\(\\*+\\)")
8115 (setq stars (match-string 1)
8116 re (concat "^" (regexp-quote stars) " +")
8117 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8118 txt (buffer-substring beg end))
8119 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8120 (if (and (not (equal stars "*")) (string-match re2 txt))
8121 (error "Region to sort contains a level above the first entry"))
8123 (unless sorting-type
8124 (message
8125 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8126 [t]ime [s]cheduled [d]eadline [c]reated
8127 A/N/T/S/D/C/P/O/F means reversed:"
8128 what)
8129 (setq sorting-type (read-char-exclusive))
8131 (and (= (downcase sorting-type) ?f)
8132 (setq getkey-func
8133 (org-icompleting-read "Sort using function: "
8134 obarray 'fboundp t nil nil))
8135 (setq getkey-func (intern getkey-func)))
8137 (and (= (downcase sorting-type) ?r)
8138 (setq property
8139 (org-icompleting-read "Property: "
8140 (mapcar 'list (org-buffer-property-keys t))
8141 nil t))))
8143 (message "Sorting entries...")
8145 (save-restriction
8146 (narrow-to-region start end)
8147 (let ((dcst (downcase sorting-type))
8148 (case-fold-search nil)
8149 (now (current-time)))
8150 (sort-subr
8151 (/= dcst sorting-type)
8152 ;; This function moves to the beginning character of the "record" to
8153 ;; be sorted.
8154 (lambda nil
8155 (if (re-search-forward re nil t)
8156 (goto-char (match-beginning 0))
8157 (goto-char (point-max))))
8158 ;; This function moves to the last character of the "record" being
8159 ;; sorted.
8160 (lambda nil
8161 (save-match-data
8162 (condition-case nil
8163 (outline-forward-same-level 1)
8164 (error
8165 (goto-char (point-max))))))
8166 ;; This function returns the value that gets sorted against.
8167 (lambda nil
8168 (cond
8169 ((= dcst ?n)
8170 (if (looking-at org-complex-heading-regexp)
8171 (string-to-number (match-string 4))
8172 nil))
8173 ((= dcst ?a)
8174 (if (looking-at org-complex-heading-regexp)
8175 (funcall case-func (match-string 4))
8176 nil))
8177 ((= dcst ?t)
8178 (let ((end (save-excursion (outline-next-heading) (point))))
8179 (if (or (re-search-forward org-ts-regexp end t)
8180 (re-search-forward org-ts-regexp-both end t))
8181 (org-time-string-to-seconds (match-string 0))
8182 (org-float-time now))))
8183 ((= dcst ?c)
8184 (let ((end (save-excursion (outline-next-heading) (point))))
8185 (if (re-search-forward
8186 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8187 end t)
8188 (org-time-string-to-seconds (match-string 0))
8189 (org-float-time now))))
8190 ((= dcst ?s)
8191 (let ((end (save-excursion (outline-next-heading) (point))))
8192 (if (re-search-forward org-scheduled-time-regexp end t)
8193 (org-time-string-to-seconds (match-string 1))
8194 (org-float-time now))))
8195 ((= dcst ?d)
8196 (let ((end (save-excursion (outline-next-heading) (point))))
8197 (if (re-search-forward org-deadline-time-regexp end t)
8198 (org-time-string-to-seconds (match-string 1))
8199 (org-float-time now))))
8200 ((= dcst ?p)
8201 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8202 (string-to-char (match-string 2))
8203 org-default-priority))
8204 ((= dcst ?r)
8205 (or (org-entry-get nil property) ""))
8206 ((= dcst ?o)
8207 (if (looking-at org-complex-heading-regexp)
8208 (- 9999 (length (member (match-string 2)
8209 org-todo-keywords-1)))))
8210 ((= dcst ?f)
8211 (if getkey-func
8212 (progn
8213 (setq tmp (funcall getkey-func))
8214 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8215 tmp)
8216 (error "Invalid key function `%s'" getkey-func)))
8217 (t (error "Invalid sorting type `%c'" sorting-type))))
8219 (cond
8220 ((= dcst ?a) 'string<)
8221 ((= dcst ?f) compare-func)
8222 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8223 (run-hooks 'org-after-sorting-entries-or-items-hook)
8224 (message "Sorting entries...done")))
8226 (defun org-do-sort (table what &optional with-case sorting-type)
8227 "Sort TABLE of WHAT according to SORTING-TYPE.
8228 The user will be prompted for the SORTING-TYPE if the call to this
8229 function does not specify it. WHAT is only for the prompt, to indicate
8230 what is being sorted. The sorting key will be extracted from
8231 the car of the elements of the table.
8232 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8233 (unless sorting-type
8234 (message
8235 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8236 what)
8237 (setq sorting-type (read-char-exclusive)))
8238 (let ((dcst (downcase sorting-type))
8239 extractfun comparefun)
8240 ;; Define the appropriate functions
8241 (cond
8242 ((= dcst ?n)
8243 (setq extractfun 'string-to-number
8244 comparefun (if (= dcst sorting-type) '< '>)))
8245 ((= dcst ?a)
8246 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8247 (lambda(x) (downcase (org-sort-remove-invisible x))))
8248 comparefun (if (= dcst sorting-type)
8249 'string<
8250 (lambda (a b) (and (not (string< a b))
8251 (not (string= a b)))))))
8252 ((= dcst ?t)
8253 (setq extractfun
8254 (lambda (x)
8255 (if (or (string-match org-ts-regexp x)
8256 (string-match org-ts-regexp-both x))
8257 (org-float-time
8258 (org-time-string-to-time (match-string 0 x)))
8260 comparefun (if (= dcst sorting-type) '< '>)))
8261 (t (error "Invalid sorting type `%c'" sorting-type)))
8263 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8264 table)
8265 (lambda (a b) (funcall comparefun (car a) (car b))))))
8268 ;;; The orgstruct minor mode
8270 ;; Define a minor mode which can be used in other modes in order to
8271 ;; integrate the org-mode structure editing commands.
8273 ;; This is really a hack, because the org-mode structure commands use
8274 ;; keys which normally belong to the major mode. Here is how it
8275 ;; works: The minor mode defines all the keys necessary to operate the
8276 ;; structure commands, but wraps the commands into a function which
8277 ;; tests if the cursor is currently at a headline or a plain list
8278 ;; item. If that is the case, the structure command is used,
8279 ;; temporarily setting many Org-mode variables like regular
8280 ;; expressions for filling etc. However, when any of those keys is
8281 ;; used at a different location, function uses `key-binding' to look
8282 ;; up if the key has an associated command in another currently active
8283 ;; keymap (minor modes, major mode, global), and executes that
8284 ;; command. There might be problems if any of the keys is otherwise
8285 ;; used as a prefix key.
8287 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8288 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8289 ;; addresses this by checking explicitly for both bindings.
8291 (defvar orgstruct-mode-map (make-sparse-keymap)
8292 "Keymap for the minor `orgstruct-mode'.")
8294 (defvar org-local-vars nil
8295 "List of local variables, for use by `orgstruct-mode'.")
8297 ;;;###autoload
8298 (define-minor-mode orgstruct-mode
8299 "Toggle the minor mode `orgstruct-mode'.
8300 This mode is for using Org-mode structure commands in other
8301 modes. The following keys behave as if Org-mode were active, if
8302 the cursor is on a headline, or on a plain list item (both as
8303 defined by Org-mode).
8305 M-up Move entry/item up
8306 M-down Move entry/item down
8307 M-left Promote
8308 M-right Demote
8309 M-S-up Move entry/item up
8310 M-S-down Move entry/item down
8311 M-S-left Promote subtree
8312 M-S-right Demote subtree
8313 M-q Fill paragraph and items like in Org-mode
8314 C-c ^ Sort entries
8315 C-c - Cycle list bullet
8316 TAB Cycle item visibility
8317 M-RET Insert new heading/item
8318 S-M-RET Insert new TODO heading / Checkbox item
8319 C-c C-c Set tags / toggle checkbox"
8320 nil " OrgStruct" nil
8321 (org-load-modules-maybe)
8322 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8324 ;;;###autoload
8325 (defun turn-on-orgstruct ()
8326 "Unconditionally turn on `orgstruct-mode'."
8327 (orgstruct-mode 1))
8329 (defvar org-fb-vars nil)
8330 (make-variable-buffer-local 'org-fb-vars)
8331 (defun orgstruct++-mode (&optional arg)
8332 "Toggle `orgstruct-mode', the enhanced version of it.
8333 In addition to setting orgstruct-mode, this also exports all
8334 indentation and autofilling variables from org-mode into the
8335 buffer. It will also recognize item context in multiline items."
8336 (interactive "P")
8337 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8338 (if (< arg 1)
8339 (progn (orgstruct-mode -1)
8340 (mapc (lambda(v)
8341 (org-set-local (car v)
8342 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8343 org-fb-vars))
8344 (orgstruct-mode 1)
8345 (setq org-fb-vars nil)
8346 (let (var val)
8347 (mapc
8348 (lambda (x)
8349 (when (string-match
8350 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8351 (symbol-name (car x)))
8352 (setq var (car x) val (nth 1 x))
8353 (push (list var `(quote ,(eval var))) org-fb-vars)
8354 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8355 org-local-vars)
8356 (org-set-local 'orgstruct-is-++ t))))
8358 (defvar orgstruct-is-++ nil
8359 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8360 (make-variable-buffer-local 'orgstruct-is-++)
8362 ;;;###autoload
8363 (defun turn-on-orgstruct++ ()
8364 "Unconditionally turn on `orgstruct++-mode'."
8365 (orgstruct++-mode 1))
8367 (defun orgstruct-error ()
8368 "Error when there is no default binding for a structure key."
8369 (interactive)
8370 (error "This key has no function outside structure elements"))
8372 (defun orgstruct-setup ()
8373 "Setup orgstruct keymaps."
8374 (let ((nfunc 0)
8375 (bindings
8376 (list
8377 '([(meta up)] org-metaup)
8378 '([(meta down)] org-metadown)
8379 '([(meta left)] org-metaleft)
8380 '([(meta right)] org-metaright)
8381 '([(meta shift up)] org-shiftmetaup)
8382 '([(meta shift down)] org-shiftmetadown)
8383 '([(meta shift left)] org-shiftmetaleft)
8384 '([(meta shift right)] org-shiftmetaright)
8385 '([?\e (up)] org-metaup)
8386 '([?\e (down)] org-metadown)
8387 '([?\e (left)] org-metaleft)
8388 '([?\e (right)] org-metaright)
8389 '([?\e (shift up)] org-shiftmetaup)
8390 '([?\e (shift down)] org-shiftmetadown)
8391 '([?\e (shift left)] org-shiftmetaleft)
8392 '([?\e (shift right)] org-shiftmetaright)
8393 '([(shift up)] org-shiftup)
8394 '([(shift down)] org-shiftdown)
8395 '([(shift left)] org-shiftleft)
8396 '([(shift right)] org-shiftright)
8397 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8398 '("\M-q" fill-paragraph)
8399 '("\C-c^" org-sort)
8400 '("\C-c-" org-cycle-list-bullet)))
8401 elt key fun cmd)
8402 (while (setq elt (pop bindings))
8403 (setq nfunc (1+ nfunc))
8404 (setq key (org-key (car elt))
8405 fun (nth 1 elt)
8406 cmd (orgstruct-make-binding fun nfunc key))
8407 (org-defkey orgstruct-mode-map key cmd))
8409 ;; Prevent an error for users who forgot to make autoloads
8410 (require 'org-element)
8412 ;; Special treatment needed for TAB and RET
8413 (org-defkey orgstruct-mode-map [(tab)]
8414 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8415 (org-defkey orgstruct-mode-map "\C-i"
8416 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8418 (org-defkey orgstruct-mode-map "\M-\C-m"
8419 (orgstruct-make-binding 'org-insert-heading 105
8420 "\M-\C-m" [(meta return)]))
8421 (org-defkey orgstruct-mode-map [(meta return)]
8422 (orgstruct-make-binding 'org-insert-heading 106
8423 [(meta return)] "\M-\C-m"))
8425 (org-defkey orgstruct-mode-map [(shift meta return)]
8426 (orgstruct-make-binding 'org-insert-todo-heading 107
8427 [(meta return)] "\M-\C-m"))
8429 (org-defkey orgstruct-mode-map "\e\C-m"
8430 (orgstruct-make-binding 'org-insert-heading 108
8431 "\e\C-m" [?\e (return)]))
8432 (org-defkey orgstruct-mode-map [?\e (return)]
8433 (orgstruct-make-binding 'org-insert-heading 109
8434 [?\e (return)] "\e\C-m"))
8435 (org-defkey orgstruct-mode-map [?\e (shift return)]
8436 (orgstruct-make-binding 'org-insert-todo-heading 110
8437 [?\e (return)] "\e\C-m"))
8439 (unless org-local-vars
8440 (setq org-local-vars (org-get-local-variables)))
8444 (defun orgstruct-make-binding (fun n &rest keys)
8445 "Create a function for binding in the structure minor mode.
8446 FUN is the command to call inside a table. N is used to create a unique
8447 command name. KEYS are keys that should be checked in for a command
8448 to execute outside of tables."
8449 (eval
8450 (list 'defun
8451 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8452 '(arg)
8453 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8454 "Outside of structure, run the binding of `"
8455 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8456 "'.")
8457 '(interactive "p")
8458 (list 'if
8459 `(org-context-p 'headline 'item
8460 (and orgstruct-is-++
8461 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8462 'item-body))
8463 (list 'org-run-like-in-org-mode (list 'quote fun))
8464 (list 'let '(orgstruct-mode)
8465 (list 'call-interactively
8466 (append '(or)
8467 (mapcar (lambda (k)
8468 (list 'key-binding k))
8469 keys)
8470 '('orgstruct-error))))))))
8472 (defun org-contextualize-keys (alist contexts)
8473 "Return valid elements in ALIST depending on CONTEXTS.
8475 `org-agenda-custom-commands' or `org-capture-templates' are the
8476 values used for ALIST, and `org-agenda-custom-commands-contexts'
8477 or `org-capture-templates-contexts' are the associated contexts
8478 definitions."
8479 (let ((contexts
8480 ;; normalize contexts
8481 (mapcar
8482 (lambda(c) (cond ((listp (cadr c))
8483 (list (car c) (car c) (cadr c)))
8484 ((string= "" (cadr c))
8485 (list (car c) (car c) (caddr c)))
8486 (t c))) contexts))
8487 (a alist) c r s)
8488 ;; loop over all commands or templates
8489 (while (setq c (pop a))
8490 (let (vrules repl)
8491 (cond
8492 ((not (assoc (car c) contexts))
8493 (push c r))
8494 ((and (assoc (car c) contexts)
8495 (setq vrules (org-contextualize-validate-key
8496 (car c) contexts)))
8497 (mapc (lambda (vr)
8498 (when (not (equal (car vr) (cadr vr)))
8499 (setq repl vr))) vrules)
8500 (if (not repl) (push c r)
8501 (push (cadr repl) s)
8502 (push
8503 (cons (car c)
8504 (cdr (or (assoc (cadr repl) alist)
8505 (error "Undefined key `%s' as contextual replacement for `%s'"
8506 (cadr repl) (car c)))))
8507 r))))))
8508 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8509 (delq
8511 (delete-dups
8512 (mapcar (lambda (x)
8513 (let ((tpl (car x)))
8514 (when (not (delq
8516 (mapcar (lambda(y)
8517 (equal y tpl)) s))) x)))
8518 (reverse r))))))
8520 (defun org-contextualize-validate-key (key contexts)
8521 "Check CONTEXTS for agenda or capture KEY."
8522 (let (r rr res)
8523 (while (setq r (pop contexts))
8524 (mapc
8525 (lambda (rr)
8526 (when
8527 (and (equal key (car r))
8528 (if (functionp rr) (funcall rr)
8529 (or (and (eq (car rr) 'in-file)
8530 (buffer-file-name)
8531 (string-match (cdr rr) (buffer-file-name)))
8532 (and (eq (car rr) 'in-mode)
8533 (string-match (cdr rr) (symbol-name major-mode)))
8534 (when (and (eq (car rr) 'not-in-file)
8535 (buffer-file-name))
8536 (not (string-match (cdr rr) (buffer-file-name))))
8537 (when (eq (car rr) 'not-in-mode)
8538 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8539 (push r res)))
8540 (car (last r))))
8541 (delete-dups (delq nil res))))
8543 (defun org-context-p (&rest contexts)
8544 "Check if local context is any of CONTEXTS.
8545 Possible values in the list of contexts are `table', `headline', and `item'."
8546 (let ((pos (point)))
8547 (goto-char (point-at-bol))
8548 (prog1 (or (and (memq 'table contexts)
8549 (looking-at "[ \t]*|"))
8550 (and (memq 'headline contexts)
8551 (looking-at org-outline-regexp))
8552 (and (memq 'item contexts)
8553 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8554 (and (memq 'item-body contexts)
8555 (org-in-item-p)))
8556 (goto-char pos))))
8558 (defun org-get-local-variables ()
8559 "Return a list of all local variables in an Org mode buffer."
8560 (let (varlist)
8561 (with-current-buffer (get-buffer-create "*Org tmp*")
8562 (erase-buffer)
8563 (org-mode)
8564 (setq varlist (buffer-local-variables)))
8565 (kill-buffer "*Org tmp*")
8566 (delq nil
8567 (mapcar
8568 (lambda (x)
8569 (setq x
8570 (if (symbolp x)
8571 (list x)
8572 (list (car x) (list 'quote (cdr x)))))
8573 (if (string-match
8574 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8575 (symbol-name (car x)))
8576 x nil))
8577 varlist))))
8579 (defun org-clone-local-variables (from-buffer &optional regexp)
8580 "Clone local variables from FROM-BUFFER.
8581 Optional argument REGEXP selects variables to clone."
8582 (mapc
8583 (lambda (pair)
8584 (and (symbolp (car pair))
8585 (or (null regexp)
8586 (string-match regexp (symbol-name (car pair))))
8587 (set (make-local-variable (car pair))
8588 (cdr pair))))
8589 (buffer-local-variables from-buffer)))
8591 ;;;###autoload
8592 (defun org-run-like-in-org-mode (cmd)
8593 "Run a command, pretending that the current buffer is in Org-mode.
8594 This will temporarily bind local variables that are typically bound in
8595 Org-mode to the values they have in Org-mode, and then interactively
8596 call CMD."
8597 (org-load-modules-maybe)
8598 (unless org-local-vars
8599 (setq org-local-vars (org-get-local-variables)))
8600 (eval (list 'let org-local-vars
8601 (list 'call-interactively (list 'quote cmd)))))
8603 ;;;; Archiving
8605 (defun org-get-category (&optional pos force-refresh)
8606 "Get the category applying to position POS."
8607 (save-match-data
8608 (if force-refresh (org-refresh-category-properties))
8609 (let ((pos (or pos (point))))
8610 (or (get-text-property pos 'org-category)
8611 (progn (org-refresh-category-properties)
8612 (get-text-property pos 'org-category))))))
8614 (defun org-refresh-category-properties ()
8615 "Refresh category text properties in the buffer."
8616 (let ((case-fold-search t)
8617 (inhibit-read-only t)
8618 (def-cat (cond
8619 ((null org-category)
8620 (if buffer-file-name
8621 (file-name-sans-extension
8622 (file-name-nondirectory buffer-file-name))
8623 "???"))
8624 ((symbolp org-category) (symbol-name org-category))
8625 (t org-category)))
8626 beg end cat pos optionp)
8627 (org-unmodified
8628 (save-excursion
8629 (save-restriction
8630 (widen)
8631 (goto-char (point-min))
8632 (put-text-property (point) (point-max) 'org-category def-cat)
8633 (while (re-search-forward
8634 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8635 (setq pos (match-end 0)
8636 optionp (equal (char-after (match-beginning 0)) ?#)
8637 cat (org-trim (match-string 2)))
8638 (if optionp
8639 (setq beg (point-at-bol) end (point-max))
8640 (org-back-to-heading t)
8641 (setq beg (point) end (org-end-of-subtree t t)))
8642 (put-text-property beg end 'org-category cat)
8643 (put-text-property beg end 'org-category-position beg)
8644 (goto-char pos)))))))
8647 ;;;; Link Stuff
8649 ;;; Link abbreviations
8651 (defun org-link-expand-abbrev (link)
8652 "Apply replacements as defined in `org-link-abbrev-alist'."
8653 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8654 (let* ((key (match-string 1 link))
8655 (as (or (assoc key org-link-abbrev-alist-local)
8656 (assoc key org-link-abbrev-alist)))
8657 (tag (and (match-end 2) (match-string 3 link)))
8658 rpl)
8659 (if (not as)
8660 link
8661 (setq rpl (cdr as))
8662 (cond
8663 ((symbolp rpl) (funcall rpl tag))
8664 ((string-match "%(\\([^)]+\\))" rpl)
8665 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8666 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8667 ((string-match "%h" rpl)
8668 (replace-match (url-hexify-string (or tag "")) t t rpl))
8669 (t (concat rpl tag)))))
8670 link))
8672 ;;; Storing and inserting links
8674 (defvar org-insert-link-history nil
8675 "Minibuffer history for links inserted with `org-insert-link'.")
8677 (defvar org-stored-links nil
8678 "Contains the links stored with `org-store-link'.")
8680 (defvar org-store-link-plist nil
8681 "Plist with info about the most recently link created with `org-store-link'.")
8683 (defvar org-link-protocols nil
8684 "Link protocols added to Org-mode using `org-add-link-type'.")
8686 (defvar org-store-link-functions nil
8687 "List of functions that are called to create and store a link.
8688 Each function will be called in turn until one returns a non-nil
8689 value. Each function should check if it is responsible for creating
8690 this link (for example by looking at the major mode).
8691 If not, it must exit and return nil.
8692 If yes, it should return a non-nil value after a calling
8693 `org-store-link-props' with a list of properties and values.
8694 Special properties are:
8696 :type The link prefix, like \"http\". This must be given.
8697 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8698 This is obligatory as well.
8699 :description Optional default description for the second pair
8700 of brackets in an Org-mode link. The user can still change
8701 this when inserting this link into an Org-mode buffer.
8703 In addition to these, any additional properties can be specified
8704 and then used in capture templates.")
8706 (defun org-add-link-type (type &optional follow export)
8707 "Add TYPE to the list of `org-link-types'.
8708 Re-compute all regular expressions depending on `org-link-types'
8710 FOLLOW and EXPORT are two functions.
8712 FOLLOW should take the link path as the single argument and do whatever
8713 is necessary to follow the link, for example find a file or display
8714 a mail message.
8716 EXPORT should format the link path for export to one of the export formats.
8717 It should be a function accepting three arguments:
8719 path the path of the link, the text after the prefix (like \"http:\")
8720 desc the description of the link, if any, or a description added by
8721 org-export-normalize-links if there is none
8722 format the export format, a symbol like `html' or `latex' or `ascii'..
8724 The function may use the FORMAT information to return different values
8725 depending on the format. The return value will be put literally into
8726 the exported file. If the return value is nil, this means Org should
8727 do what it normally does with links which do not have EXPORT defined.
8729 Org-mode has a built-in default for exporting links. If you are happy with
8730 this default, there is no need to define an export function for the link
8731 type. For a simple example of an export function, see `org-bbdb.el'."
8732 (add-to-list 'org-link-types type t)
8733 (org-make-link-regexps)
8734 (if (assoc type org-link-protocols)
8735 (setcdr (assoc type org-link-protocols) (list follow export))
8736 (push (list type follow export) org-link-protocols)))
8738 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8739 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8741 ;;;###autoload
8742 (defun org-store-link (arg)
8743 "\\<org-mode-map>Store an org-link to the current location.
8744 This link is added to `org-stored-links' and can later be inserted
8745 into an org-buffer with \\[org-insert-link].
8747 For some link types, a prefix arg is interpreted:
8748 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8749 For file links, arg negates `org-context-in-file-links'."
8750 (interactive "P")
8751 (org-load-modules-maybe)
8752 (setq org-store-link-plist nil) ; reset
8753 (org-with-limited-levels
8754 (let (link cpltxt desc description search txt custom-id agenda-link)
8755 (cond
8757 ((run-hook-with-args-until-success 'org-store-link-functions)
8758 (setq link (plist-get org-store-link-plist :link)
8759 desc (or (plist-get org-store-link-plist :description) link)))
8761 ((org-src-edit-buffer-p)
8762 (let (label gc)
8763 (while (or (not label)
8764 (save-excursion
8765 (save-restriction
8766 (widen)
8767 (goto-char (point-min))
8768 (re-search-forward
8769 (regexp-quote (format org-coderef-label-format label))
8770 nil t))))
8771 (when label (message "Label exists already") (sit-for 2))
8772 (setq label (read-string "Code line label: " label)))
8773 (end-of-line 1)
8774 (setq link (format org-coderef-label-format label))
8775 (setq gc (- 79 (length link)))
8776 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8777 (insert link)
8778 (setq link (concat "(" label ")") desc nil)))
8780 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8781 ;; We are in the agenda, link to referenced location
8782 (let ((m (or (get-text-property (point) 'org-hd-marker)
8783 (get-text-property (point) 'org-marker))))
8784 (when m
8785 (org-with-point-at m
8786 (setq agenda-link
8787 (if (org-called-interactively-p 'any)
8788 (call-interactively 'org-store-link)
8789 (org-store-link nil)))))))
8791 ((eq major-mode 'calendar-mode)
8792 (let ((cd (calendar-cursor-to-date)))
8793 (setq link
8794 (format-time-string
8795 (car org-time-stamp-formats)
8796 (apply 'encode-time
8797 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8798 nil nil nil))))
8799 (org-store-link-props :type "calendar" :date cd)))
8801 ((eq major-mode 'help-mode)
8802 (setq link (concat "help:" (save-excursion
8803 (goto-char (point-min))
8804 (looking-at "^[^ ]+")
8805 (match-string 0))))
8806 (org-store-link-props :type "help"))
8808 ((eq major-mode 'w3-mode)
8809 (setq cpltxt (if (and (buffer-name)
8810 (not (string-match "Untitled" (buffer-name))))
8811 (buffer-name)
8812 (url-view-url t))
8813 link (url-view-url t))
8814 (org-store-link-props :type "w3" :url (url-view-url t)))
8816 ((eq major-mode 'w3m-mode)
8817 (setq cpltxt (or w3m-current-title w3m-current-url)
8818 link w3m-current-url)
8819 (org-store-link-props :type "w3m" :url (url-view-url t)))
8821 ((setq search (run-hook-with-args-until-success
8822 'org-create-file-search-functions))
8823 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8824 "::" search))
8825 (setq cpltxt (or description link)))
8827 ((eq major-mode 'image-mode)
8828 (setq cpltxt (concat "file:"
8829 (abbreviate-file-name buffer-file-name))
8830 link cpltxt)
8831 (org-store-link-props :type "image" :file buffer-file-name))
8833 ((eq major-mode 'dired-mode)
8834 ;; link to the file in the current line
8835 (let ((file (dired-get-filename nil t)))
8836 (setq file (if file
8837 (abbreviate-file-name
8838 (expand-file-name (dired-get-filename nil t)))
8839 ;; otherwise, no file so use current directory.
8840 default-directory))
8841 (setq cpltxt (concat "file:" file)
8842 link cpltxt)))
8844 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8845 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8846 (cond
8847 ((org-in-regexp "<<\\(.*?\\)>>")
8848 (setq cpltxt
8849 (concat "file:"
8850 (abbreviate-file-name
8851 (buffer-file-name (buffer-base-buffer)))
8852 "::" (match-string 1))
8853 link cpltxt))
8854 ((and (featurep 'org-id)
8855 (or (eq org-link-to-org-use-id t)
8856 (and (org-called-interactively-p 'any)
8857 (or (eq org-link-to-org-use-id 'create-if-interactive)
8858 (and (eq org-link-to-org-use-id
8859 'create-if-interactive-and-no-custom-id)
8860 (not custom-id))))
8861 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
8862 ;; We can make a link using the ID.
8863 (setq link (condition-case nil
8864 (prog1 (org-id-store-link)
8865 (setq desc (plist-get org-store-link-plist :description)))
8866 (error
8867 ;; probably before first headline, link to file only
8868 (concat "file:"
8869 (abbreviate-file-name
8870 (buffer-file-name (buffer-base-buffer))))))))
8872 ;; Just link to current headline
8873 (setq cpltxt (concat "file:"
8874 (abbreviate-file-name
8875 (buffer-file-name (buffer-base-buffer)))))
8876 ;; Add a context search string
8877 (when (org-xor org-context-in-file-links arg)
8878 (setq txt (cond
8879 ((org-at-heading-p) nil)
8880 ((org-region-active-p)
8881 (buffer-substring (region-beginning) (region-end)))))
8882 (when (or (null txt) (string-match "\\S-" txt))
8883 (setq cpltxt
8884 (concat cpltxt "::"
8885 (condition-case nil
8886 (org-make-org-heading-search-string txt)
8887 (error "")))
8888 desc (or (nth 4 (ignore-errors
8889 (org-heading-components))) "NONE"))))
8890 (if (string-match "::\\'" cpltxt)
8891 (setq cpltxt (substring cpltxt 0 -2)))
8892 (setq link cpltxt))))
8894 ((buffer-file-name (buffer-base-buffer))
8895 ;; Just link to this file here.
8896 (setq cpltxt (concat "file:"
8897 (abbreviate-file-name
8898 (buffer-file-name (buffer-base-buffer)))))
8899 ;; Add a context string
8900 (when (org-xor org-context-in-file-links arg)
8901 (setq txt (if (org-region-active-p)
8902 (buffer-substring (region-beginning) (region-end))
8903 (buffer-substring (point-at-bol) (point-at-eol))))
8904 ;; Only use search option if there is some text.
8905 (when (string-match "\\S-" txt)
8906 (setq cpltxt
8907 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8908 desc "NONE")))
8909 (setq link cpltxt))
8911 ((org-called-interactively-p 'interactive)
8912 (error "Cannot link to a buffer which is not visiting a file"))
8914 (t (setq link nil)))
8916 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8917 (setq link (or link cpltxt)
8918 desc (or desc cpltxt))
8919 (if (equal desc "NONE") (setq desc nil))
8921 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8922 (progn
8923 (setq org-stored-links
8924 (cons (list link desc) org-stored-links))
8925 (message "Stored: %s" (or desc link))
8926 (when custom-id
8927 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8928 "::#" custom-id))
8929 (setq org-stored-links
8930 (cons (list link desc) org-stored-links))))
8931 (or agenda-link (and link (org-make-link-string link desc)))))))
8933 (defun org-store-link-props (&rest plist)
8934 "Store link properties, extract names and addresses."
8935 (let (x adr)
8936 (when (setq x (plist-get plist :from))
8937 (setq adr (mail-extract-address-components x))
8938 (setq plist (plist-put plist :fromname (car adr)))
8939 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8940 (when (setq x (plist-get plist :to))
8941 (setq adr (mail-extract-address-components x))
8942 (setq plist (plist-put plist :toname (car adr)))
8943 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8944 (let ((from (plist-get plist :from))
8945 (to (plist-get plist :to)))
8946 (when (and from to org-from-is-user-regexp)
8947 (setq plist
8948 (plist-put plist :fromto
8949 (if (string-match org-from-is-user-regexp from)
8950 (concat "to %t")
8951 (concat "from %f"))))))
8952 (setq org-store-link-plist plist))
8954 (defun org-add-link-props (&rest plist)
8955 "Add these properties to the link property list."
8956 (let (key value)
8957 (while plist
8958 (setq key (pop plist) value (pop plist))
8959 (setq org-store-link-plist
8960 (plist-put org-store-link-plist key value)))))
8962 (defun org-email-link-description (&optional fmt)
8963 "Return the description part of an email link.
8964 This takes information from `org-store-link-plist' and formats it
8965 according to FMT (default from `org-email-link-description-format')."
8966 (setq fmt (or fmt org-email-link-description-format))
8967 (let* ((p org-store-link-plist)
8968 (to (plist-get p :toaddress))
8969 (from (plist-get p :fromaddress))
8970 (table
8971 (list
8972 (cons "%c" (plist-get p :fromto))
8973 (cons "%F" (plist-get p :from))
8974 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8975 (cons "%T" (plist-get p :to))
8976 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8977 (cons "%s" (plist-get p :subject))
8978 (cons "%d" (plist-get p :date))
8979 (cons "%m" (plist-get p :message-id)))))
8980 (when (string-match "%c" fmt)
8981 ;; Check if the user wrote this message
8982 (if (and org-from-is-user-regexp from to
8983 (save-match-data (string-match org-from-is-user-regexp from)))
8984 (setq fmt (replace-match "to %t" t t fmt))
8985 (setq fmt (replace-match "from %f" t t fmt))))
8986 (org-replace-escapes fmt table)))
8988 (defun org-make-org-heading-search-string (&optional string heading)
8989 "Make search string for STRING or current headline."
8990 (interactive)
8991 (let ((s (or string (org-get-heading)))
8992 (lines org-context-in-file-links))
8993 (unless (and string (not heading))
8994 ;; We are using a headline, clean up garbage in there.
8995 (if (string-match org-todo-regexp s)
8996 (setq s (replace-match "" t t s)))
8997 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8998 (setq s (replace-match "" t t s)))
8999 (setq s (org-trim s))
9000 (if (string-match (concat "^\\(" org-quote-string "\\|"
9001 org-comment-string "\\)") s)
9002 (setq s (replace-match "" t t s)))
9003 (while (string-match org-ts-regexp s)
9004 (setq s (replace-match "" t t s))))
9005 (or string (setq s (concat "*" s))) ; Add * for headlines
9006 (when (and string (integerp lines) (> lines 0))
9007 (let ((slines (org-split-string s "\n")))
9008 (when (< lines (length slines))
9009 (setq s (mapconcat
9010 'identity
9011 (reverse (nthcdr (- (length slines) lines)
9012 (reverse slines))) "\n")))))
9013 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9015 (defun org-make-link-string (link &optional description)
9016 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9017 (unless (string-match "\\S-" link)
9018 (error "Empty link"))
9019 (when (and description
9020 (stringp description)
9021 (not (string-match "\\S-" description)))
9022 (setq description nil))
9023 (when (stringp description)
9024 ;; Remove brackets from the description, they are fatal.
9025 (while (string-match "\\[" description)
9026 (setq description (replace-match "{" t t description)))
9027 (while (string-match "\\]" description)
9028 (setq description (replace-match "}" t t description))))
9029 (when (equal link description)
9030 ;; No description needed, it is identical
9031 (setq description nil))
9032 (when (and (not description)
9033 (not (string-match (org-image-file-name-regexp) link))
9034 (not (equal link (org-link-escape link))))
9035 (setq description (org-extract-attributes link)))
9036 (setq link
9037 (cond ((string-match (org-image-file-name-regexp) link) link)
9038 ((string-match org-link-types-re link)
9039 (concat (match-string 1 link)
9040 (org-link-escape (substring link (match-end 1)))))
9041 (t (org-link-escape link))))
9042 (concat "[[" link "]"
9043 (if description (concat "[" description "]") "")
9044 "]"))
9046 (defconst org-link-escape-chars
9047 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9048 "List of characters that should be escaped in link.
9049 This is the list that is used for internal purposes.")
9051 (defconst org-link-escape-chars-browser
9052 '(?\ )
9053 "List of escapes for characters that are problematic in links.
9054 This is the list that is used before handing over to the browser.")
9056 (defun org-link-escape (text &optional table merge)
9057 "Return percent escaped representation of TEXT.
9058 TEXT is a string with the text to escape.
9059 Optional argument TABLE is a list with characters that should be
9060 escaped. When nil, `org-link-escape-chars' is used.
9061 If optional argument MERGE is set, merge TABLE into
9062 `org-link-escape-chars'."
9063 (cond
9064 ((and table merge)
9065 (mapc (lambda (defchr)
9066 (unless (member defchr table)
9067 (setq table (cons defchr table)))) org-link-escape-chars))
9068 ((null table)
9069 (setq table org-link-escape-chars)))
9070 (mapconcat
9071 (lambda (char)
9072 (if (or (member char table)
9073 (and (or (< char 32) (= char 37) (> char 126))
9074 org-url-hexify-p))
9075 (mapconcat (lambda (sequence-element)
9076 (format "%%%.2X" sequence-element))
9077 (or (encode-coding-char char 'utf-8)
9078 (error "Unable to percent escape character: %s"
9079 (char-to-string char))) "")
9080 (char-to-string char))) text ""))
9082 (defun org-link-unescape (str)
9083 "Unhex hexified Unicode strings as returned from the JavaScript function
9084 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9085 (unless (and (null str) (string= "" str))
9086 (let ((pos 0) (case-fold-search t) unhexed)
9087 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9088 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9089 (setq str (replace-match unhexed t t str))
9090 (setq pos (+ pos (length unhexed))))))
9091 str)
9093 (defun org-link-unescape-compound (hex)
9094 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9095 Note: this function also decodes single byte encodings like
9096 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9097 (save-match-data
9098 (let* ((bytes (cdr (split-string hex "%")))
9099 (ret "")
9100 (eat 0)
9101 (sum 0))
9102 (while bytes
9103 (let* ((val (string-to-number (pop bytes) 16))
9104 (shift-xor
9105 (if (= 0 eat)
9106 (cond
9107 ((>= val 252) (cons 6 252))
9108 ((>= val 248) (cons 5 248))
9109 ((>= val 240) (cons 4 240))
9110 ((>= val 224) (cons 3 224))
9111 ((>= val 192) (cons 2 192))
9112 (t (cons 0 0)))
9113 (cons 6 128))))
9114 (if (>= val 192) (setq eat (car shift-xor)))
9115 (setq val (logxor val (cdr shift-xor)))
9116 (setq sum (+ (lsh sum (car shift-xor)) val))
9117 (if (> eat 0) (setq eat (- eat 1)))
9118 (cond
9119 ((= 0 eat) ;multi byte
9120 (setq ret (concat ret (org-char-to-string sum)))
9121 (setq sum 0))
9122 ((not bytes) ; single byte(s)
9123 (setq ret (org-link-unescape-single-byte-sequence hex))))
9124 )) ;; end (while bytes
9125 ret )))
9127 (defun org-link-unescape-single-byte-sequence (hex)
9128 "Unhexify hex-encoded single byte character sequences."
9129 (mapconcat (lambda (byte)
9130 (char-to-string (string-to-number byte 16)))
9131 (cdr (split-string hex "%")) ""))
9133 (defun org-xor (a b)
9134 "Exclusive or."
9135 (if a (not b) b))
9137 (defun org-fixup-message-id-for-http (s)
9138 "Replace special characters in a message id, so it can be used in an http query."
9139 (when (string-match "%" s)
9140 (setq s (mapconcat (lambda (c)
9141 (if (eq c ?%)
9142 "%25"
9143 (char-to-string c)))
9144 s "")))
9145 (while (string-match "<" s)
9146 (setq s (replace-match "%3C" t t s)))
9147 (while (string-match ">" s)
9148 (setq s (replace-match "%3E" t t s)))
9149 (while (string-match "@" s)
9150 (setq s (replace-match "%40" t t s)))
9153 (defun org-link-prettify (link)
9154 "Return a human-readable representation of LINK.
9155 The car of LINK must be a raw link the cdr of LINK must be either
9156 a link description or nil."
9157 (let ((desc (or (cadr link) "<no description>")))
9158 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9159 "<" (car link) ">")))
9161 ;;;###autoload
9162 (defun org-insert-link-global ()
9163 "Insert a link like Org-mode does.
9164 This command can be called in any mode to insert a link in Org-mode syntax."
9165 (interactive)
9166 (org-load-modules-maybe)
9167 (org-run-like-in-org-mode 'org-insert-link))
9169 (defun org-insert-all-links (&optional keep)
9170 "Insert all links in `org-stored-links'."
9171 (interactive "P")
9172 (let ((links (copy-sequence org-stored-links)) l)
9173 (while (setq l (if keep (pop links) (pop org-stored-links)))
9174 (insert "- ")
9175 (org-insert-link nil (car l) (cadr l))
9176 (insert "\n"))))
9178 (defun org-link-fontify-links-to-this-file ()
9179 "Fontify links to the current file in `org-stored-links'."
9180 (let ((f (buffer-file-name)) a b)
9181 (setq a (mapcar (lambda(l)
9182 (let ((ll (car l)))
9183 (when (and (string-match "^file:\\(.+\\)::" ll)
9184 (equal f (expand-file-name (match-string 1 ll))))
9185 ll)))
9186 org-stored-links))
9187 (when (featurep 'org-id)
9188 (setq b (mapcar (lambda(l)
9189 (let ((ll (car l)))
9190 (when (and (string-match "^id:\\(.+\\)$" ll)
9191 (equal f (expand-file-name
9192 (or (org-id-find-id-file
9193 (match-string 1 ll)) ""))))
9194 ll)))
9195 org-stored-links)))
9196 (mapcar (lambda(l)
9197 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9198 (delq nil (append a b)))))
9200 (defvar org-link-links-in-this-file nil)
9201 (defun org-insert-link (&optional complete-file link-location default-description)
9202 "Insert a link. At the prompt, enter the link.
9204 Completion can be used to insert any of the link protocol prefixes like
9205 http or ftp in use.
9207 The history can be used to select a link previously stored with
9208 `org-store-link'. When the empty string is entered (i.e. if you just
9209 press RET at the prompt), the link defaults to the most recently
9210 stored link. As SPC triggers completion in the minibuffer, you need to
9211 use M-SPC or C-q SPC to force the insertion of a space character.
9213 You will also be prompted for a description, and if one is given, it will
9214 be displayed in the buffer instead of the link.
9216 If there is already a link at point, this command will allow you to edit link
9217 and description parts.
9219 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9220 be selected using completion. The path to the file will be relative to the
9221 current directory if the file is in the current directory or a subdirectory.
9222 Otherwise, the link will be the absolute path as completed in the minibuffer
9223 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9224 option `org-link-file-path-type'.
9226 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9227 the current directory or below.
9229 With three \\[universal-argument] prefixes, negate the meaning of
9230 `org-keep-stored-link-after-insertion'.
9232 If `org-make-link-description-function' is non-nil, this function will be
9233 called with the link target, and the result will be the default
9234 link description.
9236 If the LINK-LOCATION parameter is non-nil, this value will be
9237 used as the link location instead of reading one interactively.
9239 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9240 be used as the default description."
9241 (interactive "P")
9242 (let* ((wcf (current-window-configuration))
9243 (origbuf (current-buffer))
9244 (region (if (org-region-active-p)
9245 (buffer-substring (region-beginning) (region-end))))
9246 (remove (and region (list (region-beginning) (region-end))))
9247 (desc region)
9248 tmphist ; byte-compile incorrectly complains about this
9249 (link link-location)
9250 (abbrevs org-link-abbrev-alist-local)
9251 entry file all-prefixes auto-desc)
9252 (cond
9253 (link-location) ; specified by arg, just use it.
9254 ((org-in-regexp org-bracket-link-regexp 1)
9255 ;; We do have a link at point, and we are going to edit it.
9256 (setq remove (list (match-beginning 0) (match-end 0)))
9257 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9258 (setq link (read-string "Link: "
9259 (org-link-unescape
9260 (org-match-string-no-properties 1)))))
9261 ((or (org-in-regexp org-angle-link-re)
9262 (org-in-regexp org-plain-link-re))
9263 ;; Convert to bracket link
9264 (setq remove (list (match-beginning 0) (match-end 0))
9265 link (read-string "Link: "
9266 (org-remove-angle-brackets (match-string 0)))))
9267 ((member complete-file '((4) (16)))
9268 ;; Completing read for file names.
9269 (setq link (org-file-complete-link complete-file)))
9271 ;; Read link, with completion for stored links.
9272 (org-link-fontify-links-to-this-file)
9273 (org-switch-to-buffer-other-window "*Org Links*")
9274 (with-current-buffer "*Org Links*"
9275 (erase-buffer)
9276 (insert "Insert a link.
9277 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9278 (when org-stored-links
9279 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9280 (insert (mapconcat 'org-link-prettify
9281 (reverse org-stored-links) "\n")))
9282 (goto-char (point-min)))
9283 (let ((cw (selected-window)))
9284 (select-window (get-buffer-window "*Org Links*" 'visible))
9285 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9286 (unless (pos-visible-in-window-p (point-max))
9287 (org-fit-window-to-buffer))
9288 (and (window-live-p cw) (select-window cw)))
9289 ;; Fake a link history, containing the stored links.
9290 (setq tmphist (append (mapcar 'car org-stored-links)
9291 org-insert-link-history))
9292 (setq all-prefixes (append (mapcar 'car abbrevs)
9293 (mapcar 'car org-link-abbrev-alist)
9294 org-link-types))
9295 (unwind-protect
9296 (progn
9297 (setq link
9298 (let ((org-completion-use-ido nil)
9299 (org-completion-use-iswitchb nil))
9300 (org-completing-read
9301 "Link: "
9302 (append
9303 (mapcar (lambda (x) (list (concat x ":")))
9304 all-prefixes)
9305 (mapcar 'car org-stored-links)
9306 (mapcar 'cadr org-stored-links))
9307 nil nil nil
9308 'tmphist
9309 (caar org-stored-links))))
9310 (if (not (string-match "\\S-" link))
9311 (error "No link selected"))
9312 (mapc (lambda(l)
9313 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9314 org-stored-links)
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 (with-current-buffer origbuf
9320 (org-link-try-special-completion link)))))
9321 (set-window-configuration wcf)
9322 (kill-buffer "*Org Links*"))
9323 (setq entry (assoc link org-stored-links))
9324 (or entry (push link org-insert-link-history))
9325 (setq desc (or desc (nth 1 entry)))))
9327 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9328 (not org-keep-stored-link-after-insertion))
9329 (setq org-stored-links (delq (assoc link org-stored-links)
9330 org-stored-links)))
9332 (if (string-match org-plain-link-re link)
9333 ;; URL-like link, normalize the use of angular brackets.
9334 (setq link (org-remove-angle-brackets link)))
9336 ;; Check if we are linking to the current file with a search option
9337 ;; If yes, simplify the link by using only the search option.
9338 (when (and buffer-file-name
9339 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9340 (let* ((path (match-string 1 link))
9341 (case-fold-search nil)
9342 (search (match-string 2 link)))
9343 (save-match-data
9344 (if (equal (file-truename buffer-file-name) (file-truename path))
9345 ;; We are linking to this same file, with a search option
9346 (setq link search)))))
9348 ;; Check if we can/should use a relative path. If yes, simplify the link
9349 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9350 (let* ((type (match-string 1 link))
9351 (path (match-string 2 link))
9352 (origpath path)
9353 (case-fold-search nil))
9354 (cond
9355 ((or (eq org-link-file-path-type 'absolute)
9356 (equal complete-file '(16)))
9357 (setq path (abbreviate-file-name (expand-file-name path))))
9358 ((eq org-link-file-path-type 'noabbrev)
9359 (setq path (expand-file-name path)))
9360 ((eq org-link-file-path-type 'relative)
9361 (setq path (file-relative-name path)))
9363 (save-match-data
9364 (if (string-match (concat "^" (regexp-quote
9365 (expand-file-name
9366 (file-name-as-directory
9367 default-directory))))
9368 (expand-file-name path))
9369 ;; We are linking a file with relative path name.
9370 (setq path (substring (expand-file-name path)
9371 (match-end 0)))
9372 (setq path (abbreviate-file-name (expand-file-name path)))))))
9373 (setq link (concat type path))
9374 (if (equal desc origpath)
9375 (setq desc path))))
9377 (if org-make-link-description-function
9378 (setq desc
9379 (or (condition-case nil
9380 (funcall org-make-link-description-function link desc)
9381 (error (progn (message "Can't get link description from `%s'"
9382 (symbol-name org-make-link-description-function))
9383 (sit-for 2) nil)))
9384 (read-string "Description: " default-description)))
9385 (if default-description (setq desc default-description)
9386 (setq desc (or (and auto-desc desc)
9387 (read-string "Description: " desc)))))
9389 (unless (string-match "\\S-" desc) (setq desc nil))
9390 (if remove (apply 'delete-region remove))
9391 (insert (org-make-link-string link desc))))
9393 (defun org-link-try-special-completion (type)
9394 "If there is completion support for link type TYPE, offer it."
9395 (let ((fun (intern (concat "org-" type "-complete-link"))))
9396 (if (functionp fun)
9397 (funcall fun)
9398 (read-string "Link (no completion support): " (concat type ":")))))
9400 (defun org-file-complete-link (&optional arg)
9401 "Create a file link using completion."
9402 (let (file link)
9403 (setq file (read-file-name "File: "))
9404 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9405 (pwd1 (file-name-as-directory (abbreviate-file-name
9406 (expand-file-name ".")))))
9407 (cond
9408 ((equal arg '(16))
9409 (setq link (concat
9410 "file:"
9411 (abbreviate-file-name (expand-file-name file)))))
9412 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9413 (setq link (concat "file:" (match-string 1 file))))
9414 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9415 (expand-file-name file))
9416 (setq link (concat
9417 "file:" (match-string 1 (expand-file-name file)))))
9418 (t (setq link (concat "file:" file)))))
9419 link))
9421 (defun org-completing-read (&rest args)
9422 "Completing-read with SPACE being a normal character."
9423 (let ((enable-recursive-minibuffers t)
9424 (minibuffer-local-completion-map
9425 (copy-keymap minibuffer-local-completion-map)))
9426 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9427 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9428 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9429 (apply 'org-icompleting-read args)))
9431 (defun org-completing-read-no-i (&rest args)
9432 (let (org-completion-use-ido org-completion-use-iswitchb)
9433 (apply 'org-completing-read args)))
9435 (defun org-iswitchb-completing-read (prompt choices &rest args)
9436 "Use iswitch as a completing-read replacement to choose from choices.
9437 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9438 from."
9439 (let* ((iswitchb-use-virtual-buffers nil)
9440 (iswitchb-make-buflist-hook
9441 (lambda ()
9442 (setq iswitchb-temp-buflist choices))))
9443 (iswitchb-read-buffer prompt)))
9445 (defun org-icompleting-read (&rest args)
9446 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9447 (org-without-partial-completion
9448 (if (and org-completion-use-ido
9449 (fboundp 'ido-completing-read)
9450 (boundp 'ido-mode) ido-mode
9451 (listp (second args)))
9452 (let ((ido-enter-matching-directory nil))
9453 (apply 'ido-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 (if (and org-completion-use-iswitchb
9459 (boundp 'iswitchb-mode) iswitchb-mode
9460 (listp (second args)))
9461 (apply 'org-iswitchb-completing-read (concat (car args))
9462 (if (consp (car (nth 1 args)))
9463 (mapcar 'car (nth 1 args))
9464 (nth 1 args))
9465 (cddr args))
9466 (apply 'completing-read args)))))
9468 (defun org-extract-attributes (s)
9469 "Extract the attributes cookie from a string and set as text property."
9470 (let (a attr (start 0) key value)
9471 (save-match-data
9472 (when (string-match "{{\\([^}]+\\)}}$" s)
9473 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9474 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9475 (setq key (match-string 1 a) value (match-string 2 a)
9476 start (match-end 0)
9477 attr (plist-put attr (intern key) value))))
9478 (org-add-props s nil 'org-attr attr))
9481 (defun org-extract-attributes-from-string (tag)
9482 (let (key value attr)
9483 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9484 (setq key (match-string 1 tag) value (match-string 2 tag)
9485 tag (replace-match "" t t tag)
9486 attr (plist-put attr (intern key) value)))
9487 (cons tag attr)))
9489 (defun org-attributes-to-string (plist)
9490 "Format a property list into an HTML attribute list."
9491 (let ((s "") key value)
9492 (while plist
9493 (setq key (pop plist) value (pop plist))
9494 (and value
9495 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9498 ;;; Opening/following a link
9500 (defvar org-link-search-failed nil)
9502 (defvar org-open-link-functions nil
9503 "Hook for functions finding a plain text link.
9504 These functions must take a single argument, the link content.
9505 They will be called for links that look like [[link text][description]]
9506 when LINK TEXT does not have a protocol like \"http:\" and does not look
9507 like a filename (e.g. \"./blue.png\").
9509 These functions will be called *before* Org attempts to resolve the
9510 link by doing text searches in the current buffer - so if you want a
9511 link \"[[target]]\" to still find \"<<target>>\", your function should
9512 handle this as a special case.
9514 When the function does handle the link, it must return a non-nil value.
9515 If it decides that it is not responsible for this link, it must return
9516 nil to indicate that that Org-mode can continue with other options
9517 like exact and fuzzy text search.")
9519 (defun org-next-link ()
9520 "Move forward to the next link.
9521 If the link is in hidden text, expose it."
9522 (interactive)
9523 (when (and org-link-search-failed (eq this-command last-command))
9524 (goto-char (point-min))
9525 (message "Link search wrapped back to beginning of buffer"))
9526 (setq org-link-search-failed nil)
9527 (let* ((pos (point))
9528 (ct (org-context))
9529 (a (assoc :link ct)))
9530 (if a (goto-char (nth 2 a)))
9531 (if (re-search-forward org-any-link-re nil t)
9532 (progn
9533 (goto-char (match-beginning 0))
9534 (if (outline-invisible-p) (org-show-context)))
9535 (goto-char pos)
9536 (setq org-link-search-failed t)
9537 (error "No further link found"))))
9539 (defun org-previous-link ()
9540 "Move backward to the previous link.
9541 If the link is in hidden text, expose it."
9542 (interactive)
9543 (when (and org-link-search-failed (eq this-command last-command))
9544 (goto-char (point-max))
9545 (message "Link search wrapped back to end of buffer"))
9546 (setq org-link-search-failed nil)
9547 (let* ((pos (point))
9548 (ct (org-context))
9549 (a (assoc :link ct)))
9550 (if a (goto-char (nth 1 a)))
9551 (if (re-search-backward org-any-link-re nil t)
9552 (progn
9553 (goto-char (match-beginning 0))
9554 (if (outline-invisible-p) (org-show-context)))
9555 (goto-char pos)
9556 (setq org-link-search-failed t)
9557 (error "No further link found"))))
9559 (defun org-translate-link (s)
9560 "Translate a link string if a translation function has been defined."
9561 (if (and org-link-translation-function
9562 (fboundp org-link-translation-function)
9563 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9564 (progn
9565 (setq s (funcall org-link-translation-function
9566 (match-string 1 s) (match-string 2 s)))
9567 (concat (car s) ":" (cdr s)))
9570 (defun org-translate-link-from-planner (type path)
9571 "Translate a link from Emacs Planner syntax so that Org can follow it.
9572 This is still an experimental function, your mileage may vary."
9573 (cond
9574 ((member type '("http" "https" "news" "ftp"))
9575 ;; standard Internet links are the same.
9576 nil)
9577 ((and (equal type "irc") (string-match "^//" path))
9578 ;; Planner has two / at the beginning of an irc link, we have 1.
9579 ;; We should have zero, actually....
9580 (setq path (substring path 1)))
9581 ((and (equal type "lisp") (string-match "^/" path))
9582 ;; Planner has a slash, we do not.
9583 (setq type "elisp" path (substring path 1)))
9584 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9585 ;; A typical message link. Planner has the id after the final slash,
9586 ;; we separate it with a hash mark
9587 (setq path (concat (match-string 1 path) "#"
9588 (org-remove-angle-brackets (match-string 2 path)))))
9590 (cons type path))
9592 (defun org-find-file-at-mouse (ev)
9593 "Open file link or URL at mouse."
9594 (interactive "e")
9595 (mouse-set-point ev)
9596 (org-open-at-point 'in-emacs))
9598 (defun org-open-at-mouse (ev)
9599 "Open file link or URL at mouse.
9600 See the docstring of `org-open-file' for details."
9601 (interactive "e")
9602 (mouse-set-point ev)
9603 (if (eq major-mode 'org-agenda-mode)
9604 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9605 (org-open-at-point))
9607 (defvar org-window-config-before-follow-link nil
9608 "The window configuration before following a link.
9609 This is saved in case the need arises to restore it.")
9611 (defvar org-open-link-marker (make-marker)
9612 "Marker pointing to the location where `org-open-at-point; was called.")
9614 ;;;###autoload
9615 (defun org-open-at-point-global ()
9616 "Follow a link like Org-mode does.
9617 This command can be called in any mode to follow a link that has
9618 Org-mode syntax."
9619 (interactive)
9620 (org-run-like-in-org-mode 'org-open-at-point))
9622 ;;;###autoload
9623 (defun org-open-link-from-string (s &optional arg reference-buffer)
9624 "Open a link in the string S, as if it was in Org-mode."
9625 (interactive "sLink: \nP")
9626 (let ((reference-buffer (or reference-buffer (current-buffer))))
9627 (with-temp-buffer
9628 (let ((org-inhibit-startup (not reference-buffer)))
9629 (org-mode)
9630 (insert s)
9631 (goto-char (point-min))
9632 (when reference-buffer
9633 (setq org-link-abbrev-alist-local
9634 (with-current-buffer reference-buffer
9635 org-link-abbrev-alist-local)))
9636 (org-open-at-point arg reference-buffer)))))
9638 (defvar org-open-at-point-functions nil
9639 "Hook that is run when following a link at point.
9641 Functions in this hook must return t if they identify and follow
9642 a link at point. If they don't find anything interesting at point,
9643 they must return nil.")
9645 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9646 (defun org-open-at-point (&optional arg reference-buffer)
9647 "Open link at or after point.
9648 If there is no link at point, this function will search forward up to
9649 the end of the current line.
9650 Normally, files will be opened by an appropriate application. If the
9651 optional prefix argument ARG is non-nil, Emacs will visit the file.
9652 With a double prefix argument, try to open outside of Emacs, in the
9653 application the system uses for this file type."
9654 (interactive "P")
9655 ;; if in a code block, then open the block's results
9656 (unless (call-interactively #'org-babel-open-src-block-result)
9657 (org-load-modules-maybe)
9658 (move-marker org-open-link-marker (point))
9659 (setq org-window-config-before-follow-link (current-window-configuration))
9660 (org-remove-occur-highlights nil nil t)
9661 (cond
9662 ((and (org-at-heading-p)
9663 (not (org-at-timestamp-p t))
9664 (not (org-in-regexp
9665 (concat org-plain-link-re "\\|"
9666 org-bracket-link-regexp "\\|"
9667 org-angle-link-re "\\|"
9668 "[ \t]:[^ \t\n]+:[ \t]*$")))
9669 (not (get-text-property (point) 'org-linked-text)))
9670 (or (org-offer-links-in-entry arg)
9671 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9672 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9673 ((and (org-at-timestamp-p t)
9674 (not (org-in-regexp org-bracket-link-regexp)))
9675 (org-follow-timestamp-link))
9676 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9677 (not (org-in-regexp org-bracket-link-regexp)))
9678 (org-footnote-action))
9680 (let (type path link line search (pos (point)))
9681 (catch 'match
9682 (save-excursion
9683 (skip-chars-forward "^]\n\r")
9684 (when (org-in-regexp org-bracket-link-regexp 1)
9685 (setq link (org-extract-attributes
9686 (org-link-unescape (org-match-string-no-properties 1))))
9687 (while (string-match " *\n *" link)
9688 (setq link (replace-match " " t t link)))
9689 (setq link (org-link-expand-abbrev link))
9690 (cond
9691 ((or (file-name-absolute-p link)
9692 (string-match "^\\.\\.?/" link))
9693 (setq type "file" path link))
9694 ((string-match org-link-re-with-space3 link)
9695 (setq type (match-string 1 link) path (match-string 2 link)))
9696 ((string-match "^help:+\\(.+\\)" link)
9697 (setq type "help" path (match-string 1 link)))
9698 (t (setq type "thisfile" path link)))
9699 (throw 'match t)))
9701 (when (get-text-property (point) 'org-linked-text)
9702 (setq type "thisfile"
9703 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9704 (1+ (point)) (point))
9705 path (buffer-substring
9706 (or (previous-single-property-change pos 'org-linked-text)
9707 (point-min))
9708 (or (next-single-property-change pos 'org-linked-text)
9709 (point-max))))
9710 (throw 'match t))
9712 (save-excursion
9713 (when (or (org-in-regexp org-angle-link-re)
9714 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9715 (save-match-data (not (looking-back "\\[\\[")))))
9716 (setq type (match-string 1)
9717 path (org-link-unescape (match-string 2)))
9718 (throw 'match t)))
9719 (save-excursion
9720 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9721 (setq type "tags"
9722 path (match-string 1))
9723 (while (string-match ":" path)
9724 (setq path (replace-match "+" t t path)))
9725 (throw 'match t)))
9726 (when (org-in-regexp "<\\([^><\n]+\\)>")
9727 (setq type "tree-match"
9728 path (match-string 1))
9729 (throw 'match t)))
9730 (unless path
9731 (error "No link found"))
9733 ;; switch back to reference buffer
9734 ;; needed when if called in a temporary buffer through
9735 ;; org-open-link-from-string
9736 (with-current-buffer (or reference-buffer (current-buffer))
9738 ;; Remove any trailing spaces in path
9739 (if (string-match " +\\'" path)
9740 (setq path (replace-match "" t t path)))
9741 (if (and org-link-translation-function
9742 (fboundp org-link-translation-function))
9743 ;; Check if we need to translate the link
9744 (let ((tmp (funcall org-link-translation-function type path)))
9745 (setq type (car tmp) path (cdr tmp))))
9747 (cond
9749 ((assoc type org-link-protocols)
9750 (funcall (nth 1 (assoc type org-link-protocols)) path))
9752 ((equal type "help")
9753 (let ((f-or-v (intern path)))
9754 (cond ((fboundp f-or-v)
9755 (describe-function f-or-v))
9756 ((boundp f-or-v)
9757 (describe-variable f-or-v))
9758 (t (error "Not a known function or variable")))))
9760 ((equal type "mailto")
9761 (let ((cmd (car org-link-mailto-program))
9762 (args (cdr org-link-mailto-program)) args1
9763 (address path) (subject "") a)
9764 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9765 (setq address (match-string 1 path)
9766 subject (org-link-escape (match-string 2 path))))
9767 (while args
9768 (cond
9769 ((not (stringp (car args))) (push (pop args) args1))
9770 (t (setq a (pop args))
9771 (if (string-match "%a" a)
9772 (setq a (replace-match address t t a)))
9773 (if (string-match "%s" a)
9774 (setq a (replace-match subject t t a)))
9775 (push a args1))))
9776 (apply cmd (nreverse args1))))
9778 ((member type '("http" "https" "ftp" "news"))
9779 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9780 (org-link-escape
9781 path org-link-escape-chars-browser)
9782 path))))
9784 ((string= type "doi")
9785 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9786 (org-link-escape
9787 path org-link-escape-chars-browser)
9788 path))))
9790 ((member type '("message"))
9791 (browse-url (concat type ":" path)))
9793 ((string= type "tags")
9794 (org-tags-view arg path))
9796 ((string= type "tree-match")
9797 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9799 ((string= type "file")
9800 (if (string-match "::\\([0-9]+\\)\\'" path)
9801 (setq line (string-to-number (match-string 1 path))
9802 path (substring path 0 (match-beginning 0)))
9803 (if (string-match "::\\(.+\\)\\'" path)
9804 (setq search (match-string 1 path)
9805 path (substring path 0 (match-beginning 0)))))
9806 (if (string-match "[*?{]" (file-name-nondirectory path))
9807 (dired path)
9808 (org-open-file path arg line search)))
9810 ((string= type "shell")
9811 (let ((buf (generate-new-buffer "*Org Shell Output"))
9812 (cmd path))
9813 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9814 (string-match org-confirm-shell-link-not-regexp cmd))
9815 (not org-confirm-shell-link-function)
9816 (funcall org-confirm-shell-link-function
9817 (format "Execute \"%s\" in shell? "
9818 (org-add-props cmd nil
9819 'face 'org-warning))))
9820 (progn
9821 (message "Executing %s" cmd)
9822 (shell-command cmd buf)
9823 (if (featurep 'midnight)
9824 (setq clean-buffer-list-kill-buffer-names
9825 (cons buf clean-buffer-list-kill-buffer-names))))
9826 (error "Abort"))))
9828 ((string= type "elisp")
9829 (let ((cmd path))
9830 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9831 (string-match org-confirm-elisp-link-not-regexp cmd))
9832 (not org-confirm-elisp-link-function)
9833 (funcall org-confirm-elisp-link-function
9834 (format "Execute \"%s\" as elisp? "
9835 (org-add-props cmd nil
9836 'face 'org-warning))))
9837 (message "%s => %s" cmd
9838 (if (equal (string-to-char cmd) ?\()
9839 (eval (read cmd))
9840 (call-interactively (read cmd))))
9841 (error "Abort"))))
9843 ((and (string= type "thisfile")
9844 (run-hook-with-args-until-success
9845 'org-open-link-functions path)))
9847 ((string= type "thisfile")
9848 (if arg
9849 (switch-to-buffer-other-window
9850 (org-get-buffer-for-internal-link (current-buffer)))
9851 (org-mark-ring-push))
9852 (let ((cmd `(org-link-search
9853 ,path
9854 ,(cond ((equal arg '(4)) ''occur)
9855 ((equal arg '(16)) ''org-occur))
9856 ,pos)))
9857 (condition-case nil (let ((org-link-search-inhibit-query t))
9858 (eval cmd))
9859 (error (progn (widen) (eval cmd))))))
9861 (t (browse-url-at-point)))))))
9862 (move-marker org-open-link-marker nil)
9863 (run-hook-with-args 'org-follow-link-hook)))
9865 (defun org-offer-links-in-entry (&optional nth zero)
9866 "Offer links in the current entry and follow the selected link.
9867 If there is only one link, follow it immediately as well.
9868 If NTH is an integer, immediately pick the NTH link found.
9869 If ZERO is a string, check also this string for a link, and if
9870 there is one, offer it as link number zero."
9871 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9872 "\\(" org-angle-link-re "\\)\\|"
9873 "\\(" org-plain-link-re "\\)"))
9874 (cnt ?0)
9875 (in-emacs (if (integerp nth) nil nth))
9876 have-zero end links link c)
9877 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9878 (push (match-string 0 zero) links)
9879 (setq cnt (1- cnt) have-zero t))
9880 (save-excursion
9881 (org-back-to-heading t)
9882 (setq end (save-excursion (outline-next-heading) (point)))
9883 (while (re-search-forward re end t)
9884 (push (match-string 0) links))
9885 (setq links (org-uniquify (reverse links))))
9887 (cond
9888 ((null links)
9889 (message "No links"))
9890 ((equal (length links) 1)
9891 (setq link (list (car links))))
9892 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9893 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9894 (t ; we have to select a link
9895 (save-excursion
9896 (save-window-excursion
9897 (delete-other-windows)
9898 (with-output-to-temp-buffer "*Select Link*"
9899 (mapc (lambda (l)
9900 (if (not (string-match org-bracket-link-regexp l))
9901 (princ (format "[%c] %s\n" (incf cnt)
9902 (org-remove-angle-brackets l)))
9903 (if (match-end 3)
9904 (princ (format "[%c] %s (%s)\n" (incf cnt)
9905 (match-string 3 l) (match-string 1 l)))
9906 (princ (format "[%c] %s\n" (incf cnt)
9907 (match-string 1 l))))))
9908 links))
9909 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9910 (message "Select link to open, RET to open all:")
9911 (setq c (read-char-exclusive))
9912 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9913 (when (equal c ?q) (error "Abort"))
9914 (if (equal c ?\C-m)
9915 (setq link links)
9916 (setq nth (- c ?0))
9917 (if have-zero (setq nth (1+ nth)))
9918 (unless (and (integerp nth) (>= (length links) nth))
9919 (error "Invalid link selection"))
9920 (setq link (list (nth (1- nth) links))))))
9921 (if link
9922 (let ((buf (current-buffer)))
9923 (dolist (l link)
9924 (org-open-link-from-string l in-emacs buf))
9926 nil)))
9928 ;; Add special file links that specify the way of opening
9930 (org-add-link-type "file+sys" 'org-open-file-with-system)
9931 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9932 (defun org-open-file-with-system (path)
9933 "Open file at PATH using the system way of opening it."
9934 (org-open-file path 'system))
9935 (defun org-open-file-with-emacs (path)
9936 "Open file at PATH in Emacs."
9937 (org-open-file path 'emacs))
9938 (defun org-remove-file-link-modifiers ()
9939 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9940 (goto-char (point-min))
9941 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9942 (org-if-unprotected
9943 (replace-match "file:" t t))))
9944 (eval-after-load "org-exp"
9945 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9946 'org-remove-file-link-modifiers))
9948 ;;;; Time estimates
9950 (defun org-get-effort (&optional pom)
9951 "Get the effort estimate for the current entry."
9952 (org-entry-get pom org-effort-property))
9954 ;;; File search
9956 (defvar org-create-file-search-functions nil
9957 "List of functions to construct the right search string for a file link.
9958 These functions are called in turn with point at the location to
9959 which the link should point.
9961 A function in the hook should first test if it would like to
9962 handle this file type, for example by checking the `major-mode'
9963 or the file extension. If it decides not to handle this file, it
9964 should just return nil to give other functions a chance. If it
9965 does handle the file, it must return the search string to be used
9966 when following the link. The search string will be part of the
9967 file link, given after a double colon, and `org-open-at-point'
9968 will automatically search for it. If special measures must be
9969 taken to make the search successful, another function should be
9970 added to the companion hook `org-execute-file-search-functions',
9971 which see.
9973 A function in this hook may also use `setq' to set the variable
9974 `description' to provide a suggestion for the descriptive text to
9975 be used for this link when it gets inserted into an Org-mode
9976 buffer with \\[org-insert-link].")
9978 (defvar org-execute-file-search-functions nil
9979 "List of functions to execute a file search triggered by a link.
9981 Functions added to this hook must accept a single argument, the
9982 search string that was part of the file link, the part after the
9983 double colon. The function must first check if it would like to
9984 handle this search, for example by checking the `major-mode' or
9985 the file extension. If it decides not to handle this search, it
9986 should just return nil to give other functions a chance. If it
9987 does handle the search, it must return a non-nil value to keep
9988 other functions from trying.
9990 Each function can access the current prefix argument through the
9991 variable `current-prefix-argument'. Note that a single prefix is
9992 used to force opening a link in Emacs, so it may be good to only
9993 use a numeric or double prefix to guide the search function.
9995 In case this is needed, a function in this hook can also restore
9996 the window configuration before `org-open-at-point' was called using:
9998 (set-window-configuration org-window-config-before-follow-link)")
10000 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10001 (defun org-link-search (s &optional type avoid-pos stealth)
10002 "Search for a link search option.
10003 If S is surrounded by forward slashes, it is interpreted as a
10004 regular expression. In org-mode files, this will create an `org-occur'
10005 sparse tree. In ordinary files, `occur' will be used to list matches.
10006 If the current buffer is in `dired-mode', grep will be used to search
10007 in all files. If AVOID-POS is given, ignore matches near that position.
10009 When optional argument STEALTH is non-nil, do not modify
10010 visibility around point, thus ignoring
10011 `org-show-hierarchy-above', `org-show-following-heading' and
10012 `org-show-siblings' variables."
10013 (let ((case-fold-search t)
10014 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10015 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10016 (append '(("") (" ") ("\t") ("\n"))
10017 org-emphasis-alist)
10018 "\\|") "\\)"))
10019 (pos (point))
10020 (pre nil) (post nil)
10021 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10022 (cond
10023 ;; First check if there are any special search functions
10024 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10025 ;; Now try the builtin stuff
10026 ((and (equal (string-to-char s0) ?#)
10027 (> (length s0) 1)
10028 (save-excursion
10029 (goto-char (point-min))
10030 (and
10031 (re-search-forward
10032 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10033 (setq type 'dedicated
10034 pos (match-beginning 0))))
10035 ;; There is an exact target for this
10036 (goto-char pos)
10037 (org-back-to-heading t)))
10038 ((save-excursion
10039 (goto-char (point-min))
10040 (and
10041 (re-search-forward
10042 (concat "<<" (regexp-quote s0) ">>") nil t)
10043 (setq type 'dedicated
10044 pos (match-beginning 0))))
10045 ;; There is an exact target for this
10046 (goto-char pos))
10047 ((save-excursion
10048 (goto-char (point-min))
10049 (and
10050 (re-search-forward
10051 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10052 (setq type 'dedicated pos (match-beginning 0))))
10053 ;; Found an invisible target.
10054 (goto-char pos))
10055 ((save-excursion
10056 (goto-char (point-min))
10057 (and
10058 (re-search-forward
10059 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10060 (setq type 'dedicated pos (match-beginning 0))))
10061 ;; Found an element with a matching #+name affiliated keyword.
10062 (goto-char pos))
10063 ((and (string-match "^(\\(.*\\))$" s0)
10064 (save-excursion
10065 (goto-char (point-min))
10066 (and
10067 (re-search-forward
10068 (concat "[^[]" (regexp-quote
10069 (format org-coderef-label-format
10070 (match-string 1 s0))))
10071 nil t)
10072 (setq type 'dedicated
10073 pos (1+ (match-beginning 0))))))
10074 ;; There is a coderef target for this
10075 (goto-char pos))
10076 ((string-match "^/\\(.*\\)/$" s)
10077 ;; A regular expression
10078 (cond
10079 ((derived-mode-p 'org-mode)
10080 (org-occur (match-string 1 s)))
10081 ;;((eq major-mode 'dired-mode)
10082 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10083 (t (org-do-occur (match-string 1 s)))))
10084 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10085 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10086 (goto-char (point-min))
10087 (cond
10088 ((let (case-fold-search)
10089 (re-search-forward (format org-complex-heading-regexp-format
10090 (regexp-quote s))
10091 nil t))
10092 ;; OK, found a match
10093 (setq type 'dedicated)
10094 (goto-char (match-beginning 0)))
10095 ((and (not org-link-search-inhibit-query)
10096 (eq org-link-search-must-match-exact-headline 'query-to-create)
10097 (y-or-n-p "No match - create this as a new heading? "))
10098 (goto-char (point-max))
10099 (or (bolp) (newline))
10100 (insert "* " s "\n")
10101 (beginning-of-line 0))
10103 (goto-char pos)
10104 (error "No match"))))
10106 ;; A normal search string
10107 (when (equal (string-to-char s) ?*)
10108 ;; Anchor on headlines, post may include tags.
10109 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10110 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10111 s (substring s 1)))
10112 (remove-text-properties
10113 0 (length s)
10114 '(face nil mouse-face nil keymap nil fontified nil) s)
10115 ;; Make a series of regular expressions to find a match
10116 (setq words (org-split-string s "[ \n\r\t]+")
10118 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10119 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10120 "\\)" markers)
10121 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10122 re2a (concat "[ \t\r\n]" re2a_)
10123 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10124 re4 (concat "[^a-zA-Z_]" re4_)
10126 re1 (concat pre re2 post)
10127 re3 (concat pre (if pre re4_ re4) post)
10128 re5 (concat pre ".*" re4)
10129 re2 (concat pre re2)
10130 re2a (concat pre (if pre re2a_ re2a))
10131 re4 (concat pre (if pre re4_ re4))
10132 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10133 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10134 re5 "\\)"
10136 (cond
10137 ((eq type 'org-occur) (org-occur reall))
10138 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10139 (t (goto-char (point-min))
10140 (setq type 'fuzzy)
10141 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10142 (org-search-not-self 1 re1 nil t)
10143 (org-search-not-self 1 re2 nil t)
10144 (org-search-not-self 1 re2a nil t)
10145 (org-search-not-self 1 re3 nil t)
10146 (org-search-not-self 1 re4 nil t)
10147 (org-search-not-self 1 re5 nil t)
10149 (goto-char (match-beginning 1))
10150 (goto-char pos)
10151 (error "No match"))))))
10152 (and (derived-mode-p 'org-mode)
10153 (not stealth)
10154 (org-show-context 'link-search))
10155 type))
10157 (defun org-search-not-self (group &rest args)
10158 "Execute `re-search-forward', but only accept matches that do not
10159 enclose the position of `org-open-link-marker'."
10160 (let ((m org-open-link-marker))
10161 (catch 'exit
10162 (while (apply 're-search-forward args)
10163 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10164 (goto-char (match-end group))
10165 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10166 (> (match-beginning 0) (marker-position m))
10167 (< (match-end 0) (marker-position m)))
10168 (save-match-data
10169 (or (not (org-in-regexp
10170 org-bracket-link-analytic-regexp 1))
10171 (not (match-end 4)) ; no description
10172 (and (<= (match-beginning 4) (point))
10173 (>= (match-end 4) (point))))))
10174 (throw 'exit (point))))))))
10176 (defun org-get-buffer-for-internal-link (buffer)
10177 "Return a buffer to be used for displaying the link target of internal links."
10178 (cond
10179 ((not org-display-internal-link-with-indirect-buffer)
10180 buffer)
10181 ((string-match "(Clone)$" (buffer-name buffer))
10182 (message "Buffer is already a clone, not making another one")
10183 ;; we also do not modify visibility in this case
10184 buffer)
10185 (t ; make a new indirect buffer for displaying the link
10186 (let* ((bn (buffer-name buffer))
10187 (ibn (concat bn "(Clone)"))
10188 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10189 (with-current-buffer ib (org-overview))
10190 ib))))
10192 (defun org-do-occur (regexp &optional cleanup)
10193 "Call the Emacs command `occur'.
10194 If CLEANUP is non-nil, remove the printout of the regular expression
10195 in the *Occur* buffer. This is useful if the regex is long and not useful
10196 to read."
10197 (occur regexp)
10198 (when cleanup
10199 (let ((cwin (selected-window)) win beg end)
10200 (when (setq win (get-buffer-window "*Occur*"))
10201 (select-window win))
10202 (goto-char (point-min))
10203 (when (re-search-forward "match[a-z]+" nil t)
10204 (setq beg (match-end 0))
10205 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10206 (setq end (1- (match-beginning 0)))))
10207 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10208 (goto-char (point-min))
10209 (select-window cwin))))
10211 ;;; The mark ring for links jumps
10213 (defvar org-mark-ring nil
10214 "Mark ring for positions before jumps in Org-mode.")
10215 (defvar org-mark-ring-last-goto nil
10216 "Last position in the mark ring used to go back.")
10217 ;; Fill and close the ring
10218 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10219 (loop for i from 1 to org-mark-ring-length do
10220 (push (make-marker) org-mark-ring))
10221 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10222 org-mark-ring)
10224 (defun org-mark-ring-push (&optional pos buffer)
10225 "Put the current position or POS into the mark ring and rotate it."
10226 (interactive)
10227 (setq pos (or pos (point)))
10228 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10229 (move-marker (car org-mark-ring)
10230 (or pos (point))
10231 (or buffer (current-buffer)))
10232 (message "%s"
10233 (substitute-command-keys
10234 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10236 (defun org-mark-ring-goto (&optional n)
10237 "Jump to the previous position in the mark ring.
10238 With prefix arg N, jump back that many stored positions. When
10239 called several times in succession, walk through the entire ring.
10240 Org-mode commands jumping to a different position in the current file,
10241 or to another Org-mode file, automatically push the old position
10242 onto the ring."
10243 (interactive "p")
10244 (let (p m)
10245 (if (eq last-command this-command)
10246 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10247 (setq p org-mark-ring))
10248 (setq org-mark-ring-last-goto p)
10249 (setq m (car p))
10250 (org-pop-to-buffer-same-window (marker-buffer m))
10251 (goto-char m)
10252 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10254 (defun org-remove-angle-brackets (s)
10255 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10256 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10258 (defun org-add-angle-brackets (s)
10259 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10260 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10262 (defun org-remove-double-quotes (s)
10263 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10264 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10267 ;;; Following specific links
10269 (defun org-follow-timestamp-link ()
10270 "Open an agenda view for the time-stamp date/range at point."
10271 (cond
10272 ((org-at-date-range-p t)
10273 (let ((org-agenda-start-on-weekday)
10274 (t1 (match-string 1))
10275 (t2 (match-string 2)) tt1 tt2)
10276 (setq tt1 (time-to-days (org-time-string-to-time t1))
10277 tt2 (time-to-days (org-time-string-to-time t2)))
10278 (let ((org-agenda-buffer-tmp-name
10279 (format "*Org Agenda(a:%s)"
10280 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10281 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10282 ((org-at-timestamp-p t)
10283 (let ((org-agenda-buffer-tmp-name
10284 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10285 (org-agenda-list nil (time-to-days (org-time-string-to-time
10286 (substring (match-string 1) 0 10)))
10287 1)))
10288 (t (error "This should not happen"))))
10291 ;;; Following file links
10292 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10293 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10294 (declare-function mailcap-mime-info
10295 "mailcap" (string &optional request no-decode))
10296 (defvar org-wait nil)
10297 (defun org-open-file (path &optional in-emacs line search)
10298 "Open the file at PATH.
10299 First, this expands any special file name abbreviations. Then the
10300 configuration variable `org-file-apps' is checked if it contains an
10301 entry for this file type, and if yes, the corresponding command is launched.
10303 If no application is found, Emacs simply visits the file.
10305 With optional prefix argument IN-EMACS, Emacs will visit the file.
10306 With a double \\[universal-argument] \\[universal-argument] \
10307 prefix arg, Org tries to avoid opening in Emacs
10308 and to use an external application to visit the file.
10310 Optional LINE specifies a line to go to, optional SEARCH a string
10311 to search for. If LINE or SEARCH is given, the file will be
10312 opened in Emacs, unless an entry from org-file-apps that makes
10313 use of groups in a regexp matches.
10315 If you want to change the way frames are used when following a
10316 link, please customize `org-link-frame-setup'.
10318 If the file does not exist, an error is thrown."
10319 (let* ((file (if (equal path "")
10320 buffer-file-name
10321 (substitute-in-file-name (expand-file-name path))))
10322 (file-apps (append org-file-apps (org-default-apps)))
10323 (apps (org-remove-if
10324 'org-file-apps-entry-match-against-dlink-p file-apps))
10325 (apps-dlink (org-remove-if-not
10326 'org-file-apps-entry-match-against-dlink-p file-apps))
10327 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10328 (dirp (if remp nil (file-directory-p file)))
10329 (file (if (and dirp org-open-directory-means-index-dot-org)
10330 (concat (file-name-as-directory file) "index.org")
10331 file))
10332 (a-m-a-p (assq 'auto-mode apps))
10333 (dfile (downcase file))
10334 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10335 (link (cond ((and (eq line nil)
10336 (eq search nil))
10337 file)
10338 (line
10339 (concat file "::" (number-to-string line)))
10340 (search
10341 (concat file "::" search))))
10342 (dlink (downcase link))
10343 (old-buffer (current-buffer))
10344 (old-pos (point))
10345 (old-mode major-mode)
10346 ext cmd link-match-data)
10347 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10348 (setq ext (match-string 1 dfile))
10349 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10350 (setq ext (match-string 1 dfile))))
10351 (cond
10352 ((member in-emacs '((16) system))
10353 (setq cmd (cdr (assoc 'system apps))))
10354 (in-emacs (setq cmd 'emacs))
10356 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10357 (and dirp (cdr (assoc 'directory apps)))
10358 ; first, try matching against apps-dlink
10359 ; if we get a match here, store the match data for later
10360 (let ((match (assoc-default dlink apps-dlink
10361 'string-match)))
10362 (if match
10363 (progn (setq link-match-data (match-data))
10364 match)
10365 (progn (setq in-emacs (or in-emacs line search))
10366 nil))) ; if we have no match in apps-dlink,
10367 ; always open the file in emacs if line or search
10368 ; is given (for backwards compatibility)
10369 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10370 'string-match)
10371 (cdr (assoc ext apps))
10372 (cdr (assoc t apps))))))
10373 (when (eq cmd 'system)
10374 (setq cmd (cdr (assoc 'system apps))))
10375 (when (eq cmd 'default)
10376 (setq cmd (cdr (assoc t apps))))
10377 (when (eq cmd 'mailcap)
10378 (require 'mailcap)
10379 (mailcap-parse-mailcaps)
10380 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10381 (command (mailcap-mime-info mime-type)))
10382 (if (stringp command)
10383 (setq cmd command)
10384 (setq cmd 'emacs))))
10385 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10386 (not (file-exists-p file))
10387 (not org-open-non-existing-files))
10388 (error "No such file: %s" file))
10389 (cond
10390 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10391 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10392 (while (string-match "['\"]%s['\"]" cmd)
10393 (setq cmd (replace-match "%s" t t cmd)))
10394 (while (string-match "%s" cmd)
10395 (setq cmd (replace-match
10396 (save-match-data
10397 (shell-quote-argument
10398 (convert-standard-filename file)))
10399 t t cmd)))
10401 ;; Replace "%1", "%2" etc. in command with group matches from regex
10402 (save-match-data
10403 (let ((match-index 1)
10404 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10405 (set-match-data link-match-data)
10406 (while (<= match-index number-of-groups)
10407 (let ((regex (concat "%" (number-to-string match-index)))
10408 (replace-with (match-string match-index dlink)))
10409 (while (string-match regex cmd)
10410 (setq cmd (replace-match replace-with t t cmd))))
10411 (setq match-index (+ match-index 1)))))
10413 (save-window-excursion
10414 (message "Running %s...done" cmd)
10415 (start-process-shell-command cmd nil cmd)
10416 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10417 ((or (stringp cmd)
10418 (eq cmd 'emacs))
10419 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10420 (widen)
10421 (if line (org-goto-line line)
10422 (if search (org-link-search search))))
10423 ((consp cmd)
10424 (let ((file (convert-standard-filename file)))
10425 (save-match-data
10426 (set-match-data link-match-data)
10427 (eval cmd))))
10428 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10429 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10430 (or (not (equal old-buffer (current-buffer)))
10431 (not (equal old-pos (point))))
10432 (org-mark-ring-push old-pos old-buffer))))
10434 (defun org-file-apps-entry-match-against-dlink-p (entry)
10435 "This function returns non-nil if `entry' uses a regular
10436 expression which should be matched against the whole link by
10437 org-open-file.
10439 It assumes that is the case when the entry uses a regular
10440 expression which has at least one grouping construct and the
10441 action is either a lisp form or a command string containing
10442 '%1', i.e. using at least one subexpression match as a
10443 parameter."
10444 (let ((selector (car entry))
10445 (action (cdr entry)))
10446 (if (stringp selector)
10447 (and (> (regexp-opt-depth selector) 0)
10448 (or (and (stringp action)
10449 (string-match "%[0-9]" action))
10450 (consp action)))
10451 nil)))
10453 (defun org-default-apps ()
10454 "Return the default applications for this operating system."
10455 (cond
10456 ((eq system-type 'darwin)
10457 org-file-apps-defaults-macosx)
10458 ((eq system-type 'windows-nt)
10459 org-file-apps-defaults-windowsnt)
10460 (t org-file-apps-defaults-gnu)))
10462 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10463 "Convert extensions to regular expressions in the cars of LIST.
10464 Also, weed out any non-string entries, because the return value is used
10465 only for regexp matching.
10466 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10467 point to the symbol `emacs', indicating that the file should
10468 be opened in Emacs."
10469 (append
10470 (delq nil
10471 (mapcar (lambda (x)
10472 (if (not (stringp (car x)))
10474 (if (string-match "\\W" (car x))
10476 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10477 list))
10478 (if add-auto-mode
10479 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10481 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10482 (defun org-file-remote-p (file)
10483 "Test whether FILE specifies a location on a remote system.
10484 Return non-nil if the location is indeed remote.
10486 For example, the filename \"/user@host:/foo\" specifies a location
10487 on the system \"/user@host:\"."
10488 (cond ((fboundp 'file-remote-p)
10489 (file-remote-p file))
10490 ((fboundp 'tramp-handle-file-remote-p)
10491 (tramp-handle-file-remote-p file))
10492 ((and (boundp 'ange-ftp-name-format)
10493 (string-match (car ange-ftp-name-format) file))
10494 t)))
10497 ;;;; Refiling
10499 (defun org-get-org-file ()
10500 "Read a filename, with default directory `org-directory'."
10501 (let ((default (or org-default-notes-file remember-data-file)))
10502 (read-file-name (format "File name [%s]: " default)
10503 (file-name-as-directory org-directory)
10504 default)))
10506 (defun org-notes-order-reversed-p ()
10507 "Check if the current file should receive notes in reversed order."
10508 (cond
10509 ((not org-reverse-note-order) nil)
10510 ((eq t org-reverse-note-order) t)
10511 ((not (listp org-reverse-note-order)) nil)
10512 (t (catch 'exit
10513 (let ((all org-reverse-note-order)
10514 entry)
10515 (while (setq entry (pop all))
10516 (if (string-match (car entry) buffer-file-name)
10517 (throw 'exit (cdr entry))))
10518 nil)))))
10520 (defvar org-refile-target-table nil
10521 "The list of refile targets, created by `org-refile'.")
10523 (defvar org-agenda-new-buffers nil
10524 "Buffers created to visit agenda files.")
10526 (defvar org-refile-cache nil
10527 "Cache for refile targets.")
10529 (defvar org-refile-markers nil
10530 "All the markers used for caching refile locations.")
10532 (defun org-refile-marker (pos)
10533 "Get a new refile marker, but only if caching is in use."
10534 (if (not org-refile-use-cache)
10536 (let ((m (make-marker)))
10537 (move-marker m pos)
10538 (push m org-refile-markers)
10539 m)))
10541 (defun org-refile-cache-clear ()
10542 "Clear the refile cache and disable all the markers."
10543 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10544 (setq org-refile-markers nil)
10545 (setq org-refile-cache nil)
10546 (message "Refile cache has been cleared"))
10548 (defun org-refile-cache-check-set (set)
10549 "Check if all the markers in the cache still have live buffers."
10550 (let (marker)
10551 (catch 'exit
10552 (while (and set (setq marker (nth 3 (pop set))))
10553 ;; if org-refile-use-outline-path is 'file, marker may be nil
10554 (when (and marker (null (marker-buffer marker)))
10555 (message "not found") (sit-for 3)
10556 (throw 'exit nil)))
10557 t)))
10559 (defun org-refile-cache-put (set &rest identifiers)
10560 "Push the refile targets SET into the cache, under IDENTIFIERS."
10561 (let* ((key (sha1 (prin1-to-string identifiers)))
10562 (entry (assoc key org-refile-cache)))
10563 (if entry
10564 (setcdr entry set)
10565 (push (cons key set) org-refile-cache))))
10567 (defun org-refile-cache-get (&rest identifiers)
10568 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10569 (cond
10570 ((not org-refile-cache) nil)
10571 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10573 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10574 org-refile-cache))))
10575 (and set (org-refile-cache-check-set set) set)))))
10577 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10578 "Produce a table with refile targets."
10579 (let ((case-fold-search nil)
10580 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10581 (entries (or org-refile-targets '((nil . (:level . 1)))))
10582 targets tgs txt re files f desc descre fast-path-p level pos0)
10583 (message "Getting targets...")
10584 (with-current-buffer (or default-buffer (current-buffer))
10585 (while (setq entry (pop entries))
10586 (setq files (car entry) desc (cdr entry))
10587 (setq fast-path-p nil)
10588 (cond
10589 ((null files) (setq files (list (current-buffer))))
10590 ((eq files 'org-agenda-files)
10591 (setq files (org-agenda-files 'unrestricted)))
10592 ((and (symbolp files) (fboundp files))
10593 (setq files (funcall files)))
10594 ((and (symbolp files) (boundp files))
10595 (setq files (symbol-value files))))
10596 (if (stringp files) (setq files (list files)))
10597 (cond
10598 ((eq (car desc) :tag)
10599 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10600 ((eq (car desc) :todo)
10601 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10602 ((eq (car desc) :regexp)
10603 (setq descre (cdr desc)))
10604 ((eq (car desc) :level)
10605 (setq descre (concat "^\\*\\{" (number-to-string
10606 (if org-odd-levels-only
10607 (1- (* 2 (cdr desc)))
10608 (cdr desc)))
10609 "\\}[ \t]")))
10610 ((eq (car desc) :maxlevel)
10611 (setq fast-path-p t)
10612 (setq descre (concat "^\\*\\{1," (number-to-string
10613 (if org-odd-levels-only
10614 (1- (* 2 (cdr desc)))
10615 (cdr desc)))
10616 "\\}[ \t]")))
10617 (t (error "Bad refiling target description %s" desc)))
10618 (while (setq f (pop files))
10619 (with-current-buffer
10620 (if (bufferp f) f (org-get-agenda-file-buffer f))
10622 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10623 (progn
10624 (if (bufferp f) (setq f (buffer-file-name
10625 (buffer-base-buffer f))))
10626 (setq f (and f (expand-file-name f)))
10627 (if (eq org-refile-use-outline-path 'file)
10628 (push (list (file-name-nondirectory f) f nil nil) tgs))
10629 (save-excursion
10630 (save-restriction
10631 (widen)
10632 (goto-char (point-min))
10633 (while (re-search-forward descre nil t)
10634 (goto-char (setq pos0 (point-at-bol)))
10635 (catch 'next
10636 (when org-refile-target-verify-function
10637 (save-match-data
10638 (or (funcall org-refile-target-verify-function)
10639 (throw 'next t))))
10640 (when (and (looking-at org-complex-heading-regexp)
10641 (not (member (match-string 4) excluded-entries))
10642 (match-string 4))
10643 (setq level (org-reduced-level
10644 (- (match-end 1) (match-beginning 1)))
10645 txt (org-link-display-format (match-string 4))
10646 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10647 re (format org-complex-heading-regexp-format
10648 (regexp-quote (match-string 4))))
10649 (when org-refile-use-outline-path
10650 (setq txt (mapconcat
10651 'org-protect-slash
10652 (append
10653 (if (eq org-refile-use-outline-path
10654 'file)
10655 (list (file-name-nondirectory
10656 (buffer-file-name
10657 (buffer-base-buffer))))
10658 (if (eq org-refile-use-outline-path
10659 'full-file-path)
10660 (list (buffer-file-name
10661 (buffer-base-buffer)))))
10662 (org-get-outline-path fast-path-p
10663 level txt)
10664 (list txt))
10665 "/")))
10666 (push (list txt f re (org-refile-marker (point)))
10667 tgs)))
10668 (when (= (point) pos0)
10669 ;; verification function has not moved point
10670 (goto-char (point-at-eol))))))))
10671 (when org-refile-use-cache
10672 (org-refile-cache-put tgs (buffer-file-name) descre))
10673 (setq targets (append tgs targets))
10674 ))))
10675 (message "Getting targets...done")
10676 (nreverse targets)))
10678 (defun org-protect-slash (s)
10679 (while (string-match "/" s)
10680 (setq s (replace-match "\\" t t s)))
10683 (defvar org-olpa (make-vector 20 nil))
10685 (defun org-get-outline-path (&optional fastp level heading)
10686 "Return the outline path to the current entry, as a list.
10688 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10689 routine which makes outline path derivations for an entire file,
10690 avoiding backtracing. Refile target collection makes use of that."
10691 (if fastp
10692 (progn
10693 (if (> level 19)
10694 (error "Outline path failure, more than 19 levels"))
10695 (loop for i from level upto 19 do
10696 (aset org-olpa i nil))
10697 (prog1
10698 (delq nil (append org-olpa nil))
10699 (aset org-olpa level heading)))
10700 (let (rtn case-fold-search)
10701 (save-excursion
10702 (save-restriction
10703 (widen)
10704 (while (org-up-heading-safe)
10705 (when (looking-at org-complex-heading-regexp)
10706 (push (org-match-string-no-properties 4) rtn)))
10707 rtn)))))
10709 (defun org-format-outline-path (path &optional width prefix separator)
10710 "Format the outline path PATH for display.
10711 WIDTH is the maximum number of characters that is available.
10712 PREFIX is a prefix to be included in the returned string,
10713 such as the file name.
10714 SEPARATOR is inserted between the different parts of the path,
10715 the default is \"/\"."
10716 (setq width (or width 79))
10717 (if prefix (setq width (- width (length prefix))))
10718 (if (not path)
10719 (or prefix "")
10720 (let* ((nsteps (length path))
10721 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10722 (maxwidth (if (<= total-width width)
10723 10000 ;; everything fits
10724 ;; we need to shorten the level headings
10725 (/ (- width nsteps) nsteps)))
10726 (org-odd-levels-only nil)
10727 (n 0)
10728 (total (1+ (length prefix))))
10729 (setq maxwidth (max maxwidth 10))
10730 (concat prefix
10731 (if prefix (or separator "/"))
10732 (mapconcat
10733 (lambda (h)
10734 (setq n (1+ n))
10735 (if (and (= n nsteps) (< maxwidth 10000))
10736 (setq maxwidth (- total-width total)))
10737 (if (< (length h) maxwidth)
10738 (progn (setq total (+ total (length h) 1)) h)
10739 (setq h (substring h 0 (- maxwidth 2))
10740 total (+ total maxwidth 1))
10741 (if (string-match "[ \t]+\\'" h)
10742 (setq h (substring h 0 (match-beginning 0))))
10743 (setq h (concat h "..")))
10744 (org-add-props h nil 'face
10745 (nth (% (1- n) org-n-level-faces)
10746 org-level-faces))
10748 path (or separator "/"))))))
10750 (defun org-display-outline-path (&optional file current separator just-return-string)
10751 "Display the current outline path in the echo area.
10753 If FILE is non-nil, prepend the output with the file name.
10754 If CURRENT is non-nil, append the current heading to the output.
10755 SEPARATOR is passed through to `org-format-outline-path'. It separates
10756 the different parts of the path and defaults to \"/\".
10757 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
10758 (interactive "P")
10759 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10760 (case-fold-search nil)
10761 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
10762 res)
10763 (if current (setq path (append path
10764 (save-excursion
10765 (org-back-to-heading t)
10766 (if (looking-at org-complex-heading-regexp)
10767 (list (match-string 4)))))))
10768 (setq res
10769 (org-format-outline-path
10770 path
10771 (1- (frame-width))
10772 (and file bfn (concat (file-name-nondirectory bfn) separator))
10773 separator))
10774 (if just-return-string
10775 (org-no-properties res)
10776 (message "%s" res))))
10778 (defvar org-refile-history nil
10779 "History for refiling operations.")
10781 (defvar org-after-refile-insert-hook nil
10782 "Hook run after `org-refile' has inserted its stuff at the new location.
10783 Note that this is still *before* the stuff will be removed from
10784 the *old* location.")
10786 (defvar org-capture-last-stored-marker)
10787 (defvar org-refile-keep nil
10788 "Non-nil means `org-refile' will copy instead of refile.")
10790 (defun org-copy ()
10791 "Like `org-refile', but copy."
10792 (interactive)
10793 (let ((org-refile-keep t))
10794 (funcall 'org-refile nil nil nil "Copy")))
10796 (defun org-refile (&optional goto default-buffer rfloc msg)
10797 "Move the entry or entries at point to another heading.
10798 The list of target headings is compiled using the information in
10799 `org-refile-targets', which see.
10801 At the target location, the entry is filed as a subitem of the target
10802 heading. Depending on `org-reverse-note-order', the new subitem will
10803 either be the first or the last subitem.
10805 If there is an active region, all entries in that region will be moved.
10806 However, the region must fulfill the requirement that the first heading
10807 is the first one sets the top-level of the moved text - at most siblings
10808 below it are allowed.
10810 With prefix arg GOTO, the command will only visit the target location
10811 and not actually move anything.
10813 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10814 go to the location where the last refiling operation has put the subtree.
10815 With a prefix argument of `2', refile to the running clock.
10817 RFLOC can be a refile location obtained in a different way.
10819 MSG is a string to replace \"Refile\" in the default prompt with
10820 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
10822 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10824 If you are using target caching (see `org-refile-use-cache'),
10825 you have to clear the target cache in order to find new targets.
10826 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10827 prefix argument (`C-u C-u C-u C-c C-w')."
10829 (interactive "P")
10830 (if (member goto '(0 (64)))
10831 (org-refile-cache-clear)
10832 (let* ((actionmsg (or msg "Refile"))
10833 (cbuf (current-buffer))
10834 (regionp (org-region-active-p))
10835 (region-start (and regionp (region-beginning)))
10836 (region-end (and regionp (region-end)))
10837 (region-length (and regionp (- region-end region-start)))
10838 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10839 pos it nbuf file re level reversed)
10840 (setq last-command nil)
10841 (when regionp
10842 (goto-char region-start)
10843 (or (bolp) (goto-char (point-at-bol)))
10844 (setq region-start (point))
10845 (unless (or (org-kill-is-subtree-p
10846 (buffer-substring region-start region-end))
10847 (prog1 org-refile-active-region-within-subtree
10848 (org-toggle-heading)))
10849 (error "The region is not a (sequence of) subtree(s)")))
10850 (if (equal goto '(16))
10851 (org-refile-goto-last-stored)
10852 (when (or
10853 (and (equal goto 2)
10854 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10855 (prog1
10856 (setq it (list (or org-clock-heading "running clock")
10857 (buffer-file-name
10858 (marker-buffer org-clock-hd-marker))
10860 (marker-position org-clock-hd-marker)))
10861 (setq goto nil)))
10862 (setq it (or rfloc
10863 (let (heading-text)
10864 (save-excursion
10865 (unless goto
10866 (org-back-to-heading t)
10867 (setq heading-text
10868 (nth 4 (org-heading-components))))
10870 (org-refile-get-location
10871 (cond (goto "Goto")
10872 (regionp (concat actionmsg " region to"))
10873 (t (concat actionmsg " subtree \""
10874 heading-text "\" to")))
10875 default-buffer
10876 (and (not (equal '(4) goto))
10877 org-refile-allow-creating-parent-nodes)
10878 goto))))))
10879 (setq file (nth 1 it)
10880 re (nth 2 it)
10881 pos (nth 3 it))
10882 (if (and (not goto)
10884 (equal (buffer-file-name) file)
10885 (if regionp
10886 (and (>= pos region-start)
10887 (<= pos region-end))
10888 (and (>= pos (point))
10889 (< pos (save-excursion
10890 (org-end-of-subtree t t))))))
10891 (error "Cannot refile to position inside the tree or region"))
10893 (setq nbuf (or (find-buffer-visiting file)
10894 (find-file-noselect file)))
10895 (if goto
10896 (progn
10897 (org-pop-to-buffer-same-window nbuf)
10898 (goto-char pos)
10899 (org-show-context 'org-goto))
10900 (if regionp
10901 (progn
10902 (org-kill-new (buffer-substring region-start region-end))
10903 (org-save-markers-in-region region-start region-end))
10904 (org-copy-subtree 1 nil t))
10905 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10906 (find-file-noselect file)))
10907 (setq reversed (org-notes-order-reversed-p))
10908 (save-excursion
10909 (save-restriction
10910 (widen)
10911 (if pos
10912 (progn
10913 (goto-char pos)
10914 (looking-at org-outline-regexp)
10915 (setq level (org-get-valid-level (funcall outline-level) 1))
10916 (goto-char
10917 (if reversed
10918 (or (outline-next-heading) (point-max))
10919 (or (save-excursion (org-get-next-sibling))
10920 (org-end-of-subtree t t)
10921 (point-max)))))
10922 (setq level 1)
10923 (if (not reversed)
10924 (goto-char (point-max))
10925 (goto-char (point-min))
10926 (or (outline-next-heading) (goto-char (point-max)))))
10927 (if (not (bolp)) (newline))
10928 (org-paste-subtree level)
10929 (when org-log-refile
10930 (org-add-log-setup 'refile nil nil 'findpos
10931 org-log-refile)
10932 (unless (eq org-log-refile 'note)
10933 (save-excursion (org-add-log-note))))
10934 (and org-auto-align-tags
10935 (let ((org-loop-over-headlines-in-active-region nil))
10936 (org-set-tags nil t)))
10937 (bookmark-set "org-refile-last-stored")
10938 ;; If we are refiling for capture, make sure that the
10939 ;; last-capture pointers point here
10940 (when (org-bound-and-true-p org-refile-for-capture)
10941 (bookmark-set "org-capture-last-stored-marker")
10942 (move-marker org-capture-last-stored-marker (point)))
10943 (if (fboundp 'deactivate-mark) (deactivate-mark))
10944 (run-hooks 'org-after-refile-insert-hook))))
10945 (unless org-refile-keep
10946 (if regionp
10947 (delete-region (point) (+ (point) region-length))
10948 (org-cut-subtree)))
10949 (when (featurep 'org-inlinetask)
10950 (org-inlinetask-remove-END-maybe))
10951 (setq org-markers-to-move nil)
10952 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
10954 (defun org-refile-goto-last-stored ()
10955 "Go to the location where the last refile was stored."
10956 (interactive)
10957 (bookmark-jump "org-refile-last-stored")
10958 (message "This is the location of the last refile"))
10960 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10961 no-exclude)
10962 "Prompt the user for a refile location, using PROMPT.
10963 PROMPT should not be suffixed with a colon and a space, because
10964 this function appends the default value from
10965 `org-refile-history' automatically, if that is not empty.
10966 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10967 this is used for the GOTO interface."
10968 (let ((org-refile-targets org-refile-targets)
10969 (org-refile-use-outline-path org-refile-use-outline-path)
10970 excluded-entries)
10971 (when (and (derived-mode-p 'org-mode)
10972 (not org-refile-use-cache)
10973 (not no-exclude))
10974 (org-map-tree
10975 (lambda()
10976 (setq excluded-entries
10977 (append excluded-entries (list (org-get-heading t t)))))))
10978 (setq org-refile-target-table
10979 (org-refile-get-targets default-buffer excluded-entries)))
10980 (unless org-refile-target-table
10981 (error "No refile targets"))
10982 (let* ((cbuf (current-buffer))
10983 (partial-completion-mode nil)
10984 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10985 (cfunc (if (and org-refile-use-outline-path
10986 org-outline-path-complete-in-steps)
10987 'org-olpath-completing-read
10988 'org-icompleting-read))
10989 (extra (if org-refile-use-outline-path "/" ""))
10990 (cbnex (concat (buffer-name) extra))
10991 (filename (and cfn (expand-file-name cfn)))
10992 (tbl (mapcar
10993 (lambda (x)
10994 (if (and (not (member org-refile-use-outline-path
10995 '(file full-file-path)))
10996 (not (equal filename (nth 1 x))))
10997 (cons (concat (car x) extra " ("
10998 (file-name-nondirectory (nth 1 x)) ")")
10999 (cdr x))
11000 (cons (concat (car x) extra) (cdr x))))
11001 org-refile-target-table))
11002 (completion-ignore-case t)
11003 cdef
11004 (prompt (concat prompt
11005 (or (and (car org-refile-history)
11006 (concat " (default " (car org-refile-history) ")"))
11007 (and (assoc cbnex tbl) (setq cdef cbnex)
11008 (concat " (default " cbnex ")"))) ": "))
11009 pa answ parent-target child parent old-hist)
11010 (setq old-hist org-refile-history)
11011 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11012 nil 'org-refile-history (or cdef (car org-refile-history))))
11013 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11014 (org-refile-check-position pa)
11015 (if pa
11016 (progn
11017 (when (or (not org-refile-history)
11018 (not (eq old-hist org-refile-history))
11019 (not (equal (car pa) (car org-refile-history))))
11020 (setq org-refile-history
11021 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11022 org-refile-history
11023 (cdr org-refile-history))))
11024 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11025 (pop org-refile-history)))
11027 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11028 (progn
11029 (setq parent (match-string 1 answ)
11030 child (match-string 2 answ))
11031 (setq parent-target (or (assoc parent tbl)
11032 (assoc (concat parent "/") tbl)))
11033 (when (and parent-target
11034 (or (eq new-nodes t)
11035 (and (eq new-nodes 'confirm)
11036 (y-or-n-p (format "Create new node \"%s\"? "
11037 child)))))
11038 (org-refile-new-child parent-target child)))
11039 (error "Invalid target location")))))
11041 (declare-function org-string-nw-p "org-macs.el" (s))
11042 (defun org-refile-check-position (refile-pointer)
11043 "Check if the refile pointer matches the readline to which it points."
11044 (let* ((file (nth 1 refile-pointer))
11045 (re (nth 2 refile-pointer))
11046 (pos (nth 3 refile-pointer))
11047 buffer)
11048 (when (org-string-nw-p re)
11049 (setq buffer (if (markerp pos)
11050 (marker-buffer pos)
11051 (or (find-buffer-visiting file)
11052 (find-file-noselect file))))
11053 (with-current-buffer buffer
11054 (save-excursion
11055 (save-restriction
11056 (widen)
11057 (goto-char pos)
11058 (beginning-of-line 1)
11059 (unless (org-looking-at-p re)
11060 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11062 (defun org-refile-new-child (parent-target child)
11063 "Use refile target PARENT-TARGET to add new CHILD below it."
11064 (unless parent-target
11065 (error "Cannot find parent for new node"))
11066 (let ((file (nth 1 parent-target))
11067 (pos (nth 3 parent-target))
11068 level)
11069 (with-current-buffer (or (find-buffer-visiting file)
11070 (find-file-noselect file))
11071 (save-excursion
11072 (save-restriction
11073 (widen)
11074 (if pos
11075 (goto-char pos)
11076 (goto-char (point-max))
11077 (if (not (bolp)) (newline)))
11078 (when (looking-at org-outline-regexp)
11079 (setq level (funcall outline-level))
11080 (org-end-of-subtree t t))
11081 (org-back-over-empty-lines)
11082 (insert "\n" (make-string
11083 (if pos (org-get-valid-level level 1) 1) ?*)
11084 " " child "\n")
11085 (beginning-of-line 0)
11086 (list (concat (car parent-target) "/" child) file "" (point)))))))
11088 (defun org-olpath-completing-read (prompt collection &rest args)
11089 "Read an outline path like a file name."
11090 (let ((thetable collection)
11091 (org-completion-use-ido nil) ; does not work with ido.
11092 (org-completion-use-iswitchb nil)) ; or iswitchb
11093 (apply
11094 'org-icompleting-read prompt
11095 (lambda (string predicate &optional flag)
11096 (let (rtn r f (l (length string)))
11097 (cond
11098 ((eq flag nil)
11099 ;; try completion
11100 (try-completion string thetable))
11101 ((eq flag t)
11102 ;; all-completions
11103 (setq rtn (all-completions string thetable predicate))
11104 (mapcar
11105 (lambda (x)
11106 (setq r (substring x l))
11107 (if (string-match " ([^)]*)$" x)
11108 (setq f (match-string 0 x))
11109 (setq f ""))
11110 (if (string-match "/" r)
11111 (concat string (substring r 0 (match-end 0)) f)
11113 rtn))
11114 ((eq flag 'lambda)
11115 ;; exact match?
11116 (assoc string thetable)))))
11117 args)))
11119 ;;;; Dynamic blocks
11121 (defun org-find-dblock (name)
11122 "Find the first dynamic block with name NAME in the buffer.
11123 If not found, stay at current position and return nil."
11124 (let ((case-fold-search t) pos)
11125 (save-excursion
11126 (goto-char (point-min))
11127 (setq pos (and (re-search-forward
11128 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11129 (match-beginning 0))))
11130 (if pos (goto-char pos))
11131 pos))
11133 (defconst org-dblock-start-re
11134 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11135 "Matches the start line of a dynamic block, with parameters.")
11137 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11138 "Matches the end of a dynamic block.")
11140 (defun org-create-dblock (plist)
11141 "Create a dynamic block section, with parameters taken from PLIST.
11142 PLIST must contain a :name entry which is used as name of the block."
11143 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11144 (end-of-line 1)
11145 (newline))
11146 (let ((col (current-column))
11147 (name (plist-get plist :name)))
11148 (insert "#+BEGIN: " name)
11149 (while plist
11150 (if (eq (car plist) :name)
11151 (setq plist (cddr plist))
11152 (insert " " (prin1-to-string (pop plist)))))
11153 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11154 (beginning-of-line -2)))
11156 (defun org-prepare-dblock ()
11157 "Prepare dynamic block for refresh.
11158 This empties the block, puts the cursor at the insert position and returns
11159 the property list including an extra property :name with the block name."
11160 (unless (looking-at org-dblock-start-re)
11161 (error "Not at a dynamic block"))
11162 (let* ((begdel (1+ (match-end 0)))
11163 (name (org-no-properties (match-string 1)))
11164 (params (append (list :name name)
11165 (read (concat "(" (match-string 3) ")")))))
11166 (save-excursion
11167 (beginning-of-line 1)
11168 (skip-chars-forward " \t")
11169 (setq params (plist-put params :indentation-column (current-column))))
11170 (unless (re-search-forward org-dblock-end-re nil t)
11171 (error "Dynamic block not terminated"))
11172 (setq params
11173 (append params
11174 (list :content (buffer-substring
11175 begdel (match-beginning 0)))))
11176 (delete-region begdel (match-beginning 0))
11177 (goto-char begdel)
11178 (open-line 1)
11179 params))
11181 (defun org-map-dblocks (&optional command)
11182 "Apply COMMAND to all dynamic blocks in the current buffer.
11183 If COMMAND is not given, use `org-update-dblock'."
11184 (let ((cmd (or command 'org-update-dblock)))
11185 (save-excursion
11186 (goto-char (point-min))
11187 (while (re-search-forward org-dblock-start-re nil t)
11188 (goto-char (match-beginning 0))
11189 (save-excursion
11190 (condition-case nil
11191 (funcall cmd)
11192 (error (message "Error during update of dynamic block"))))
11193 (unless (re-search-forward org-dblock-end-re nil t)
11194 (error "Dynamic block not terminated"))))))
11196 (defun org-dblock-update (&optional arg)
11197 "User command for updating dynamic blocks.
11198 Update the dynamic block at point. With prefix ARG, update all dynamic
11199 blocks in the buffer."
11200 (interactive "P")
11201 (if arg
11202 (org-update-all-dblocks)
11203 (or (looking-at org-dblock-start-re)
11204 (org-beginning-of-dblock))
11205 (org-update-dblock)))
11207 (defun org-update-dblock ()
11208 "Update the dynamic block at point.
11209 This means to empty the block, parse for parameters and then call
11210 the correct writing function."
11211 (interactive)
11212 (save-window-excursion
11213 (let* ((pos (point))
11214 (line (org-current-line))
11215 (params (org-prepare-dblock))
11216 (name (plist-get params :name))
11217 (indent (plist-get params :indentation-column))
11218 (cmd (intern (concat "org-dblock-write:" name))))
11219 (message "Updating dynamic block `%s' at line %d..." name line)
11220 (funcall cmd params)
11221 (message "Updating dynamic block `%s' at line %d...done" name line)
11222 (goto-char pos)
11223 (when (and indent (> indent 0))
11224 (setq indent (make-string indent ?\ ))
11225 (save-excursion
11226 (org-beginning-of-dblock)
11227 (forward-line 1)
11228 (while (not (looking-at org-dblock-end-re))
11229 (insert indent)
11230 (beginning-of-line 2))
11231 (when (looking-at org-dblock-end-re)
11232 (and (looking-at "[ \t]+")
11233 (replace-match ""))
11234 (insert indent)))))))
11236 (defun org-beginning-of-dblock ()
11237 "Find the beginning of the dynamic block at point.
11238 Error if there is no such block at point."
11239 (let ((pos (point))
11240 beg)
11241 (end-of-line 1)
11242 (if (and (re-search-backward org-dblock-start-re nil t)
11243 (setq beg (match-beginning 0))
11244 (re-search-forward org-dblock-end-re nil t)
11245 (> (match-end 0) pos))
11246 (goto-char beg)
11247 (goto-char pos)
11248 (error "Not in a dynamic block"))))
11250 (defun org-update-all-dblocks ()
11251 "Update all dynamic blocks in the buffer.
11252 This function can be used in a hook."
11253 (interactive)
11254 (when (derived-mode-p 'org-mode)
11255 (org-map-dblocks 'org-update-dblock)))
11258 ;;;; Completion
11260 (defconst org-additional-option-like-keywords
11261 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11262 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11263 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11264 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11265 "BEGIN:" "END:"
11266 "ORGTBL" "TBLFM:" "TBLNAME:"
11267 "BEGIN_EXAMPLE" "END_EXAMPLE"
11268 "BEGIN_VERBATIM" "END_VERBATIM"
11269 "BEGIN_QUOTE" "END_QUOTE"
11270 "BEGIN_VERSE" "END_VERSE"
11271 "BEGIN_CENTER" "END_CENTER"
11272 "BEGIN_SRC" "END_SRC"
11273 "BEGIN_RESULT" "END_RESULT"
11274 "BEGIN_lstlisting" "END_lstlisting"
11275 "NAME:" "RESULTS:"
11276 "HEADER:" "HEADERS:"
11277 "COLUMNS:" "PROPERTY:"
11278 "CAPTION:" "LABEL:"
11279 "SETUPFILE:"
11280 "INCLUDE:"
11281 "BIND:"
11282 "MACRO:"))
11284 (defconst org-options-keywords
11285 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11286 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11287 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11288 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11289 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11290 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11291 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11293 (defconst org-additional-option-like-keywords-for-flyspell
11294 (delete-dups
11295 (split-string
11296 (mapconcat (lambda(k)
11297 (replace-regexp-in-string
11298 "_\\|:" " "
11299 (concat k " " (downcase k) " " (upcase k))))
11300 (append org-options-keywords org-additional-option-like-keywords)
11301 " ")
11302 " +" t)))
11304 (defcustom org-structure-template-alist
11306 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11307 "<src lang=\"?\">\n\n</src>")
11308 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11309 "<example>\n?\n</example>")
11310 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11311 "<quote>\n?\n</quote>")
11312 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11313 "<verse>\n?\n</verse>")
11314 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11315 "<center>\n?\n</center>")
11316 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11317 "<literal style=\"latex\">\n?\n</literal>")
11318 ("L" "#+LaTeX: "
11319 "<literal style=\"latex\">?</literal>")
11320 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11321 "<literal style=\"html\">\n?\n</literal>")
11322 ("H" "#+HTML: "
11323 "<literal style=\"html\">?</literal>")
11324 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11325 ("A" "#+ASCII: ")
11326 ("i" "#+INDEX: ?"
11327 "#+INDEX: ?")
11328 ("I" "#+INCLUDE: %file ?"
11329 "<include file=%file markup=\"?\">")
11331 "Structure completion elements.
11332 This is a list of abbreviation keys and values. The value gets inserted
11333 if you type `<' followed by the key and then press the completion key,
11334 usually `M-TAB'. %file will be replaced by a file name after prompting
11335 for the file using completion. The cursor will be placed at the position
11336 of the `?` in the template.
11337 There are two templates for each key, the first uses the original Org syntax,
11338 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11339 the default when the /org-mtags.el/ module has been loaded. See also the
11340 variable `org-mtags-prefer-muse-templates'."
11341 :group 'org-completion
11342 :type '(repeat
11343 (string :tag "Key")
11344 (string :tag "Template")
11345 (string :tag "Muse Template")))
11347 (defun org-try-structure-completion ()
11348 "Try to complete a structure template before point.
11349 This looks for strings like \"<e\" on an otherwise empty line and
11350 expands them."
11351 (let ((l (buffer-substring (point-at-bol) (point)))
11353 (when (and (looking-at "[ \t]*$")
11354 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11355 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11356 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11357 (match-beginning 1)) a)
11358 t)))
11360 (defun org-complete-expand-structure-template (start cell)
11361 "Expand a structure template."
11362 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11363 (rpl (nth (if musep 2 1) cell))
11364 (ind ""))
11365 (delete-region start (point))
11366 (when (string-match "\\`#\\+" rpl)
11367 (cond
11368 ((bolp))
11369 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11370 (setq ind (buffer-substring (point-at-bol) (point))))
11371 (t (newline))))
11372 (setq start (point))
11373 (if (string-match "%file" rpl)
11374 (setq rpl (replace-match
11375 (concat
11376 "\""
11377 (save-match-data
11378 (abbreviate-file-name (read-file-name "Include file: ")))
11379 "\"")
11380 t t rpl)))
11381 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11382 (concat "\n" ind)))
11383 (insert rpl)
11384 (if (re-search-backward "\\?" start t) (delete-char 1))))
11386 ;;;; TODO, DEADLINE, Comments
11388 (defun org-toggle-comment ()
11389 "Change the COMMENT state of an entry."
11390 (interactive)
11391 (save-excursion
11392 (org-back-to-heading)
11393 (let (case-fold-search)
11394 (cond
11395 ((looking-at (format org-heading-keyword-regexp-format
11396 org-comment-string))
11397 (goto-char (match-end 1))
11398 (looking-at (concat " +" org-comment-string))
11399 (replace-match "" t t)
11400 (when (eolp) (insert " ")))
11401 ((looking-at org-outline-regexp)
11402 (goto-char (match-end 0))
11403 (insert org-comment-string " "))))))
11405 (defvar org-last-todo-state-is-todo nil
11406 "This is non-nil when the last TODO state change led to a TODO state.
11407 If the last change removed the TODO tag or switched to DONE, then
11408 this is nil.")
11410 (defvar org-setting-tags nil) ; dynamically skipped
11412 (defvar org-todo-setup-filter-hook nil
11413 "Hook for functions that pre-filter todo specs.
11414 Each function takes a todo spec and returns either nil or the spec
11415 transformed into canonical form." )
11417 (defvar org-todo-get-default-hook nil
11418 "Hook for functions that get a default item for todo.
11419 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11420 nil or a string to be used for the todo mark." )
11422 (defvar org-agenda-headline-snapshot-before-repeat)
11424 (defun org-current-effective-time ()
11425 "Return current time adjusted for `org-extend-today-until' variable."
11426 (let* ((ct (org-current-time))
11427 (dct (decode-time ct))
11428 (ct1
11429 (cond
11430 (org-use-last-clock-out-time-as-effective-time
11431 (or (org-clock-get-last-clock-out-time) ct))
11432 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11433 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11434 (t ct))))
11435 ct1))
11437 (defun org-todo-yesterday (&optional arg)
11438 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11439 (interactive "P")
11440 (if (eq major-mode 'org-agenda-mode)
11441 (apply 'org-agenda-todo-yesterday arg)
11442 (let* ((hour (third (decode-time
11443 (org-current-time))))
11444 (org-extend-today-until (1+ hour)))
11445 (org-todo arg))))
11447 (defun org-todo (&optional arg)
11448 "Change the TODO state of an item.
11449 The state of an item is given by a keyword at the start of the heading,
11450 like
11451 *** TODO Write paper
11452 *** DONE Call mom
11454 The different keywords are specified in the variable `org-todo-keywords'.
11455 By default the available states are \"TODO\" and \"DONE\".
11456 So for this example: when the item starts with TODO, it is changed to DONE.
11457 When it starts with DONE, the DONE is removed. And when neither TODO nor
11458 DONE are present, add TODO at the beginning of the heading.
11460 With \\[universal-argument] prefix arg, use completion to determine the new \
11461 state.
11462 With numeric prefix arg, switch to that state.
11463 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11464 keywords (nextset).
11465 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11466 With a numeric prefix arg of 0, inhibit note taking for the change.
11468 For calling through lisp, arg is also interpreted in the following way:
11469 'none -> empty state
11470 \"\"(empty string) -> switch to empty state
11471 'done -> switch to DONE
11472 'nextset -> switch to the next set of keywords
11473 'previousset -> switch to the previous set of keywords
11474 \"WAITING\" -> switch to the specified keyword, but only if it
11475 really is a member of `org-todo-keywords'."
11476 (interactive "P")
11477 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11478 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11479 'region-start-level 'region))
11480 org-loop-over-headlines-in-active-region)
11481 (org-map-entries
11482 `(org-todo ,arg)
11483 org-loop-over-headlines-in-active-region
11484 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11485 (if (equal arg '(16)) (setq arg 'nextset))
11486 (let ((org-blocker-hook org-blocker-hook)
11487 (case-fold-search nil))
11488 (when (equal arg '(64))
11489 (setq arg nil org-blocker-hook nil))
11490 (when (and org-blocker-hook
11491 (or org-inhibit-blocking
11492 (org-entry-get nil "NOBLOCKING")))
11493 (setq org-blocker-hook nil))
11494 (save-excursion
11495 (catch 'exit
11496 (org-back-to-heading t)
11497 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11498 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11499 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11500 (let* ((match-data (match-data))
11501 (startpos (point-at-bol))
11502 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11503 (org-log-done org-log-done)
11504 (org-log-repeat org-log-repeat)
11505 (org-todo-log-states org-todo-log-states)
11506 (org-inhibit-logging
11507 (if (equal arg 0)
11508 (progn (setq arg nil) 'note) org-inhibit-logging))
11509 (this (match-string 1))
11510 (hl-pos (match-beginning 0))
11511 (head (org-get-todo-sequence-head this))
11512 (ass (assoc head org-todo-kwd-alist))
11513 (interpret (nth 1 ass))
11514 (done-word (nth 3 ass))
11515 (final-done-word (nth 4 ass))
11516 (org-last-state (or this ""))
11517 (completion-ignore-case t)
11518 (member (member this org-todo-keywords-1))
11519 (tail (cdr member))
11520 (org-state (cond
11521 ((and org-todo-key-trigger
11522 (or (and (equal arg '(4))
11523 (eq org-use-fast-todo-selection 'prefix))
11524 (and (not arg) org-use-fast-todo-selection
11525 (not (eq org-use-fast-todo-selection
11526 'prefix)))))
11527 ;; Use fast selection
11528 (org-fast-todo-selection))
11529 ((and (equal arg '(4))
11530 (or (not org-use-fast-todo-selection)
11531 (not org-todo-key-trigger)))
11532 ;; Read a state with completion
11533 (org-icompleting-read
11534 "State: " (mapcar (lambda(x) (list x))
11535 org-todo-keywords-1)
11536 nil t))
11537 ((eq arg 'right)
11538 (if this
11539 (if tail (car tail) nil)
11540 (car org-todo-keywords-1)))
11541 ((eq arg 'left)
11542 (if (equal member org-todo-keywords-1)
11544 (if this
11545 (nth (- (length org-todo-keywords-1)
11546 (length tail) 2)
11547 org-todo-keywords-1)
11548 (org-last org-todo-keywords-1))))
11549 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11550 (setq arg nil))) ; hack to fall back to cycling
11551 (arg
11552 ;; user or caller requests a specific state
11553 (cond
11554 ((equal arg "") nil)
11555 ((eq arg 'none) nil)
11556 ((eq arg 'done) (or done-word (car org-done-keywords)))
11557 ((eq arg 'nextset)
11558 (or (car (cdr (member head org-todo-heads)))
11559 (car org-todo-heads)))
11560 ((eq arg 'previousset)
11561 (let ((org-todo-heads (reverse org-todo-heads)))
11562 (or (car (cdr (member head org-todo-heads)))
11563 (car org-todo-heads))))
11564 ((car (member arg org-todo-keywords-1)))
11565 ((stringp arg)
11566 (error "State `%s' not valid in this file" arg))
11567 ((nth (1- (prefix-numeric-value arg))
11568 org-todo-keywords-1))))
11569 ((null member) (or head (car org-todo-keywords-1)))
11570 ((equal this final-done-word) nil) ;; -> make empty
11571 ((null tail) nil) ;; -> first entry
11572 ((memq interpret '(type priority))
11573 (if (eq this-command last-command)
11574 (car tail)
11575 (if (> (length tail) 0)
11576 (or done-word (car org-done-keywords))
11577 nil)))
11579 (car tail))))
11580 (org-state (or
11581 (run-hook-with-args-until-success
11582 'org-todo-get-default-hook org-state org-last-state)
11583 org-state))
11584 (next (if org-state (concat " " org-state " ") " "))
11585 (change-plist (list :type 'todo-state-change :from this :to org-state
11586 :position startpos))
11587 dolog now-done-p)
11588 (when org-blocker-hook
11589 (setq org-last-todo-state-is-todo
11590 (not (member this org-done-keywords)))
11591 (unless (save-excursion
11592 (save-match-data
11593 (org-with-wide-buffer
11594 (run-hook-with-args-until-failure
11595 'org-blocker-hook change-plist))))
11596 (if (org-called-interactively-p 'interactive)
11597 (error "TODO state change from %s to %s blocked" this org-state)
11598 ;; fail silently
11599 (message "TODO state change from %s to %s blocked" this org-state)
11600 (throw 'exit nil))))
11601 (store-match-data match-data)
11602 (replace-match next t t)
11603 (unless (pos-visible-in-window-p hl-pos)
11604 (message "TODO state changed to %s" (org-trim next)))
11605 (unless head
11606 (setq head (org-get-todo-sequence-head org-state)
11607 ass (assoc head org-todo-kwd-alist)
11608 interpret (nth 1 ass)
11609 done-word (nth 3 ass)
11610 final-done-word (nth 4 ass)))
11611 (when (memq arg '(nextset previousset))
11612 (message "Keyword-Set %d/%d: %s"
11613 (- (length org-todo-sets) -1
11614 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11615 (length org-todo-sets)
11616 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11617 (setq org-last-todo-state-is-todo
11618 (not (member org-state org-done-keywords)))
11619 (setq now-done-p (and (member org-state org-done-keywords)
11620 (not (member this org-done-keywords))))
11621 (and logging (org-local-logging logging))
11622 (when (and (or org-todo-log-states org-log-done)
11623 (not (eq org-inhibit-logging t))
11624 (not (memq arg '(nextset previousset))))
11625 ;; we need to look at recording a time and note
11626 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11627 (nth 2 (assoc this org-todo-log-states))))
11628 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11629 (setq dolog 'time))
11630 (when (and org-state
11631 (member org-state org-not-done-keywords)
11632 (not (member this org-not-done-keywords)))
11633 ;; This is now a todo state and was not one before
11634 ;; If there was a CLOSED time stamp, get rid of it.
11635 (org-add-planning-info nil nil 'closed))
11636 (when (and now-done-p org-log-done)
11637 ;; It is now done, and it was not done before
11638 (org-add-planning-info 'closed (org-current-effective-time))
11639 (if (and (not dolog) (eq 'note org-log-done))
11640 (org-add-log-setup 'done org-state this 'findpos 'note)))
11641 (when (and org-state dolog)
11642 ;; This is a non-nil state, and we need to log it
11643 (org-add-log-setup 'state org-state this 'findpos dolog)))
11644 ;; Fixup tag positioning
11645 (org-todo-trigger-tag-changes org-state)
11646 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11647 (when org-provide-todo-statistics
11648 (org-update-parent-todo-statistics))
11649 (run-hooks 'org-after-todo-state-change-hook)
11650 (if (and arg (not (member org-state org-done-keywords)))
11651 (setq head (org-get-todo-sequence-head org-state)))
11652 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11653 ;; Do we need to trigger a repeat?
11654 (when now-done-p
11655 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11656 ;; This is for the agenda, take a snapshot of the headline.
11657 (save-match-data
11658 (setq org-agenda-headline-snapshot-before-repeat
11659 (org-get-heading))))
11660 (org-auto-repeat-maybe org-state))
11661 ;; Fixup cursor location if close to the keyword
11662 (if (and (outline-on-heading-p)
11663 (not (bolp))
11664 (save-excursion (beginning-of-line 1)
11665 (looking-at org-todo-line-regexp))
11666 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11667 (progn
11668 (goto-char (or (match-end 2) (match-end 1)))
11669 (and (looking-at " ") (just-one-space))))
11670 (when org-trigger-hook
11671 (save-excursion
11672 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11674 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11675 "Block turning an entry into a TODO, using the hierarchy.
11676 This checks whether the current task should be blocked from state
11677 changes. Such blocking occurs when:
11679 1. The task has children which are not all in a completed state.
11681 2. A task has a parent with the property :ORDERED:, and there
11682 are siblings prior to the current task with incomplete
11683 status.
11685 3. The parent of the task is blocked because it has siblings that should
11686 be done first, or is child of a block grandparent TODO entry."
11688 (if (not org-enforce-todo-dependencies)
11689 t ; if locally turned off don't block
11690 (catch 'dont-block
11691 ;; If this is not a todo state change, or if this entry is already DONE,
11692 ;; do not block
11693 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11694 (member (plist-get change-plist :from)
11695 (cons 'done org-done-keywords))
11696 (member (plist-get change-plist :to)
11697 (cons 'todo org-not-done-keywords))
11698 (not (plist-get change-plist :to)))
11699 (throw 'dont-block t))
11700 ;; If this task has children, and any are undone, it's blocked
11701 (save-excursion
11702 (org-back-to-heading t)
11703 (let ((this-level (funcall outline-level)))
11704 (outline-next-heading)
11705 (let ((child-level (funcall outline-level)))
11706 (while (and (not (eobp))
11707 (> child-level this-level))
11708 ;; this todo has children, check whether they are all
11709 ;; completed
11710 (if (and (not (org-entry-is-done-p))
11711 (org-entry-is-todo-p))
11712 (throw 'dont-block nil))
11713 (outline-next-heading)
11714 (setq child-level (funcall outline-level))))))
11715 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11716 ;; any previous siblings are undone, it's blocked
11717 (save-excursion
11718 (org-back-to-heading t)
11719 (let* ((pos (point))
11720 (parent-pos (and (org-up-heading-safe) (point))))
11721 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11722 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11723 (forward-line 1)
11724 (re-search-forward org-not-done-heading-regexp pos t))
11725 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11726 ;; Search further up the hierarchy, to see if an ancestor is blocked
11727 (while t
11728 (goto-char parent-pos)
11729 (if (not (looking-at org-not-done-heading-regexp))
11730 (throw 'dont-block t)) ; do not block, parent is not a TODO
11731 (setq pos (point))
11732 (setq parent-pos (and (org-up-heading-safe) (point)))
11733 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11734 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11735 (forward-line 1)
11736 (re-search-forward org-not-done-heading-regexp pos t))
11737 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11739 (defcustom org-track-ordered-property-with-tag nil
11740 "Should the ORDERED property also be shown as a tag?
11741 The ORDERED property decides if an entry should require subtasks to be
11742 completed in sequence. Since a property is not very visible, setting
11743 this option means that toggling the ORDERED property with the command
11744 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11745 not relevant for the behavior, but it makes things more visible.
11747 Note that toggling the tag with tags commands will not change the property
11748 and therefore not influence behavior!
11750 This can be t, meaning the tag ORDERED should be used, It can also be a
11751 string to select a different tag for this task."
11752 :group 'org-todo
11753 :type '(choice
11754 (const :tag "No tracking" nil)
11755 (const :tag "Track with ORDERED tag" t)
11756 (string :tag "Use other tag")))
11758 (defun org-toggle-ordered-property ()
11759 "Toggle the ORDERED property of the current entry.
11760 For better visibility, you can track the value of this property with a tag.
11761 See variable `org-track-ordered-property-with-tag'."
11762 (interactive)
11763 (let* ((t1 org-track-ordered-property-with-tag)
11764 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11765 (save-excursion
11766 (org-back-to-heading)
11767 (if (org-entry-get nil "ORDERED")
11768 (progn
11769 (org-delete-property "ORDERED")
11770 (and tag (org-toggle-tag tag 'off))
11771 (message "Subtasks can be completed in arbitrary order"))
11772 (org-entry-put nil "ORDERED" "t")
11773 (and tag (org-toggle-tag tag 'on))
11774 (message "Subtasks must be completed in sequence")))))
11776 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11777 (defun org-block-todo-from-checkboxes (change-plist)
11778 "Block turning an entry into a TODO, using checkboxes.
11779 This checks whether the current task should be blocked from state
11780 changes because there are unchecked boxes in this entry."
11781 (if (not org-enforce-todo-checkbox-dependencies)
11782 t ; if locally turned off don't block
11783 (catch 'dont-block
11784 ;; If this is not a todo state change, or if this entry is already DONE,
11785 ;; do not block
11786 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11787 (member (plist-get change-plist :from)
11788 (cons 'done org-done-keywords))
11789 (member (plist-get change-plist :to)
11790 (cons 'todo org-not-done-keywords))
11791 (not (plist-get change-plist :to)))
11792 (throw 'dont-block t))
11793 ;; If this task has checkboxes that are not checked, it's blocked
11794 (save-excursion
11795 (org-back-to-heading t)
11796 (let ((beg (point)) end)
11797 (outline-next-heading)
11798 (setq end (point))
11799 (goto-char beg)
11800 (if (org-list-search-forward
11801 (concat (org-item-beginning-re)
11802 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11803 "\\[[- ]\\]")
11804 end t)
11805 (progn
11806 (if (boundp 'org-blocked-by-checkboxes)
11807 (setq org-blocked-by-checkboxes t))
11808 (throw 'dont-block nil)))))
11809 t))) ; do not block
11811 (defun org-entry-blocked-p ()
11812 "Is the current entry blocked?"
11813 (if (org-entry-get nil "NOBLOCKING")
11814 nil ;; Never block this entry
11815 (not
11816 (run-hook-with-args-until-failure
11817 'org-blocker-hook
11818 (list :type 'todo-state-change
11819 :position (point)
11820 :from 'todo
11821 :to 'done)))))
11823 (defun org-update-statistics-cookies (all)
11824 "Update the statistics cookie, either from TODO or from checkboxes.
11825 This should be called with the cursor in a line with a statistics cookie."
11826 (interactive "P")
11827 (if all
11828 (progn
11829 (org-update-checkbox-count 'all)
11830 (org-map-entries 'org-update-parent-todo-statistics))
11831 (if (not (org-at-heading-p))
11832 (org-update-checkbox-count)
11833 (let ((pos (move-marker (make-marker) (point)))
11834 end l1 l2)
11835 (ignore-errors (org-back-to-heading t))
11836 (if (not (org-at-heading-p))
11837 (org-update-checkbox-count)
11838 (setq l1 (org-outline-level))
11839 (setq end (save-excursion
11840 (outline-next-heading)
11841 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11842 (point)))
11843 (if (and (save-excursion
11844 (re-search-forward
11845 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11846 (not (save-excursion (re-search-forward
11847 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11848 (org-update-checkbox-count)
11849 (if (and l2 (> l2 l1))
11850 (progn
11851 (goto-char end)
11852 (org-update-parent-todo-statistics))
11853 (goto-char pos)
11854 (beginning-of-line 1)
11855 (while (re-search-forward
11856 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11857 (point-at-eol) t)
11858 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11859 (goto-char pos)
11860 (move-marker pos nil)))))
11862 (defvar org-entry-property-inherited-from) ;; defined below
11863 (defun org-update-parent-todo-statistics ()
11864 "Update any statistics cookie in the parent of the current headline.
11865 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11866 the entire subtree and this will travel up the hierarchy and update
11867 statistics everywhere."
11868 (let* ((prop (save-excursion (org-up-heading-safe)
11869 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11870 (recursive (or (not org-hierarchical-todo-statistics)
11871 (and prop (string-match "\\<recursive\\>" prop))))
11872 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11874 (first t)
11875 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11876 level ltoggle l1 new ndel
11877 (cnt-all 0) (cnt-done 0) is-percent kwd
11878 checkbox-beg ov ovs ove cookie-present)
11879 (catch 'exit
11880 (save-excursion
11881 (beginning-of-line 1)
11882 (setq ltoggle (funcall outline-level))
11883 ;; Three situations are to consider:
11885 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11886 ;; to the top-level ancestor on the headline;
11888 ;; 2. If parent has "recursive" property, repeat up to the
11889 ;; headline setting that property, taking inheritance into
11890 ;; account;
11892 ;; 3. Else, move up to direct parent and proceed only once.
11893 (while (and (setq level (org-up-heading-safe))
11894 (or recursive first)
11895 (>= (point) lim))
11896 (setq first nil cookie-present nil)
11897 (unless (and level
11898 (not (string-match
11899 "\\<checkbox\\>"
11900 (downcase (or (org-entry-get nil "COOKIE_DATA")
11901 "")))))
11902 (throw 'exit nil))
11903 (while (re-search-forward box-re (point-at-eol) t)
11904 (setq cnt-all 0 cnt-done 0 cookie-present t)
11905 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11906 (save-match-data
11907 (unless (outline-next-heading) (throw 'exit nil))
11908 (while (and (looking-at org-complex-heading-regexp)
11909 (> (setq l1 (length (match-string 1))) level))
11910 (setq kwd (and (or recursive (= l1 ltoggle))
11911 (match-string 2)))
11912 (if (or (eq org-provide-todo-statistics 'all-headlines)
11913 (and (listp org-provide-todo-statistics)
11914 (or (member kwd org-provide-todo-statistics)
11915 (member kwd org-done-keywords))))
11916 (setq cnt-all (1+ cnt-all))
11917 (if (eq org-provide-todo-statistics t)
11918 (and kwd (setq cnt-all (1+ cnt-all)))))
11919 (and (member kwd org-done-keywords)
11920 (setq cnt-done (1+ cnt-done)))
11921 (outline-next-heading)))
11922 (setq new
11923 (if is-percent
11924 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11925 (format "[%d/%d]" cnt-done cnt-all))
11926 ndel (- (match-end 0) checkbox-beg))
11927 ;; handle overlays when updating cookie from column view
11928 (when (setq ov (car (overlays-at checkbox-beg)))
11929 (setq ovs (overlay-start ov) ove (overlay-end ov))
11930 (delete-overlay ov))
11931 (goto-char checkbox-beg)
11932 (insert new)
11933 (delete-region (point) (+ (point) ndel))
11934 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11935 (when ov (move-overlay ov ovs ove)))
11936 (when cookie-present
11937 (run-hook-with-args 'org-after-todo-statistics-hook
11938 cnt-done (- cnt-all cnt-done))))))
11939 (run-hooks 'org-todo-statistics-hook)))
11941 (defvar org-after-todo-statistics-hook nil
11942 "Hook that is called after a TODO statistics cookie has been updated.
11943 Each function is called with two arguments: the number of not-done entries
11944 and the number of done entries.
11946 For example, the following function, when added to this hook, will switch
11947 an entry to DONE when all children are done, and back to TODO when new
11948 entries are set to a TODO status. Note that this hook is only called
11949 when there is a statistics cookie in the headline!
11951 (defun org-summary-todo (n-done n-not-done)
11952 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11953 (let (org-log-done org-log-states) ; turn off logging
11954 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11957 (defvar org-todo-statistics-hook nil
11958 "Hook that is run whenever Org thinks TODO statistics should be updated.
11959 This hook runs even if there is no statistics cookie present, in which case
11960 `org-after-todo-statistics-hook' would not run.")
11962 (defun org-todo-trigger-tag-changes (state)
11963 "Apply the changes defined in `org-todo-state-tags-triggers'."
11964 (let ((l org-todo-state-tags-triggers)
11965 changes)
11966 (when (or (not state) (equal state ""))
11967 (setq changes (append changes (cdr (assoc "" l)))))
11968 (when (and (stringp state) (> (length state) 0))
11969 (setq changes (append changes (cdr (assoc state l)))))
11970 (when (member state org-not-done-keywords)
11971 (setq changes (append changes (cdr (assoc 'todo l)))))
11972 (when (member state org-done-keywords)
11973 (setq changes (append changes (cdr (assoc 'done l)))))
11974 (dolist (c changes)
11975 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11977 (defun org-local-logging (value)
11978 "Get logging settings from a property VALUE."
11979 (let* (words w a)
11980 ;; directly set the variables, they are already local.
11981 (setq org-log-done nil
11982 org-log-repeat nil
11983 org-todo-log-states nil)
11984 (setq words (org-split-string value))
11985 (while (setq w (pop words))
11986 (cond
11987 ((setq a (assoc w org-startup-options))
11988 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11989 (set (nth 1 a) (nth 2 a))))
11990 ((setq a (org-extract-log-state-settings w))
11991 (and (member (car a) org-todo-keywords-1)
11992 (push a org-todo-log-states)))))))
11994 (defun org-get-todo-sequence-head (kwd)
11995 "Return the head of the TODO sequence to which KWD belongs.
11996 If KWD is not set, check if there is a text property remembering the
11997 right sequence."
11998 (let (p)
11999 (cond
12000 ((not kwd)
12001 (or (get-text-property (point-at-bol) 'org-todo-head)
12002 (progn
12003 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12004 nil (point-at-eol)))
12005 (get-text-property p 'org-todo-head))))
12006 ((not (member kwd org-todo-keywords-1))
12007 (car org-todo-keywords-1))
12008 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12010 (defun org-fast-todo-selection ()
12011 "Fast TODO keyword selection with single keys.
12012 Returns the new TODO keyword, or nil if no state change should occur."
12013 (let* ((fulltable org-todo-key-alist)
12014 (done-keywords org-done-keywords) ;; needed for the faces.
12015 (maxlen (apply 'max (mapcar
12016 (lambda (x)
12017 (if (stringp (car x)) (string-width (car x)) 0))
12018 fulltable)))
12019 (expert nil)
12020 (fwidth (+ maxlen 3 1 3))
12021 (ncol (/ (- (window-width) 4) fwidth))
12022 tg cnt e c tbl
12023 groups ingroup)
12024 (save-excursion
12025 (save-window-excursion
12026 (if expert
12027 (set-buffer (get-buffer-create " *Org todo*"))
12028 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12029 (erase-buffer)
12030 (org-set-local 'org-done-keywords done-keywords)
12031 (setq tbl fulltable cnt 0)
12032 (while (setq e (pop tbl))
12033 (cond
12034 ((equal e '(:startgroup))
12035 (push '() groups) (setq ingroup t)
12036 (when (not (= cnt 0))
12037 (setq cnt 0)
12038 (insert "\n"))
12039 (insert "{ "))
12040 ((equal e '(:endgroup))
12041 (setq ingroup nil cnt 0)
12042 (insert "}\n"))
12043 ((equal e '(:newline))
12044 (when (not (= cnt 0))
12045 (setq cnt 0)
12046 (insert "\n")
12047 (setq e (car tbl))
12048 (while (equal (car tbl) '(:newline))
12049 (insert "\n")
12050 (setq tbl (cdr tbl)))))
12052 (setq tg (car e) c (cdr e))
12053 (if ingroup (push tg (car groups)))
12054 (setq tg (org-add-props tg nil 'face
12055 (org-get-todo-face tg)))
12056 (if (and (= cnt 0) (not ingroup)) (insert " "))
12057 (insert "[" c "] " tg (make-string
12058 (- fwidth 4 (length tg)) ?\ ))
12059 (when (= (setq cnt (1+ cnt)) ncol)
12060 (insert "\n")
12061 (if ingroup (insert " "))
12062 (setq cnt 0)))))
12063 (insert "\n")
12064 (goto-char (point-min))
12065 (if (not expert) (org-fit-window-to-buffer))
12066 (message "[a-z..]:Set [SPC]:clear")
12067 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12068 (cond
12069 ((or (= c ?\C-g)
12070 (and (= c ?q) (not (rassoc c fulltable))))
12071 (setq quit-flag t))
12072 ((= c ?\ ) nil)
12073 ((setq e (rassoc c fulltable) tg (car e))
12075 (t (setq quit-flag t)))))))
12077 (defun org-entry-is-todo-p ()
12078 (member (org-get-todo-state) org-not-done-keywords))
12080 (defun org-entry-is-done-p ()
12081 (member (org-get-todo-state) org-done-keywords))
12083 (defun org-get-todo-state ()
12084 (save-excursion
12085 (org-back-to-heading t)
12086 (and (looking-at org-todo-line-regexp)
12087 (match-end 2)
12088 (match-string 2))))
12090 (defun org-at-date-range-p (&optional inactive-ok)
12091 "Is the cursor inside a date range?"
12092 (interactive)
12093 (save-excursion
12094 (catch 'exit
12095 (let ((pos (point)))
12096 (skip-chars-backward "^[<\r\n")
12097 (skip-chars-backward "<[")
12098 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12099 (>= (match-end 0) pos)
12100 (throw 'exit t))
12101 (skip-chars-backward "^<[\r\n")
12102 (skip-chars-backward "<[")
12103 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12104 (>= (match-end 0) pos)
12105 (throw 'exit t)))
12106 nil)))
12108 (defun org-get-repeat (&optional tagline)
12109 "Check if there is a deadline/schedule with repeater in this entry."
12110 (save-match-data
12111 (save-excursion
12112 (org-back-to-heading t)
12113 (and (re-search-forward (if tagline
12114 (concat tagline "\\s-*" org-repeat-re)
12115 org-repeat-re)
12116 (org-entry-end-position) t)
12117 (match-string-no-properties 1)))))
12119 (defvar org-last-changed-timestamp)
12120 (defvar org-last-inserted-timestamp)
12121 (defvar org-log-post-message)
12122 (defvar org-log-note-purpose)
12123 (defvar org-log-note-how)
12124 (defvar org-log-note-extra)
12125 (defun org-auto-repeat-maybe (done-word)
12126 "Check if the current headline contains a repeated deadline/schedule.
12127 If yes, set TODO state back to what it was and change the base date
12128 of repeating deadline/scheduled time stamps to new date.
12129 This function is run automatically after each state change to a DONE state."
12130 ;; last-state is dynamically scoped into this function
12131 (let* ((repeat (org-get-repeat))
12132 (aa (assoc org-last-state org-todo-kwd-alist))
12133 (interpret (nth 1 aa))
12134 (head (nth 2 aa))
12135 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12136 (msg "Entry repeats: ")
12137 (org-log-done nil)
12138 (org-todo-log-states nil)
12139 re type n what ts time to-state)
12140 (when repeat
12141 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12142 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12143 org-todo-repeat-to-state))
12144 (unless (and to-state (member to-state org-todo-keywords-1))
12145 (setq to-state (if (eq interpret 'type) org-last-state head)))
12146 (org-todo to-state)
12147 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12148 (org-entry-put nil "LAST_REPEAT" (format-time-string
12149 (org-time-stamp-format t t))))
12150 (when org-log-repeat
12151 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12152 (memq 'org-add-log-note post-command-hook))
12153 ;; OK, we are already setup for some record
12154 (if (eq org-log-repeat 'note)
12155 ;; make sure we take a note, not only a time stamp
12156 (setq org-log-note-how 'note))
12157 ;; Set up for taking a record
12158 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12159 org-last-state
12160 'findpos org-log-repeat)))
12161 (org-back-to-heading t)
12162 (org-add-planning-info nil nil 'closed)
12163 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12164 org-deadline-time-regexp "\\)\\|\\("
12165 org-ts-regexp "\\)"))
12166 (while (re-search-forward
12167 re (save-excursion (outline-next-heading) (point)) t)
12168 (setq type (if (match-end 1) org-scheduled-string
12169 (if (match-end 3) org-deadline-string "Plain:"))
12170 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12171 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12172 (setq n (string-to-number (match-string 2 ts))
12173 what (match-string 3 ts))
12174 (if (equal what "w") (setq n (* n 7) what "d"))
12175 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12176 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12177 ;; Preparation, see if we need to modify the start date for the change
12178 (when (match-end 1)
12179 (setq time (save-match-data (org-time-string-to-time ts)))
12180 (cond
12181 ((equal (match-string 1 ts) ".")
12182 ;; Shift starting date to today
12183 (org-timestamp-change
12184 (- (org-today) (time-to-days time))
12185 'day))
12186 ((equal (match-string 1 ts) "+")
12187 (let ((nshiftmax 10) (nshift 0))
12188 (while (or (= nshift 0)
12189 (<= (time-to-days time)
12190 (time-to-days (current-time))))
12191 (when (= (incf nshift) nshiftmax)
12192 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12193 (error "Abort")))
12194 (org-timestamp-change n (cdr (assoc what whata)))
12195 (org-at-timestamp-p t)
12196 (setq ts (match-string 1))
12197 (setq time (save-match-data (org-time-string-to-time ts)))))
12198 (org-timestamp-change (- n) (cdr (assoc what whata)))
12199 ;; rematch, so that we have everything in place for the real shift
12200 (org-at-timestamp-p t)
12201 (setq ts (match-string 1))
12202 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12203 (org-timestamp-change n (cdr (assoc what whata)))
12204 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12205 (setq org-log-post-message msg)
12206 (message "%s" msg))))
12208 (defun org-show-todo-tree (arg)
12209 "Make a compact tree which shows all headlines marked with TODO.
12210 The tree will show the lines where the regexp matches, and all higher
12211 headlines above the match.
12212 With a \\[universal-argument] prefix, prompt for a regexp to match.
12213 With a numeric prefix N, construct a sparse tree for the Nth element
12214 of `org-todo-keywords-1'."
12215 (interactive "P")
12216 (let ((case-fold-search nil)
12217 (kwd-re
12218 (cond ((null arg) org-not-done-regexp)
12219 ((equal arg '(4))
12220 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12221 (mapcar 'list org-todo-keywords-1))))
12222 (concat "\\("
12223 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12224 "\\)\\>")))
12225 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12226 (regexp-quote (nth (1- (prefix-numeric-value arg))
12227 org-todo-keywords-1)))
12228 (t (error "Invalid prefix argument: %s" arg)))))
12229 (message "%d TODO entries found"
12230 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12232 (defun org-deadline (&optional remove time)
12233 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12234 With argument REMOVE, remove any deadline from the item.
12235 With argument TIME, set the deadline at the corresponding date. TIME
12236 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12237 (interactive "P")
12238 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12239 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12240 'region-start-level 'region))
12241 org-loop-over-headlines-in-active-region)
12242 (org-map-entries
12243 `(org-deadline ',remove ,time)
12244 org-loop-over-headlines-in-active-region
12245 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12246 (let* ((old-date (org-entry-get nil "DEADLINE"))
12247 (repeater (and old-date
12248 (string-match
12249 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12250 old-date)
12251 (match-string 1 old-date))))
12252 (if remove
12253 (progn
12254 (when (and old-date org-log-redeadline)
12255 (org-add-log-setup 'deldeadline nil old-date 'findpos
12256 org-log-redeadline))
12257 (org-remove-timestamp-with-keyword org-deadline-string)
12258 (message "Item no longer has a deadline."))
12259 (org-add-planning-info 'deadline time 'closed)
12260 (when (and old-date org-log-redeadline
12261 (not (equal old-date
12262 (substring org-last-inserted-timestamp 1 -1))))
12263 (org-add-log-setup 'redeadline nil old-date 'findpos
12264 org-log-redeadline))
12265 (when repeater
12266 (save-excursion
12267 (org-back-to-heading t)
12268 (when (re-search-forward (concat org-deadline-string " "
12269 org-last-inserted-timestamp)
12270 (save-excursion
12271 (outline-next-heading) (point)) t)
12272 (goto-char (1- (match-end 0)))
12273 (insert " " repeater)
12274 (setq org-last-inserted-timestamp
12275 (concat (substring org-last-inserted-timestamp 0 -1)
12276 " " repeater
12277 (substring org-last-inserted-timestamp -1))))))
12278 (message "Deadline on %s" org-last-inserted-timestamp)))))
12280 (defun org-schedule (&optional remove time)
12281 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12282 With argument REMOVE, remove any scheduling date from the item.
12283 With argument TIME, scheduled at the corresponding date. TIME can
12284 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12285 (interactive "P")
12286 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12287 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12288 'region-start-level 'region))
12289 org-loop-over-headlines-in-active-region)
12290 (org-map-entries
12291 `(org-schedule ',remove ,time)
12292 org-loop-over-headlines-in-active-region
12293 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12294 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12295 (repeater (and old-date
12296 (string-match
12297 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12298 old-date)
12299 (match-string 1 old-date))))
12300 (if remove
12301 (progn
12302 (when (and old-date org-log-reschedule)
12303 (org-add-log-setup 'delschedule nil old-date 'findpos
12304 org-log-reschedule))
12305 (org-remove-timestamp-with-keyword org-scheduled-string)
12306 (message "Item is no longer scheduled."))
12307 (org-add-planning-info 'scheduled time 'closed)
12308 (when (and old-date org-log-reschedule
12309 (not (equal old-date
12310 (substring org-last-inserted-timestamp 1 -1))))
12311 (org-add-log-setup 'reschedule nil old-date 'findpos
12312 org-log-reschedule))
12313 (when repeater
12314 (save-excursion
12315 (org-back-to-heading t)
12316 (when (re-search-forward (concat org-scheduled-string " "
12317 org-last-inserted-timestamp)
12318 (save-excursion
12319 (outline-next-heading) (point)) t)
12320 (goto-char (1- (match-end 0)))
12321 (insert " " repeater)
12322 (setq org-last-inserted-timestamp
12323 (concat (substring org-last-inserted-timestamp 0 -1)
12324 " " repeater
12325 (substring org-last-inserted-timestamp -1))))))
12326 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12328 (defun org-get-scheduled-time (pom &optional inherit)
12329 "Get the scheduled time as a time tuple, of a format suitable
12330 for calling org-schedule with, or if there is no scheduling,
12331 returns nil."
12332 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12333 (when time
12334 (apply 'encode-time (org-parse-time-string time)))))
12336 (defun org-get-deadline-time (pom &optional inherit)
12337 "Get the deadline as a time tuple, of a format suitable for
12338 calling org-deadline with, or if there is no scheduling, returns
12339 nil."
12340 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12341 (when time
12342 (apply 'encode-time (org-parse-time-string time)))))
12344 (defun org-remove-timestamp-with-keyword (keyword)
12345 "Remove all time stamps with KEYWORD in the current entry."
12346 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12347 beg)
12348 (save-excursion
12349 (org-back-to-heading t)
12350 (setq beg (point))
12351 (outline-next-heading)
12352 (while (re-search-backward re beg t)
12353 (replace-match "")
12354 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12355 (equal (char-before) ?\ ))
12356 (backward-delete-char 1)
12357 (if (string-match "^[ \t]*$" (buffer-substring
12358 (point-at-bol) (point-at-eol)))
12359 (delete-region (point-at-bol)
12360 (min (point-max) (1+ (point-at-eol))))))))))
12362 (defun org-add-planning-info (what &optional time &rest remove)
12363 "Insert new timestamp with keyword in the line directly after the headline.
12364 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12365 If non is given, the user is prompted for a date.
12366 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12367 be removed."
12368 (interactive)
12369 (let (org-time-was-given org-end-time-was-given ts
12370 end default-time default-input)
12372 (catch 'exit
12373 (when (and (memq what '(scheduled deadline))
12374 (or (not time)
12375 (and (stringp time)
12376 (string-match "^[-+]+[0-9]" time))))
12377 ;; Try to get a default date/time from existing timestamp
12378 (save-excursion
12379 (org-back-to-heading t)
12380 (setq end (save-excursion (outline-next-heading) (point)))
12381 (when (re-search-forward (if (eq what 'scheduled)
12382 org-scheduled-time-regexp
12383 org-deadline-time-regexp)
12384 end t)
12385 (setq ts (match-string 1)
12386 default-time
12387 (apply 'encode-time (org-parse-time-string ts))
12388 default-input (and ts (org-get-compact-tod ts))))))
12389 (when what
12390 (setq time
12391 (if (stringp time)
12392 ;; This is a string (relative or absolute), set proper date
12393 (apply 'encode-time
12394 (org-read-date-analyze
12395 time default-time (decode-time default-time)))
12396 ;; If necessary, get the time from the user
12397 (or time (org-read-date nil 'to-time nil nil
12398 default-time default-input)))))
12400 (when (and org-insert-labeled-timestamps-at-point
12401 (member what '(scheduled deadline)))
12402 (insert
12403 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12404 (org-insert-time-stamp time org-time-was-given
12405 nil nil nil (list org-end-time-was-given))
12406 (setq what nil))
12407 (save-excursion
12408 (save-restriction
12409 (let (col list elt ts buffer-invisibility-spec)
12410 (org-back-to-heading t)
12411 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12412 (goto-char (match-end 1))
12413 (setq col (current-column))
12414 (goto-char (match-end 0))
12415 (if (eobp) (insert "\n") (forward-char 1))
12416 (when (and (not what)
12417 (not (looking-at
12418 (concat "[ \t]*"
12419 org-keyword-time-not-clock-regexp))))
12420 ;; Nothing to add, nothing to remove...... :-)
12421 (throw 'exit nil))
12422 (if (and (not (looking-at org-outline-regexp))
12423 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12424 "[^\r\n]*"))
12425 (not (equal (match-string 1) org-clock-string)))
12426 (narrow-to-region (match-beginning 0) (match-end 0))
12427 (insert-before-markers "\n")
12428 (backward-char 1)
12429 (narrow-to-region (point) (point))
12430 (and org-adapt-indentation (org-indent-to-column col)))
12431 ;; Check if we have to remove something.
12432 (setq list (cons what remove))
12433 (while list
12434 (setq elt (pop list))
12435 (when (or (and (eq elt 'scheduled)
12436 (re-search-forward org-scheduled-time-regexp nil t))
12437 (and (eq elt 'deadline)
12438 (re-search-forward org-deadline-time-regexp nil t))
12439 (and (eq elt 'closed)
12440 (re-search-forward org-closed-time-regexp nil t)))
12441 (replace-match "")
12442 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12443 (and (looking-at "[ \t]+") (replace-match ""))
12444 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12445 (when what
12446 (insert
12447 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12448 (cond ((eq what 'scheduled) org-scheduled-string)
12449 ((eq what 'deadline) org-deadline-string)
12450 ((eq what 'closed) org-closed-string))
12451 " ")
12452 (setq ts (org-insert-time-stamp
12453 time
12454 (or org-time-was-given
12455 (and (eq what 'closed) org-log-done-with-time))
12456 (eq what 'closed)
12457 nil nil (list org-end-time-was-given)))
12458 (insert
12459 (if (not (or (bolp) (eq (char-before) ?\ )
12460 (memq (char-after) '(32 10))
12461 (eobp))) " " ""))
12462 (end-of-line 1))
12463 (goto-char (point-min))
12464 (widen)
12465 (if (and (looking-at "[ \t]*\n")
12466 (equal (char-before) ?\n))
12467 (delete-region (1- (point)) (point-at-eol)))
12468 ts))))))
12470 (defvar org-log-note-marker (make-marker))
12471 (defvar org-log-note-purpose nil)
12472 (defvar org-log-note-state nil)
12473 (defvar org-log-note-previous-state nil)
12474 (defvar org-log-note-how nil)
12475 (defvar org-log-note-extra nil)
12476 (defvar org-log-note-window-configuration nil)
12477 (defvar org-log-note-return-to (make-marker))
12478 (defvar org-log-note-effective-time nil
12479 "Remembered current time so that dynamically scoped
12480 `org-extend-today-until' affects tha timestamps in state change
12481 log")
12483 (defvar org-log-post-message nil
12484 "Message to be displayed after a log note has been stored.
12485 The auto-repeater uses this.")
12487 (defun org-add-note ()
12488 "Add a note to the current entry.
12489 This is done in the same way as adding a state change note."
12490 (interactive)
12491 (org-add-log-setup 'note nil nil 'findpos nil))
12493 (defvar org-property-end-re)
12494 (defun org-add-log-setup (&optional purpose state prev-state
12495 findpos how extra)
12496 "Set up the post command hook to take a note.
12497 If this is about to TODO state change, the new state is expected in STATE.
12498 When FINDPOS is non-nil, find the correct position for the note in
12499 the current entry. If not, assume that it can be inserted at point.
12500 HOW is an indicator what kind of note should be created.
12501 EXTRA is additional text that will be inserted into the notes buffer."
12502 (let* ((org-log-into-drawer (org-log-into-drawer))
12503 (drawer (cond ((stringp org-log-into-drawer)
12504 org-log-into-drawer)
12505 (org-log-into-drawer "LOGBOOK"))))
12506 (save-restriction
12507 (save-excursion
12508 (when findpos
12509 (org-back-to-heading t)
12510 (narrow-to-region (point) (save-excursion
12511 (outline-next-heading) (point)))
12512 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12513 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12514 "[^\r\n]*\\)?"))
12515 (goto-char (match-end 0))
12516 (cond
12517 (drawer
12518 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12519 nil t)
12520 (progn
12521 (goto-char (match-end 0))
12522 (or org-log-states-order-reversed
12523 (and (re-search-forward org-property-end-re nil t)
12524 (goto-char (1- (match-beginning 0))))))
12525 (insert "\n:" drawer ":\n:END:")
12526 (beginning-of-line 0)
12527 (org-indent-line)
12528 (beginning-of-line 2)
12529 (org-indent-line)
12530 (end-of-line 0)))
12531 ((and org-log-state-notes-insert-after-drawers
12532 (save-excursion
12533 (forward-line) (looking-at org-drawer-regexp)))
12534 (forward-line)
12535 (while (looking-at org-drawer-regexp)
12536 (goto-char (match-end 0))
12537 (re-search-forward org-property-end-re (point-max) t)
12538 (forward-line))
12539 (forward-line -1)))
12540 (unless org-log-states-order-reversed
12541 (and (= (char-after) ?\n) (forward-char 1))
12542 (org-skip-over-state-notes)
12543 (skip-chars-backward " \t\n\r")))
12544 (move-marker org-log-note-marker (point))
12545 (setq org-log-note-purpose purpose
12546 org-log-note-state state
12547 org-log-note-previous-state prev-state
12548 org-log-note-how how
12549 org-log-note-extra extra
12550 org-log-note-effective-time (org-current-effective-time))
12551 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12553 (defun org-skip-over-state-notes ()
12554 "Skip past the list of State notes in an entry."
12555 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12556 (when (ignore-errors (goto-char (org-in-item-p)))
12557 (let* ((struct (org-list-struct))
12558 (prevs (org-list-prevs-alist struct)))
12559 (while (looking-at "[ \t]*- State")
12560 (goto-char (or (org-list-get-next-item (point) struct prevs)
12561 (org-list-get-item-end (point) struct)))))))
12563 (defun org-add-log-note (&optional purpose)
12564 "Pop up a window for taking a note, and add this note later at point."
12565 (remove-hook 'post-command-hook 'org-add-log-note)
12566 (setq org-log-note-window-configuration (current-window-configuration))
12567 (delete-other-windows)
12568 (move-marker org-log-note-return-to (point))
12569 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12570 (goto-char org-log-note-marker)
12571 (org-switch-to-buffer-other-window "*Org Note*")
12572 (erase-buffer)
12573 (if (memq org-log-note-how '(time state))
12574 (let (current-prefix-arg) (org-store-log-note))
12575 (let ((org-inhibit-startup t)) (org-mode))
12576 (insert (format "# Insert note for %s.
12577 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12578 (cond
12579 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12580 ((eq org-log-note-purpose 'done) "closed todo item")
12581 ((eq org-log-note-purpose 'state)
12582 (format "state change from \"%s\" to \"%s\""
12583 (or org-log-note-previous-state "")
12584 (or org-log-note-state "")))
12585 ((eq org-log-note-purpose 'reschedule)
12586 "rescheduling")
12587 ((eq org-log-note-purpose 'delschedule)
12588 "no longer scheduled")
12589 ((eq org-log-note-purpose 'redeadline)
12590 "changing deadline")
12591 ((eq org-log-note-purpose 'deldeadline)
12592 "removing deadline")
12593 ((eq org-log-note-purpose 'refile)
12594 "refiling")
12595 ((eq org-log-note-purpose 'note)
12596 "this entry")
12597 (t (error "This should not happen")))))
12598 (if org-log-note-extra (insert org-log-note-extra))
12599 (org-set-local 'org-finish-function 'org-store-log-note)
12600 (run-hooks 'org-log-buffer-setup-hook)))
12602 (defvar org-note-abort nil) ; dynamically scoped
12603 (defun org-store-log-note ()
12604 "Finish taking a log note, and insert it to where it belongs."
12605 (let ((txt (buffer-string))
12606 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12607 lines ind bul)
12608 (kill-buffer (current-buffer))
12609 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12610 (setq txt (replace-match "" t t txt)))
12611 (if (string-match "\\s-+\\'" txt)
12612 (setq txt (replace-match "" t t txt)))
12613 (setq lines (org-split-string txt "\n"))
12614 (when (and note (string-match "\\S-" note))
12615 (setq note
12616 (org-replace-escapes
12617 note
12618 (list (cons "%u" (user-login-name))
12619 (cons "%U" user-full-name)
12620 (cons "%t" (format-time-string
12621 (org-time-stamp-format 'long 'inactive)
12622 org-log-note-effective-time))
12623 (cons "%T" (format-time-string
12624 (org-time-stamp-format 'long nil)
12625 org-log-note-effective-time))
12626 (cons "%d" (format-time-string
12627 (org-time-stamp-format nil 'inactive)
12628 org-log-note-effective-time))
12629 (cons "%D" (format-time-string
12630 (org-time-stamp-format nil nil)
12631 org-log-note-effective-time))
12632 (cons "%s" (if org-log-note-state
12633 (concat "\"" org-log-note-state "\"")
12634 ""))
12635 (cons "%S" (if org-log-note-previous-state
12636 (concat "\"" org-log-note-previous-state "\"")
12637 "\"\"")))))
12638 (if lines (setq note (concat note " \\\\")))
12639 (push note lines))
12640 (when (or current-prefix-arg org-note-abort)
12641 (when org-log-into-drawer
12642 (org-remove-empty-drawer-at
12643 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12644 org-log-note-marker))
12645 (setq lines nil))
12646 (when lines
12647 (with-current-buffer (marker-buffer org-log-note-marker)
12648 (save-excursion
12649 (goto-char org-log-note-marker)
12650 (move-marker org-log-note-marker nil)
12651 (end-of-line 1)
12652 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12653 (setq ind (save-excursion
12654 (if (ignore-errors (goto-char (org-in-item-p)))
12655 (let ((struct (org-list-struct)))
12656 (org-list-get-ind
12657 (org-list-get-top-point struct) struct))
12658 (skip-chars-backward " \r\t\n")
12659 (cond
12660 ((and (org-at-heading-p)
12661 org-adapt-indentation)
12662 (1+ (org-current-level)))
12663 ((org-at-heading-p) 0)
12664 (t (org-get-indentation))))))
12665 (setq bul (org-list-bullet-string "-"))
12666 (org-indent-line-to ind)
12667 (insert bul (pop lines))
12668 (let ((ind-body (+ (length bul) ind)))
12669 (while lines
12670 (insert "\n")
12671 (org-indent-line-to ind-body)
12672 (insert (pop lines))))
12673 (message "Note stored")
12674 (org-back-to-heading t)
12675 (org-cycle-hide-drawers 'children)))))
12676 (set-window-configuration org-log-note-window-configuration)
12677 (with-current-buffer (marker-buffer org-log-note-return-to)
12678 (goto-char org-log-note-return-to))
12679 (move-marker org-log-note-return-to nil)
12680 (and org-log-post-message (message "%s" org-log-post-message)))
12682 (defun org-remove-empty-drawer-at (drawer pos)
12683 "Remove an empty drawer DRAWER at position POS.
12684 POS may also be a marker."
12685 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12686 (save-excursion
12687 (save-restriction
12688 (widen)
12689 (goto-char pos)
12690 (if (org-in-regexp
12691 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12692 (replace-match ""))))))
12694 (defvar org-ts-type nil)
12695 (defun org-sparse-tree (&optional arg type)
12696 "Create a sparse tree, prompt for the details.
12697 This command can create sparse trees. You first need to select the type
12698 of match used to create the tree:
12700 t Show all TODO entries.
12701 T Show entries with a specific TODO keyword.
12702 m Show entries selected by a tags/property match.
12703 p Enter a property name and its value (both with completion on existing
12704 names/values) and show entries with that property.
12705 r Show entries matching a regular expression (`/' can be used as well).
12706 b Show deadlines and scheduled items before a date.
12707 a Show deadlines and scheduled items after a date.
12708 d Show deadlines due within `org-deadline-warning-days'.
12709 D Show deadlines and scheduled items between a date range."
12710 (interactive "P")
12711 (let (ans kwd value ts-type)
12712 (setq type (or type org-sparse-tree-default-date-type))
12713 (setq org-ts-type type)
12714 (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"
12715 (cond ((eq type 'all) "all timestamps")
12716 ((eq type 'scheduled) "only scheduled")
12717 ((eq type 'deadline) "only deadline")
12718 ((eq type 'active) "only active timestamps")
12719 ((eq type 'inactive) "only inactive timestamps")
12720 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12721 (t "scheduled/deadline")))
12722 (setq ans (read-char-exclusive))
12723 (cond
12724 ((equal ans ?c)
12725 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12726 ((equal ans ?d)
12727 (call-interactively 'org-check-deadlines))
12728 ((equal ans ?b)
12729 (call-interactively 'org-check-before-date))
12730 ((equal ans ?a)
12731 (call-interactively 'org-check-after-date))
12732 ((equal ans ?D)
12733 (call-interactively 'org-check-dates-range))
12734 ((equal ans ?t)
12735 (org-show-todo-tree nil))
12736 ((equal ans ?T)
12737 (org-show-todo-tree '(4)))
12738 ((member ans '(?T ?m))
12739 (call-interactively 'org-match-sparse-tree))
12740 ((member ans '(?p ?P))
12741 (setq kwd (org-icompleting-read "Property: "
12742 (mapcar 'list (org-buffer-property-keys))))
12743 (setq value (org-icompleting-read "Value: "
12744 (mapcar 'list (org-property-values kwd))))
12745 (unless (string-match "\\`{.*}\\'" value)
12746 (setq value (concat "\"" value "\"")))
12747 (org-match-sparse-tree arg (concat kwd "=" value)))
12748 ((member ans '(?r ?R ?/))
12749 (call-interactively 'org-occur))
12750 (t (error "No such sparse tree command \"%c\"" ans)))))
12752 (defvar org-occur-highlights nil
12753 "List of overlays used for occur matches.")
12754 (make-variable-buffer-local 'org-occur-highlights)
12755 (defvar org-occur-parameters nil
12756 "Parameters of the active org-occur calls.
12757 This is a list, each call to org-occur pushes as cons cell,
12758 containing the regular expression and the callback, onto the list.
12759 The list can contain several entries if `org-occur' has been called
12760 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12761 will only contain one set of parameters. When the highlights are
12762 removed (for example with `C-c C-c', or with the next edit (depending
12763 on `org-remove-highlights-with-change'), this variable is emptied
12764 as well.")
12765 (make-variable-buffer-local 'org-occur-parameters)
12767 (defun org-occur (regexp &optional keep-previous callback)
12768 "Make a compact tree which shows all matches of REGEXP.
12769 The tree will show the lines where the regexp matches, and all higher
12770 headlines above the match. It will also show the heading after the match,
12771 to make sure editing the matching entry is easy.
12772 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12773 call to `org-occur' will be kept, to allow stacking of calls to this
12774 command.
12775 If CALLBACK is non-nil, it is a function which is called to confirm
12776 that the match should indeed be shown."
12777 (interactive "sRegexp: \nP")
12778 (when (equal regexp "")
12779 (error "Regexp cannot be empty"))
12780 (unless keep-previous
12781 (org-remove-occur-highlights nil nil t))
12782 (push (cons regexp callback) org-occur-parameters)
12783 (let ((cnt 0))
12784 (save-excursion
12785 (goto-char (point-min))
12786 (if (or (not keep-previous) ; do not want to keep
12787 (not org-occur-highlights)) ; no previous matches
12788 ;; hide everything
12789 (org-overview))
12790 (while (re-search-forward regexp nil t)
12791 (when (or (not callback)
12792 (save-match-data (funcall callback)))
12793 (setq cnt (1+ cnt))
12794 (when org-highlight-sparse-tree-matches
12795 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12796 (org-show-context 'occur-tree))))
12797 (when org-remove-highlights-with-change
12798 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12799 nil 'local))
12800 (unless org-sparse-tree-open-archived-trees
12801 (org-hide-archived-subtrees (point-min) (point-max)))
12802 (run-hooks 'org-occur-hook)
12803 (if (org-called-interactively-p 'interactive)
12804 (message "%d match(es) for regexp %s" cnt regexp))
12805 cnt))
12807 (defun org-occur-next-match (&optional n reset)
12808 "Function for `next-error-function' to find sparse tree matches.
12809 N is the number of matches to move, when negative move backwards.
12810 RESET is entirely ignored - this function always goes back to the
12811 starting point when no match is found."
12812 (let* ((limit (if (< n 0) (point-min) (point-max)))
12813 (search-func (if (< n 0)
12814 'previous-single-char-property-change
12815 'next-single-char-property-change))
12816 (n (abs n))
12817 (pos (point))
12819 (catch 'exit
12820 (while (setq p1 (funcall search-func (point) 'org-type))
12821 (when (equal p1 limit)
12822 (goto-char pos)
12823 (error "No more matches"))
12824 (when (equal (get-char-property p1 'org-type) 'org-occur)
12825 (setq n (1- n))
12826 (when (= n 0)
12827 (goto-char p1)
12828 (throw 'exit (point))))
12829 (goto-char p1))
12830 (goto-char p1)
12831 (error "No more matches"))))
12833 (defun org-show-context (&optional key)
12834 "Make sure point and context are visible.
12835 How much context is shown depends upon the variables
12836 `org-show-hierarchy-above', `org-show-following-heading',
12837 `org-show-entry-below' and `org-show-siblings'."
12838 (let ((heading-p (org-at-heading-p t))
12839 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12840 (following-p (org-get-alist-option org-show-following-heading key))
12841 (entry-p (org-get-alist-option org-show-entry-below key))
12842 (siblings-p (org-get-alist-option org-show-siblings key)))
12843 (catch 'exit
12844 ;; Show heading or entry text
12845 (if (and heading-p (not entry-p))
12846 (org-flag-heading nil) ; only show the heading
12847 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12848 (org-show-hidden-entry))) ; show entire entry
12849 (when following-p
12850 ;; Show next sibling, or heading below text
12851 (save-excursion
12852 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12853 (org-flag-heading nil))))
12854 (when siblings-p (org-show-siblings))
12855 (when hierarchy-p
12856 ;; show all higher headings, possibly with siblings
12857 (save-excursion
12858 (while (and (condition-case nil
12859 (progn (org-up-heading-all 1) t)
12860 (error nil))
12861 (not (bobp)))
12862 (org-flag-heading nil)
12863 (when siblings-p (org-show-siblings))))))))
12865 (defvar org-reveal-start-hook nil
12866 "Hook run before revealing a location.")
12868 (defun org-reveal (&optional siblings)
12869 "Show current entry, hierarchy above it, and the following headline.
12870 This can be used to show a consistent set of context around locations
12871 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12872 not t for the search context.
12874 With optional argument SIBLINGS, on each level of the hierarchy all
12875 siblings are shown. This repairs the tree structure to what it would
12876 look like when opened with hierarchical calls to `org-cycle'.
12877 With double optional argument \\[universal-argument] \\[universal-argument], \
12878 go to the parent and show the
12879 entire tree."
12880 (interactive "P")
12881 (run-hooks 'org-reveal-start-hook)
12882 (let ((org-show-hierarchy-above t)
12883 (org-show-following-heading t)
12884 (org-show-siblings (if siblings t org-show-siblings)))
12885 (org-show-context nil))
12886 (when (equal siblings '(16))
12887 (save-excursion
12888 (when (org-up-heading-safe)
12889 (org-show-subtree)
12890 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12892 (defun org-highlight-new-match (beg end)
12893 "Highlight from BEG to END and mark the highlight is an occur headline."
12894 (let ((ov (make-overlay beg end)))
12895 (overlay-put ov 'face 'secondary-selection)
12896 (overlay-put ov 'org-type 'org-occur)
12897 (push ov org-occur-highlights)))
12899 (defun org-remove-occur-highlights (&optional beg end noremove)
12900 "Remove the occur highlights from the buffer.
12901 BEG and END are ignored. If NOREMOVE is nil, remove this function
12902 from the `before-change-functions' in the current buffer."
12903 (interactive)
12904 (unless org-inhibit-highlight-removal
12905 (mapc 'delete-overlay org-occur-highlights)
12906 (setq org-occur-highlights nil)
12907 (setq org-occur-parameters nil)
12908 (unless noremove
12909 (remove-hook 'before-change-functions
12910 'org-remove-occur-highlights 'local))))
12912 ;;;; Priorities
12914 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12915 "Regular expression matching the priority indicator.")
12917 (defvar org-remove-priority-next-time nil)
12919 (defun org-priority-up ()
12920 "Increase the priority of the current item."
12921 (interactive)
12922 (org-priority 'up))
12924 (defun org-priority-down ()
12925 "Decrease the priority of the current item."
12926 (interactive)
12927 (org-priority 'down))
12929 (defun org-priority (&optional action show)
12930 "Change the priority of an item.
12931 ACTION can be `set', `up', `down', or a character."
12932 (interactive "P")
12933 (if (equal action '(4))
12934 (org-show-priority)
12935 (unless org-enable-priority-commands
12936 (error "Priority commands are disabled"))
12937 (setq action (or action 'set))
12938 (let (current new news have remove)
12939 (save-excursion
12940 (org-back-to-heading t)
12941 (if (looking-at org-priority-regexp)
12942 (setq current (string-to-char (match-string 2))
12943 have t))
12944 (cond
12945 ((eq action 'remove)
12946 (setq remove t new ?\ ))
12947 ((or (eq action 'set)
12948 (if (featurep 'xemacs) (characterp action) (integerp action)))
12949 (if (not (eq action 'set))
12950 (setq new action)
12951 (message "Priority %c-%c, SPC to remove: "
12952 org-highest-priority org-lowest-priority)
12953 (save-match-data
12954 (setq new (read-char-exclusive))))
12955 (if (and (= (upcase org-highest-priority) org-highest-priority)
12956 (= (upcase org-lowest-priority) org-lowest-priority))
12957 (setq new (upcase new)))
12958 (cond ((equal new ?\ ) (setq remove t))
12959 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12960 (error "Priority must be between `%c' and `%c'"
12961 org-highest-priority org-lowest-priority))))
12962 ((eq action 'up)
12963 (setq new (if have
12964 (1- current) ; normal cycling
12965 ;; last priority was empty
12966 (if (eq last-command this-command)
12967 org-lowest-priority ; wrap around empty to lowest
12968 ;; default
12969 (if org-priority-start-cycle-with-default
12970 org-default-priority
12971 (1- org-default-priority))))))
12972 ((eq action 'down)
12973 (setq new (if have
12974 (1+ current) ; normal cycling
12975 ;; last priority was empty
12976 (if (eq last-command this-command)
12977 org-highest-priority ; wrap around empty to highest
12978 ;; default
12979 (if org-priority-start-cycle-with-default
12980 org-default-priority
12981 (1+ org-default-priority))))))
12982 (t (error "Invalid action")))
12983 (if (or (< (upcase new) org-highest-priority)
12984 (> (upcase new) org-lowest-priority))
12985 (if (and (memq action '(up down))
12986 (not have) (not (eq last-command this-command)))
12987 ;; `new' is from default priority
12988 (error
12989 "The default can not be set, see `org-default-priority' why")
12990 ;; normal cycling: `new' is beyond highest/lowest priority
12991 ;; and is wrapped around to the empty priority
12992 (setq remove t)))
12993 (setq news (format "%c" new))
12994 (if have
12995 (if remove
12996 (replace-match "" t t nil 1)
12997 (replace-match news t t nil 2))
12998 (if remove
12999 (error "No priority cookie found in line")
13000 (let ((case-fold-search nil))
13001 (looking-at org-todo-line-regexp))
13002 (if (match-end 2)
13003 (progn
13004 (goto-char (match-end 2))
13005 (insert " [#" news "]"))
13006 (goto-char (match-beginning 3))
13007 (insert "[#" news "] "))))
13008 (org-preserve-lc (org-set-tags nil 'align)))
13009 (if remove
13010 (message "Priority removed")
13011 (message "Priority of current item set to %s" news)))))
13013 (defun org-show-priority ()
13014 "Show the priority of the current item.
13015 This priority is composed of the main priority given with the [#A] cookies,
13016 and by additional input from the age of a schedules or deadline entry."
13017 (interactive)
13018 (let ((pri (if (eq major-mode 'org-agenda-mode)
13019 (org-get-at-bol 'priority)
13020 (save-excursion
13021 (save-match-data
13022 (beginning-of-line)
13023 (and (looking-at org-heading-regexp)
13024 (org-get-priority (match-string 0))))))))
13025 (message "Priority is %d" (if pri pri -1000))))
13027 (defun org-get-priority (s)
13028 "Find priority cookie and return priority."
13029 (if (functionp org-get-priority-function)
13030 (funcall org-get-priority-function)
13031 (save-match-data
13032 (if (not (string-match org-priority-regexp s))
13033 (* 1000 (- org-lowest-priority org-default-priority))
13034 (* 1000 (- org-lowest-priority
13035 (string-to-char (match-string 2 s))))))))
13037 ;;;; Tags
13039 (defvar org-agenda-archives-mode)
13040 (defvar org-map-continue-from nil
13041 "Position from where mapping should continue.
13042 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13044 (defvar org-scanner-tags nil
13045 "The current tag list while the tags scanner is running.")
13046 (defvar org-trust-scanner-tags nil
13047 "Should `org-get-tags-at' use the tags for the scanner.
13048 This is for internal dynamical scoping only.
13049 When this is non-nil, the function `org-get-tags-at' will return the value
13050 of `org-scanner-tags' instead of building the list by itself. This
13051 can lead to large speed-ups when the tags scanner is used in a file with
13052 many entries, and when the list of tags is retrieved, for example to
13053 obtain a list of properties. Building the tags list for each entry in such
13054 a file becomes an N^2 operation - but with this variable set, it scales
13055 as N.")
13057 (defun org-scan-tags (action matcher todo-only &optional start-level)
13058 "Scan headline tags with inheritance and produce output ACTION.
13060 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13061 or `agenda' to produce an entry list for an agenda view. It can also be
13062 a Lisp form or a function that should be called at each matched headline, in
13063 this case the return value is a list of all return values from these calls.
13065 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13066 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13067 only lines with a not-done TODO keyword are included in the output.
13068 This should be the same variable that was scoped into
13069 and set by `org-make-tags-matcher' when it constructed MATCHER.
13071 START-LEVEL can be a string with asterisks, reducing the scope to
13072 headlines matching this string."
13073 (require 'org-agenda)
13074 (let* ((re (concat "^"
13075 (if start-level
13076 ;; Get the correct level to match
13077 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13078 org-outline-regexp)
13079 " *\\(\\<\\("
13080 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13081 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13082 (props (list 'face 'default
13083 'done-face 'org-agenda-done
13084 'undone-face 'default
13085 'mouse-face 'highlight
13086 'org-not-done-regexp org-not-done-regexp
13087 'org-todo-regexp org-todo-regexp
13088 'org-complex-heading-regexp org-complex-heading-regexp
13089 'help-echo
13090 (format "mouse-2 or RET jump to org file %s"
13091 (abbreviate-file-name
13092 (or (buffer-file-name (buffer-base-buffer))
13093 (buffer-name (buffer-base-buffer)))))))
13094 (case-fold-search nil)
13095 (org-map-continue-from nil)
13096 lspos tags tags-list
13097 (tags-alist (list (cons 0 org-file-tags)))
13098 (llast 0) rtn rtn1 level category i txt
13099 todo marker entry priority)
13100 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13101 (setq action (list 'lambda nil action)))
13102 (save-excursion
13103 (goto-char (point-min))
13104 (when (eq action 'sparse-tree)
13105 (org-overview)
13106 (org-remove-occur-highlights))
13107 (while (re-search-forward re nil t)
13108 (setq org-map-continue-from nil)
13109 (catch :skip
13110 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13111 tags (if (match-end 4) (org-match-string-no-properties 4)))
13112 (goto-char (setq lspos (match-beginning 0)))
13113 (setq level (org-reduced-level (org-outline-level))
13114 category (org-get-category))
13115 (setq i llast llast level)
13116 ;; remove tag lists from same and sublevels
13117 (while (>= i level)
13118 (when (setq entry (assoc i tags-alist))
13119 (setq tags-alist (delete entry tags-alist)))
13120 (setq i (1- i)))
13121 ;; add the next tags
13122 (when tags
13123 (setq tags (org-split-string tags ":")
13124 tags-alist
13125 (cons (cons level tags) tags-alist)))
13126 ;; compile tags for current headline
13127 (setq tags-list
13128 (if org-use-tag-inheritance
13129 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13130 tags)
13131 org-scanner-tags tags-list)
13132 (when org-use-tag-inheritance
13133 (setcdr (car tags-alist)
13134 (mapcar (lambda (x)
13135 (setq x (copy-sequence x))
13136 (org-add-prop-inherited x))
13137 (cdar tags-alist))))
13138 (when (and tags org-use-tag-inheritance
13139 (or (not (eq t org-use-tag-inheritance))
13140 org-tags-exclude-from-inheritance))
13141 ;; selective inheritance, remove uninherited ones
13142 (setcdr (car tags-alist)
13143 (org-remove-uninherited-tags (cdar tags-alist))))
13144 (when (and
13146 ;; eval matcher only when the todo condition is OK
13147 (and (or (not todo-only) (member todo org-not-done-keywords))
13148 (let ((case-fold-search t) (org-trust-scanner-tags t))
13149 (eval matcher)))
13151 ;; Call the skipper, but return t if it does not skip,
13152 ;; so that the `and' form continues evaluating
13153 (progn
13154 (unless (eq action 'sparse-tree) (org-agenda-skip))
13157 ;; Check if timestamps are deselecting this entry
13158 (or (not todo-only)
13159 (and (member todo org-not-done-keywords)
13160 (or (not org-agenda-tags-todo-honor-ignore-options)
13161 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13163 ;; Extra check for the archive tag
13164 ;; FIXME: Does the skipper already do this????
13166 (not (member org-archive-tag tags-list))
13167 ;; we have an archive tag, should we use this anyway?
13168 (or (not org-agenda-skip-archived-trees)
13169 (and (eq action 'agenda) org-agenda-archives-mode))))
13171 ;; select this headline
13172 (cond
13173 ((eq action 'sparse-tree)
13174 (and org-highlight-sparse-tree-matches
13175 (org-get-heading) (match-end 0)
13176 (org-highlight-new-match
13177 (match-beginning 1) (match-end 1)))
13178 (org-show-context 'tags-tree))
13179 ((eq action 'agenda)
13180 (setq txt (org-agenda-format-item
13182 (concat
13183 (if (eq org-tags-match-list-sublevels 'indented)
13184 (make-string (1- level) ?.) "")
13185 (org-get-heading))
13186 level category
13187 tags-list)
13188 priority (org-get-priority txt))
13189 (goto-char lspos)
13190 (setq marker (org-agenda-new-marker))
13191 (org-add-props txt props
13192 'org-marker marker 'org-hd-marker marker 'org-category category
13193 'todo-state todo
13194 'priority priority 'type "tagsmatch")
13195 (push txt rtn))
13196 ((functionp action)
13197 (setq org-map-continue-from nil)
13198 (save-excursion
13199 (setq rtn1 (funcall action))
13200 (push rtn1 rtn)))
13201 (t (error "Invalid action")))
13203 ;; if we are to skip sublevels, jump to end of subtree
13204 (unless org-tags-match-list-sublevels
13205 (org-end-of-subtree t)
13206 (backward-char 1))))
13207 ;; Get the correct position from where to continue
13208 (if org-map-continue-from
13209 (goto-char org-map-continue-from)
13210 (and (= (point) lspos) (end-of-line 1)))))
13211 (when (and (eq action 'sparse-tree)
13212 (not org-sparse-tree-open-archived-trees))
13213 (org-hide-archived-subtrees (point-min) (point-max)))
13214 (nreverse rtn)))
13216 (defun org-remove-uninherited-tags (tags)
13217 "Remove all tags that are not inherited from the list TAGS."
13218 (cond
13219 ((eq org-use-tag-inheritance t)
13220 (if org-tags-exclude-from-inheritance
13221 (org-delete-all org-tags-exclude-from-inheritance tags)
13222 tags))
13223 ((not org-use-tag-inheritance) nil)
13224 ((stringp org-use-tag-inheritance)
13225 (delq nil (mapcar
13226 (lambda (x)
13227 (if (and (string-match org-use-tag-inheritance x)
13228 (not (member x org-tags-exclude-from-inheritance)))
13229 x nil))
13230 tags)))
13231 ((listp org-use-tag-inheritance)
13232 (delq nil (mapcar
13233 (lambda (x)
13234 (if (member x org-use-tag-inheritance) x nil))
13235 tags)))))
13237 (defun org-match-sparse-tree (&optional todo-only match)
13238 "Create a sparse tree according to tags string MATCH.
13239 MATCH can contain positive and negative selection of tags, like
13240 \"+WORK+URGENT-WITHBOSS\".
13241 If optional argument TODO-ONLY is non-nil, only select lines that are
13242 also TODO lines."
13243 (interactive "P")
13244 (org-agenda-prepare-buffers (list (current-buffer)))
13245 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13247 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13249 (defvar org-cached-props nil)
13250 (defun org-cached-entry-get (pom property)
13251 (if (or (eq t org-use-property-inheritance)
13252 (and (stringp org-use-property-inheritance)
13253 (string-match org-use-property-inheritance property))
13254 (and (listp org-use-property-inheritance)
13255 (member property org-use-property-inheritance)))
13256 ;; Caching is not possible, check it directly
13257 (org-entry-get pom property 'inherit)
13258 ;; Get all properties, so that we can do complicated checks easily
13259 (cdr (assoc property (or org-cached-props
13260 (setq org-cached-props
13261 (org-entry-properties pom)))))))
13263 (defun org-global-tags-completion-table (&optional files)
13264 "Return the list of all tags in all agenda buffer/files.
13265 Optional FILES argument is a list of files which can be used
13266 instead of the agenda files."
13267 (save-excursion
13268 (org-uniquify
13269 (delq nil
13270 (apply 'append
13271 (mapcar
13272 (lambda (file)
13273 (set-buffer (find-file-noselect file))
13274 (append (org-get-buffer-tags)
13275 (mapcar (lambda (x) (if (stringp (car-safe x))
13276 (list (car-safe x)) nil))
13277 org-tag-alist)))
13278 (if (and files (car files))
13279 files
13280 (org-agenda-files))))))))
13282 (defun org-make-tags-matcher (match)
13283 "Create the TAGS/TODO matcher form for the selection string MATCH.
13285 The variable `todo-only' is scoped dynamically into this function.
13286 It will be set to t if the matcher restricts matching to TODO entries,
13287 otherwise will not be touched.
13289 Returns a cons of the selection string MATCH and the constructed
13290 lisp form implementing the matcher. The matcher is to be evaluated
13291 at an Org entry, with point on the headline, and returns t if the
13292 entry matches the selection string MATCH. The returned lisp form
13293 references two variables with information about the entry, which
13294 must be bound around the form's evaluation: todo, the TODO keyword
13295 at the entry (or nil of none); and tags-list, the list of all tags
13296 at the entry including inherited ones. Additionally, the category
13297 of the entry (if any) must be specified as the text property
13298 'org-category on the headline.
13300 See also `org-scan-tags'.
13302 (declare (special todo-only))
13303 (unless (boundp 'todo-only)
13304 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13305 (unless match
13306 ;; Get a new match request, with completion
13307 (let ((org-last-tags-completion-table
13308 (org-global-tags-completion-table)))
13309 (setq match (org-completing-read-no-i
13310 "Match: " 'org-tags-completion-function nil nil nil
13311 'org-tags-history))))
13313 ;; Parse the string and create a lisp form
13314 (let ((match0 match)
13315 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13316 minus tag mm
13317 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13318 orterms term orlist re-p str-p level-p level-op time-p
13319 prop-p pn pv po gv rest)
13320 (if (string-match "/+" match)
13321 ;; match contains also a todo-matching request
13322 (progn
13323 (setq tagsmatch (substring match 0 (match-beginning 0))
13324 todomatch (substring match (match-end 0)))
13325 (if (string-match "^!" todomatch)
13326 (setq todo-only t todomatch (substring todomatch 1)))
13327 (if (string-match "^\\s-*$" todomatch)
13328 (setq todomatch nil)))
13329 ;; only matching tags
13330 (setq tagsmatch match todomatch nil))
13332 ;; Make the tags matcher
13333 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13334 (setq tagsmatcher t)
13335 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13336 (while (setq term (pop orterms))
13337 (while (and (equal (substring term -1) "\\") orterms)
13338 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13339 (while (string-match re term)
13340 (setq rest (substring term (match-end 0))
13341 minus (and (match-end 1)
13342 (equal (match-string 1 term) "-"))
13343 tag (save-match-data (replace-regexp-in-string
13344 "\\\\-" "-"
13345 (match-string 2 term)))
13346 re-p (equal (string-to-char tag) ?{)
13347 level-p (match-end 4)
13348 prop-p (match-end 5)
13349 mm (cond
13350 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13351 (level-p
13352 (setq level-op (org-op-to-function (match-string 3 term)))
13353 `(,level-op level ,(string-to-number
13354 (match-string 4 term))))
13355 (prop-p
13356 (setq pn (match-string 5 term)
13357 po (match-string 6 term)
13358 pv (match-string 7 term)
13359 re-p (equal (string-to-char pv) ?{)
13360 str-p (equal (string-to-char pv) ?\")
13361 time-p (save-match-data
13362 (string-match "^\"[[<].*[]>]\"$" pv))
13363 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13364 (if time-p (setq pv (org-matcher-time pv)))
13365 (setq po (org-op-to-function po (if time-p 'time str-p)))
13366 (cond
13367 ((equal pn "CATEGORY")
13368 (setq gv '(get-text-property (point) 'org-category)))
13369 ((equal pn "TODO")
13370 (setq gv 'todo))
13372 (setq gv `(org-cached-entry-get nil ,pn))))
13373 (if re-p
13374 (if (eq po 'org<>)
13375 `(not (string-match ,pv (or ,gv "")))
13376 `(string-match ,pv (or ,gv "")))
13377 (if str-p
13378 `(,po (or ,gv "") ,pv)
13379 `(,po (string-to-number (or ,gv ""))
13380 ,(string-to-number pv) ))))
13381 (t `(member ,tag tags-list)))
13382 mm (if minus (list 'not mm) mm)
13383 term rest)
13384 (push mm tagsmatcher))
13385 (push (if (> (length tagsmatcher) 1)
13386 (cons 'and tagsmatcher)
13387 (car tagsmatcher))
13388 orlist)
13389 (setq tagsmatcher nil))
13390 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13391 (setq tagsmatcher
13392 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13393 ;; Make the todo matcher
13394 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13395 (setq todomatcher t)
13396 (setq orterms (org-split-string todomatch "|") orlist nil)
13397 (while (setq term (pop orterms))
13398 (while (string-match re term)
13399 (setq minus (and (match-end 1)
13400 (equal (match-string 1 term) "-"))
13401 kwd (match-string 2 term)
13402 re-p (equal (string-to-char kwd) ?{)
13403 term (substring term (match-end 0))
13404 mm (if re-p
13405 `(string-match ,(substring kwd 1 -1) todo)
13406 (list 'equal 'todo kwd))
13407 mm (if minus (list 'not mm) mm))
13408 (push mm todomatcher))
13409 (push (if (> (length todomatcher) 1)
13410 (cons 'and todomatcher)
13411 (car todomatcher))
13412 orlist)
13413 (setq todomatcher nil))
13414 (setq todomatcher (if (> (length orlist) 1)
13415 (cons 'or orlist) (car orlist))))
13417 ;; Return the string and lisp forms of the matcher
13418 (setq matcher (if todomatcher
13419 (list 'and tagsmatcher todomatcher)
13420 tagsmatcher))
13421 (when todo-only
13422 (setq matcher (list 'and '(member todo org-not-done-keywords)
13423 matcher)))
13424 (cons match0 matcher)))
13426 (defun org-op-to-function (op &optional stringp)
13427 "Turn an operator into the appropriate function."
13428 (setq op
13429 (cond
13430 ((equal op "<" ) '(< string< org-time<))
13431 ((equal op ">" ) '(> org-string> org-time>))
13432 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13433 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13434 ((member op '("=" "==")) '(= string= org-time=))
13435 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13436 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13438 (defun org<> (a b) (not (= a b)))
13439 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13440 (defun org-string>= (a b) (not (string< a b)))
13441 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13442 (defun org-string<> (a b) (not (string= a b)))
13443 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13444 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13445 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13446 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13447 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13448 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13449 (defun org-2ft (s)
13450 "Convert S to a floating point time.
13451 If S is already a number, just return it. If it is a string, parse
13452 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13453 (cond
13454 ((numberp s) s)
13455 ((stringp s)
13456 (condition-case nil
13457 (float-time (apply 'encode-time (org-parse-time-string s)))
13458 (error 0.)))
13459 (t 0.)))
13461 (defun org-time-today ()
13462 "Time in seconds today at 0:00.
13463 Returns the float number of seconds since the beginning of the
13464 epoch to the beginning of today (00:00)."
13465 (float-time (apply 'encode-time
13466 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13468 (defun org-matcher-time (s)
13469 "Interpret a time comparison value."
13470 (save-match-data
13471 (cond
13472 ((string= s "<now>") (float-time))
13473 ((string= s "<today>") (org-time-today))
13474 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13475 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13476 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13477 (+ (org-time-today)
13478 (* (string-to-number (match-string 1 s))
13479 (cdr (assoc (match-string 2 s)
13480 '(("d" . 86400.0) ("w" . 604800.0)
13481 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13482 (t (org-2ft s)))))
13484 (defun org-match-any-p (re list)
13485 "Does re match any element of list?"
13486 (setq list (mapcar (lambda (x) (string-match re x)) list))
13487 (delq nil list))
13489 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13490 (defvar org-tags-overlay (make-overlay 1 1))
13491 (org-detach-overlay org-tags-overlay)
13493 (defun org-get-local-tags-at (&optional pos)
13494 "Get a list of tags defined in the current headline."
13495 (org-get-tags-at pos 'local))
13497 (defun org-get-local-tags ()
13498 "Get a list of tags defined in the current headline."
13499 (org-get-tags-at nil 'local))
13501 (defun org-get-tags-at (&optional pos local)
13502 "Get a list of all headline tags applicable at POS.
13503 POS defaults to point. If tags are inherited, the list contains
13504 the targets in the same sequence as the headlines appear, i.e.
13505 the tags of the current headline come last.
13506 When LOCAL is non-nil, only return tags from the current headline,
13507 ignore inherited ones."
13508 (interactive)
13509 (if (and org-trust-scanner-tags
13510 (or (not pos) (equal pos (point)))
13511 (not local))
13512 org-scanner-tags
13513 (let (tags ltags lastpos parent)
13514 (save-excursion
13515 (save-restriction
13516 (widen)
13517 (goto-char (or pos (point)))
13518 (save-match-data
13519 (catch 'done
13520 (condition-case nil
13521 (progn
13522 (org-back-to-heading t)
13523 (while (not (equal lastpos (point)))
13524 (setq lastpos (point))
13525 (when (looking-at
13526 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13527 (setq ltags (org-split-string
13528 (org-match-string-no-properties 1) ":"))
13529 (when parent
13530 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13531 (setq tags (append
13532 (if parent
13533 (org-remove-uninherited-tags ltags)
13534 ltags)
13535 tags)))
13536 (or org-use-tag-inheritance (throw 'done t))
13537 (if local (throw 'done t))
13538 (or (org-up-heading-safe) (error nil))
13539 (setq parent t)))
13540 (error nil)))))
13541 (if local
13542 tags
13543 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13545 (defun org-add-prop-inherited (s)
13546 (add-text-properties 0 (length s) '(inherited t) s)
13549 (defun org-toggle-tag (tag &optional onoff)
13550 "Toggle the tag TAG for the current line.
13551 If ONOFF is `on' or `off', don't toggle but set to this state."
13552 (let (res current)
13553 (save-excursion
13554 (org-back-to-heading t)
13555 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13556 (point-at-eol) t)
13557 (progn
13558 (setq current (match-string 1))
13559 (replace-match ""))
13560 (setq current ""))
13561 (setq current (nreverse (org-split-string current ":")))
13562 (cond
13563 ((eq onoff 'on)
13564 (setq res t)
13565 (or (member tag current) (push tag current)))
13566 ((eq onoff 'off)
13567 (or (not (member tag current)) (setq current (delete tag current))))
13568 (t (if (member tag current)
13569 (setq current (delete tag current))
13570 (setq res t)
13571 (push tag current))))
13572 (end-of-line 1)
13573 (if current
13574 (progn
13575 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13576 (org-set-tags nil t))
13577 (delete-horizontal-space))
13578 (run-hooks 'org-after-tags-change-hook))
13579 res))
13581 (defun org-align-tags-here (to-col)
13582 ;; Assumes that this is a headline
13583 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13584 (beginning-of-line 1)
13585 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13586 (< pos (match-beginning 2)))
13587 (progn
13588 (setq tags-l (- (match-end 2) (match-beginning 2)))
13589 (goto-char (match-beginning 1))
13590 (insert " ")
13591 (delete-region (point) (1+ (match-beginning 2)))
13592 (setq ncol (max (current-column)
13593 (1+ col)
13594 (if (> to-col 0)
13595 to-col
13596 (- (abs to-col) tags-l))))
13597 (setq p (point))
13598 (insert (make-string (- ncol (current-column)) ?\ ))
13599 (setq ncol (current-column))
13600 (when indent-tabs-mode (tabify p (point-at-eol)))
13601 (org-move-to-column (min ncol col) t))
13602 (goto-char pos))))
13604 (defun org-set-tags-command (&optional arg just-align)
13605 "Call the set-tags command for the current entry."
13606 (interactive "P")
13607 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13608 (org-set-tags arg just-align)
13609 (save-excursion
13610 (org-back-to-heading t)
13611 (org-set-tags arg just-align))))
13613 (defun org-set-tags-to (data)
13614 "Set the tags of the current entry to DATA, replacing the current tags.
13615 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13616 If DATA is nil or the empty string, any tags will be removed."
13617 (interactive "sTags: ")
13618 (setq data
13619 (cond
13620 ((eq data nil) "")
13621 ((equal data "") "")
13622 ((stringp data)
13623 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13624 ":"))
13625 ((listp data)
13626 (concat ":" (mapconcat 'identity data ":") ":"))))
13627 (when data
13628 (save-excursion
13629 (org-back-to-heading t)
13630 (when (looking-at org-complex-heading-regexp)
13631 (if (match-end 5)
13632 (progn
13633 (goto-char (match-beginning 5))
13634 (insert data)
13635 (delete-region (point) (point-at-eol))
13636 (org-set-tags nil 'align))
13637 (goto-char (point-at-eol))
13638 (insert " " data)
13639 (org-set-tags nil 'align)))
13640 (beginning-of-line 1)
13641 (if (looking-at ".*?\\([ \t]+\\)$")
13642 (delete-region (match-beginning 1) (match-end 1))))))
13644 (defun org-align-all-tags ()
13645 "Align the tags i all headings."
13646 (interactive)
13647 (save-excursion
13648 (or (ignore-errors (org-back-to-heading t))
13649 (outline-next-heading))
13650 (if (org-at-heading-p)
13651 (org-set-tags t)
13652 (message "No headings"))))
13654 (defvar org-indent-indentation-per-level)
13655 (defun org-set-tags (&optional arg just-align)
13656 "Set the tags for the current headline.
13657 With prefix ARG, realign all tags in headings in the current buffer."
13658 (interactive "P")
13659 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13660 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13661 'region-start-level 'region))
13662 org-loop-over-headlines-in-active-region)
13663 (org-map-entries
13664 ;; We don't use ARG and JUST-ALIGN here these args are not
13665 ;; useful when looping over headlines
13666 `(org-set-tags)
13667 org-loop-over-headlines-in-active-region
13668 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13669 (let* ((re org-outline-regexp-bol)
13670 (current (unless arg (org-get-tags-string)))
13671 (col (current-column))
13672 (org-setting-tags t)
13673 table current-tags inherited-tags ; computed below when needed
13674 tags p0 c0 c1 rpl di tc level)
13675 (if arg
13676 (save-excursion
13677 (goto-char (point-min))
13678 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13679 (while (re-search-forward re nil t)
13680 (org-set-tags nil t)
13681 (end-of-line 1)))
13682 (message "All tags realigned to column %d" org-tags-column))
13683 (if just-align
13684 (setq tags current)
13685 ;; Get a new set of tags from the user
13686 (save-excursion
13687 (setq table (append org-tag-persistent-alist
13688 (or org-tag-alist (org-get-buffer-tags))
13689 (and
13690 org-complete-tags-always-offer-all-agenda-tags
13691 (org-global-tags-completion-table
13692 (org-agenda-files))))
13693 org-last-tags-completion-table table
13694 current-tags (org-split-string current ":")
13695 inherited-tags (nreverse
13696 (nthcdr (length current-tags)
13697 (nreverse (org-get-tags-at))))
13698 tags
13699 (if (or (eq t org-use-fast-tag-selection)
13700 (and org-use-fast-tag-selection
13701 (delq nil (mapcar 'cdr table))))
13702 (org-fast-tag-selection
13703 current-tags inherited-tags table
13704 (if org-fast-tag-selection-include-todo
13705 org-todo-key-alist))
13706 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13707 (org-trim
13708 (org-icompleting-read "Tags: "
13709 'org-tags-completion-function
13710 nil nil current 'org-tags-history))))))
13711 (while (string-match "[-+&]+" tags)
13712 ;; No boolean logic, just a list
13713 (setq tags (replace-match ":" t t tags))))
13715 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13717 (if org-tags-sort-function
13718 (setq tags (mapconcat 'identity
13719 (sort (org-split-string
13720 tags (org-re "[^[:alnum:]_@#%]+"))
13721 org-tags-sort-function) ":")))
13723 (if (string-match "\\`[\t ]*\\'" tags)
13724 (setq tags "")
13725 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13726 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13728 ;; Insert new tags at the correct column
13729 (beginning-of-line 1)
13730 (setq level (or (and (looking-at org-outline-regexp)
13731 (- (match-end 0) (point) 1))
13733 (cond
13734 ((and (equal current "") (equal tags "")))
13735 ((re-search-forward
13736 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13737 (point-at-eol) t)
13738 (if (equal tags "")
13739 (setq rpl "")
13740 (goto-char (match-beginning 0))
13741 (setq c0 (current-column)
13742 ;; compute offset for the case of org-indent-mode active
13743 di (if org-indent-mode
13744 (* (1- org-indent-indentation-per-level) (1- level))
13746 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13747 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13748 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13749 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13750 (replace-match rpl t t)
13751 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13752 tags)
13753 (t (error "Tags alignment failed")))
13754 (org-move-to-column col)
13755 (unless just-align
13756 (run-hooks 'org-after-tags-change-hook))))))
13758 (defun org-change-tag-in-region (beg end tag off)
13759 "Add or remove TAG for each entry in the region.
13760 This works in the agenda, and also in an org-mode buffer."
13761 (interactive
13762 (list (region-beginning) (region-end)
13763 (let ((org-last-tags-completion-table
13764 (if (derived-mode-p 'org-mode)
13765 (org-get-buffer-tags)
13766 (org-global-tags-completion-table))))
13767 (org-icompleting-read
13768 "Tag: " 'org-tags-completion-function nil nil nil
13769 'org-tags-history))
13770 (progn
13771 (message "[s]et or [r]emove? ")
13772 (equal (read-char-exclusive) ?r))))
13773 (if (fboundp 'deactivate-mark) (deactivate-mark))
13774 (let ((agendap (equal major-mode 'org-agenda-mode))
13775 l1 l2 m buf pos newhead (cnt 0))
13776 (goto-char end)
13777 (setq l2 (1- (org-current-line)))
13778 (goto-char beg)
13779 (setq l1 (org-current-line))
13780 (loop for l from l1 to l2 do
13781 (org-goto-line l)
13782 (setq m (get-text-property (point) 'org-hd-marker))
13783 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13784 (and agendap m))
13785 (setq buf (if agendap (marker-buffer m) (current-buffer))
13786 pos (if agendap m (point)))
13787 (with-current-buffer buf
13788 (save-excursion
13789 (save-restriction
13790 (goto-char pos)
13791 (setq cnt (1+ cnt))
13792 (org-toggle-tag tag (if off 'off 'on))
13793 (setq newhead (org-get-heading)))))
13794 (and agendap (org-agenda-change-all-lines newhead m))))
13795 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13797 (defun org-tags-completion-function (string predicate &optional flag)
13798 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13799 (confirm (lambda (x) (stringp (car x)))))
13800 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13801 (setq s1 (match-string 1 string)
13802 s2 (match-string 2 string))
13803 (setq s1 "" s2 string))
13804 (cond
13805 ((eq flag nil)
13806 ;; try completion
13807 (setq rtn (try-completion s2 ctable confirm))
13808 (if (stringp rtn)
13809 (setq rtn
13810 (concat s1 s2 (substring rtn (length s2))
13811 (if (and org-add-colon-after-tag-completion
13812 (assoc rtn ctable))
13813 ":" ""))))
13814 rtn)
13815 ((eq flag t)
13816 ;; all-completions
13817 (all-completions s2 ctable confirm)
13819 ((eq flag 'lambda)
13820 ;; exact match?
13821 (assoc s2 ctable)))
13824 (defun org-fast-tag-insert (kwd tags face &optional end)
13825 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13826 (insert (format "%-12s" (concat kwd ":"))
13827 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13828 (or end "")))
13830 (defun org-fast-tag-show-exit (flag)
13831 (save-excursion
13832 (org-goto-line 3)
13833 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13834 (replace-match ""))
13835 (when flag
13836 (end-of-line 1)
13837 (org-move-to-column (- (window-width) 19) t)
13838 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13840 (defun org-set-current-tags-overlay (current prefix)
13841 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13842 (if (featurep 'xemacs)
13843 (org-overlay-display org-tags-overlay (concat prefix s)
13844 'secondary-selection)
13845 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13846 (org-overlay-display org-tags-overlay (concat prefix s)))))
13848 (defvar org-last-tag-selection-key nil)
13849 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13850 "Fast tag selection with single keys.
13851 CURRENT is the current list of tags in the headline, INHERITED is the
13852 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13853 possibly with grouping information. TODO-TABLE is a similar table with
13854 TODO keywords, should these have keys assigned to them.
13855 If the keys are nil, a-z are automatically assigned.
13856 Returns the new tags string, or nil to not change the current settings."
13857 (let* ((fulltable (append table todo-table))
13858 (maxlen (apply 'max (mapcar
13859 (lambda (x)
13860 (if (stringp (car x)) (string-width (car x)) 0))
13861 fulltable)))
13862 (buf (current-buffer))
13863 (expert (eq org-fast-tag-selection-single-key 'expert))
13864 (buffer-tags nil)
13865 (fwidth (+ maxlen 3 1 3))
13866 (ncol (/ (- (window-width) 4) fwidth))
13867 (i-face 'org-done)
13868 (c-face 'org-todo)
13869 tg cnt e c char c1 c2 ntable tbl rtn
13870 ov-start ov-end ov-prefix
13871 (exit-after-next org-fast-tag-selection-single-key)
13872 (done-keywords org-done-keywords)
13873 groups ingroup)
13874 (save-excursion
13875 (beginning-of-line 1)
13876 (if (looking-at
13877 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13878 (setq ov-start (match-beginning 1)
13879 ov-end (match-end 1)
13880 ov-prefix "")
13881 (setq ov-start (1- (point-at-eol))
13882 ov-end (1+ ov-start))
13883 (skip-chars-forward "^\n\r")
13884 (setq ov-prefix
13885 (concat
13886 (buffer-substring (1- (point)) (point))
13887 (if (> (current-column) org-tags-column)
13889 (make-string (- org-tags-column (current-column)) ?\ ))))))
13890 (move-overlay org-tags-overlay ov-start ov-end)
13891 (save-window-excursion
13892 (if expert
13893 (set-buffer (get-buffer-create " *Org tags*"))
13894 (delete-other-windows)
13895 (split-window-vertically)
13896 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13897 (erase-buffer)
13898 (org-set-local 'org-done-keywords done-keywords)
13899 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13900 (org-fast-tag-insert "Current" current c-face "\n\n")
13901 (org-fast-tag-show-exit exit-after-next)
13902 (org-set-current-tags-overlay current ov-prefix)
13903 (setq tbl fulltable char ?a cnt 0)
13904 (while (setq e (pop tbl))
13905 (cond
13906 ((equal (car e) :startgroup)
13907 (push '() groups) (setq ingroup t)
13908 (when (not (= cnt 0))
13909 (setq cnt 0)
13910 (insert "\n"))
13911 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13912 ((equal (car e) :endgroup)
13913 (setq ingroup nil cnt 0)
13914 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13915 ((equal e '(:newline))
13916 (when (not (= cnt 0))
13917 (setq cnt 0)
13918 (insert "\n")
13919 (setq e (car tbl))
13920 (while (equal (car tbl) '(:newline))
13921 (insert "\n")
13922 (setq tbl (cdr tbl)))))
13924 (setq tg (copy-sequence (car e)) c2 nil)
13925 (if (cdr e)
13926 (setq c (cdr e))
13927 ;; automatically assign a character.
13928 (setq c1 (string-to-char
13929 (downcase (substring
13930 tg (if (= (string-to-char tg) ?@) 1 0)))))
13931 (if (or (rassoc c1 ntable) (rassoc c1 table))
13932 (while (or (rassoc char ntable) (rassoc char table))
13933 (setq char (1+ char)))
13934 (setq c2 c1))
13935 (setq c (or c2 char)))
13936 (if ingroup (push tg (car groups)))
13937 (setq tg (org-add-props tg nil 'face
13938 (cond
13939 ((not (assoc tg table))
13940 (org-get-todo-face tg))
13941 ((member tg current) c-face)
13942 ((member tg inherited) i-face))))
13943 (if (and (= cnt 0) (not ingroup)) (insert " "))
13944 (insert "[" c "] " tg (make-string
13945 (- fwidth 4 (length tg)) ?\ ))
13946 (push (cons tg c) ntable)
13947 (when (= (setq cnt (1+ cnt)) ncol)
13948 (insert "\n")
13949 (if ingroup (insert " "))
13950 (setq cnt 0)))))
13951 (setq ntable (nreverse ntable))
13952 (insert "\n")
13953 (goto-char (point-min))
13954 (if (not expert) (org-fit-window-to-buffer))
13955 (setq rtn
13956 (catch 'exit
13957 (while t
13958 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13959 (if (not groups) "no " "")
13960 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13961 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13962 (setq org-last-tag-selection-key c)
13963 (cond
13964 ((= c ?\r) (throw 'exit t))
13965 ((= c ?!)
13966 (setq groups (not groups))
13967 (goto-char (point-min))
13968 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13969 ((= c ?\C-c)
13970 (if (not expert)
13971 (org-fast-tag-show-exit
13972 (setq exit-after-next (not exit-after-next)))
13973 (setq expert nil)
13974 (delete-other-windows)
13975 (set-window-buffer (split-window-vertically) " *Org tags*")
13976 (org-switch-to-buffer-other-window " *Org tags*")
13977 (org-fit-window-to-buffer)))
13978 ((or (= c ?\C-g)
13979 (and (= c ?q) (not (rassoc c ntable))))
13980 (org-detach-overlay org-tags-overlay)
13981 (setq quit-flag t))
13982 ((= c ?\ )
13983 (setq current nil)
13984 (if exit-after-next (setq exit-after-next 'now)))
13985 ((= c ?\t)
13986 (condition-case nil
13987 (setq tg (org-icompleting-read
13988 "Tag: "
13989 (or buffer-tags
13990 (with-current-buffer buf
13991 (org-get-buffer-tags)))))
13992 (quit (setq tg "")))
13993 (when (string-match "\\S-" tg)
13994 (add-to-list 'buffer-tags (list tg))
13995 (if (member tg current)
13996 (setq current (delete tg current))
13997 (push tg current)))
13998 (if exit-after-next (setq exit-after-next 'now)))
13999 ((setq e (rassoc c todo-table) tg (car e))
14000 (with-current-buffer buf
14001 (save-excursion (org-todo tg)))
14002 (if exit-after-next (setq exit-after-next 'now)))
14003 ((setq e (rassoc c ntable) tg (car e))
14004 (if (member tg current)
14005 (setq current (delete tg current))
14006 (loop for g in groups do
14007 (if (member tg g)
14008 (mapc (lambda (x)
14009 (setq current (delete x current)))
14010 g)))
14011 (push tg current))
14012 (if exit-after-next (setq exit-after-next 'now))))
14014 ;; Create a sorted list
14015 (setq current
14016 (sort current
14017 (lambda (a b)
14018 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14019 (if (eq exit-after-next 'now) (throw 'exit t))
14020 (goto-char (point-min))
14021 (beginning-of-line 2)
14022 (delete-region (point) (point-at-eol))
14023 (org-fast-tag-insert "Current" current c-face)
14024 (org-set-current-tags-overlay current ov-prefix)
14025 (while (re-search-forward
14026 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14027 (setq tg (match-string 1))
14028 (add-text-properties
14029 (match-beginning 1) (match-end 1)
14030 (list 'face
14031 (cond
14032 ((member tg current) c-face)
14033 ((member tg inherited) i-face)
14034 (t (get-text-property (match-beginning 1) 'face))))))
14035 (goto-char (point-min)))))
14036 (org-detach-overlay org-tags-overlay)
14037 (if rtn
14038 (mapconcat 'identity current ":")
14039 nil))))
14041 (defun org-get-tags-string ()
14042 "Get the TAGS string in the current headline."
14043 (unless (org-at-heading-p t)
14044 (error "Not on a heading"))
14045 (save-excursion
14046 (beginning-of-line 1)
14047 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14048 (org-match-string-no-properties 1)
14049 "")))
14051 (defun org-get-tags ()
14052 "Get the list of tags specified in the current headline."
14053 (org-split-string (org-get-tags-string) ":"))
14055 (defun org-get-buffer-tags ()
14056 "Get a table of all tags used in the buffer, for completion."
14057 (let (tags)
14058 (save-excursion
14059 (goto-char (point-min))
14060 (while (re-search-forward
14061 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14062 (when (equal (char-after (point-at-bol 0)) ?*)
14063 (mapc (lambda (x) (add-to-list 'tags x))
14064 (org-split-string (org-match-string-no-properties 1) ":")))))
14065 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14066 (mapcar 'list tags)))
14068 ;;;; The mapping API
14070 (defun org-map-entries (func &optional match scope &rest skip)
14071 "Call FUNC at each headline selected by MATCH in SCOPE.
14073 FUNC is a function or a lisp form. The function will be called without
14074 arguments, with the cursor positioned at the beginning of the headline.
14075 The return values of all calls to the function will be collected and
14076 returned as a list.
14078 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14079 does not need to preserve point. After evaluation, the cursor will be
14080 moved to the end of the line (presumably of the headline of the
14081 processed entry) and search continues from there. Under some
14082 circumstances, this may not produce the wanted results. For example,
14083 if you have removed (e.g. archived) the current (sub)tree it could
14084 mean that the next entry will be skipped entirely. In such cases, you
14085 can specify the position from where search should continue by making
14086 FUNC set the variable `org-map-continue-from' to the desired buffer
14087 position.
14089 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14090 Only headlines that are matched by this query will be considered during
14091 the iteration. When MATCH is nil or t, all headlines will be
14092 visited by the iteration.
14094 SCOPE determines the scope of this command. It can be any of:
14096 nil The current buffer, respecting the restriction if any
14097 tree The subtree started with the entry at point
14098 region The entries within the active region, if any
14099 region-start-level
14100 The entries within the active region, but only those at
14101 the same level than the first one.
14102 file The current buffer, without restriction
14103 file-with-archives
14104 The current buffer, and any archives associated with it
14105 agenda All agenda files
14106 agenda-with-archives
14107 All agenda files with any archive files associated with them
14108 \(file1 file2 ...)
14109 If this is a list, all files in the list will be scanned
14111 The remaining args are treated as settings for the skipping facilities of
14112 the scanner. The following items can be given here:
14114 archive skip trees with the archive tag.
14115 comment skip trees with the COMMENT keyword
14116 function or Emacs Lisp form:
14117 will be used as value for `org-agenda-skip-function', so whenever
14118 the function returns t, FUNC will not be called for that
14119 entry and search will continue from the point where the
14120 function leaves it.
14122 If your function needs to retrieve the tags including inherited tags
14123 at the *current* entry, you can use the value of the variable
14124 `org-scanner-tags' which will be much faster than getting the value
14125 with `org-get-tags-at'. If your function gets properties with
14126 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14127 to t around the call to `org-entry-properties' to get the same speedup.
14128 Note that if your function moves around to retrieve tags and properties at
14129 a *different* entry, you cannot use these techniques."
14130 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14131 (not (org-region-active-p)))
14132 (let* ((org-agenda-archives-mode nil) ; just to make sure
14133 (org-agenda-skip-archived-trees (memq 'archive skip))
14134 (org-agenda-skip-comment-trees (memq 'comment skip))
14135 (org-agenda-skip-function
14136 (car (org-delete-all '(comment archive) skip)))
14137 (org-tags-match-list-sublevels t)
14138 (start-level (eq scope 'region-start-level))
14139 matcher file res
14140 org-todo-keywords-for-agenda
14141 org-done-keywords-for-agenda
14142 org-todo-keyword-alist-for-agenda
14143 org-drawers-for-agenda
14144 org-tag-alist-for-agenda
14145 todo-only)
14147 (cond
14148 ((eq match t) (setq matcher t))
14149 ((eq match nil) (setq matcher t))
14150 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14152 (save-excursion
14153 (save-restriction
14154 (cond ((eq scope 'tree)
14155 (org-back-to-heading t)
14156 (org-narrow-to-subtree)
14157 (setq scope nil))
14158 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14159 (org-region-active-p))
14160 ;; If needed, set start-level to a string like "2"
14161 (when start-level
14162 (save-excursion
14163 (goto-char (region-beginning))
14164 (unless (org-at-heading-p) (outline-next-heading))
14165 (setq start-level (org-current-level))))
14166 (narrow-to-region (region-beginning)
14167 (save-excursion
14168 (goto-char (region-end))
14169 (unless (and (bolp) (org-at-heading-p))
14170 (outline-next-heading))
14171 (point)))
14172 (setq scope nil)))
14174 (if (not scope)
14175 (progn
14176 (org-agenda-prepare-buffers
14177 (list (buffer-file-name (current-buffer))))
14178 (setq res (org-scan-tags func matcher todo-only start-level)))
14179 ;; Get the right scope
14180 (cond
14181 ((and scope (listp scope) (symbolp (car scope)))
14182 (setq scope (eval scope)))
14183 ((eq scope 'agenda)
14184 (setq scope (org-agenda-files t)))
14185 ((eq scope 'agenda-with-archives)
14186 (setq scope (org-agenda-files t))
14187 (setq scope (org-add-archive-files scope)))
14188 ((eq scope 'file)
14189 (setq scope (list (buffer-file-name))))
14190 ((eq scope 'file-with-archives)
14191 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14192 (org-agenda-prepare-buffers scope)
14193 (while (setq file (pop scope))
14194 (with-current-buffer (org-find-base-buffer-visiting file)
14195 (save-excursion
14196 (save-restriction
14197 (widen)
14198 (goto-char (point-min))
14199 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14200 res)))
14202 ;;;; Properties
14204 ;;; Setting and retrieving properties
14206 (defconst org-special-properties
14207 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14208 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14209 "The special properties valid in Org-mode.
14211 These are properties that are not defined in the property drawer,
14212 but in some other way.")
14214 (defconst org-default-properties
14215 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14216 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14217 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14218 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14219 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14220 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14221 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14222 "Some properties that are used by Org-mode for various purposes.
14223 Being in this list makes sure that they are offered for completion.")
14225 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14226 "Regular expression matching the first line of a property drawer.")
14228 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14229 "Regular expression matching the last line of a property drawer.")
14231 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14232 "Regular expression matching the first line of a property drawer.")
14234 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14235 "Regular expression matching the first line of a property drawer.")
14237 (defconst org-property-drawer-re
14238 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14239 org-property-end-re "\\)\n?")
14240 "Matches an entire property drawer.")
14242 (defconst org-clock-drawer-re
14243 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14244 org-property-end-re "\\)\n?")
14245 "Matches an entire clock drawer.")
14247 (defsubst org-re-property (property)
14248 "Return a regexp matching a PROPERTY line.
14249 Match group 1 will be set to the value."
14250 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14252 (defsubst org-re-property-keyword (property)
14253 "Return a regexp matching a PROPERTY line, possibly with no
14254 value for the property."
14255 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14257 (defun org-property-action ()
14258 "Do an action on properties."
14259 (interactive)
14260 (let (c)
14261 (org-at-property-p)
14262 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14263 (setq c (read-char-exclusive))
14264 (cond
14265 ((equal c ?s)
14266 (call-interactively 'org-set-property))
14267 ((equal c ?d)
14268 (call-interactively 'org-delete-property))
14269 ((equal c ?D)
14270 (call-interactively 'org-delete-property-globally))
14271 ((equal c ?c)
14272 (call-interactively 'org-compute-property-at-point))
14273 (t (error "No such property action %c" c)))))
14275 (defun org-inc-effort ()
14276 "Increment the value of the effort property in the current entry."
14277 (interactive)
14278 (org-set-effort nil t))
14280 (defun org-set-effort (&optional value increment)
14281 "Set the effort property of the current entry.
14282 With numerical prefix arg, use the nth allowed value, 0 stands for the
14283 10th allowed value.
14285 When INCREMENT is non-nil, set the property to the next allowed value."
14286 (interactive "P")
14287 (if (equal value 0) (setq value 10))
14288 (let* ((completion-ignore-case t)
14289 (prop org-effort-property)
14290 (cur (org-entry-get nil prop))
14291 (allowed (org-property-get-allowed-values nil prop 'table))
14292 (existing (mapcar 'list (org-property-values prop)))
14294 (val (cond
14295 ((stringp value) value)
14296 ((and allowed (integerp value))
14297 (or (car (nth (1- value) allowed))
14298 (car (org-last allowed))))
14299 ((and allowed increment)
14300 (or (caadr (member (list cur) allowed))
14301 (error "Allowed effort values are not set")))
14302 (allowed
14303 (message "Select 1-9,0, [RET%s]: %s"
14304 (if cur (concat "=" cur) "")
14305 (mapconcat 'car allowed " "))
14306 (setq rpl (read-char-exclusive))
14307 (if (equal rpl ?\r)
14309 (setq rpl (- rpl ?0))
14310 (if (equal rpl 0) (setq rpl 10))
14311 (if (and (> rpl 0) (<= rpl (length allowed)))
14312 (car (nth (1- rpl) allowed))
14313 (org-completing-read "Effort: " allowed nil))))
14315 (let (org-completion-use-ido org-completion-use-iswitchb)
14316 (org-completing-read
14317 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14318 (concat "[" cur "]") "")
14319 ": ")
14320 existing nil nil "" nil cur))))))
14321 (unless (equal (org-entry-get nil prop) val)
14322 (org-entry-put nil prop val))
14323 (message "%s is now %s" prop val)))
14325 (defun org-at-property-p ()
14326 "Is cursor inside a property drawer?"
14327 (save-excursion
14328 (beginning-of-line 1)
14329 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14330 (save-match-data ;; Used by calling procedures
14331 (let ((p (point))
14332 (range (unless (org-before-first-heading-p)
14333 (org-get-property-block))))
14334 (and range (<= (car range) p) (< p (cdr range))))))))
14336 (defun org-get-property-block (&optional beg end force)
14337 "Return the (beg . end) range of the body of the property drawer.
14338 BEG and END are the beginning and end of the current subtree, or of
14339 the part before the first headline. If they are not given, they will
14340 be found. If the drawer does not exist and FORCE is non-nil, create
14341 the drawer."
14342 (catch 'exit
14343 (save-excursion
14344 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14345 (progn (org-back-to-heading t) (point))))
14346 (end (or end (and (not (outline-next-heading)) (point-max))
14347 (point))))
14348 (goto-char beg)
14349 (if (re-search-forward org-property-start-re end t)
14350 (setq beg (1+ (match-end 0)))
14351 (if force
14352 (save-excursion
14353 (org-insert-property-drawer)
14354 (setq end (progn (outline-next-heading) (point))))
14355 (throw 'exit nil))
14356 (goto-char beg)
14357 (if (re-search-forward org-property-start-re end t)
14358 (setq beg (1+ (match-end 0)))))
14359 (if (re-search-forward org-property-end-re end t)
14360 (setq end (match-beginning 0))
14361 (or force (throw 'exit nil))
14362 (goto-char beg)
14363 (setq end beg)
14364 (org-indent-line)
14365 (insert ":END:\n"))
14366 (cons beg end)))))
14368 (defun org-entry-properties (&optional pom which specific)
14369 "Get all properties of the entry at point-or-marker POM.
14370 This includes the TODO keyword, the tags, time strings for deadline,
14371 scheduled, and clocking, and any additional properties defined in the
14372 entry. The return value is an alist, keys may occur multiple times
14373 if the property key was used several times.
14374 POM may also be nil, in which case the current entry is used.
14375 If WHICH is nil or `all', get all properties. If WHICH is
14376 `special' or `standard', only get that subclass. If WHICH
14377 is a string only get exactly this property. SPECIFIC can be a string, the
14378 specific property we are interested in. Specifying it can speed
14379 things up because then unnecessary parsing is avoided."
14380 (setq which (or which 'all))
14381 (org-with-point-at pom
14382 (let ((clockstr (substring org-clock-string 0 -1))
14383 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14384 (case-fold-search nil)
14385 beg end range props sum-props key key1 value string clocksum clocksumt)
14386 (save-excursion
14387 (when (condition-case nil
14388 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14389 (error nil))
14390 (setq beg (point))
14391 (setq sum-props (get-text-property (point) 'org-summaries))
14392 (setq clocksum (get-text-property (point) :org-clock-minutes)
14393 clocksumt (get-text-property (point) :org-clock-minutes-today))
14394 (outline-next-heading)
14395 (setq end (point))
14396 (when (memq which '(all special))
14397 ;; Get the special properties, like TODO and tags
14398 (goto-char beg)
14399 (when (and (or (not specific) (string= specific "TODO"))
14400 (looking-at org-todo-line-regexp) (match-end 2))
14401 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14402 (when (and (or (not specific) (string= specific "PRIORITY"))
14403 (looking-at org-priority-regexp))
14404 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14405 (when (or (not specific) (string= specific "FILE"))
14406 (push (cons "FILE" buffer-file-name) props))
14407 (when (and (or (not specific) (string= specific "TAGS"))
14408 (setq value (org-get-tags-string))
14409 (string-match "\\S-" value))
14410 (push (cons "TAGS" value) props))
14411 (when (and (or (not specific) (string= specific "ALLTAGS"))
14412 (setq value (org-get-tags-at)))
14413 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14414 ":"))
14415 props))
14416 (when (or (not specific) (string= specific "BLOCKED"))
14417 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14418 (when (or (not specific)
14419 (member specific
14420 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14421 "TIMESTAMP" "TIMESTAMP_IA")))
14422 (catch 'match
14423 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14424 (setq key (if (match-end 1)
14425 (substring (org-match-string-no-properties 1)
14426 0 -1))
14427 string (if (equal key clockstr)
14428 (org-trim
14429 (buffer-substring-no-properties
14430 (match-beginning 3) (goto-char
14431 (point-at-eol))))
14432 (substring (org-match-string-no-properties 3)
14433 1 -1)))
14434 ;; Get the correct property name from the key. This is
14435 ;; necessary if the user has configured time keywords.
14436 (setq key1 (concat key ":"))
14437 (cond
14438 ((not key)
14439 (setq key
14440 (if (= (char-after (match-beginning 3)) ?\[)
14441 "TIMESTAMP_IA" "TIMESTAMP")))
14442 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14443 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14444 ((equal key1 org-closed-string) (setq key "CLOSED"))
14445 ((equal key1 org-clock-string) (setq key "CLOCK")))
14446 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14447 (progn
14448 (push (cons key string) props)
14449 ;; no need to search further if match is found
14450 (throw 'match t))
14451 (when (or (equal key "CLOCK") (not (assoc key props)))
14452 (push (cons key string) props)))))))
14454 (when (memq which '(all standard))
14455 ;; Get the standard properties, like :PROP: ...
14456 (setq range (org-get-property-block beg end))
14457 (when range
14458 (goto-char (car range))
14459 (while (re-search-forward
14460 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14461 (cdr range) t)
14462 (setq key (org-match-string-no-properties 1)
14463 value (org-trim (or (org-match-string-no-properties 2) "")))
14464 (unless (member key excluded)
14465 (push (cons key (or value "")) props)))))
14466 (if clocksum
14467 (push (cons "CLOCKSUM"
14468 (org-columns-number-to-string (/ (float clocksum) 60.)
14469 'add_times))
14470 props))
14471 (if clocksumt
14472 (push (cons "CLOCKSUM_T"
14473 (org-columns-number-to-string (/ (float clocksumt) 60.)
14474 'add_times))
14475 props))
14476 (unless (assoc "CATEGORY" props)
14477 (push (cons "CATEGORY" (org-get-category)) props))
14478 (append sum-props (nreverse props)))))))
14480 (defun org-entry-get (pom property &optional inherit literal-nil)
14481 "Get value of PROPERTY for entry or content at point-or-marker POM.
14482 If INHERIT is non-nil and the entry does not have the property,
14483 then also check higher levels of the hierarchy.
14484 If INHERIT is the symbol `selective', use inheritance only if the setting
14485 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14486 If the property is present but empty, the return value is the empty string.
14487 If the property is not present at all, nil is returned.
14489 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14490 do not interpret it as the list atom nil. This is used for inheritance
14491 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14492 (org-with-point-at pom
14493 (if (and inherit (if (eq inherit 'selective)
14494 (org-property-inherit-p property)
14496 (org-entry-get-with-inheritance property literal-nil)
14497 (if (member property org-special-properties)
14498 ;; We need a special property. Use `org-entry-properties' to
14499 ;; retrieve it, but specify the wanted property
14500 (cdr (assoc property (org-entry-properties nil 'special property)))
14501 (let* ((range (org-get-property-block))
14502 (props (list (or (assoc property org-file-properties)
14503 (assoc property org-global-properties)
14504 (assoc property org-global-properties-fixed))))
14505 (ap (lambda (key)
14506 (when (re-search-forward
14507 (org-re-property key) (cdr range) t)
14508 (setq props
14509 (org-update-property-plist
14511 (if (match-end 1)
14512 (org-match-string-no-properties 1) "")
14513 props)))))
14514 val)
14515 (when (and range (goto-char (car range)))
14516 (funcall ap property)
14517 (goto-char (car range))
14518 (while (funcall ap (concat property "+")))
14519 (setq val (cdr (assoc property props)))
14520 (when val (if literal-nil val (org-not-nil val)))))))))
14522 (defun org-property-or-variable-value (var &optional inherit)
14523 "Check if there is a property fixing the value of VAR.
14524 If yes, return this value. If not, return the current value of the variable."
14525 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14526 (if (and prop (stringp prop) (string-match "\\S-" prop))
14527 (read prop)
14528 (symbol-value var))))
14530 (defun org-entry-delete (pom property)
14531 "Delete the property PROPERTY from entry at point-or-marker POM."
14532 (org-with-point-at pom
14533 (if (member property org-special-properties)
14534 nil ; cannot delete these properties.
14535 (let ((range (org-get-property-block)))
14536 (if (and range
14537 (goto-char (car range))
14538 (re-search-forward
14539 (org-re-property property)
14540 (cdr range) t))
14541 (progn
14542 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14544 nil)))))
14546 ;; Multi-values properties are properties that contain multiple values
14547 ;; These values are assumed to be single words, separated by whitespace.
14548 (defun org-entry-add-to-multivalued-property (pom property value)
14549 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14550 (let* ((old (org-entry-get pom property))
14551 (values (and old (org-split-string old "[ \t]"))))
14552 (setq value (org-entry-protect-space value))
14553 (unless (member value values)
14554 (setq values (cons value values))
14555 (org-entry-put pom property
14556 (mapconcat 'identity values " ")))))
14558 (defun org-entry-remove-from-multivalued-property (pom property value)
14559 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14560 (let* ((old (org-entry-get pom property))
14561 (values (and old (org-split-string old "[ \t]"))))
14562 (setq value (org-entry-protect-space value))
14563 (when (member value values)
14564 (setq values (delete value values))
14565 (org-entry-put pom property
14566 (mapconcat 'identity values " ")))))
14568 (defun org-entry-member-in-multivalued-property (pom property value)
14569 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14570 (let* ((old (org-entry-get pom property))
14571 (values (and old (org-split-string old "[ \t]"))))
14572 (setq value (org-entry-protect-space value))
14573 (member value values)))
14575 (defun org-entry-get-multivalued-property (pom property)
14576 "Return a list of values in a multivalued property."
14577 (let* ((value (org-entry-get pom property))
14578 (values (and value (org-split-string value "[ \t]"))))
14579 (mapcar 'org-entry-restore-space values)))
14581 (defun org-entry-put-multivalued-property (pom property &rest values)
14582 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14583 VALUES should be a list of strings. Spaces will be protected."
14584 (org-entry-put pom property
14585 (mapconcat 'org-entry-protect-space values " "))
14586 (let* ((value (org-entry-get pom property))
14587 (values (and value (org-split-string value "[ \t]"))))
14588 (mapcar 'org-entry-restore-space values)))
14590 (defun org-entry-protect-space (s)
14591 "Protect spaces and newline in string S."
14592 (while (string-match " " s)
14593 (setq s (replace-match "%20" t t s)))
14594 (while (string-match "\n" s)
14595 (setq s (replace-match "%0A" t t s)))
14598 (defun org-entry-restore-space (s)
14599 "Restore spaces and newline in string S."
14600 (while (string-match "%20" s)
14601 (setq s (replace-match " " t t s)))
14602 (while (string-match "%0A" s)
14603 (setq s (replace-match "\n" t t s)))
14606 (defvar org-entry-property-inherited-from (make-marker)
14607 "Marker pointing to the entry from where a property was inherited.
14608 Each call to `org-entry-get-with-inheritance' will set this marker to the
14609 location of the entry where the inheritance search matched. If there was
14610 no match, the marker will point nowhere.
14611 Note that also `org-entry-get' calls this function, if the INHERIT flag
14612 is set.")
14614 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14615 "Get PROPERTY of entry or content at point, search higher levels if needed.
14616 The search will stop at the first ancestor which has the property defined.
14617 If the value found is \"nil\", return nil to show that the property
14618 should be considered as undefined (this is the meaning of nil here).
14619 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14620 (move-marker org-entry-property-inherited-from nil)
14621 (let (tmp)
14622 (save-excursion
14623 (save-restriction
14624 (widen)
14625 (catch 'ex
14626 (while t
14627 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14628 (or (ignore-errors (org-back-to-heading t))
14629 (goto-char (point-min)))
14630 (move-marker org-entry-property-inherited-from (point))
14631 (throw 'ex tmp))
14632 (or (ignore-errors (org-up-heading-safe))
14633 (throw 'ex nil))))))
14634 (setq tmp (or tmp
14635 (cdr (assoc property org-file-properties))
14636 (cdr (assoc property org-global-properties))
14637 (cdr (assoc property org-global-properties-fixed))))
14638 (if literal-nil tmp (org-not-nil tmp))))
14640 (defvar org-property-changed-functions nil
14641 "Hook called when the value of a property has changed.
14642 Each hook function should accept two arguments, the name of the property
14643 and the new value.")
14645 (defun org-entry-put (pom property value)
14646 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14647 (org-with-point-at pom
14648 (org-back-to-heading t)
14649 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14650 range)
14651 (cond
14652 ((equal property "TODO")
14653 (when (and (stringp value) (string-match "\\S-" value)
14654 (not (member value org-todo-keywords-1)))
14655 (error "\"%s\" is not a valid TODO state" value))
14656 (if (or (not value)
14657 (not (string-match "\\S-" value)))
14658 (setq value 'none))
14659 (org-todo value)
14660 (org-set-tags nil 'align))
14661 ((equal property "PRIORITY")
14662 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14663 (string-to-char value) ?\ ))
14664 (org-set-tags nil 'align))
14665 ((equal property "CLOCKSUM")
14666 (if (not (re-search-forward
14667 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14668 (error "Cannot find a clock log")
14669 (goto-char (- (match-end 1) 2))
14670 (cond
14671 ((eq value 'earlier) (org-timestamp-down))
14672 ((eq value 'later) (org-timestamp-up)))
14673 (org-clock-sum-current-item)))
14674 ((equal property "SCHEDULED")
14675 (if (re-search-forward org-scheduled-time-regexp end t)
14676 (cond
14677 ((eq value 'earlier) (org-timestamp-change -1 'day))
14678 ((eq value 'later) (org-timestamp-change 1 'day))
14679 (t (call-interactively 'org-schedule)))
14680 (call-interactively 'org-schedule)))
14681 ((equal property "DEADLINE")
14682 (if (re-search-forward org-deadline-time-regexp end t)
14683 (cond
14684 ((eq value 'earlier) (org-timestamp-change -1 'day))
14685 ((eq value 'later) (org-timestamp-change 1 'day))
14686 (t (call-interactively 'org-deadline)))
14687 (call-interactively 'org-deadline)))
14688 ((member property org-special-properties)
14689 (error "The %s property can not yet be set with `org-entry-put'"
14690 property))
14691 (t ; a non-special property
14692 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14693 (setq range (org-get-property-block beg end 'force))
14694 (goto-char (car range))
14695 (if (re-search-forward
14696 (org-re-property-keyword property) (cdr range) t)
14697 (progn
14698 (delete-region (match-beginning 0) (match-end 0))
14699 (goto-char (match-beginning 0)))
14700 (goto-char (cdr range))
14701 (insert "\n")
14702 (backward-char 1)
14703 (org-indent-line))
14704 (insert ":" property ":")
14705 (and value (insert " " value))
14706 (org-indent-line)))))
14707 (run-hook-with-args 'org-property-changed-functions property value)))
14709 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14710 "Get all property keys in the current buffer.
14711 With INCLUDE-SPECIALS, also list the special properties that reflect things
14712 like tags and TODO state.
14713 With INCLUDE-DEFAULTS, also include properties that has special meaning
14714 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14715 and others.
14716 With INCLUDE-COLUMNS, also include property names given in COLUMN
14717 formats in the current buffer."
14718 (let (rtn range cfmt s p)
14719 (save-excursion
14720 (save-restriction
14721 (widen)
14722 (goto-char (point-min))
14723 (while (re-search-forward org-property-start-re nil t)
14724 (setq range (org-get-property-block))
14725 (goto-char (car range))
14726 (while (re-search-forward
14727 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14728 (cdr range) t)
14729 (add-to-list 'rtn (org-match-string-no-properties 1)))
14730 (outline-next-heading))))
14732 (when include-specials
14733 (setq rtn (append org-special-properties rtn)))
14735 (when include-defaults
14736 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14737 (add-to-list 'rtn org-effort-property))
14739 (when include-columns
14740 (save-excursion
14741 (save-restriction
14742 (widen)
14743 (goto-char (point-min))
14744 (while (re-search-forward
14745 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14746 nil t)
14747 (setq cfmt (match-string 2) s 0)
14748 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14749 cfmt s)
14750 (setq s (match-end 0)
14751 p (match-string 1 cfmt))
14752 (unless (or (equal p "ITEM")
14753 (member p org-special-properties))
14754 (add-to-list 'rtn (match-string 1 cfmt))))))))
14756 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14758 (defun org-property-values (key)
14759 "Return a list of all values of property KEY in the current buffer."
14760 (save-excursion
14761 (save-restriction
14762 (widen)
14763 (goto-char (point-min))
14764 (let ((re (org-re-property key))
14765 values)
14766 (while (re-search-forward re nil t)
14767 (add-to-list 'values (org-trim (match-string 1))))
14768 (delete "" values)))))
14770 (defun org-insert-property-drawer ()
14771 "Insert a property drawer into the current entry."
14772 (org-back-to-heading t)
14773 (looking-at org-outline-regexp)
14774 (let ((indent (if org-adapt-indentation
14775 (- (match-end 0) (match-beginning 0))
14777 (beg (point))
14778 (re (concat "^[ \t]*" org-keyword-time-regexp))
14779 end hiddenp)
14780 (outline-next-heading)
14781 (setq end (point))
14782 (goto-char beg)
14783 (while (re-search-forward re end t))
14784 (setq hiddenp (outline-invisible-p))
14785 (end-of-line 1)
14786 (and (equal (char-after) ?\n) (forward-char 1))
14787 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14788 (if (member (match-string 1) '("CLOCK:" ":END:"))
14789 ;; just skip this line
14790 (beginning-of-line 2)
14791 ;; Drawer start, find the end
14792 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14793 (beginning-of-line 1)))
14794 (org-skip-over-state-notes)
14795 (skip-chars-backward " \t\n\r")
14796 (if (eq (char-before) ?*) (forward-char 1))
14797 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14798 (beginning-of-line 0)
14799 (org-indent-to-column indent)
14800 (beginning-of-line 2)
14801 (org-indent-to-column indent)
14802 (beginning-of-line 0)
14803 (if hiddenp
14804 (save-excursion
14805 (org-back-to-heading t)
14806 (hide-entry))
14807 (org-flag-drawer t))))
14809 (defun org-insert-drawer (&optional arg drawer)
14810 "Insert a drawer at point.
14812 Optional argument DRAWER, when non-nil, is a string representing
14813 drawer's name. Otherwise, the user is prompted for a name.
14815 If a region is active, insert the drawer around that region
14816 instead.
14818 Point is left between drawer's boundaries."
14819 (interactive "P")
14820 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14821 "LOGBOOK"))
14822 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14823 ;; internally by Org. They are meant to be inserted
14824 ;; automatically.
14825 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14826 ;; Remove system drawers from list. Note: For some reason,
14827 ;; `org-completing-read' ignores the predicate while
14828 ;; `completing-read' handles it fine.
14829 (drawer (if arg "PROPERTIES"
14830 (or drawer
14831 (completing-read
14832 "Drawer: " org-drawers
14833 (lambda (d) (not (member d system-drawers))))))))
14834 (cond
14835 ;; With C-u, fall back on `org-insert-property-drawer'
14836 (arg (org-insert-property-drawer))
14837 ;; With an active region, insert a drawer at point.
14838 ((not (org-region-active-p))
14839 (progn
14840 (unless (bolp) (insert "\n"))
14841 (insert (format ":%s:\n\n:END:\n" drawer))
14842 (forward-line -2)))
14843 ;; Otherwise, insert the drawer at point
14845 (let ((rbeg (region-beginning))
14846 (rend (copy-marker (region-end))))
14847 (unwind-protect
14848 (progn
14849 (goto-char rbeg)
14850 (beginning-of-line)
14851 (when (save-excursion
14852 (re-search-forward org-outline-regexp-bol rend t))
14853 (error "Drawers cannot contain headlines"))
14854 ;; Position point at the beginning of the first
14855 ;; non-blank line in region. Insert drawer's opening
14856 ;; there, then indent it.
14857 (org-skip-whitespace)
14858 (beginning-of-line)
14859 (insert ":" drawer ":\n")
14860 (forward-line -1)
14861 (indent-for-tab-command)
14862 ;; Move point to the beginning of the first blank line
14863 ;; after the last non-blank line in region. Insert
14864 ;; drawer's closing, then indent it.
14865 (goto-char rend)
14866 (skip-chars-backward " \r\t\n")
14867 (insert "\n:END:")
14868 (deactivate-mark t)
14869 (indent-for-tab-command)
14870 (unless (eolp) (insert "\n")))
14871 ;; Clear marker, whatever the outcome of insertion is.
14872 (set-marker rend nil)))))))
14874 (defvar org-property-set-functions-alist nil
14875 "Property set function alist.
14876 Each entry should have the following format:
14878 (PROPERTY . READ-FUNCTION)
14880 The read function will be called with the same argument as
14881 `org-completing-read'.")
14883 (defun org-set-property-function (property)
14884 "Get the function that should be used to set PROPERTY.
14885 This is computed according to `org-property-set-functions-alist'."
14886 (or (cdr (assoc property org-property-set-functions-alist))
14887 'org-completing-read))
14889 (defun org-read-property-value (property)
14890 "Read PROPERTY value from user."
14891 (let* ((completion-ignore-case t)
14892 (allowed (org-property-get-allowed-values nil property 'table))
14893 (cur (org-entry-get nil property))
14894 (prompt (concat property " value"
14895 (if (and cur (string-match "\\S-" cur))
14896 (concat " [" cur "]") "") ": "))
14897 (set-function (org-set-property-function property))
14898 (val (if allowed
14899 (funcall set-function prompt allowed nil
14900 (not (get-text-property 0 'org-unrestricted
14901 (caar allowed))))
14902 (let (org-completion-use-ido org-completion-use-iswitchb)
14903 (funcall set-function prompt
14904 (mapcar 'list (org-property-values property))
14905 nil nil "" nil cur)))))
14906 (if (equal val "")
14908 val)))
14910 (defvar org-last-set-property nil)
14911 (defun org-read-property-name ()
14912 "Read a property name."
14913 (let* ((completion-ignore-case t)
14914 (keys (org-buffer-property-keys nil t t))
14915 (default-prop (or (save-excursion
14916 (save-match-data
14917 (beginning-of-line)
14918 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14919 (null (string= (match-string 1) "END"))
14920 (match-string 1))))
14921 org-last-set-property))
14922 (property (org-icompleting-read
14923 (concat "Property"
14924 (if default-prop (concat " [" default-prop "]") "")
14925 ": ")
14926 (mapcar 'list keys)
14927 nil nil nil nil
14928 default-prop
14930 (if (member property keys)
14931 property
14932 (or (cdr (assoc (downcase property)
14933 (mapcar (lambda (x) (cons (downcase x) x))
14934 keys)))
14935 property))))
14937 (defun org-set-property (property value)
14938 "In the current entry, set PROPERTY to VALUE.
14939 When called interactively, this will prompt for a property name, offering
14940 completion on existing and default properties. And then it will prompt
14941 for a value, offering completion either on allowed values (via an inherited
14942 xxx_ALL property) or on existing values in other instances of this property
14943 in the current file."
14944 (interactive (list nil nil))
14945 (let* ((property (or property (org-read-property-name)))
14946 (value (or value (org-read-property-value property)))
14947 (fn (cdr (assoc property org-properties-postprocess-alist))))
14948 (setq org-last-set-property property)
14949 ;; Possibly postprocess the inserted value:
14950 (when fn (setq value (funcall fn value)))
14951 (unless (equal (org-entry-get nil property) value)
14952 (org-entry-put nil property value))))
14954 (defun org-delete-property (property)
14955 "In the current entry, delete PROPERTY."
14956 (interactive
14957 (let* ((completion-ignore-case t)
14958 (prop (org-icompleting-read "Property: "
14959 (org-entry-properties nil 'standard))))
14960 (list prop)))
14961 (message "Property %s %s" property
14962 (if (org-entry-delete nil property)
14963 "deleted"
14964 "was not present in the entry")))
14966 (defun org-delete-property-globally (property)
14967 "Remove PROPERTY globally, from all entries."
14968 (interactive
14969 (let* ((completion-ignore-case t)
14970 (prop (org-icompleting-read
14971 "Globally remove property: "
14972 (mapcar 'list (org-buffer-property-keys)))))
14973 (list prop)))
14974 (save-excursion
14975 (save-restriction
14976 (widen)
14977 (goto-char (point-min))
14978 (let ((cnt 0))
14979 (while (re-search-forward
14980 (org-re-property property)
14981 nil t)
14982 (setq cnt (1+ cnt))
14983 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14984 (message "Property \"%s\" removed from %d entries" property cnt)))))
14986 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14988 (defun org-compute-property-at-point ()
14989 "Compute the property at point.
14990 This looks for an enclosing column format, extracts the operator and
14991 then applies it to the property in the column format's scope."
14992 (interactive)
14993 (unless (org-at-property-p)
14994 (error "Not at a property"))
14995 (let ((prop (org-match-string-no-properties 2)))
14996 (org-columns-get-format-and-top-level)
14997 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14998 (error "No operator defined for property %s" prop))
14999 (org-columns-compute prop)))
15001 (defvar org-property-allowed-value-functions nil
15002 "Hook for functions supplying allowed values for a specific property.
15003 The functions must take a single argument, the name of the property, and
15004 return a flat list of allowed values. If \":ETC\" is one of
15005 the values, this means that these values are intended as defaults for
15006 completion, but that other values should be allowed too.
15007 The functions must return nil if they are not responsible for this
15008 property.")
15010 (defun org-property-get-allowed-values (pom property &optional table)
15011 "Get allowed values for the property PROPERTY.
15012 When TABLE is non-nil, return an alist that can directly be used for
15013 completion."
15014 (let (vals)
15015 (cond
15016 ((equal property "TODO")
15017 (setq vals (org-with-point-at pom
15018 (append org-todo-keywords-1 '("")))))
15019 ((equal property "PRIORITY")
15020 (let ((n org-lowest-priority))
15021 (while (>= n org-highest-priority)
15022 (push (char-to-string n) vals)
15023 (setq n (1- n)))))
15024 ((member property org-special-properties))
15025 ((setq vals (run-hook-with-args-until-success
15026 'org-property-allowed-value-functions property)))
15028 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15029 (when (and vals (string-match "\\S-" vals))
15030 (setq vals (car (read-from-string (concat "(" vals ")"))))
15031 (setq vals (mapcar (lambda (x)
15032 (cond ((stringp x) x)
15033 ((numberp x) (number-to-string x))
15034 ((symbolp x) (symbol-name x))
15035 (t "???")))
15036 vals)))))
15037 (when (member ":ETC" vals)
15038 (setq vals (remove ":ETC" vals))
15039 (org-add-props (car vals) '(org-unrestricted t)))
15040 (if table (mapcar 'list vals) vals)))
15042 (defun org-property-previous-allowed-value (&optional previous)
15043 "Switch to the next allowed value for this property."
15044 (interactive)
15045 (org-property-next-allowed-value t))
15047 (defun org-property-next-allowed-value (&optional previous)
15048 "Switch to the next allowed value for this property."
15049 (interactive)
15050 (unless (org-at-property-p)
15051 (error "Not at a property"))
15052 (let* ((key (match-string 2))
15053 (value (match-string 3))
15054 (allowed (or (org-property-get-allowed-values (point) key)
15055 (and (member value '("[ ]" "[-]" "[X]"))
15056 '("[ ]" "[X]"))))
15057 nval)
15058 (unless allowed
15059 (error "Allowed values for this property have not been defined"))
15060 (if previous (setq allowed (reverse allowed)))
15061 (if (member value allowed)
15062 (setq nval (car (cdr (member value allowed)))))
15063 (setq nval (or nval (car allowed)))
15064 (if (equal nval value)
15065 (error "Only one allowed value for this property"))
15066 (org-at-property-p)
15067 (replace-match (concat " :" key ": " nval) t t)
15068 (org-indent-line)
15069 (beginning-of-line 1)
15070 (skip-chars-forward " \t")
15071 (run-hook-with-args 'org-property-changed-functions key nval)))
15073 (defun org-find-olp (path &optional this-buffer)
15074 "Return a marker pointing to the entry at outline path OLP.
15075 If anything goes wrong, throw an error.
15076 You can wrap this call to catch the error like this:
15078 (condition-case msg
15079 (org-mobile-locate-entry (match-string 4))
15080 (error (nth 1 msg)))
15082 The return value will then be either a string with the error message,
15083 or a marker if everything is OK.
15085 If THIS-BUFFER is set, the outline path does not contain a file,
15086 only headings."
15087 (let* ((file (if this-buffer buffer-file-name (pop path)))
15088 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15089 (level 1)
15090 (lmin 1)
15091 (lmax 1)
15092 limit re end found pos heading cnt flevel)
15093 (unless buffer (error "File not found :%s" file))
15094 (with-current-buffer buffer
15095 (save-excursion
15096 (save-restriction
15097 (widen)
15098 (setq limit (point-max))
15099 (goto-char (point-min))
15100 (while (setq heading (pop path))
15101 (setq re (format org-complex-heading-regexp-format
15102 (regexp-quote heading)))
15103 (setq cnt 0 pos (point))
15104 (while (re-search-forward re end t)
15105 (setq level (- (match-end 1) (match-beginning 1)))
15106 (if (and (>= level lmin) (<= level lmax))
15107 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15108 (when (= cnt 0) (error "Heading not found on level %d: %s"
15109 lmax heading))
15110 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15111 lmax heading))
15112 (goto-char found)
15113 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15114 (setq end (save-excursion (org-end-of-subtree t t))))
15115 (when (org-at-heading-p)
15116 (move-marker (make-marker) (point))))))))
15118 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15119 "Find node HEADING in BUFFER.
15120 Return a marker to the heading if it was found, or nil if not.
15121 If POS-ONLY is set, return just the position instead of a marker.
15123 The heading text must match exact, but it may have a TODO keyword,
15124 a priority cookie and tags in the standard locations."
15125 (with-current-buffer (or buffer (current-buffer))
15126 (save-excursion
15127 (save-restriction
15128 (widen)
15129 (goto-char (point-min))
15130 (let (case-fold-search)
15131 (if (re-search-forward
15132 (format org-complex-heading-regexp-format
15133 (regexp-quote heading)) nil t)
15134 (if pos-only
15135 (match-beginning 0)
15136 (move-marker (make-marker) (match-beginning 0)))))))))
15138 (defun org-find-exact-heading-in-directory (heading &optional dir)
15139 "Find Org node headline HEADING in all .org files in directory DIR.
15140 When the target headline is found, return a marker to this location."
15141 (let ((files (directory-files (or dir default-directory)
15142 nil "\\`[^.#].*\\.org\\'"))
15143 file visiting m buffer)
15144 (catch 'found
15145 (while (setq file (pop files))
15146 (message "trying %s" file)
15147 (setq visiting (org-find-base-buffer-visiting file))
15148 (setq buffer (or visiting (find-file-noselect file)))
15149 (setq m (org-find-exact-headline-in-buffer
15150 heading buffer))
15151 (when (and (not m) (not visiting)) (kill-buffer buffer))
15152 (and m (throw 'found m))))))
15154 (defun org-find-entry-with-id (ident)
15155 "Locate the entry that contains the ID property with exact value IDENT.
15156 IDENT can be a string, a symbol or a number, this function will search for
15157 the string representation of it.
15158 Return the position where this entry starts, or nil if there is no such entry."
15159 (interactive "sID: ")
15160 (let ((id (cond
15161 ((stringp ident) ident)
15162 ((symbol-name ident) (symbol-name ident))
15163 ((numberp ident) (number-to-string ident))
15164 (t (error "IDENT %s must be a string, symbol or number" ident))))
15165 (case-fold-search nil))
15166 (save-excursion
15167 (save-restriction
15168 (widen)
15169 (goto-char (point-min))
15170 (when (re-search-forward
15171 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15172 nil t)
15173 (org-back-to-heading t)
15174 (point))))))
15176 ;;;; Timestamps
15178 (defvar org-last-changed-timestamp nil)
15179 (defvar org-last-inserted-timestamp nil
15180 "The last time stamp inserted with `org-insert-time-stamp'.")
15181 (defvar org-time-was-given) ; dynamically scoped parameter
15182 (defvar org-end-time-was-given) ; dynamically scoped parameter
15183 (defvar org-ts-what) ; dynamically scoped parameter
15185 (defun org-time-stamp (arg &optional inactive)
15186 "Prompt for a date/time and insert a time stamp.
15187 If the user specifies a time like HH:MM or if this command is
15188 called with at least one prefix argument, the time stamp contains
15189 the date and the time. Otherwise, only the date is be included.
15191 All parts of a date not specified by the user is filled in from
15192 the current date/time. So if you just press return without
15193 typing anything, the time stamp will represent the current
15194 date/time.
15196 If there is already a timestamp at the cursor, it will be
15197 modified.
15199 With two universal prefix arguments, insert an active timestamp
15200 with the current time without prompting the user."
15201 (interactive "P")
15202 (let* ((ts nil)
15203 (default-time
15204 ;; Default time is either today, or, when entering a range,
15205 ;; the range start.
15206 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15207 (save-excursion
15208 (re-search-backward
15209 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15210 (- (point) 20) t)))
15211 (apply 'encode-time (org-parse-time-string (match-string 1)))
15212 (current-time)))
15213 (default-input (and ts (org-get-compact-tod ts)))
15214 (repeater (save-excursion
15215 (save-match-data
15216 (beginning-of-line)
15217 (when (re-search-forward
15218 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15219 (save-excursion (progn (end-of-line) (point))) t)
15220 (match-string 0)))))
15221 org-time-was-given org-end-time-was-given time)
15222 (cond
15223 ((and (org-at-timestamp-p t)
15224 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15225 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15226 (insert "--")
15227 (setq time (let ((this-command this-command))
15228 (org-read-date arg 'totime nil nil
15229 default-time default-input inactive)))
15230 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15231 ((org-at-timestamp-p t)
15232 (setq time (let ((this-command this-command))
15233 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15234 (when (org-at-timestamp-p t) ; just to get the match data
15235 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15236 (replace-match "")
15237 (setq org-last-changed-timestamp
15238 (org-insert-time-stamp
15239 time (or org-time-was-given arg)
15240 inactive nil nil (list org-end-time-was-given)))
15241 (when repeater (goto-char (1- (point))) (insert " " repeater)
15242 (setq org-last-changed-timestamp
15243 (concat (substring org-last-inserted-timestamp 0 -1)
15244 " " repeater ">"))))
15245 (message "Timestamp updated"))
15246 ((equal arg '(16))
15247 (org-insert-time-stamp (current-time) t))
15249 (setq time (let ((this-command this-command))
15250 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15251 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15252 nil nil (list org-end-time-was-given))))))
15254 ;; FIXME: can we use this for something else, like computing time differences?
15255 (defun org-get-compact-tod (s)
15256 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15257 (let* ((t1 (match-string 1 s))
15258 (h1 (string-to-number (match-string 2 s)))
15259 (m1 (string-to-number (match-string 3 s)))
15260 (t2 (and (match-end 4) (match-string 5 s)))
15261 (h2 (and t2 (string-to-number (match-string 6 s))))
15262 (m2 (and t2 (string-to-number (match-string 7 s))))
15263 dh dm)
15264 (if (not t2)
15266 (setq dh (- h2 h1) dm (- m2 m1))
15267 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15268 (concat t1 "+" (number-to-string dh)
15269 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15271 (defun org-time-stamp-inactive (&optional arg)
15272 "Insert an inactive time stamp.
15273 An inactive time stamp is enclosed in square brackets instead of angle
15274 brackets. It is inactive in the sense that it does not trigger agenda entries,
15275 does not link to the calendar and cannot be changed with the S-cursor keys.
15276 So these are more for recording a certain time/date."
15277 (interactive "P")
15278 (org-time-stamp arg 'inactive))
15280 (defvar org-date-ovl (make-overlay 1 1))
15281 (overlay-put org-date-ovl 'face 'org-date-selected)
15282 (org-detach-overlay org-date-ovl)
15284 (defvar org-ans1) ; dynamically scoped parameter
15285 (defvar org-ans2) ; dynamically scoped parameter
15287 (defvar org-plain-time-of-day-regexp) ; defined below
15289 (defvar org-overriding-default-time nil) ; dynamically scoped
15290 (defvar org-read-date-overlay nil)
15291 (defvar org-dcst nil) ; dynamically scoped
15292 (defvar org-read-date-history nil)
15293 (defvar org-read-date-final-answer nil)
15294 (defvar org-read-date-analyze-futurep nil)
15295 (defvar org-read-date-analyze-forced-year nil)
15296 (defvar org-read-date-inactive)
15298 (defun org-read-date (&optional org-with-time to-time from-string prompt
15299 default-time default-input inactive)
15300 "Read a date, possibly a time, and make things smooth for the user.
15301 The prompt will suggest to enter an ISO date, but you can also enter anything
15302 which will at least partially be understood by `parse-time-string'.
15303 Unrecognized parts of the date will default to the current day, month, year,
15304 hour and minute. If this command is called to replace a timestamp at point,
15305 or to enter the second timestamp of a range, the default time is taken
15306 from the existing stamp. Furthermore, the command prefers the future,
15307 so if you are giving a date where the year is not given, and the day-month
15308 combination is already past in the current year, it will assume you
15309 mean next year. For details, see the manual. A few examples:
15311 3-2-5 --> 2003-02-05
15312 feb 15 --> currentyear-02-15
15313 2/15 --> currentyear-02-15
15314 sep 12 9 --> 2009-09-12
15315 12:45 --> today 12:45
15316 22 sept 0:34 --> currentyear-09-22 0:34
15317 12 --> currentyear-currentmonth-12
15318 Fri --> nearest Friday (today or later)
15319 etc.
15321 Furthermore you can specify a relative date by giving, as the *first* thing
15322 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15323 change in days weeks, months, years.
15324 With a single plus or minus, the date is relative to today. With a double
15325 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15326 +4d --> four days from today
15327 +4 --> same as above
15328 +2w --> two weeks from today
15329 ++5 --> five days from default date
15331 The function understands only English month and weekday abbreviations.
15333 While prompting, a calendar is popped up - you can also select the
15334 date with the mouse (button 1). The calendar shows a period of three
15335 months. To scroll it to other months, use the keys `>' and `<'.
15336 If you don't like the calendar, turn it off with
15337 \(setq org-read-date-popup-calendar nil)
15339 With optional argument TO-TIME, the date will immediately be converted
15340 to an internal time.
15341 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15342 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15343 still enter a time, and this function will inform the calling routine
15344 about this change. The calling routine may then choose to change the
15345 format used to insert the time stamp into the buffer to include the time.
15346 With optional argument FROM-STRING, read from this string instead from
15347 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15348 the time/date that is used for everything that is not specified by the
15349 user."
15350 (require 'parse-time)
15351 (let* ((org-time-stamp-rounding-minutes
15352 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15353 (org-dcst org-display-custom-times)
15354 (ct (org-current-time))
15355 (org-def (or org-overriding-default-time default-time ct))
15356 (org-defdecode (decode-time org-def))
15357 (dummy (progn
15358 (when (< (nth 2 org-defdecode) org-extend-today-until)
15359 (setcar (nthcdr 2 org-defdecode) -1)
15360 (setcar (nthcdr 1 org-defdecode) 59)
15361 (setq org-def (apply 'encode-time org-defdecode)
15362 org-defdecode (decode-time org-def)))))
15363 (calendar-frame-setup nil)
15364 (calendar-setup nil)
15365 (calendar-move-hook nil)
15366 (calendar-view-diary-initially-flag nil)
15367 (calendar-view-holidays-initially-flag nil)
15368 (timestr (format-time-string
15369 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15370 (prompt (concat (if prompt (concat prompt " ") "")
15371 (format "Date+time [%s]: " timestr)))
15372 ans (org-ans0 "") org-ans1 org-ans2 final)
15374 (cond
15375 (from-string (setq ans from-string))
15376 (org-read-date-popup-calendar
15377 (save-excursion
15378 (save-window-excursion
15379 (calendar)
15380 (org-eval-in-calendar '(setq cursor-type nil) t)
15381 (unwind-protect
15382 (progn
15383 (calendar-forward-day (- (time-to-days org-def)
15384 (calendar-absolute-from-gregorian
15385 (calendar-current-date))))
15386 (org-eval-in-calendar nil t)
15387 (let* ((old-map (current-local-map))
15388 (map (copy-keymap calendar-mode-map))
15389 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15390 (org-defkey map (kbd "RET") 'org-calendar-select)
15391 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15392 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15393 (org-defkey minibuffer-local-map [(meta shift left)]
15394 (lambda () (interactive)
15395 (org-eval-in-calendar '(calendar-backward-month 1))))
15396 (org-defkey minibuffer-local-map [(meta shift right)]
15397 (lambda () (interactive)
15398 (org-eval-in-calendar '(calendar-forward-month 1))))
15399 (org-defkey minibuffer-local-map [(meta shift up)]
15400 (lambda () (interactive)
15401 (org-eval-in-calendar '(calendar-backward-year 1))))
15402 (org-defkey minibuffer-local-map [(meta shift down)]
15403 (lambda () (interactive)
15404 (org-eval-in-calendar '(calendar-forward-year 1))))
15405 (org-defkey minibuffer-local-map [?\e (shift left)]
15406 (lambda () (interactive)
15407 (org-eval-in-calendar '(calendar-backward-month 1))))
15408 (org-defkey minibuffer-local-map [?\e (shift right)]
15409 (lambda () (interactive)
15410 (org-eval-in-calendar '(calendar-forward-month 1))))
15411 (org-defkey minibuffer-local-map [?\e (shift up)]
15412 (lambda () (interactive)
15413 (org-eval-in-calendar '(calendar-backward-year 1))))
15414 (org-defkey minibuffer-local-map [?\e (shift down)]
15415 (lambda () (interactive)
15416 (org-eval-in-calendar '(calendar-forward-year 1))))
15417 (org-defkey minibuffer-local-map [(shift up)]
15418 (lambda () (interactive)
15419 (org-eval-in-calendar '(calendar-backward-week 1))))
15420 (org-defkey minibuffer-local-map [(shift down)]
15421 (lambda () (interactive)
15422 (org-eval-in-calendar '(calendar-forward-week 1))))
15423 (org-defkey minibuffer-local-map [(shift left)]
15424 (lambda () (interactive)
15425 (org-eval-in-calendar '(calendar-backward-day 1))))
15426 (org-defkey minibuffer-local-map [(shift right)]
15427 (lambda () (interactive)
15428 (org-eval-in-calendar '(calendar-forward-day 1))))
15429 (org-defkey minibuffer-local-map ">"
15430 (lambda () (interactive)
15431 (org-eval-in-calendar '(scroll-calendar-left 1))))
15432 (org-defkey minibuffer-local-map "<"
15433 (lambda () (interactive)
15434 (org-eval-in-calendar '(scroll-calendar-right 1))))
15435 (org-defkey minibuffer-local-map "\C-v"
15436 (lambda () (interactive)
15437 (org-eval-in-calendar
15438 '(calendar-scroll-left-three-months 1))))
15439 (org-defkey minibuffer-local-map "\M-v"
15440 (lambda () (interactive)
15441 (org-eval-in-calendar
15442 '(calendar-scroll-right-three-months 1))))
15443 (run-hooks 'org-read-date-minibuffer-setup-hook)
15444 (unwind-protect
15445 (progn
15446 (use-local-map map)
15447 (setq org-read-date-inactive inactive)
15448 (add-hook 'post-command-hook 'org-read-date-display)
15449 (setq org-ans0 (read-string prompt default-input
15450 'org-read-date-history nil))
15451 ;; org-ans0: from prompt
15452 ;; org-ans1: from mouse click
15453 ;; org-ans2: from calendar motion
15454 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15455 (remove-hook 'post-command-hook 'org-read-date-display)
15456 (use-local-map old-map)
15457 (when org-read-date-overlay
15458 (delete-overlay org-read-date-overlay)
15459 (setq org-read-date-overlay nil)))))
15460 (bury-buffer "*Calendar*")))))
15462 (t ; Naked prompt only
15463 (unwind-protect
15464 (setq ans (read-string prompt default-input
15465 'org-read-date-history timestr))
15466 (when org-read-date-overlay
15467 (delete-overlay org-read-date-overlay)
15468 (setq org-read-date-overlay nil)))))
15470 (setq final (org-read-date-analyze ans org-def org-defdecode))
15472 (when org-read-date-analyze-forced-year
15473 (message "Year was forced into %s"
15474 (if org-read-date-force-compatible-dates
15475 "compatible range (1970-2037)"
15476 "range representable on this machine"))
15477 (ding))
15479 ;; One round trip to get rid of 34th of August and stuff like that....
15480 (setq final (decode-time (apply 'encode-time final)))
15482 (setq org-read-date-final-answer ans)
15484 (if to-time
15485 (apply 'encode-time final)
15486 (if (and (boundp 'org-time-was-given) org-time-was-given)
15487 (format "%04d-%02d-%02d %02d:%02d"
15488 (nth 5 final) (nth 4 final) (nth 3 final)
15489 (nth 2 final) (nth 1 final))
15490 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15492 (defvar org-def)
15493 (defvar org-defdecode)
15494 (defvar org-with-time)
15495 (defun org-read-date-display ()
15496 "Display the current date prompt interpretation in the minibuffer."
15497 (when org-read-date-display-live
15498 (when org-read-date-overlay
15499 (delete-overlay org-read-date-overlay))
15500 (when (minibufferp (current-buffer))
15501 (save-excursion
15502 (end-of-line 1)
15503 (while (not (equal (buffer-substring
15504 (max (point-min) (- (point) 4)) (point))
15505 " "))
15506 (insert " ")))
15507 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15508 " " (or org-ans1 org-ans2)))
15509 (org-end-time-was-given nil)
15510 (f (org-read-date-analyze ans org-def org-defdecode))
15511 (fmts (if org-dcst
15512 org-time-stamp-custom-formats
15513 org-time-stamp-formats))
15514 (fmt (if (or org-with-time
15515 (and (boundp 'org-time-was-given) org-time-was-given))
15516 (cdr fmts)
15517 (car fmts)))
15518 (txt (format-time-string fmt (apply 'encode-time f)))
15519 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15520 (txt (concat "=> " txt)))
15521 (when (and org-end-time-was-given
15522 (string-match org-plain-time-of-day-regexp txt))
15523 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15524 org-end-time-was-given
15525 (substring txt (match-end 0)))))
15526 (when org-read-date-analyze-futurep
15527 (setq txt (concat txt " (=>F)")))
15528 (setq org-read-date-overlay
15529 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15530 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15532 (defun org-read-date-analyze (ans org-def org-defdecode)
15533 "Analyze the combined answer of the date prompt."
15534 ;; FIXME: cleanup and comment
15535 (let ((nowdecode (decode-time (current-time)))
15536 delta deltan deltaw deltadef year month day
15537 hour minute second wday pm h2 m2 tl wday1
15538 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15539 (setq org-read-date-analyze-futurep nil
15540 org-read-date-analyze-forced-year nil)
15541 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15542 (setq ans "+0"))
15544 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15545 (setq ans (replace-match "" t t ans)
15546 deltan (car delta)
15547 deltaw (nth 1 delta)
15548 deltadef (nth 2 delta)))
15550 ;; Check if there is an iso week date in there. If yes, store the
15551 ;; info and postpone interpreting it until the rest of the parsing
15552 ;; is done.
15553 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15554 (setq iso-year (if (match-end 1)
15555 (org-small-year-to-year
15556 (string-to-number (match-string 1 ans))))
15557 iso-weekday (if (match-end 3)
15558 (string-to-number (match-string 3 ans)))
15559 iso-week (string-to-number (match-string 2 ans)))
15560 (setq ans (replace-match "" t t ans)))
15562 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15563 (when (string-match
15564 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15565 (setq year (if (match-end 2)
15566 (string-to-number (match-string 2 ans))
15567 (progn (setq kill-year t)
15568 (string-to-number (format-time-string "%Y"))))
15569 month (string-to-number (match-string 3 ans))
15570 day (string-to-number (match-string 4 ans)))
15571 (if (< year 100) (setq year (+ 2000 year)))
15572 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15573 t nil ans)))
15575 ;; Help matching dotted european dates
15576 (when (string-match
15577 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15578 (setq year (if (match-end 3)
15579 (string-to-number (match-string 3 ans))
15580 (progn (setq kill-year t)
15581 (string-to-number (format-time-string "%Y"))))
15582 day (string-to-number (match-string 1 ans))
15583 month (string-to-number (match-string 2 ans))
15584 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15585 t nil ans)))
15587 ;; Help matching american dates, like 5/30 or 5/30/7
15588 (when (string-match
15589 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15590 (setq year (if (match-end 4)
15591 (string-to-number (match-string 4 ans))
15592 (progn (setq kill-year t)
15593 (string-to-number (format-time-string "%Y"))))
15594 month (string-to-number (match-string 1 ans))
15595 day (string-to-number (match-string 2 ans)))
15596 (if (< year 100) (setq year (+ 2000 year)))
15597 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15598 t nil ans)))
15599 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15600 ;; If there is a time with am/pm, and *no* time without it, we convert
15601 ;; so that matching will be successful.
15602 (loop for i from 1 to 2 do ; twice, for end time as well
15603 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15604 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15605 (setq hour (string-to-number (match-string 1 ans))
15606 minute (if (match-end 3)
15607 (string-to-number (match-string 3 ans))
15609 pm (equal ?p
15610 (string-to-char (downcase (match-string 4 ans)))))
15611 (if (and (= hour 12) (not pm))
15612 (setq hour 0)
15613 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15614 (setq ans (replace-match (format "%02d:%02d" hour minute)
15615 t t ans))))
15617 ;; Check if a time range is given as a duration
15618 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15619 (setq hour (string-to-number (match-string 1 ans))
15620 h2 (+ hour (string-to-number (match-string 3 ans)))
15621 minute (string-to-number (match-string 2 ans))
15622 m2 (+ minute (if (match-end 5) (string-to-number
15623 (match-string 5 ans))0)))
15624 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15625 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15626 t t ans)))
15628 ;; Check if there is a time range
15629 (when (boundp 'org-end-time-was-given)
15630 (setq org-time-was-given nil)
15631 (when (and (string-match org-plain-time-of-day-regexp ans)
15632 (match-end 8))
15633 (setq org-end-time-was-given (match-string 8 ans))
15634 (setq ans (concat (substring ans 0 (match-beginning 7))
15635 (substring ans (match-end 7))))))
15637 (setq tl (parse-time-string ans)
15638 day (or (nth 3 tl) (nth 3 org-defdecode))
15639 month (or (nth 4 tl)
15640 (if (and org-read-date-prefer-future
15641 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15642 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15643 (nth 4 org-defdecode)))
15644 year (or (and (not kill-year) (nth 5 tl))
15645 (if (and org-read-date-prefer-future
15646 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15647 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15648 (nth 5 org-defdecode)))
15649 hour (or (nth 2 tl) (nth 2 org-defdecode))
15650 minute (or (nth 1 tl) (nth 1 org-defdecode))
15651 second (or (nth 0 tl) 0)
15652 wday (nth 6 tl))
15654 (when (and (eq org-read-date-prefer-future 'time)
15655 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15656 (equal day (nth 3 nowdecode))
15657 (equal month (nth 4 nowdecode))
15658 (equal year (nth 5 nowdecode))
15659 (nth 2 tl)
15660 (or (< (nth 2 tl) (nth 2 nowdecode))
15661 (and (= (nth 2 tl) (nth 2 nowdecode))
15662 (nth 1 tl)
15663 (< (nth 1 tl) (nth 1 nowdecode)))))
15664 (setq day (1+ day)
15665 futurep t))
15667 ;; Special date definitions below
15668 (cond
15669 (iso-week
15670 ;; There was an iso week
15671 (require 'cal-iso)
15672 (setq futurep nil)
15673 (setq year (or iso-year year)
15674 day (or iso-weekday wday 1)
15675 wday nil ; to make sure that the trigger below does not match
15676 iso-date (calendar-gregorian-from-absolute
15677 (calendar-absolute-from-iso
15678 (list iso-week day year))))
15679 ; FIXME: Should we also push ISO weeks into the future?
15680 ; (when (and org-read-date-prefer-future
15681 ; (not iso-year)
15682 ; (< (calendar-absolute-from-gregorian iso-date)
15683 ; (time-to-days (current-time))))
15684 ; (setq year (1+ year)
15685 ; iso-date (calendar-gregorian-from-absolute
15686 ; (calendar-absolute-from-iso
15687 ; (list iso-week day year)))))
15688 (setq month (car iso-date)
15689 year (nth 2 iso-date)
15690 day (nth 1 iso-date)))
15691 (deltan
15692 (setq futurep nil)
15693 (unless deltadef
15694 (let ((now (decode-time (current-time))))
15695 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15696 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15697 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15698 ((equal deltaw "m") (setq month (+ month deltan)))
15699 ((equal deltaw "y") (setq year (+ year deltan)))))
15700 ((and wday (not (nth 3 tl)))
15701 ;; Weekday was given, but no day, so pick that day in the week
15702 ;; on or after the derived date.
15703 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15704 (unless (equal wday wday1)
15705 (setq day (+ day (% (- wday wday1 -7) 7))))))
15706 (if (and (boundp 'org-time-was-given)
15707 (nth 2 tl))
15708 (setq org-time-was-given t))
15709 (if (< year 100) (setq year (+ 2000 year)))
15710 ;; Check of the date is representable
15711 (if org-read-date-force-compatible-dates
15712 (progn
15713 (if (< year 1970)
15714 (setq year 1970 org-read-date-analyze-forced-year t))
15715 (if (> year 2037)
15716 (setq year 2037 org-read-date-analyze-forced-year t)))
15717 (condition-case nil
15718 (ignore (encode-time second minute hour day month year))
15719 (error
15720 (setq year (nth 5 org-defdecode))
15721 (setq org-read-date-analyze-forced-year t))))
15722 (setq org-read-date-analyze-futurep futurep)
15723 (list second minute hour day month year)))
15725 (defvar parse-time-weekdays)
15726 (defun org-read-date-get-relative (s today default)
15727 "Check string S for special relative date string.
15728 TODAY and DEFAULT are internal times, for today and for a default.
15729 Return shift list (N what def-flag)
15730 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15731 N is the number of WHATs to shift.
15732 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15733 the DEFAULT date rather than TODAY."
15734 (require 'parse-time)
15735 (when (and
15736 (string-match
15737 (concat
15738 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15739 "\\([0-9]+\\)?"
15740 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15741 "\\([ \t]\\|$\\)") s)
15742 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15743 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15744 (string-to-char (substring (match-string 1 s) -1))
15745 ?+))
15746 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15747 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15748 (what (if (match-end 3) (match-string 3 s) "d"))
15749 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15750 (date (if rel default today))
15751 (wday (nth 6 (decode-time date)))
15752 delta)
15753 (if wday1
15754 (progn
15755 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15756 (if (= dir ?-) (setq delta (- delta 7)))
15757 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15758 (list delta "d" rel))
15759 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15761 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15762 "Turn a user-specified date into the internal representation.
15763 The internal representation needed by the calendar is (month day year).
15764 This is a wrapper to handle the brain-dead convention in calendar that
15765 user function argument order change dependent on argument order."
15766 (if (boundp 'calendar-date-style)
15767 (cond
15768 ((eq calendar-date-style 'american)
15769 (list arg1 arg2 arg3))
15770 ((eq calendar-date-style 'european)
15771 (list arg2 arg1 arg3))
15772 ((eq calendar-date-style 'iso)
15773 (list arg2 arg3 arg1)))
15774 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15775 (if (org-bound-and-true-p european-calendar-style)
15776 (list arg2 arg1 arg3)
15777 (list arg1 arg2 arg3)))))
15779 (defun org-eval-in-calendar (form &optional keepdate)
15780 "Eval FORM in the calendar window and return to current window.
15781 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15782 otherwise stick to the current value of `org-ans2'."
15783 (let ((sf (selected-frame))
15784 (sw (selected-window)))
15785 (select-window (get-buffer-window "*Calendar*" t))
15786 (eval form)
15787 (when (and (not keepdate) (calendar-cursor-to-date))
15788 (let* ((date (calendar-cursor-to-date))
15789 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15790 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15791 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15792 (select-window sw)
15793 (org-select-frame-set-input-focus sf)))
15795 (defun org-calendar-select ()
15796 "Return to `org-read-date' with the date currently selected.
15797 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15798 (interactive)
15799 (when (calendar-cursor-to-date)
15800 (let* ((date (calendar-cursor-to-date))
15801 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15802 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15803 (if (active-minibuffer-window) (exit-minibuffer))))
15805 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15806 "Insert a date stamp for the date given by the internal TIME.
15807 WITH-HM means use the stamp format that includes the time of the day.
15808 INACTIVE means use square brackets instead of angular ones, so that the
15809 stamp will not contribute to the agenda.
15810 PRE and POST are optional strings to be inserted before and after the
15811 stamp.
15812 The command returns the inserted time stamp."
15813 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15814 stamp)
15815 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15816 (insert-before-markers (or pre ""))
15817 (when (listp extra)
15818 (setq extra (car extra))
15819 (if (and (stringp extra)
15820 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15821 (setq extra (format "-%02d:%02d"
15822 (string-to-number (match-string 1 extra))
15823 (string-to-number (match-string 2 extra))))
15824 (setq extra nil)))
15825 (when extra
15826 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15827 (insert-before-markers (setq stamp (format-time-string fmt time)))
15828 (insert-before-markers (or post ""))
15829 (setq org-last-inserted-timestamp stamp)))
15831 (defun org-toggle-time-stamp-overlays ()
15832 "Toggle the use of custom time stamp formats."
15833 (interactive)
15834 (setq org-display-custom-times (not org-display-custom-times))
15835 (unless org-display-custom-times
15836 (let ((p (point-min)) (bmp (buffer-modified-p)))
15837 (while (setq p (next-single-property-change p 'display))
15838 (if (and (get-text-property p 'display)
15839 (eq (get-text-property p 'face) 'org-date))
15840 (remove-text-properties
15841 p (setq p (next-single-property-change p 'display))
15842 '(display t))))
15843 (set-buffer-modified-p bmp)))
15844 (if (featurep 'xemacs)
15845 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15846 (org-restart-font-lock)
15847 (setq org-table-may-need-update t)
15848 (if org-display-custom-times
15849 (message "Time stamps are overlaid with custom format")
15850 (message "Time stamp overlays removed")))
15852 (defun org-display-custom-time (beg end)
15853 "Overlay modified time stamp format over timestamp between BEG and END."
15854 (let* ((ts (buffer-substring beg end))
15855 t1 w1 with-hm tf time str w2 (off 0))
15856 (save-match-data
15857 (setq t1 (org-parse-time-string ts t))
15858 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15859 (setq off (- (match-end 0) (match-beginning 0)))))
15860 (setq end (- end off))
15861 (setq w1 (- end beg)
15862 with-hm (and (nth 1 t1) (nth 2 t1))
15863 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15864 time (org-fix-decoded-time t1)
15865 str (org-add-props
15866 (format-time-string
15867 (substring tf 1 -1) (apply 'encode-time time))
15868 nil 'mouse-face 'highlight)
15869 w2 (length str))
15870 (if (not (= w2 w1))
15871 (add-text-properties (1+ beg) (+ 2 beg)
15872 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15873 (if (featurep 'xemacs)
15874 (progn
15875 (put-text-property beg end 'invisible t)
15876 (put-text-property beg end 'end-glyph (make-glyph str)))
15877 (put-text-property beg end 'display str))))
15879 (defun org-translate-time (string)
15880 "Translate all timestamps in STRING to custom format.
15881 But do this only if the variable `org-display-custom-times' is set."
15882 (when org-display-custom-times
15883 (save-match-data
15884 (let* ((start 0)
15885 (re org-ts-regexp-both)
15886 t1 with-hm inactive tf time str beg end)
15887 (while (setq start (string-match re string start))
15888 (setq beg (match-beginning 0)
15889 end (match-end 0)
15890 t1 (save-match-data
15891 (org-parse-time-string (substring string beg end) t))
15892 with-hm (and (nth 1 t1) (nth 2 t1))
15893 inactive (equal (substring string beg (1+ beg)) "[")
15894 tf (funcall (if with-hm 'cdr 'car)
15895 org-time-stamp-custom-formats)
15896 time (org-fix-decoded-time t1)
15897 str (format-time-string
15898 (concat
15899 (if inactive "[" "<") (substring tf 1 -1)
15900 (if inactive "]" ">"))
15901 (apply 'encode-time time))
15902 string (replace-match str t t string)
15903 start (+ start (length str)))))))
15904 string)
15906 (defun org-fix-decoded-time (time)
15907 "Set 0 instead of nil for the first 6 elements of time.
15908 Don't touch the rest."
15909 (let ((n 0))
15910 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15912 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
15914 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
15915 "Difference between TIMESTAMP-STRING and now in days.
15916 If SECONDS is non-nil, return the difference in seconds."
15917 (let ((fdiff (if seconds 'time-to-seconds 'time-to-days)))
15918 (- (funcall fdiff (org-time-string-to-time timestamp-string))
15919 (funcall fdiff (current-time)))))
15921 (defun org-deadline-close (timestamp-string &optional ndays)
15922 "Is the time in TIMESTAMP-STRING close to the current date?"
15923 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15924 (and (< (org-days-to-time timestamp-string) ndays)
15925 (not (org-entry-is-done-p))))
15927 (defun org-get-wdays (ts)
15928 "Get the deadline lead time appropriate for timestring TS."
15929 (cond
15930 ((<= org-deadline-warning-days 0)
15931 ;; 0 or negative, enforce this value no matter what
15932 (- org-deadline-warning-days))
15933 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15934 ;; lead time is specified.
15935 (floor (* (string-to-number (match-string 1 ts))
15936 (cdr (assoc (match-string 2 ts)
15937 '(("d" . 1) ("w" . 7)
15938 ("m" . 30.4) ("y" . 365.25)))))))
15939 ;; go for the default.
15940 (t org-deadline-warning-days)))
15942 (defun org-calendar-select-mouse (ev)
15943 "Return to `org-read-date' with the date currently selected.
15944 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15945 (interactive "e")
15946 (mouse-set-point ev)
15947 (when (calendar-cursor-to-date)
15948 (let* ((date (calendar-cursor-to-date))
15949 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15950 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15951 (if (active-minibuffer-window) (exit-minibuffer))))
15953 (defun org-check-deadlines (ndays)
15954 "Check if there are any deadlines due or past due.
15955 A deadline is considered due if it happens within `org-deadline-warning-days'
15956 days from today's date. If the deadline appears in an entry marked DONE,
15957 it is not shown. The prefix arg NDAYS can be used to test that many
15958 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15959 (interactive "P")
15960 (let* ((org-warn-days
15961 (cond
15962 ((equal ndays '(4)) 100000)
15963 (ndays (prefix-numeric-value ndays))
15964 (t (abs org-deadline-warning-days))))
15965 (case-fold-search nil)
15966 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15967 (callback
15968 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15970 (message "%d deadlines past-due or due within %d days"
15971 (org-occur regexp nil callback)
15972 org-warn-days)))
15974 (defsubst org-re-timestamp (type)
15975 "Return a regexp for timestamp TYPE.
15976 Allowed values for TYPE are:
15978 all: all timestamps
15979 active: only active timestamps (<...>)
15980 inactive: only inactive timestamps ([...])
15981 scheduled: only scheduled timestamps
15982 deadline: only deadline timestamps
15984 When TYPE is nil, fall back on returning a regexp that matches
15985 both scheduled and deadline timestamps."
15986 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
15987 ((eq type 'active) org-ts-regexp)
15988 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
15989 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
15990 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15991 ((eq type 'scheduled-or-deadline)
15992 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
15994 (defun org-check-before-date (date)
15995 "Check if there are deadlines or scheduled entries before DATE."
15996 (interactive (list (org-read-date)))
15997 (let ((case-fold-search nil)
15998 (regexp (org-re-timestamp org-ts-type))
15999 (callback
16000 (lambda () (time-less-p
16001 (org-time-string-to-time (match-string 1))
16002 (org-time-string-to-time date)))))
16003 (message "%d entries before %s"
16004 (org-occur regexp nil callback) date)))
16006 (defun org-check-after-date (date)
16007 "Check if there are deadlines or scheduled entries after DATE."
16008 (interactive (list (org-read-date)))
16009 (let ((case-fold-search nil)
16010 (regexp (org-re-timestamp org-ts-type))
16011 (callback
16012 (lambda () (not
16013 (time-less-p
16014 (org-time-string-to-time (match-string 1))
16015 (org-time-string-to-time date))))))
16016 (message "%d entries after %s"
16017 (org-occur regexp nil callback) date)))
16019 (defun org-check-dates-range (start-date end-date)
16020 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16021 (interactive (list (org-read-date nil nil nil "Range starts")
16022 (org-read-date nil nil nil "Range end")))
16023 (let ((case-fold-search nil)
16024 (regexp (org-re-timestamp org-ts-type))
16025 (callback
16026 (lambda ()
16027 (let ((match (match-string 1)))
16028 (and
16029 (not (time-less-p
16030 (org-time-string-to-time match)
16031 (org-time-string-to-time start-date)))
16032 (time-less-p
16033 (org-time-string-to-time match)
16034 (org-time-string-to-time end-date)))))))
16035 (message "%d entries between %s and %s"
16036 (org-occur regexp nil callback) start-date end-date)))
16038 (defun org-evaluate-time-range (&optional to-buffer)
16039 "Evaluate a time range by computing the difference between start and end.
16040 Normally the result is just printed in the echo area, but with prefix arg
16041 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16042 If the time range is actually in a table, the result is inserted into the
16043 next column.
16044 For time difference computation, a year is assumed to be exactly 365
16045 days in order to avoid rounding problems."
16046 (interactive "P")
16048 (org-clock-update-time-maybe)
16049 (save-excursion
16050 (unless (org-at-date-range-p t)
16051 (goto-char (point-at-bol))
16052 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16053 (if (not (org-at-date-range-p t))
16054 (error "Not at a time-stamp range, and none found in current line")))
16055 (let* ((ts1 (match-string 1))
16056 (ts2 (match-string 2))
16057 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16058 (match-end (match-end 0))
16059 (time1 (org-time-string-to-time ts1))
16060 (time2 (org-time-string-to-time ts2))
16061 (t1 (org-float-time time1))
16062 (t2 (org-float-time time2))
16063 (diff (abs (- t2 t1)))
16064 (negative (< (- t2 t1) 0))
16065 ;; (ys (floor (* 365 24 60 60)))
16066 (ds (* 24 60 60))
16067 (hs (* 60 60))
16068 (fy "%dy %dd %02d:%02d")
16069 (fy1 "%dy %dd")
16070 (fd "%dd %02d:%02d")
16071 (fd1 "%dd")
16072 (fh "%02d:%02d")
16073 y d h m align)
16074 (if havetime
16075 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16077 d (floor (/ diff ds)) diff (mod diff ds)
16078 h (floor (/ diff hs)) diff (mod diff hs)
16079 m (floor (/ diff 60)))
16080 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16082 d (floor (+ (/ diff ds) 0.5))
16083 h 0 m 0))
16084 (if (not to-buffer)
16085 (message "%s" (org-make-tdiff-string y d h m))
16086 (if (org-at-table-p)
16087 (progn
16088 (goto-char match-end)
16089 (setq align t)
16090 (and (looking-at " *|") (goto-char (match-end 0))))
16091 (goto-char match-end))
16092 (if (looking-at
16093 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16094 (replace-match ""))
16095 (if negative (insert " -"))
16096 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16097 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16098 (insert " " (format fh h m))))
16099 (if align (org-table-align))
16100 (message "Time difference inserted")))))
16102 (defun org-make-tdiff-string (y d h m)
16103 (let ((fmt "")
16104 (l nil))
16105 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16106 l (push y l)))
16107 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16108 l (push d l)))
16109 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16110 l (push h l)))
16111 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16112 l (push m l)))
16113 (apply 'format fmt (nreverse l))))
16115 (defun org-time-string-to-time (s &optional buffer pos)
16116 "Convert a timestamp string into internal time."
16117 (condition-case errdata
16118 (apply 'encode-time (org-parse-time-string s))
16119 (error (error "Bad timestamp `%s'%s\nError was: %s"
16120 s (if (not (and buffer pos))
16122 (format " at %d in buffer `%s'" pos buffer))
16123 (cdr errdata)))))
16125 (defun org-time-string-to-seconds (s)
16126 "Convert a timestamp string to a number of seconds."
16127 (org-float-time (org-time-string-to-time s)))
16129 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16130 "Convert a time stamp to an absolute day number.
16131 If there is a specifier for a cyclic time stamp, get the closest date to
16132 DAYNR.
16133 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16134 The variable date is bound by the calendar when this is called."
16135 (cond
16136 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16137 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16138 daynr
16139 (+ daynr 1000)))
16140 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16141 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16142 (time-to-days (current-time))) (match-string 0 s)
16143 prefer show-all))
16144 (t (time-to-days
16145 (condition-case errdata
16146 (apply 'encode-time (org-parse-time-string s))
16147 (error (error "Bad timestamp `%s'%s\nError was: %s"
16148 s (if (not (and buffer pos))
16150 (format " at %d in buffer `%s'" pos buffer))
16151 (cdr errdata))))))))
16153 (defun org-days-to-iso-week (days)
16154 "Return the iso week number."
16155 (require 'cal-iso)
16156 (car (calendar-iso-from-absolute days)))
16158 (defun org-small-year-to-year (year)
16159 "Convert 2-digit years into 4-digit years.
16160 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16161 The year 2000 cannot be abbreviated. Any year larger than 99
16162 is returned unchanged."
16163 (if (< year 38)
16164 (setq year (+ 2000 year))
16165 (if (< year 100)
16166 (setq year (+ 1900 year))))
16167 year)
16169 (defun org-time-from-absolute (d)
16170 "Return the time corresponding to date D.
16171 D may be an absolute day number, or a calendar-type list (month day year)."
16172 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16173 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16175 (defun org-calendar-holiday ()
16176 "List of holidays, for Diary display in Org-mode."
16177 (require 'holidays)
16178 (let ((hl (funcall
16179 (if (fboundp 'calendar-check-holidays)
16180 'calendar-check-holidays 'check-calendar-holidays) date)))
16181 (if hl (mapconcat 'identity hl "; "))))
16183 (defun org-diary-sexp-entry (sexp entry date)
16184 "Process a SEXP diary ENTRY for DATE."
16185 (require 'diary-lib)
16186 (let ((result (if calendar-debug-sexp
16187 (let ((stack-trace-on-error t))
16188 (eval (car (read-from-string sexp))))
16189 (condition-case nil
16190 (eval (car (read-from-string sexp)))
16191 (error
16192 (beep)
16193 (message "Bad sexp at line %d in %s: %s"
16194 (org-current-line)
16195 (buffer-file-name) sexp)
16196 (sleep-for 2))))))
16197 (cond ((stringp result) (split-string result "; "))
16198 ((and (consp result)
16199 (not (consp (cdr result)))
16200 (stringp (cdr result))) (cdr result))
16201 ((and (consp result)
16202 (stringp (car result))) result)
16203 (result entry))))
16205 (defun org-diary-to-ical-string (frombuf)
16206 "Get iCalendar entries from diary entries in buffer FROMBUF.
16207 This uses the icalendar.el library."
16208 (let* ((tmpdir (if (featurep 'xemacs)
16209 (temp-directory)
16210 temporary-file-directory))
16211 (tmpfile (make-temp-name
16212 (expand-file-name "orgics" tmpdir)))
16213 buf rtn b e)
16214 (with-current-buffer frombuf
16215 (icalendar-export-region (point-min) (point-max) tmpfile)
16216 (setq buf (find-buffer-visiting tmpfile))
16217 (set-buffer buf)
16218 (goto-char (point-min))
16219 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16220 (setq b (match-beginning 0)))
16221 (goto-char (point-max))
16222 (if (re-search-backward "^END:VEVENT" nil t)
16223 (setq e (match-end 0)))
16224 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16225 (kill-buffer buf)
16226 (delete-file tmpfile)
16227 rtn))
16229 (defun org-closest-date (start current change prefer show-all)
16230 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16231 When PREFER is `past', return a date that is either CURRENT or past.
16232 When PREFER is `future', return a date that is either CURRENT or future.
16233 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16234 ;; Make the proper lists from the dates
16235 (catch 'exit
16236 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16237 dn dw sday cday n1 n2 n0
16238 d m y y1 y2 date1 date2 nmonths nm ny m2)
16240 (setq start (org-date-to-gregorian start)
16241 current (org-date-to-gregorian
16242 (if show-all
16243 current
16244 (time-to-days (current-time))))
16245 sday (calendar-absolute-from-gregorian start)
16246 cday (calendar-absolute-from-gregorian current))
16248 (if (<= cday sday) (throw 'exit sday))
16250 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16251 (setq dn (string-to-number (match-string 1 change))
16252 dw (cdr (assoc (match-string 2 change) a1)))
16253 (error "Invalid change specifier: %s" change))
16254 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16255 (cond
16256 ((eq dw 'day)
16257 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16258 n2 (+ n1 dn)))
16259 ((eq dw 'year)
16260 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16261 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16262 (setq date1 (list m d y1)
16263 n1 (calendar-absolute-from-gregorian date1)
16264 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16265 n2 (calendar-absolute-from-gregorian date2)))
16266 ((eq dw 'month)
16267 ;; approx number of month between the two dates
16268 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16269 ;; How often does dn fit in there?
16270 (setq d (nth 1 start) m (car start) y (nth 2 start)
16271 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16272 m (+ m nm)
16273 ny (floor (/ m 12))
16274 y (+ y ny)
16275 m (- m (* ny 12)))
16276 (while (> m 12) (setq m (- m 12) y (1+ y)))
16277 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16278 (setq m2 (+ m dn) y2 y)
16279 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16280 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16281 (while (<= n2 cday)
16282 (setq n1 n2 m m2 y y2)
16283 (setq m2 (+ m dn) y2 y)
16284 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16285 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16286 ;; Make sure n1 is the earlier date
16287 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16288 (if show-all
16289 (cond
16290 ((eq prefer 'past) (if (= cday n2) n2 n1))
16291 ((eq prefer 'future) (if (= cday n1) n1 n2))
16292 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16293 (cond
16294 ((eq prefer 'past) (if (= cday n2) n2 n1))
16295 ((eq prefer 'future) (if (= cday n1) n1 n2))
16296 (t (if (= cday n1) n1 n2)))))))
16298 (defun org-date-to-gregorian (date)
16299 "Turn any specification of DATE into a Gregorian date for the calendar."
16300 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16301 ((and (listp date) (= (length date) 3)) date)
16302 ((stringp date)
16303 (setq date (org-parse-time-string date))
16304 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16305 ((listp date)
16306 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16308 (defun org-parse-time-string (s &optional nodefault)
16309 "Parse the standard Org-mode time string.
16310 This should be a lot faster than the normal `parse-time-string'.
16311 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16312 hour and minute fields will be nil if not given."
16313 (if (string-match org-ts-regexp0 s)
16314 (list 0
16315 (if (or (match-beginning 8) (not nodefault))
16316 (string-to-number (or (match-string 8 s) "0")))
16317 (if (or (match-beginning 7) (not nodefault))
16318 (string-to-number (or (match-string 7 s) "0")))
16319 (string-to-number (match-string 4 s))
16320 (string-to-number (match-string 3 s))
16321 (string-to-number (match-string 2 s))
16322 nil nil nil)
16323 (error "Not a standard Org-mode time string: %s" s)))
16325 (defun org-timestamp-up (&optional arg)
16326 "Increase the date item at the cursor by one.
16327 If the cursor is on the year, change the year. If it is on the month,
16328 the day or the time, change that.
16329 With prefix ARG, change by that many units."
16330 (interactive "p")
16331 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16333 (defun org-timestamp-down (&optional arg)
16334 "Decrease the date item at the cursor by one.
16335 If the cursor is on the year, change the year. If it is on the month,
16336 the day or the time, change that.
16337 With prefix ARG, change by that many units."
16338 (interactive "p")
16339 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16341 (defun org-timestamp-up-day (&optional arg)
16342 "Increase the date in the time stamp by one day.
16343 With prefix ARG, change that many days."
16344 (interactive "p")
16345 (if (and (not (org-at-timestamp-p t))
16346 (org-at-heading-p))
16347 (org-todo 'up)
16348 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16350 (defun org-timestamp-down-day (&optional arg)
16351 "Decrease the date in the time stamp by one day.
16352 With prefix ARG, change that many days."
16353 (interactive "p")
16354 (if (and (not (org-at-timestamp-p t))
16355 (org-at-heading-p))
16356 (org-todo 'down)
16357 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16359 (defun org-at-timestamp-p (&optional inactive-ok)
16360 "Determine if the cursor is in or at a timestamp."
16361 (interactive)
16362 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16363 (pos (point))
16364 (ans (or (looking-at tsr)
16365 (save-excursion
16366 (skip-chars-backward "^[<\n\r\t")
16367 (if (> (point) (point-min)) (backward-char 1))
16368 (and (looking-at tsr)
16369 (> (- (match-end 0) pos) -1))))))
16370 (and ans
16371 (boundp 'org-ts-what)
16372 (setq org-ts-what
16373 (cond
16374 ((= pos (match-beginning 0)) 'bracket)
16375 ;; Point is considered to be "on the bracket" whether
16376 ;; it's really on it or right after it.
16377 ((= pos (1- (match-end 0))) 'bracket)
16378 ((= pos (match-end 0)) 'after)
16379 ((org-pos-in-match-range pos 2) 'year)
16380 ((org-pos-in-match-range pos 3) 'month)
16381 ((org-pos-in-match-range pos 7) 'hour)
16382 ((org-pos-in-match-range pos 8) 'minute)
16383 ((or (org-pos-in-match-range pos 4)
16384 (org-pos-in-match-range pos 5)) 'day)
16385 ((and (> pos (or (match-end 8) (match-end 5)))
16386 (< pos (match-end 0)))
16387 (- pos (or (match-end 8) (match-end 5))))
16388 (t 'day))))
16389 ans))
16391 (defun org-toggle-timestamp-type ()
16392 "Toggle the type (<active> or [inactive]) of a time stamp."
16393 (interactive)
16394 (when (org-at-timestamp-p t)
16395 (let ((beg (match-beginning 0)) (end (match-end 0))
16396 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16397 (save-excursion
16398 (goto-char beg)
16399 (while (re-search-forward "[][<>]" end t)
16400 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16401 t t)))
16402 (message "Timestamp is now %sactive"
16403 (if (equal (char-after beg) ?<) "" "in")))))
16405 (defvar org-clock-history) ; defined in org-clock.el
16406 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16407 (defun org-timestamp-change (n &optional what updown)
16408 "Change the date in the time stamp at point.
16409 The date will be changed by N times WHAT. WHAT can be `day', `month',
16410 `year', `minute', `second'. If WHAT is not given, the cursor position
16411 in the timestamp determines what will be changed."
16412 (let ((origin (point)) origin-cat
16413 with-hm inactive
16414 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16415 org-ts-what
16416 extra rem
16417 ts time time0 fixnext clrgx)
16418 (if (not (org-at-timestamp-p t))
16419 (error "Not at a timestamp"))
16420 (if (and (not what) (eq org-ts-what 'bracket))
16421 (org-toggle-timestamp-type)
16422 ;; Point isn't on brackets. Remember the part of the time-stamp
16423 ;; the point was in. Indeed, size of time-stamps may change,
16424 ;; but point must be kept in the same category nonetheless.
16425 (setq origin-cat org-ts-what)
16426 (if (and (not what) (not (eq org-ts-what 'day))
16427 org-display-custom-times
16428 (get-text-property (point) 'display)
16429 (not (get-text-property (1- (point)) 'display)))
16430 (setq org-ts-what 'day))
16431 (setq org-ts-what (or what org-ts-what)
16432 inactive (= (char-after (match-beginning 0)) ?\[)
16433 ts (match-string 0))
16434 (replace-match "")
16435 (if (string-match
16436 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16438 (setq extra (match-string 1 ts)))
16439 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16440 (setq with-hm t))
16441 (setq time0 (org-parse-time-string ts))
16442 (when (and updown
16443 (eq org-ts-what 'minute)
16444 (not current-prefix-arg))
16445 ;; This looks like s-up and s-down. Change by one rounding step.
16446 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16447 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16448 (setcar (cdr time0) (+ (nth 1 time0)
16449 (if (> n 0) (- rem) (- dm rem))))))
16450 (setq time
16451 (encode-time (or (car time0) 0)
16452 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16453 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16454 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16455 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16456 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16457 (nthcdr 6 time0)))
16458 (when (and (member org-ts-what '(hour minute))
16459 extra
16460 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16461 (setq extra (org-modify-ts-extra
16462 extra
16463 (if (eq org-ts-what 'hour) 2 5)
16464 n dm)))
16465 (when (integerp org-ts-what)
16466 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16467 (if (eq what 'calendar)
16468 (let ((cal-date (org-get-date-from-calendar)))
16469 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16470 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16471 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16472 (setcar time0 (or (car time0) 0))
16473 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16474 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16475 (setq time (apply 'encode-time time0))))
16476 ;; Insert the new time-stamp, and ensure point stays in the same
16477 ;; category as before (i.e. not after the last position in that
16478 ;; category).
16479 (let ((pos (point)))
16480 ;; Stay before inserted string. `save-excursion' is of no use.
16481 (setq org-last-changed-timestamp
16482 (org-insert-time-stamp time with-hm inactive nil nil extra))
16483 (goto-char pos))
16484 (save-match-data
16485 (looking-at org-ts-regexp3)
16486 (goto-char (cond
16487 ;; `day' category ends before `hour' if any, or at
16488 ;; the end of the day name.
16489 ((eq origin-cat 'day)
16490 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16491 ((eq origin-cat 'hour) (min (match-end 7) origin))
16492 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16493 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16494 ;; `year' and `month' have both fixed size: point
16495 ;; couldn't have moved into another part.
16496 (t origin))))
16497 ;; Update clock if on a CLOCK line.
16498 (org-clock-update-time-maybe)
16499 ;; Maybe adjust the closest clock in `org-clock-history'
16500 (when org-clock-adjust-closest
16501 (if (not (and (org-at-clock-log-p)
16502 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16503 org-clock-history))))))
16504 (message "No clock to adjust")
16505 (cond ((save-excursion ; fix previous clock?
16506 (re-search-backward org-ts-regexp0 nil t)
16507 (org-looking-back (concat org-clock-string " \\[")))
16508 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16509 ((save-excursion ; fix next clock?
16510 (re-search-backward org-ts-regexp0 nil t)
16511 (looking-at (concat org-ts-regexp0 "\\] =>")))
16512 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16513 (save-window-excursion
16514 ;; Find closest clock to point, adjust the previous/next one in history
16515 (let* ((p (save-excursion (org-back-to-heading t)))
16516 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16517 (clfixnth
16518 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16519 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16520 (if (not clfixpos)
16521 (message "No clock to adjust")
16522 (save-excursion
16523 (org-goto-marker-or-bmk clfixpos)
16524 (org-show-subtree)
16525 (when (re-search-forward clrgx nil t)
16526 (goto-char (match-beginning 1))
16527 (let (org-clock-adjust-closest)
16528 (org-timestamp-change n org-ts-what updown))
16529 (message "Clock adjusted in %s for heading: %s"
16530 (file-name-nondirectory (buffer-file-name))
16531 (org-get-heading t t)))))))))
16532 ;; Try to recenter the calendar window, if any.
16533 (if (and org-calendar-follow-timestamp-change
16534 (get-buffer-window "*Calendar*" t)
16535 (memq org-ts-what '(day month year)))
16536 (org-recenter-calendar (time-to-days time))))))
16538 (defun org-modify-ts-extra (s pos n dm)
16539 "Change the different parts of the lead-time and repeat fields in timestamp."
16540 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16541 ng h m new rem)
16542 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16543 (cond
16544 ((or (org-pos-in-match-range pos 2)
16545 (org-pos-in-match-range pos 3))
16546 (setq m (string-to-number (match-string 3 s))
16547 h (string-to-number (match-string 2 s)))
16548 (if (org-pos-in-match-range pos 2)
16549 (setq h (+ h n))
16550 (setq n (* dm (org-no-warnings (signum n))))
16551 (when (not (= 0 (setq rem (% m dm))))
16552 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16553 (setq m (+ m n)))
16554 (if (< m 0) (setq m (+ m 60) h (1- h)))
16555 (if (> m 59) (setq m (- m 60) h (1+ h)))
16556 (setq h (min 24 (max 0 h)))
16557 (setq ng 1 new (format "-%02d:%02d" h m)))
16558 ((org-pos-in-match-range pos 6)
16559 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16560 ((org-pos-in-match-range pos 5)
16561 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16563 ((org-pos-in-match-range pos 9)
16564 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16565 ((org-pos-in-match-range pos 8)
16566 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16568 (when ng
16569 (setq s (concat
16570 (substring s 0 (match-beginning ng))
16572 (substring s (match-end ng))))))
16575 (defun org-recenter-calendar (date)
16576 "If the calendar is visible, recenter it to DATE."
16577 (let ((cwin (get-buffer-window "*Calendar*" t)))
16578 (when cwin
16579 (let ((calendar-move-hook nil))
16580 (with-selected-window cwin
16581 (calendar-goto-date (if (listp date) date
16582 (calendar-gregorian-from-absolute date))))))))
16584 (defun org-goto-calendar (&optional arg)
16585 "Go to the Emacs calendar at the current date.
16586 If there is a time stamp in the current line, go to that date.
16587 A prefix ARG can be used to force the current date."
16588 (interactive "P")
16589 (let ((tsr org-ts-regexp) diff
16590 (calendar-move-hook nil)
16591 (calendar-view-holidays-initially-flag nil)
16592 (calendar-view-diary-initially-flag nil))
16593 (if (or (org-at-timestamp-p)
16594 (save-excursion
16595 (beginning-of-line 1)
16596 (looking-at (concat ".*" tsr))))
16597 (let ((d1 (time-to-days (current-time)))
16598 (d2 (time-to-days
16599 (org-time-string-to-time (match-string 1)))))
16600 (setq diff (- d2 d1))))
16601 (calendar)
16602 (calendar-goto-today)
16603 (if (and diff (not arg)) (calendar-forward-day diff))))
16605 (defun org-get-date-from-calendar ()
16606 "Return a list (month day year) of date at point in calendar."
16607 (with-current-buffer "*Calendar*"
16608 (save-match-data
16609 (calendar-cursor-to-date))))
16611 (defun org-date-from-calendar ()
16612 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16613 If there is already a time stamp at the cursor position, update it."
16614 (interactive)
16615 (if (org-at-timestamp-p t)
16616 (org-timestamp-change 0 'calendar)
16617 (let ((cal-date (org-get-date-from-calendar)))
16618 (org-insert-time-stamp
16619 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16621 (defun org-minutes-to-hh:mm-string (m)
16622 "Compute H:MM from a number of minutes."
16623 (let ((h (/ m 60)))
16624 (setq m (- m (* 60 h)))
16625 (format org-time-clocksum-format h m)))
16627 (defun org-hh:mm-string-to-minutes (s)
16628 "Convert a string H:MM to a number of minutes.
16629 If the string is just a number, interpret it as minutes.
16630 In fact, the first hh:mm or number in the string will be taken,
16631 there can be extra stuff in the string.
16632 If no number is found, the return value is 0."
16633 (cond
16634 ((integerp s) s)
16635 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16636 (+ (* (string-to-number (match-string 1 s)) 60)
16637 (string-to-number (match-string 2 s))))
16638 ((string-match "\\([0-9]+\\)" s)
16639 (string-to-number (match-string 1 s)))
16640 (t 0)))
16642 (defcustom org-effort-durations
16643 `(("h" . 60)
16644 ("d" . ,(* 60 8))
16645 ("w" . ,(* 60 8 5))
16646 ("m" . ,(* 60 8 5 4))
16647 ("y" . ,(* 60 8 5 40)))
16648 "Conversion factor to minutes for an effort modifier.
16650 Each entry has the form (MODIFIER . MINUTES).
16652 In an effort string, a number followed by MODIFIER is multiplied
16653 by the specified number of MINUTES to obtain an effort in
16654 minutes.
16656 For example, if the value of this variable is ((\"hours\" . 60)), then an
16657 effort string \"2hours\" is equivalent to 120 minutes."
16658 :group 'org-agenda
16659 :version "24.1"
16660 :type '(alist :key-type (string :tag "Modifier")
16661 :value-type (number :tag "Minutes")))
16663 (defcustom org-image-actual-width t
16664 "Should we use the actual width of images when inlining them?
16666 When set to `t', always use the image width.
16668 When set to a number, use imagemagick (when available) to set
16669 the image's width to this value.
16671 When set to a number in a list, try to get the width from the
16672 #+ATTR.* keyword if it matches a width specification like
16673 width=\"[0-9]+\", and fall back on that number if none is found.
16675 When set to nil, try to get the width from an #+ATTR.* keyword
16676 and fall back on the original width if none is found.
16678 This requires Emacs >= 24.1, build with imagemagick support."
16679 :group 'org-appearance
16680 :version "24.3"
16681 :type '(choice
16682 (const :tag "Use the image width" t)
16683 (integer :tag "Use a number of pixels")
16684 (list :tag "Use #+ATTR* or a number of pixels" (integer))
16685 (const :tag "Use #+ATTR* or don't resize" nil)))
16687 (defun org-duration-string-to-minutes (s &optional output-to-string)
16688 "Convert a duration string S to minutes.
16690 A bare number is interpreted as minutes, modifiers can be set by
16691 customizing `org-effort-durations' (which see).
16693 Entries containing a colon are interpreted as H:MM by
16694 `org-hh:mm-string-to-minutes'."
16695 (let ((result 0)
16696 (re (concat "\\([0-9.]+\\) *\\("
16697 (regexp-opt (mapcar 'car org-effort-durations))
16698 "\\)")))
16699 (while (string-match re s)
16700 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16701 (string-to-number (match-string 1 s))))
16702 (setq s (replace-match "" nil t s)))
16703 (setq result (floor result))
16704 (incf result (org-hh:mm-string-to-minutes s))
16705 (if output-to-string (number-to-string result) result)))
16707 ;;;; Files
16709 (defun org-save-all-org-buffers ()
16710 "Save all Org-mode buffers without user confirmation."
16711 (interactive)
16712 (message "Saving all Org-mode buffers...")
16713 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16714 (when (featurep 'org-id) (org-id-locations-save))
16715 (message "Saving all Org-mode buffers... done"))
16717 (defun org-revert-all-org-buffers ()
16718 "Revert all Org-mode buffers.
16719 Prompt for confirmation when there are unsaved changes.
16720 Be sure you know what you are doing before letting this function
16721 overwrite your changes.
16723 This function is useful in a setup where one tracks org files
16724 with a version control system, to revert on one machine after pulling
16725 changes from another. I believe the procedure must be like this:
16727 1. M-x org-save-all-org-buffers
16728 2. Pull changes from the other machine, resolve conflicts
16729 3. M-x org-revert-all-org-buffers"
16730 (interactive)
16731 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16732 (error "Abort"))
16733 (save-excursion
16734 (save-window-excursion
16735 (mapc
16736 (lambda (b)
16737 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16738 (with-current-buffer b buffer-file-name))
16739 (org-pop-to-buffer-same-window b)
16740 (revert-buffer t 'no-confirm)))
16741 (buffer-list))
16742 (when (and (featurep 'org-id) org-id-track-globally)
16743 (org-id-locations-load)))))
16745 ;;;; Agenda files
16747 ;;;###autoload
16748 (defun org-switchb (&optional arg)
16749 "Switch between Org buffers.
16750 With one prefix argument, restrict available buffers to files.
16751 With two prefix arguments, restrict available buffers to agenda files.
16753 Defaults to `iswitchb' for buffer name completion.
16754 Set `org-completion-use-ido' to make it use ido instead."
16755 (interactive "P")
16756 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16757 ((equal arg '(16)) (org-buffer-list 'agenda))
16758 (t (org-buffer-list))))
16759 (org-completion-use-iswitchb org-completion-use-iswitchb)
16760 (org-completion-use-ido org-completion-use-ido))
16761 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16762 (setq org-completion-use-iswitchb t))
16763 (org-pop-to-buffer-same-window
16764 (org-icompleting-read "Org buffer: "
16765 (mapcar 'list (mapcar 'buffer-name blist))
16766 nil t))))
16768 ;;; Define some older names previously used for this functionality
16769 ;;;###autoload
16770 (defalias 'org-ido-switchb 'org-switchb)
16771 ;;;###autoload
16772 (defalias 'org-iswitchb 'org-switchb)
16774 (defun org-buffer-list (&optional predicate exclude-tmp)
16775 "Return a list of Org buffers.
16776 PREDICATE can be `export', `files' or `agenda'.
16778 export restrict the list to Export buffers.
16779 files restrict the list to buffers visiting Org files.
16780 agenda restrict the list to buffers visiting agenda files.
16782 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16783 (let* ((bfn nil)
16784 (agenda-files (and (eq predicate 'agenda)
16785 (mapcar 'file-truename (org-agenda-files t))))
16786 (filter
16787 (cond
16788 ((eq predicate 'files)
16789 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16790 ((eq predicate 'export)
16791 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16792 ((eq predicate 'agenda)
16793 (lambda (b)
16794 (with-current-buffer b
16795 (and (derived-mode-p 'org-mode)
16796 (setq bfn (buffer-file-name b))
16797 (member (file-truename bfn) agenda-files)))))
16798 (t (lambda (b) (with-current-buffer b
16799 (or (derived-mode-p 'org-mode)
16800 (string-match "\*Org .*Export"
16801 (buffer-name b)))))))))
16802 (delq nil
16803 (mapcar
16804 (lambda(b)
16805 (if (and (funcall filter b)
16806 (or (not exclude-tmp)
16807 (not (string-match "tmp" (buffer-name b)))))
16809 nil))
16810 (buffer-list)))))
16812 (defun org-agenda-files (&optional unrestricted archives)
16813 "Get the list of agenda files.
16814 Optional UNRESTRICTED means return the full list even if a restriction
16815 is currently in place.
16816 When ARCHIVES is t, include all archive files that are really being
16817 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16818 `org-agenda-archives-mode' is t."
16819 (let ((files
16820 (cond
16821 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16822 ((stringp org-agenda-files) (org-read-agenda-file-list))
16823 ((listp org-agenda-files) org-agenda-files)
16824 (t (error "Invalid value of `org-agenda-files'")))))
16825 (setq files (apply 'append
16826 (mapcar (lambda (f)
16827 (if (file-directory-p f)
16828 (directory-files
16829 f t org-agenda-file-regexp)
16830 (list f)))
16831 files)))
16832 (when org-agenda-skip-unavailable-files
16833 (setq files (delq nil
16834 (mapcar (function
16835 (lambda (file)
16836 (and (file-readable-p file) file)))
16837 files))))
16838 (when (or (eq archives t)
16839 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16840 (setq files (org-add-archive-files files)))
16841 files))
16843 (defun org-agenda-file-p (&optional file)
16844 "Return non-nil, if FILE is an agenda file.
16845 If FILE is omitted, use the file associated with the current
16846 buffer."
16847 (member (or file (buffer-file-name))
16848 (org-agenda-files t)))
16850 (defun org-edit-agenda-file-list ()
16851 "Edit the list of agenda files.
16852 Depending on setup, this either uses customize to edit the variable
16853 `org-agenda-files', or it visits the file that is holding the list. In the
16854 latter case, the buffer is set up in a way that saving it automatically kills
16855 the buffer and restores the previous window configuration."
16856 (interactive)
16857 (if (stringp org-agenda-files)
16858 (let ((cw (current-window-configuration)))
16859 (find-file org-agenda-files)
16860 (org-set-local 'org-window-configuration cw)
16861 (org-add-hook 'after-save-hook
16862 (lambda ()
16863 (set-window-configuration
16864 (prog1 org-window-configuration
16865 (kill-buffer (current-buffer))))
16866 (org-install-agenda-files-menu)
16867 (message "New agenda file list installed"))
16868 nil 'local)
16869 (message "%s" (substitute-command-keys
16870 "Edit list and finish with \\[save-buffer]")))
16871 (customize-variable 'org-agenda-files)))
16873 (defun org-store-new-agenda-file-list (list)
16874 "Set new value for the agenda file list and save it correctly."
16875 (if (stringp org-agenda-files)
16876 (let ((fe (org-read-agenda-file-list t)) b u)
16877 (while (setq b (find-buffer-visiting org-agenda-files))
16878 (kill-buffer b))
16879 (with-temp-file org-agenda-files
16880 (insert
16881 (mapconcat
16882 (lambda (f) ;; Keep un-expanded entries.
16883 (if (setq u (assoc f fe))
16884 (cdr u)
16886 list "\n")
16887 "\n")))
16888 (let ((org-mode-hook nil) (org-inhibit-startup t)
16889 (org-insert-mode-line-in-empty-file nil))
16890 (setq org-agenda-files list)
16891 (customize-save-variable 'org-agenda-files org-agenda-files))))
16893 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16894 "Read the list of agenda files from a file.
16895 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16896 filenames, used by `org-store-new-agenda-file-list' to write back
16897 un-expanded file names."
16898 (when (file-directory-p org-agenda-files)
16899 (error "`org-agenda-files' cannot be a single directory"))
16900 (when (stringp org-agenda-files)
16901 (with-temp-buffer
16902 (insert-file-contents org-agenda-files)
16903 (mapcar
16904 (lambda (f)
16905 (let ((e (expand-file-name (substitute-in-file-name f)
16906 org-directory)))
16907 (if pair-with-expansion
16908 (cons e f)
16909 e)))
16910 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16912 ;;;###autoload
16913 (defun org-cycle-agenda-files ()
16914 "Cycle through the files in `org-agenda-files'.
16915 If the current buffer visits an agenda file, find the next one in the list.
16916 If the current buffer does not, find the first agenda file."
16917 (interactive)
16918 (let* ((fs (org-agenda-files t))
16919 (files (append fs (list (car fs))))
16920 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16921 file)
16922 (unless files (error "No agenda files"))
16923 (catch 'exit
16924 (while (setq file (pop files))
16925 (if (equal (file-truename file) tcf)
16926 (when (car files)
16927 (find-file (car files))
16928 (throw 'exit t))))
16929 (find-file (car fs)))
16930 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16932 (defun org-agenda-file-to-front (&optional to-end)
16933 "Move/add the current file to the top of the agenda file list.
16934 If the file is not present in the list, it is added to the front. If it is
16935 present, it is moved there. With optional argument TO-END, add/move to the
16936 end of the list."
16937 (interactive "P")
16938 (let ((org-agenda-skip-unavailable-files nil)
16939 (file-alist (mapcar (lambda (x)
16940 (cons (file-truename x) x))
16941 (org-agenda-files t)))
16942 (ctf (file-truename buffer-file-name))
16943 x had)
16944 (setq x (assoc ctf file-alist) had x)
16946 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16947 (if to-end
16948 (setq file-alist (append (delq x file-alist) (list x)))
16949 (setq file-alist (cons x (delq x file-alist))))
16950 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16951 (org-install-agenda-files-menu)
16952 (message "File %s to %s of agenda file list"
16953 (if had "moved" "added") (if to-end "end" "front"))))
16955 (defun org-remove-file (&optional file)
16956 "Remove current file from the list of files in variable `org-agenda-files'.
16957 These are the files which are being checked for agenda entries.
16958 Optional argument FILE means use this file instead of the current."
16959 (interactive)
16960 (let* ((org-agenda-skip-unavailable-files nil)
16961 (file (or file buffer-file-name))
16962 (true-file (file-truename file))
16963 (afile (abbreviate-file-name file))
16964 (files (delq nil (mapcar
16965 (lambda (x)
16966 (if (equal true-file
16967 (file-truename x))
16968 nil x))
16969 (org-agenda-files t)))))
16970 (if (not (= (length files) (length (org-agenda-files t))))
16971 (progn
16972 (org-store-new-agenda-file-list files)
16973 (org-install-agenda-files-menu)
16974 (message "Removed file: %s" afile))
16975 (message "File was not in list: %s (not removed)" afile))))
16977 (defun org-file-menu-entry (file)
16978 (vector file (list 'find-file file) t))
16980 (defun org-check-agenda-file (file)
16981 "Make sure FILE exists. If not, ask user what to do."
16982 (when (not (file-exists-p file))
16983 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16984 (abbreviate-file-name file))
16985 (let ((r (downcase (read-char-exclusive))))
16986 (cond
16987 ((equal r ?r)
16988 (org-remove-file file)
16989 (throw 'nextfile t))
16990 (t (error "Abort"))))))
16992 (defun org-get-agenda-file-buffer (file)
16993 "Get a buffer visiting FILE. If the buffer needs to be created, add
16994 it to the list of buffers which might be released later."
16995 (let ((buf (org-find-base-buffer-visiting file)))
16996 (if buf
16997 buf ; just return it
16998 ;; Make a new buffer and remember it
16999 (setq buf (find-file-noselect file))
17000 (if buf (push buf org-agenda-new-buffers))
17001 buf)))
17003 (defun org-release-buffers (blist)
17004 "Release all buffers in list, asking the user for confirmation when needed.
17005 When a buffer is unmodified, it is just killed. When modified, it is saved
17006 \(if the user agrees) and then killed."
17007 (let (buf file)
17008 (while (setq buf (pop blist))
17009 (setq file (buffer-file-name buf))
17010 (when (and (buffer-modified-p buf)
17011 file
17012 (y-or-n-p (format "Save file %s? " file)))
17013 (with-current-buffer buf (save-buffer)))
17014 (kill-buffer buf))))
17016 (defun org-agenda-prepare-buffers (files)
17017 "Create buffers for all agenda files, protect archived trees and comments."
17018 (interactive)
17019 (let ((pa '(:org-archived t))
17020 (pc '(:org-comment t))
17021 (pall '(:org-archived t :org-comment t))
17022 (inhibit-read-only t)
17023 (rea (concat ":" org-archive-tag ":"))
17024 bmp file re)
17025 (save-excursion
17026 (save-restriction
17027 (while (setq file (pop files))
17028 (catch 'nextfile
17029 (if (bufferp file)
17030 (set-buffer file)
17031 (org-check-agenda-file file)
17032 (set-buffer (org-get-agenda-file-buffer file)))
17033 (widen)
17034 (setq bmp (buffer-modified-p))
17035 (org-refresh-category-properties)
17036 (setq org-todo-keywords-for-agenda
17037 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17038 (setq org-done-keywords-for-agenda
17039 (append org-done-keywords-for-agenda org-done-keywords))
17040 (setq org-todo-keyword-alist-for-agenda
17041 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17042 (setq org-drawers-for-agenda
17043 (append org-drawers-for-agenda org-drawers))
17044 (setq org-tag-alist-for-agenda
17045 (append org-tag-alist-for-agenda org-tag-alist))
17047 (save-excursion
17048 (remove-text-properties (point-min) (point-max) pall)
17049 (when org-agenda-skip-archived-trees
17050 (goto-char (point-min))
17051 (while (re-search-forward rea nil t)
17052 (if (org-at-heading-p t)
17053 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17054 (goto-char (point-min))
17055 (setq re (format org-heading-keyword-regexp-format
17056 org-comment-string))
17057 (while (re-search-forward re nil t)
17058 (add-text-properties
17059 (match-beginning 0) (org-end-of-subtree t) pc)))
17060 (set-buffer-modified-p bmp)))))
17061 (setq org-todo-keywords-for-agenda
17062 (org-uniquify org-todo-keywords-for-agenda))
17063 (setq org-todo-keyword-alist-for-agenda
17064 (org-uniquify org-todo-keyword-alist-for-agenda)
17065 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17067 ;;;; Embedded LaTeX
17069 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17070 "Keymap for the minor `org-cdlatex-mode'.")
17072 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17073 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17074 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17075 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17076 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17078 (defvar org-cdlatex-texmathp-advice-is-done nil
17079 "Flag remembering if we have applied the advice to texmathp already.")
17081 (define-minor-mode org-cdlatex-mode
17082 "Toggle the minor `org-cdlatex-mode'.
17083 This mode supports entering LaTeX environment and math in LaTeX fragments
17084 in Org-mode.
17085 \\{org-cdlatex-mode-map}"
17086 nil " OCDL" nil
17087 (when org-cdlatex-mode
17088 (require 'cdlatex)
17089 (run-hooks 'cdlatex-mode-hook)
17090 (cdlatex-compute-tables))
17091 (unless org-cdlatex-texmathp-advice-is-done
17092 (setq org-cdlatex-texmathp-advice-is-done t)
17093 (defadvice texmathp (around org-math-always-on activate)
17094 "Always return t in org-mode buffers.
17095 This is because we want to insert math symbols without dollars even outside
17096 the LaTeX math segments. If Orgmode thinks that point is actually inside
17097 an embedded LaTeX fragment, let texmathp do its job.
17098 \\[org-cdlatex-mode-map]"
17099 (interactive)
17100 (let (p)
17101 (cond
17102 ((not (derived-mode-p 'org-mode)) ad-do-it)
17103 ((eq this-command 'cdlatex-math-symbol)
17104 (setq ad-return-value t
17105 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17107 (let ((p (org-inside-LaTeX-fragment-p)))
17108 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17109 (setq ad-return-value t
17110 texmathp-why '("Org-mode embedded math" . 0))
17111 (if p ad-do-it)))))))))
17113 (defun turn-on-org-cdlatex ()
17114 "Unconditionally turn on `org-cdlatex-mode'."
17115 (org-cdlatex-mode 1))
17117 (defun org-inside-LaTeX-fragment-p ()
17118 "Test if point is inside a LaTeX fragment.
17119 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17120 sequence appearing also before point.
17121 Even though the matchers for math are configurable, this function assumes
17122 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17123 delimiters are skipped when they have been removed by customization.
17124 The return value is nil, or a cons cell with the delimiter and the
17125 position of this delimiter.
17127 This function does a reasonably good job, but can locally be fooled by
17128 for example currency specifications. For example it will assume being in
17129 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17130 fragments that are properly closed, but during editing, we have to live
17131 with the uncertainty caused by missing closing delimiters. This function
17132 looks only before point, not after."
17133 (catch 'exit
17134 (let ((pos (point))
17135 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17136 (lim (progn
17137 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17138 (point)))
17139 dd-on str (start 0) m re)
17140 (goto-char pos)
17141 (when dodollar
17142 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17143 re (nth 1 (assoc "$" org-latex-regexps)))
17144 (while (string-match re str start)
17145 (cond
17146 ((= (match-end 0) (length str))
17147 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17148 ((= (match-end 0) (- (length str) 5))
17149 (throw 'exit nil))
17150 (t (setq start (match-end 0))))))
17151 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17152 (goto-char pos)
17153 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17154 (and (match-beginning 2) (throw 'exit nil))
17155 ;; count $$
17156 (while (re-search-backward "\\$\\$" lim t)
17157 (setq dd-on (not dd-on)))
17158 (goto-char pos)
17159 (if dd-on (cons "$$" m))))))
17161 (defun org-inside-latex-macro-p ()
17162 "Is point inside a LaTeX macro or its arguments?"
17163 (save-match-data
17164 (org-in-regexp
17165 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17167 (defun org-try-cdlatex-tab ()
17168 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17169 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17170 - inside a LaTeX fragment, or
17171 - after the first word in a line, where an abbreviation expansion could
17172 insert a LaTeX environment."
17173 (when org-cdlatex-mode
17174 (cond
17175 ;; Before any word on the line: No expansion possible.
17176 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17177 ;; Just after first word on the line: Expand it. Make sure it
17178 ;; cannot happen on headlines, though.
17179 ((save-excursion
17180 (skip-chars-backward "a-zA-Z0-9*")
17181 (skip-chars-backward " \t")
17182 (and (bolp) (not (org-at-heading-p))))
17183 (cdlatex-tab) t)
17184 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17186 (defun org-cdlatex-underscore-caret (&optional arg)
17187 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17188 Revert to the normal definition outside of these fragments."
17189 (interactive "P")
17190 (if (org-inside-LaTeX-fragment-p)
17191 (call-interactively 'cdlatex-sub-superscript)
17192 (let (org-cdlatex-mode)
17193 (call-interactively (key-binding (vector last-input-event))))))
17195 (defun org-cdlatex-math-modify (&optional arg)
17196 "Execute `cdlatex-math-modify' in LaTeX fragments.
17197 Revert to the normal definition outside of these fragments."
17198 (interactive "P")
17199 (if (org-inside-LaTeX-fragment-p)
17200 (call-interactively 'cdlatex-math-modify)
17201 (let (org-cdlatex-mode)
17202 (call-interactively (key-binding (vector last-input-event))))))
17204 (defvar org-latex-fragment-image-overlays nil
17205 "List of overlays carrying the images of latex fragments.")
17206 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17208 (defun org-remove-latex-fragment-image-overlays ()
17209 "Remove all overlays with LaTeX fragment images in current buffer."
17210 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17211 (setq org-latex-fragment-image-overlays nil))
17213 (defun org-preview-latex-fragment (&optional subtree)
17214 "Preview the LaTeX fragment at point, or all locally or globally.
17215 If the cursor is in a LaTeX fragment, create the image and overlay
17216 it over the source code. If there is no fragment at point, display
17217 all fragments in the current text, from one headline to the next. With
17218 prefix SUBTREE, display all fragments in the current subtree. With a
17219 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17220 the cursor is before the first headline,
17221 display all fragments in the buffer.
17222 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17223 (interactive "P")
17224 (unless buffer-file-name
17225 (error "Can't preview LaTeX fragment in a non-file buffer"))
17226 (org-remove-latex-fragment-image-overlays)
17227 (save-excursion
17228 (save-restriction
17229 (let (beg end at msg)
17230 (cond
17231 ((or (equal subtree '(16))
17232 (not (save-excursion
17233 (re-search-backward org-outline-regexp-bol nil t))))
17234 (setq beg (point-min) end (point-max)
17235 msg "Creating images for buffer...%s"))
17236 ((equal subtree '(4))
17237 (org-back-to-heading)
17238 (setq beg (point) end (org-end-of-subtree t)
17239 msg "Creating images for subtree...%s"))
17241 (if (setq at (org-inside-LaTeX-fragment-p))
17242 (goto-char (max (point-min) (- (cdr at) 2)))
17243 (org-back-to-heading))
17244 (setq beg (point) end (progn (outline-next-heading) (point))
17245 msg (if at "Creating image...%s"
17246 "Creating images for entry...%s"))))
17247 (message msg "")
17248 (narrow-to-region beg end)
17249 (goto-char beg)
17250 (org-format-latex
17251 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17252 (file-name-nondirectory
17253 buffer-file-name)))
17254 default-directory 'overlays msg at 'forbuffer
17255 org-latex-create-formula-image-program)
17256 (message msg "done. Use `C-c C-c' to remove images.")))))
17258 (defvar org-latex-regexps
17259 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17260 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17261 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17262 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17263 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17264 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17265 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17266 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17267 "Regular expressions for matching embedded LaTeX.")
17269 (defvar org-export-have-math nil) ;; dynamic scoping
17270 (defun org-format-latex (prefix &optional dir overlays msg at
17271 forbuffer processing-type)
17272 "Replace LaTeX fragments with links to an image, and produce images.
17273 Some of the options can be changed using the variable
17274 `org-format-latex-options'."
17275 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17276 (let* ((prefixnodir (file-name-nondirectory prefix))
17277 (absprefix (expand-file-name prefix dir))
17278 (todir (file-name-directory absprefix))
17279 (opt org-format-latex-options)
17280 (optnew org-format-latex-options)
17281 (matchers (plist-get opt :matchers))
17282 (re-list org-latex-regexps)
17283 (org-format-latex-header-extra
17284 (plist-get (org-infile-export-plist) :latex-header-extra))
17285 (cnt 0) txt hash link beg end re e checkdir
17286 string
17287 m n block-type block linkfile movefile ov)
17288 ;; Check the different regular expressions
17289 (while (setq e (pop re-list))
17290 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17291 block (if block-type "\n\n" ""))
17292 (when (member m matchers)
17293 (goto-char (point-min))
17294 (while (re-search-forward re nil t)
17295 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17296 (not (get-text-property (match-beginning n)
17297 'org-protected))
17298 (or (not overlays)
17299 (not (eq (get-char-property (match-beginning n)
17300 'org-overlay-type)
17301 'org-latex-overlay))))
17302 (setq org-export-have-math t)
17303 (cond
17304 ((eq processing-type 'verbatim)
17305 ;; Leave the text verbatim, just protect it
17306 (add-text-properties (match-beginning n) (match-end n)
17307 '(org-protected t)))
17308 ((eq processing-type 'mathjax)
17309 ;; Prepare for MathJax processing
17310 (setq string (match-string n))
17311 (if (member m '("$" "$1"))
17312 (save-excursion
17313 (delete-region (match-beginning n) (match-end n))
17314 (goto-char (match-beginning n))
17315 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17316 "\\)")
17317 '(org-protected t))))
17318 (add-text-properties (match-beginning n) (match-end n)
17319 '(org-protected t))))
17320 ((or (eq processing-type 'dvipng)
17321 (eq processing-type 'imagemagick))
17322 ;; Process to an image
17323 (setq txt (match-string n)
17324 beg (match-beginning n) end (match-end n)
17325 cnt (1+ cnt))
17326 (let ((face (face-at-point))
17327 (fg (plist-get opt :foreground))
17328 (bg (plist-get opt :background))
17329 print-length print-level) ; make sure full list is printed
17330 (when forbuffer
17331 ; Get the colors from the face at point
17332 (goto-char beg)
17333 (when (eq fg 'auto)
17334 (setq fg (face-attribute face :foreground nil 'default)))
17335 (when (eq bg 'auto)
17336 (setq bg (face-attribute face :background nil 'default)))
17337 (setq optnew (copy-sequence opt))
17338 (plist-put optnew :foreground fg)
17339 (plist-put optnew :background bg))
17340 (setq hash (sha1 (prin1-to-string
17341 (list org-format-latex-header
17342 org-format-latex-header-extra
17343 org-export-latex-default-packages-alist
17344 org-export-latex-packages-alist
17345 org-format-latex-options
17346 forbuffer txt fg bg)))
17347 linkfile (format "%s_%s.png" prefix hash)
17348 movefile (format "%s_%s.png" absprefix hash)))
17349 (setq link (concat block "[[file:" linkfile "]]" block))
17350 (if msg (message msg cnt))
17351 (goto-char beg)
17352 (unless checkdir ; make sure the directory exists
17353 (setq checkdir t)
17354 (or (file-directory-p todir) (make-directory todir t)))
17355 (org-create-formula-image
17356 txt movefile optnew forbuffer processing-type)
17357 (if overlays
17358 (progn
17359 (mapc (lambda (o)
17360 (if (eq (overlay-get o 'org-overlay-type)
17361 'org-latex-overlay)
17362 (delete-overlay o)))
17363 (overlays-in beg end))
17364 (setq ov (make-overlay beg end))
17365 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17366 (if (featurep 'xemacs)
17367 (progn
17368 (overlay-put ov 'invisible t)
17369 (overlay-put
17370 ov 'end-glyph
17371 (make-glyph (vector 'png :file movefile))))
17372 (overlay-put
17373 ov 'display
17374 (list 'image :type 'png :file movefile :ascent 'center)))
17375 (push ov org-latex-fragment-image-overlays)
17376 (goto-char end))
17377 (delete-region beg end)
17378 (insert (org-add-props link
17379 (list 'org-latex-src
17380 (replace-regexp-in-string
17381 "\"" "" txt)
17382 'org-latex-src-embed-type
17383 (if block-type 'paragraph 'character))))))
17384 ((eq processing-type 'mathml)
17385 ;; Process to MathML
17386 (unless (save-match-data (org-format-latex-mathml-available-p))
17387 (error "LaTeX to MathML converter not configured"))
17388 (setq txt (match-string n)
17389 beg (match-beginning n) end (match-end n)
17390 cnt (1+ cnt))
17391 (if msg (message msg cnt))
17392 (goto-char beg)
17393 (delete-region beg end)
17394 (insert (org-format-latex-as-mathml
17395 txt block-type prefix dir)))
17397 (error "Unknown conversion type %s for latex fragments"
17398 processing-type)))))))))
17400 (defun org-create-math-formula (latex-frag &optional mathml-file)
17401 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17402 Use `org-latex-to-mathml-convert-command'. If the conversion is
17403 sucessful, return the portion between \"<math...> </math>\"
17404 elements otherwise return nil. When MATHML-FILE is specified,
17405 write the results in to that file. When invoked as an
17406 interactive command, prompt for LATEX-FRAG, with initial value
17407 set to the current active region and echo the results for user
17408 inspection."
17409 (interactive (list (let ((frag (when (org-region-active-p)
17410 (buffer-substring-no-properties
17411 (region-beginning) (region-end)))))
17412 (read-string "LaTeX Fragment: " frag nil frag))))
17413 (unless latex-frag (error "Invalid latex-frag"))
17414 (let* ((tmp-in-file (file-relative-name
17415 (make-temp-name (expand-file-name "ltxmathml-in"))))
17416 (ignore (write-region latex-frag nil tmp-in-file))
17417 (tmp-out-file (file-relative-name
17418 (make-temp-name (expand-file-name "ltxmathml-out"))))
17419 (cmd (format-spec
17420 org-latex-to-mathml-convert-command
17421 `((?j . ,(shell-quote-argument
17422 (expand-file-name org-latex-to-mathml-jar-file)))
17423 (?I . ,(shell-quote-argument tmp-in-file))
17424 (?o . ,(shell-quote-argument tmp-out-file)))))
17425 mathml shell-command-output)
17426 (when (org-called-interactively-p 'any)
17427 (unless (org-format-latex-mathml-available-p)
17428 (error "LaTeX to MathML converter not configured")))
17429 (message "Running %s" cmd)
17430 (setq shell-command-output (shell-command-to-string cmd))
17431 (setq mathml
17432 (when (file-readable-p tmp-out-file)
17433 (with-current-buffer (find-file-noselect tmp-out-file t)
17434 (goto-char (point-min))
17435 (when (re-search-forward
17436 (concat
17437 (regexp-quote
17438 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17439 "\\(.\\|\n\\)*"
17440 (regexp-quote "</math>")) nil t)
17441 (prog1 (match-string 0) (kill-buffer))))))
17442 (cond
17443 (mathml
17444 (setq mathml
17445 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17446 (when mathml-file
17447 (write-region mathml nil mathml-file))
17448 (when (org-called-interactively-p 'any)
17449 (message mathml)))
17450 ((message "LaTeX to MathML conversion failed")
17451 (message shell-command-output)))
17452 (delete-file tmp-in-file)
17453 (when (file-exists-p tmp-out-file)
17454 (delete-file tmp-out-file))
17455 mathml))
17457 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17458 prefix &optional dir)
17459 "Use `org-create-math-formula' but check local cache first."
17460 (let* ((absprefix (expand-file-name prefix dir))
17461 (print-length nil) (print-level nil)
17462 (formula-id (concat
17463 "formula-"
17464 (sha1
17465 (prin1-to-string
17466 (list latex-frag
17467 org-latex-to-mathml-convert-command)))))
17468 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17469 (formula-cache-dir (file-name-directory formula-cache)))
17471 (unless (file-directory-p formula-cache-dir)
17472 (make-directory formula-cache-dir t))
17474 (unless (file-exists-p formula-cache)
17475 (org-create-math-formula latex-frag formula-cache))
17477 (if (file-exists-p formula-cache)
17478 ;; Successful conversion. Return the link to MathML file.
17479 (org-add-props
17480 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17481 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17482 'org-latex-src-embed-type (if latex-frag-type
17483 'paragraph 'character)))
17484 ;; Failed conversion. Return the LaTeX fragment verbatim
17485 (add-text-properties
17486 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17487 latex-frag)))
17489 (defun org-create-formula-image (string tofile options buffer &optional type)
17490 "Create an image from LaTeX source using dvipng or convert.
17491 This function calls either `org-create-formula-image-with-dvipng'
17492 or `org-create-formula-image-with-imagemagick' depending on the
17493 value of `org-latex-create-formula-image-program' or on the value
17494 of the optional TYPE variable.
17496 Note: ultimately these two function should be combined as they
17497 share a good deal of logic."
17498 (org-check-external-command
17499 "latex" "needed to convert LaTeX fragments to images")
17500 (funcall
17501 (case (or type org-latex-create-formula-image-program)
17502 ('dvipng
17503 (org-check-external-command
17504 "dvipng" "needed to convert LaTeX fragments to images")
17505 #'org-create-formula-image-with-dvipng)
17506 ('imagemagick
17507 (org-check-external-command
17508 "convert" "you need to install imagemagick")
17509 #'org-create-formula-image-with-imagemagick)
17510 (t (error
17511 "invalid value of `org-latex-create-formula-image-program'")))
17512 string tofile options buffer))
17514 ;; This function borrows from Ganesh Swami's latex2png.el
17515 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17516 "This calls dvipng."
17517 (require 'org-latex)
17518 (let* ((tmpdir (if (featurep 'xemacs)
17519 (temp-directory)
17520 temporary-file-directory))
17521 (texfilebase (make-temp-name
17522 (expand-file-name "orgtex" tmpdir)))
17523 (texfile (concat texfilebase ".tex"))
17524 (dvifile (concat texfilebase ".dvi"))
17525 (pngfile (concat texfilebase ".png"))
17526 (fnh (if (featurep 'xemacs)
17527 (font-height (face-font 'default))
17528 (face-attribute 'default :height nil)))
17529 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17530 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17531 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17532 "Black"))
17533 (bg (or (plist-get options (if buffer :background :html-background))
17534 "Transparent")))
17535 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17536 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17537 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17538 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17539 (with-temp-file texfile
17540 (insert (org-splice-latex-header
17541 org-format-latex-header
17542 org-export-latex-default-packages-alist
17543 org-export-latex-packages-alist t
17544 org-format-latex-header-extra))
17545 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17546 (require 'org-latex)
17547 (org-export-latex-fix-inputenc))
17548 (let ((dir default-directory))
17549 (condition-case nil
17550 (progn
17551 (cd tmpdir)
17552 (call-process "latex" nil nil nil texfile))
17553 (error nil))
17554 (cd dir))
17555 (if (not (file-exists-p dvifile))
17556 (progn (message "Failed to create dvi file from %s" texfile) nil)
17557 (condition-case nil
17558 (if (featurep 'xemacs)
17559 (call-process "dvipng" nil nil nil
17560 "-fg" fg "-bg" bg
17561 "-T" "tight"
17562 "-o" pngfile
17563 dvifile)
17564 (call-process "dvipng" nil nil nil
17565 "-fg" fg "-bg" bg
17566 "-D" dpi
17567 ;;"-x" scale "-y" scale
17568 "-T" "tight"
17569 "-o" pngfile
17570 dvifile))
17571 (error nil))
17572 (if (not (file-exists-p pngfile))
17573 (if org-format-latex-signal-error
17574 (error "Failed to create png file from %s" texfile)
17575 (message "Failed to create png file from %s" texfile)
17576 nil)
17577 ;; Use the requested file name and clean up
17578 (copy-file pngfile tofile 'replace)
17579 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17580 (if (file-exists-p (concat texfilebase e))
17581 (delete-file (concat texfilebase e))))
17582 pngfile))))
17584 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17585 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17586 "This calls convert, which is included into imagemagick."
17587 (require 'org-latex)
17588 (let* ((tmpdir (if (featurep 'xemacs)
17589 (temp-directory)
17590 temporary-file-directory))
17591 (texfilebase (make-temp-name
17592 (expand-file-name "orgtex" tmpdir)))
17593 (texfile (concat texfilebase ".tex"))
17594 (pdffile (concat texfilebase ".pdf"))
17595 (pngfile (concat texfilebase ".png"))
17596 (fnh (if (featurep 'xemacs)
17597 (font-height (face-font 'default))
17598 (face-attribute 'default :height nil)))
17599 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17600 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17601 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17602 "black"))
17603 (bg (or (plist-get options (if buffer :background :html-background))
17604 "white")))
17605 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17606 (setq fg (org-latex-color-format fg)))
17607 (if (eq bg 'default) (setq bg (org-latex-color :background))
17608 (setq bg (org-latex-color-format
17609 (if (string= bg "Transparent") "white" bg))))
17610 (with-temp-file texfile
17611 (insert (org-splice-latex-header
17612 org-format-latex-header
17613 org-export-latex-default-packages-alist
17614 org-export-latex-packages-alist t
17615 org-format-latex-header-extra))
17616 (insert "\n\\begin{document}\n"
17617 "\\definecolor{fg}{rgb}{" fg "}\n"
17618 "\\definecolor{bg}{rgb}{" bg "}\n"
17619 "\n\\pagecolor{bg}\n"
17620 "\n{\\color{fg}\n"
17621 string
17622 "\n}\n"
17623 "\n\\end{document}\n" )
17624 (require 'org-latex)
17625 (org-export-latex-fix-inputenc))
17626 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17627 (condition-case nil
17628 (progn
17629 (cd tmpdir)
17630 (setq cmds org-latex-to-pdf-process)
17631 (while cmds
17632 (setq latex-frags-cmds (pop cmds))
17633 (if (listp latex-frags-cmds)
17634 (setq cmds nil)
17635 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17636 (while latex-frags-cmds
17637 (setq cmd (pop latex-frags-cmds))
17638 (while (string-match "%b" cmd)
17639 (setq cmd (replace-match
17640 (save-match-data
17641 (shell-quote-argument texfile))
17642 t t cmd)))
17643 (while (string-match "%f" cmd)
17644 (setq cmd (replace-match
17645 (save-match-data
17646 (shell-quote-argument (file-name-nondirectory texfile)))
17647 t t cmd)))
17648 (while (string-match "%o" cmd)
17649 (setq cmd (replace-match
17650 (save-match-data
17651 (shell-quote-argument (file-name-directory texfile)))
17652 t t cmd)))
17653 (setq cmd (split-string cmd))
17654 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17655 (error nil))
17656 (cd dir))
17657 (if (not (file-exists-p pdffile))
17658 (progn (message "Failed to create pdf file from %s" texfile) nil)
17659 (condition-case nil
17660 (if (featurep 'xemacs)
17661 (call-process "convert" nil nil nil
17662 "-density" "96"
17663 "-trim"
17664 "-antialias"
17665 pdffile
17666 "-quality" "100"
17667 ;; "-sharpen" "0x1.0"
17668 pngfile)
17669 (call-process "convert" nil nil nil
17670 "-density" dpi
17671 "-trim"
17672 "-antialias"
17673 pdffile
17674 "-quality" "100"
17675 ; "-sharpen" "0x1.0"
17676 pngfile))
17677 (error nil))
17678 (if (not (file-exists-p pngfile))
17679 (if org-format-latex-signal-error
17680 (error "Failed to create png file from %s" texfile)
17681 (message "Failed to create png file from %s" texfile)
17682 nil)
17683 ;; Use the requested file name and clean up
17684 (copy-file pngfile tofile 'replace)
17685 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17686 (if (file-exists-p (concat texfilebase e))
17687 (delete-file (concat texfilebase e))))
17688 pngfile))))
17690 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17691 "Fill a LaTeX header template TPL.
17692 In the template, the following place holders will be recognized:
17694 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17695 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17696 [PACKAGES] \\usepackage statements for PKG
17697 [NO-PACKAGES] do not include PKG
17698 [EXTRA] the string EXTRA
17699 [NO-EXTRA] do not include EXTRA
17701 For backward compatibility, if both the positive and the negative place
17702 holder is missing, the positive one (without the \"NO-\") will be
17703 assumed to be present at the end of the template.
17704 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17705 EXTRA is a string.
17706 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17707 (let (rpl (end ""))
17708 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17709 (setq rpl (if (or (match-end 1) (not def-pkg))
17710 "" (org-latex-packages-to-string def-pkg snippets-p t))
17711 tpl (replace-match rpl t t tpl))
17712 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17714 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17715 (setq rpl (if (or (match-end 1) (not pkg))
17716 "" (org-latex-packages-to-string pkg snippets-p t))
17717 tpl (replace-match rpl t t tpl))
17718 (if pkg (setq end
17719 (concat end "\n"
17720 (org-latex-packages-to-string pkg snippets-p)))))
17722 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17723 (setq rpl (if (or (match-end 1) (not extra))
17724 "" (concat extra "\n"))
17725 tpl (replace-match rpl t t tpl))
17726 (if (and extra (string-match "\\S-" extra))
17727 (setq end (concat end "\n" extra))))
17729 (if (string-match "\\S-" end)
17730 (concat tpl "\n" end)
17731 tpl)))
17733 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17734 "Turn an alist of packages into a string with the \\usepackage macros."
17735 (setq pkg (mapconcat (lambda(p)
17736 (cond
17737 ((stringp p) p)
17738 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17739 (format "%% Package %s omitted" (cadr p)))
17740 ((equal "" (car p))
17741 (format "\\usepackage{%s}" (cadr p)))
17743 (format "\\usepackage[%s]{%s}"
17744 (car p) (cadr p)))))
17746 "\n"))
17747 (if newline (concat pkg "\n") pkg))
17749 (defun org-dvipng-color (attr)
17750 "Return a RGB color specification for dvipng."
17751 (apply 'format "rgb %s %s %s"
17752 (mapcar 'org-normalize-color
17753 (if (featurep 'xemacs)
17754 (color-rgb-components
17755 (face-property 'default
17756 (cond ((eq attr :foreground) 'foreground)
17757 ((eq attr :background) 'background))))
17758 (color-values (face-attribute 'default attr nil))))))
17760 (defun org-dvipng-color-format (color-name)
17761 "Convert COLOR-NAME to a RGB color value for dvipng."
17762 (apply 'format "rgb %s %s %s"
17763 (mapcar 'org-normalize-color
17764 (color-values color-name))))
17766 (defun org-latex-color (attr)
17767 "Return a RGB color for the LaTeX color package."
17768 (apply 'format "%s,%s,%s"
17769 (mapcar 'org-normalize-color
17770 (if (featurep 'xemacs)
17771 (color-rgb-components
17772 (face-property 'default
17773 (cond ((eq attr :foreground) 'foreground)
17774 ((eq attr :background) 'background))))
17775 (color-values (face-attribute 'default attr nil))))))
17777 (defun org-latex-color-format (color-name)
17778 "Convert COLOR-NAME to a RGB color value."
17779 (apply 'format "%s,%s,%s"
17780 (mapcar 'org-normalize-color
17781 (color-values color-name))))
17783 (defun org-normalize-color (value)
17784 "Return string to be used as color value for an RGB component."
17785 (format "%g" (/ value 65535.0)))
17787 ;; Image display
17790 (defvar org-inline-image-overlays nil)
17791 (make-variable-buffer-local 'org-inline-image-overlays)
17793 (defun org-toggle-inline-images (&optional include-linked)
17794 "Toggle the display of inline images.
17795 INCLUDE-LINKED is passed to `org-display-inline-images'."
17796 (interactive "P")
17797 (if org-inline-image-overlays
17798 (progn
17799 (org-remove-inline-images)
17800 (message "Inline image display turned off"))
17801 (org-display-inline-images include-linked)
17802 (if (and (org-called-interactively-p)
17803 org-inline-image-overlays)
17804 (message "%d images displayed inline"
17805 (length org-inline-image-overlays))
17806 (message "No images to display inline"))))
17808 (defun org-redisplay-inline-images ()
17809 "Refresh the display of inline images."
17810 (interactive)
17811 (if (not org-inline-image-overlays)
17812 (org-toggle-inline-images)
17813 (org-toggle-inline-images)
17814 (org-toggle-inline-images)))
17816 (defun org-display-inline-images (&optional include-linked refresh beg end)
17817 "Display inline images.
17818 Normally only links without a description part are inlined, because this
17819 is how it will work for export. When INCLUDE-LINKED is set, also links
17820 with a description part will be inlined. This can be nice for a quick
17821 look at those images, but it does not reflect what exported files will look
17822 like.
17823 When REFRESH is set, refresh existing images between BEG and END.
17824 This will create new image displays only if necessary.
17825 BEG and END default to the buffer boundaries."
17826 (interactive "P")
17827 (unless refresh
17828 (org-remove-inline-images)
17829 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17830 (save-excursion
17831 (save-restriction
17832 (widen)
17833 (setq beg (or beg (point-min)) end (or end (point-max)))
17834 (goto-char beg)
17835 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17836 (substring (org-image-file-name-regexp) 0 -2)
17837 "\\)\\]" (if include-linked "" "\\]")))
17838 old file ov img type attrwidth width)
17839 (while (re-search-forward re end t)
17840 (setq old (get-char-property-and-overlay (match-beginning 1)
17841 'org-image-overlay)
17842 file (expand-file-name
17843 (concat (or (match-string 3) "") (match-string 4))))
17844 (when (image-type-available-p 'imagemagick)
17845 (setq attrwidth (if (or (listp org-image-actual-width)
17846 (null org-image-actual-width))
17847 (save-excursion
17848 (save-match-data
17849 (when (re-search-backward
17850 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
17851 (save-excursion
17852 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
17853 (string-to-number (match-string 1))))))
17854 width (cond ((eq org-image-actual-width t) nil)
17855 ((null org-image-actual-width) attrwidth)
17856 ((numberp org-image-actual-width)
17857 org-image-actual-width)
17858 ((listp org-image-actual-width)
17859 (or attrwidth (car org-image-actual-width))))
17860 type (if width 'imagemagick)))
17861 (when (file-exists-p file)
17862 (if (and (car-safe old) refresh)
17863 (image-refresh (overlay-get (cdr old) 'display))
17864 (setq img (save-match-data (create-image file type nil :width width)))
17865 (when img
17866 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17867 (overlay-put ov 'display img)
17868 (overlay-put ov 'face 'default)
17869 (overlay-put ov 'org-image-overlay t)
17870 (overlay-put ov 'modification-hooks
17871 (list 'org-display-inline-remove-overlay))
17872 (push ov org-inline-image-overlays)))))))))
17874 (define-obsolete-function-alias
17875 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
17877 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
17878 "Remove inline-display overlay if a corresponding region is modified."
17879 (let ((inhibit-modification-hooks t))
17880 (when (and ov after)
17881 (delete ov org-inline-image-overlays)
17882 (delete-overlay ov))))
17884 (defun org-remove-inline-images ()
17885 "Remove inline display of images."
17886 (interactive)
17887 (mapc 'delete-overlay org-inline-image-overlays)
17888 (setq org-inline-image-overlays nil))
17890 ;;;; Key bindings
17892 ;; Outline functions from `outline-mode-prefix-map'
17893 ;; that can be remapped in Org:
17894 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17895 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17896 (define-key org-mode-map [remap outline-forward-same-level]
17897 'org-forward-heading-same-level)
17898 (define-key org-mode-map [remap outline-backward-same-level]
17899 'org-backward-heading-same-level)
17900 (define-key org-mode-map [remap show-branches]
17901 'org-kill-note-or-show-branches)
17902 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17903 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17904 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17906 ;; Outline functions from `outline-mode-prefix-map' that can not
17907 ;; be remapped in Org:
17909 ;; - the column "key binding" shows whether the Outline function is still
17910 ;; available in Org mode on the same key that it has been bound to in
17911 ;; Outline mode:
17912 ;; - "overridden": key used for a different functionality in Org mode
17913 ;; - else: key still bound to the same Outline function in Org mode
17915 ;; | Outline function | key binding | Org replacement |
17916 ;; |------------------------------------+-------------+-----------------------|
17917 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17918 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17919 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17920 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17921 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17922 ;; | `show-entry' | overridden | no replacement |
17923 ;; | `show-children' | `C-c C-i' | visibility cycling |
17924 ;; | `show-branches' | `C-c C-k' | still same function |
17925 ;; | `show-subtree' | overridden | visibility cycling |
17926 ;; | `show-all' | overridden | no replacement |
17927 ;; | `hide-subtree' | overridden | visibility cycling |
17928 ;; | `hide-body' | overridden | no replacement |
17929 ;; | `hide-entry' | overridden | visibility cycling |
17930 ;; | `hide-leaves' | overridden | no replacement |
17931 ;; | `hide-sublevels' | overridden | no replacement |
17932 ;; | `hide-other' | overridden | no replacement |
17934 ;; Make `C-c C-x' a prefix key
17935 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17937 ;; TAB key with modifiers
17938 (org-defkey org-mode-map "\C-i" 'org-cycle)
17939 (org-defkey org-mode-map [(tab)] 'org-cycle)
17940 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17941 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17942 ;; The following line is necessary under Suse GNU/Linux
17943 (unless (featurep 'xemacs)
17944 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17945 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17946 (define-key org-mode-map [backtab] 'org-shifttab)
17948 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17949 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17950 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17952 ;; Cursor keys with modifiers
17953 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17954 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17955 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17956 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17958 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17959 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17960 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17961 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17963 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17964 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17965 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17966 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17968 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17969 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17970 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17971 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17973 ;; Babel keys
17974 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17975 (mapc (lambda (pair)
17976 (define-key org-babel-map (car pair) (cdr pair)))
17977 org-babel-key-bindings)
17979 ;;; Extra keys for tty access.
17980 ;; We only set them when really needed because otherwise the
17981 ;; menus don't show the simple keys
17983 (when (or org-use-extra-keys
17984 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17985 (not window-system))
17986 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17987 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17988 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17989 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17990 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17991 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17992 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17993 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17994 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17995 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17996 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17997 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17998 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17999 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18000 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18001 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18002 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18003 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18004 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18005 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18006 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18007 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18008 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18009 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18010 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18011 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18012 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18013 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18015 ;; All the other keys
18017 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18018 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18019 (if (boundp 'narrow-map)
18020 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18021 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18022 (if (boundp 'narrow-map)
18023 (org-defkey narrow-map "b" 'org-narrow-to-block)
18024 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18025 (if (boundp 'narrow-map)
18026 (org-defkey narrow-map "e" 'org-narrow-to-element)
18027 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18028 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18029 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18030 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18031 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18032 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18033 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18034 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18035 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18036 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18037 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18038 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18039 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18040 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18041 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18042 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18043 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18044 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18045 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18046 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18047 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18048 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18049 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18050 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18051 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18052 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18053 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18054 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18055 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18056 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18057 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18058 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18059 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18060 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18061 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18062 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18063 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18064 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18065 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18066 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18067 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18068 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18069 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18070 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18071 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18072 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18073 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18074 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18075 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18076 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18077 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18078 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18079 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18080 (org-defkey org-mode-map "\C-c^" 'org-sort)
18081 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18082 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18083 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18084 (org-defkey org-mode-map "\C-m" 'org-return)
18085 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18086 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18087 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18088 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18089 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18090 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18091 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18092 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18093 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18094 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18095 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18096 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18097 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18098 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18099 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18100 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18101 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18102 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18103 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18104 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18105 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18106 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18107 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18109 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18110 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18111 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18113 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18114 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18115 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18116 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18117 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18118 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18119 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18120 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18121 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18122 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18123 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18124 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18125 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18126 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18127 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18128 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18129 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18130 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18131 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18132 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18133 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18134 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18136 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18137 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18138 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18139 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18140 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18142 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18144 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18146 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18147 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18149 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18152 (when (featurep 'xemacs)
18153 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18156 (defconst org-speed-commands-default
18158 ("Outline Navigation")
18159 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18160 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18161 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18162 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18163 ("u" . (org-speed-move-safe 'outline-up-heading))
18164 ("j" . org-goto)
18165 ("g" . (org-refile t))
18166 ("Outline Visibility")
18167 ("c" . org-cycle)
18168 ("C" . org-shifttab)
18169 (" " . org-display-outline-path)
18170 (":" . org-columns)
18171 ("Outline Structure Editing")
18172 ("U" . org-shiftmetaup)
18173 ("D" . org-shiftmetadown)
18174 ("r" . org-metaright)
18175 ("l" . org-metaleft)
18176 ("R" . org-shiftmetaright)
18177 ("L" . org-shiftmetaleft)
18178 ("i" . (progn (forward-char 1) (call-interactively
18179 'org-insert-heading-respect-content)))
18180 ("^" . org-sort)
18181 ("w" . org-refile)
18182 ("a" . org-archive-subtree-default-with-confirmation)
18183 ("." . org-mark-subtree)
18184 ("#" . org-toggle-comment)
18185 ("Clock Commands")
18186 ("I" . org-clock-in)
18187 ("O" . org-clock-out)
18188 ("Meta Data Editing")
18189 ("t" . org-todo)
18190 ("," . (org-priority))
18191 ("0" . (org-priority ?\ ))
18192 ("1" . (org-priority ?A))
18193 ("2" . (org-priority ?B))
18194 ("3" . (org-priority ?C))
18195 (";" . org-set-tags-command)
18196 ("e" . org-set-effort)
18197 ("E" . org-inc-effort)
18198 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18199 (org-entry-put (point) "APPT_WARNTIME" m)))
18200 ("Agenda Views etc")
18201 ("v" . org-agenda)
18202 ("/" . org-sparse-tree)
18203 ("Misc")
18204 ("o" . org-open-at-point)
18205 ("?" . org-speed-command-help)
18206 ("<" . (org-agenda-set-restriction-lock 'subtree))
18207 (">" . (org-agenda-remove-restriction-lock))
18209 "The default speed commands.")
18211 (defun org-print-speed-command (e)
18212 (if (> (length (car e)) 1)
18213 (progn
18214 (princ "\n")
18215 (princ (car e))
18216 (princ "\n")
18217 (princ (make-string (length (car e)) ?-))
18218 (princ "\n"))
18219 (princ (car e))
18220 (princ " ")
18221 (if (symbolp (cdr e))
18222 (princ (symbol-name (cdr e)))
18223 (prin1 (cdr e)))
18224 (princ "\n")))
18226 (defun org-speed-command-help ()
18227 "Show the available speed commands."
18228 (interactive)
18229 (if (not org-use-speed-commands)
18230 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18231 (with-output-to-temp-buffer "*Help*"
18232 (princ "User-defined Speed commands\n===========================\n")
18233 (mapc 'org-print-speed-command org-speed-commands-user)
18234 (princ "\n")
18235 (princ "Built-in Speed commands\n=======================\n")
18236 (mapc 'org-print-speed-command org-speed-commands-default))
18237 (with-current-buffer "*Help*"
18238 (setq truncate-lines t))))
18240 (defun org-speed-move-safe (cmd)
18241 "Execute CMD, but make sure that the cursor always ends up in a headline.
18242 If not, return to the original position and throw an error."
18243 (interactive)
18244 (let ((pos (point)))
18245 (call-interactively cmd)
18246 (unless (and (bolp) (org-at-heading-p))
18247 (goto-char pos)
18248 (error "Boundary reached while executing %s" cmd))))
18250 (defvar org-self-insert-command-undo-counter 0)
18252 (defvar org-table-auto-blank-field) ; defined in org-table.el
18253 (defvar org-speed-command nil)
18255 (define-obsolete-function-alias
18256 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18258 (defun org-speed-command-activate (keys)
18259 "Hook for activating single-letter speed commands.
18260 `org-speed-commands-default' specifies a minimal command set.
18261 Use `org-speed-commands-user' for further customization."
18262 (when (or (and (bolp) (looking-at org-outline-regexp))
18263 (and (functionp org-use-speed-commands)
18264 (funcall org-use-speed-commands)))
18265 (cdr (assoc keys (append org-speed-commands-user
18266 org-speed-commands-default)))))
18268 (define-obsolete-function-alias
18269 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18271 (defun org-babel-speed-command-activate (keys)
18272 "Hook for activating single-letter code block commands."
18273 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18274 (cdr (assoc keys org-babel-key-bindings))))
18276 (defcustom org-speed-command-hook
18277 '(org-speed-command-default-hook org-babel-speed-command-hook)
18278 "Hook for activating speed commands at strategic locations.
18279 Hook functions are called in sequence until a valid handler is
18280 found.
18282 Each hook takes a single argument, a user-pressed command key
18283 which is also a `self-insert-command' from the global map.
18285 Within the hook, examine the cursor position and the command key
18286 and return nil or a valid handler as appropriate. Handler could
18287 be one of an interactive command, a function, or a form.
18289 Set `org-use-speed-commands' to non-nil value to enable this
18290 hook. The default setting is `org-speed-command-activate'."
18291 :group 'org-structure
18292 :version "24.1"
18293 :type 'hook)
18295 (defun org-self-insert-command (N)
18296 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18297 If the cursor is in a table looking at whitespace, the whitespace is
18298 overwritten, and the table is not marked as requiring realignment."
18299 (interactive "p")
18300 (org-check-before-invisible-edit 'insert)
18301 (cond
18302 ((and org-use-speed-commands
18303 (setq org-speed-command
18304 (run-hook-with-args-until-success
18305 'org-speed-command-hook (this-command-keys))))
18306 (cond
18307 ((commandp org-speed-command)
18308 (setq this-command org-speed-command)
18309 (call-interactively org-speed-command))
18310 ((functionp org-speed-command)
18311 (funcall org-speed-command))
18312 ((and org-speed-command (listp org-speed-command))
18313 (eval org-speed-command))
18314 (t (let (org-use-speed-commands)
18315 (call-interactively 'org-self-insert-command)))))
18316 ((and
18317 (org-table-p)
18318 (progn
18319 ;; check if we blank the field, and if that triggers align
18320 (and (featurep 'org-table) org-table-auto-blank-field
18321 (member last-command
18322 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18323 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18324 ;; got extra space, this field does not determine column width
18325 (let (org-table-may-need-update) (org-table-blank-field))
18326 ;; no extra space, this field may determine column width
18327 (org-table-blank-field)))
18329 (eq N 1)
18330 (looking-at "[^|\n]* |"))
18331 (let (org-table-may-need-update)
18332 (goto-char (1- (match-end 0)))
18333 (backward-delete-char 1)
18334 (goto-char (match-beginning 0))
18335 (self-insert-command N)))
18337 (setq org-table-may-need-update t)
18338 (self-insert-command N)
18339 (org-fix-tags-on-the-fly)
18340 (if org-self-insert-cluster-for-undo
18341 (if (not (eq last-command 'org-self-insert-command))
18342 (setq org-self-insert-command-undo-counter 1)
18343 (if (>= org-self-insert-command-undo-counter 20)
18344 (setq org-self-insert-command-undo-counter 1)
18345 (and (> org-self-insert-command-undo-counter 0)
18346 buffer-undo-list (listp buffer-undo-list)
18347 (not (cadr buffer-undo-list)) ; remove nil entry
18348 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18349 (setq org-self-insert-command-undo-counter
18350 (1+ org-self-insert-command-undo-counter))))))))
18352 (defun org-check-before-invisible-edit (kind)
18353 "Check is editing if kind KIND would be dangerous with invisible text around.
18354 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18355 ;; First, try to get out of here as quickly as possible, to reduce overhead
18356 (if (and org-catch-invisible-edits
18357 (or (not (boundp 'visible-mode)) (not visible-mode))
18358 (or (get-char-property (point) 'invisible)
18359 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18360 ;; OK, we need to take a closer look
18361 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18362 (invisible-before-point (if (bobp) nil (get-char-property
18363 (1- (point)) 'invisible)))
18364 (border-and-ok-direction
18366 ;; Check if we are acting predictably before invisible text
18367 (and invisible-at-point (not invisible-before-point)
18368 (memq kind '(insert delete-backward)))
18369 ;; Check if we are acting predictably after invisible text
18370 ;; This works not well, and I have turned it off. It seems
18371 ;; better to always show and stop after invisible text.
18372 ;; (and (not invisible-at-point) invisible-before-point
18373 ;; (memq kind '(insert delete)))
18375 (when (or (memq invisible-at-point '(outline org-hide-block t))
18376 (memq invisible-before-point '(outline org-hide-block t)))
18377 (if (eq org-catch-invisible-edits 'error)
18378 (error "Editing in invisible areas is prohibited - make visible first"))
18379 (if (and org-custom-properties-overlays
18380 (y-or-n-p "Display invisible properties in this buffer? "))
18381 (org-toggle-custom-properties-visibility)
18382 ;; Make the area visible
18383 (save-excursion
18384 (if invisible-before-point
18385 (goto-char (previous-single-char-property-change
18386 (point) 'invisible)))
18387 (org-cycle))
18388 (cond
18389 ((eq org-catch-invisible-edits 'show)
18390 ;; That's it, we do the edit after showing
18391 (message
18392 "Unfolding invisible region around point before editing")
18393 (sit-for 1))
18394 ((and (eq org-catch-invisible-edits 'smart)
18395 border-and-ok-direction)
18396 (message "Unfolding invisible region around point before editing"))
18398 ;; Don't do the edit, make the user repeat it in full visibility
18399 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18401 (defun org-fix-tags-on-the-fly ()
18402 (when (and (equal (char-after (point-at-bol)) ?*)
18403 (org-at-heading-p))
18404 (org-align-tags-here org-tags-column)))
18406 (defun org-delete-backward-char (N)
18407 "Like `delete-backward-char', insert whitespace at field end in tables.
18408 When deleting backwards, in tables this function will insert whitespace in
18409 front of the next \"|\" separator, to keep the table aligned. The table will
18410 still be marked for re-alignment if the field did fill the entire column,
18411 because, in this case the deletion might narrow the column."
18412 (interactive "p")
18413 (org-check-before-invisible-edit 'delete-backward)
18414 (if (and (org-table-p)
18415 (eq N 1)
18416 (string-match "|" (buffer-substring (point-at-bol) (point)))
18417 (looking-at ".*?|"))
18418 (let ((pos (point))
18419 (noalign (looking-at "[^|\n\r]* |"))
18420 (c org-table-may-need-update))
18421 (backward-delete-char N)
18422 (if (not overwrite-mode)
18423 (progn
18424 (skip-chars-forward "^|")
18425 (insert " ")
18426 (goto-char (1- pos))))
18427 ;; noalign: if there were two spaces at the end, this field
18428 ;; does not determine the width of the column.
18429 (if noalign (setq org-table-may-need-update c)))
18430 (backward-delete-char N)
18431 (org-fix-tags-on-the-fly)))
18433 (defun org-delete-char (N)
18434 "Like `delete-char', but insert whitespace at field end in tables.
18435 When deleting characters, in tables this function will insert whitespace in
18436 front of the next \"|\" separator, to keep the table aligned. The table will
18437 still be marked for re-alignment if the field did fill the entire column,
18438 because, in this case the deletion might narrow the column."
18439 (interactive "p")
18440 (org-check-before-invisible-edit 'delete)
18441 (if (and (org-table-p)
18442 (not (bolp))
18443 (not (= (char-after) ?|))
18444 (eq N 1))
18445 (if (looking-at ".*?|")
18446 (let ((pos (point))
18447 (noalign (looking-at "[^|\n\r]* |"))
18448 (c org-table-may-need-update))
18449 (replace-match (concat
18450 (substring (match-string 0) 1 -1)
18451 " |"))
18452 (goto-char pos)
18453 ;; noalign: if there were two spaces at the end, this field
18454 ;; does not determine the width of the column.
18455 (if noalign (setq org-table-may-need-update c)))
18456 (delete-char N))
18457 (delete-char N)
18458 (org-fix-tags-on-the-fly)))
18460 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18461 (put 'org-self-insert-command 'delete-selection t)
18462 (put 'orgtbl-self-insert-command 'delete-selection t)
18463 (put 'org-delete-char 'delete-selection 'supersede)
18464 (put 'org-delete-backward-char 'delete-selection 'supersede)
18465 (put 'org-yank 'delete-selection 'yank)
18467 ;; Make `flyspell-mode' delay after some commands
18468 (put 'org-self-insert-command 'flyspell-delayed t)
18469 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18470 (put 'org-delete-char 'flyspell-delayed t)
18471 (put 'org-delete-backward-char 'flyspell-delayed t)
18473 ;; Make pabbrev-mode expand after org-mode commands
18474 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18475 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18477 ;; How to do this: Measure non-white length of current string
18478 ;; If equal to column width, we should realign.
18480 (defun org-remap (map &rest commands)
18481 "In MAP, remap the functions given in COMMANDS.
18482 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18483 (let (new old)
18484 (while commands
18485 (setq old (pop commands) new (pop commands))
18486 (if (fboundp 'command-remapping)
18487 (org-defkey map (vector 'remap old) new)
18488 (substitute-key-definition old new map global-map)))))
18490 (when (eq org-enable-table-editor 'optimized)
18491 ;; If the user wants maximum table support, we need to hijack
18492 ;; some standard editing functions
18493 (org-remap org-mode-map
18494 'self-insert-command 'org-self-insert-command
18495 'delete-char 'org-delete-char
18496 'delete-backward-char 'org-delete-backward-char)
18497 (org-defkey org-mode-map "|" 'org-force-self-insert))
18499 (defvar org-ctrl-c-ctrl-c-hook nil
18500 "Hook for functions attaching themselves to `C-c C-c'.
18502 This can be used to add additional functionality to the C-c C-c
18503 key which executes context-dependent commands. This hook is run
18504 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18505 run after the last test.
18507 Each function will be called with no arguments. The function
18508 must check if the context is appropriate for it to act. If yes,
18509 it should do its thing and then return a non-nil value. If the
18510 context is wrong, just do nothing and return nil.")
18512 (defvar org-ctrl-c-ctrl-c-final-hook nil
18513 "Hook for functions attaching themselves to `C-c C-c'.
18515 This can be used to add additional functionality to the C-c C-c
18516 key which executes context-dependent commands. This hook is run
18517 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18518 before the first test.
18520 Each function will be called with no arguments. The function
18521 must check if the context is appropriate for it to act. If yes,
18522 it should do its thing and then return a non-nil value. If the
18523 context is wrong, just do nothing and return nil.")
18525 (defvar org-tab-first-hook nil
18526 "Hook for functions to attach themselves to TAB.
18527 See `org-ctrl-c-ctrl-c-hook' for more information.
18528 This hook runs as the first action when TAB is pressed, even before
18529 `org-cycle' messes around with the `outline-regexp' to cater for
18530 inline tasks and plain list item folding.
18531 If any function in this hook returns t, any other actions that
18532 would have been caused by TAB (such as table field motion or visibility
18533 cycling) will not occur.")
18535 (defvar org-tab-after-check-for-table-hook nil
18536 "Hook for functions to attach themselves to TAB.
18537 See `org-ctrl-c-ctrl-c-hook' for more information.
18538 This hook runs after it has been established that the cursor is not in a
18539 table, but before checking if the cursor is in a headline or if global cycling
18540 should be done.
18541 If any function in this hook returns t, not other actions like visibility
18542 cycling will be done.")
18544 (defvar org-tab-after-check-for-cycling-hook nil
18545 "Hook for functions to attach themselves to TAB.
18546 See `org-ctrl-c-ctrl-c-hook' for more information.
18547 This hook runs after it has been established that not table field motion and
18548 not visibility should be done because of current context. This is probably
18549 the place where a package like yasnippets can hook in.")
18551 (defvar org-tab-before-tab-emulation-hook nil
18552 "Hook for functions to attach themselves to TAB.
18553 See `org-ctrl-c-ctrl-c-hook' for more information.
18554 This hook runs after every other options for TAB have been exhausted, but
18555 before indentation and \t insertion takes place.")
18557 (defvar org-metaleft-hook nil
18558 "Hook for functions attaching themselves to `M-left'.
18559 See `org-ctrl-c-ctrl-c-hook' for more information.")
18560 (defvar org-metaright-hook nil
18561 "Hook for functions attaching themselves to `M-right'.
18562 See `org-ctrl-c-ctrl-c-hook' for more information.")
18563 (defvar org-metaup-hook nil
18564 "Hook for functions attaching themselves to `M-up'.
18565 See `org-ctrl-c-ctrl-c-hook' for more information.")
18566 (defvar org-metadown-hook nil
18567 "Hook for functions attaching themselves to `M-down'.
18568 See `org-ctrl-c-ctrl-c-hook' for more information.")
18569 (defvar org-shiftmetaleft-hook nil
18570 "Hook for functions attaching themselves to `M-S-left'.
18571 See `org-ctrl-c-ctrl-c-hook' for more information.")
18572 (defvar org-shiftmetaright-hook nil
18573 "Hook for functions attaching themselves to `M-S-right'.
18574 See `org-ctrl-c-ctrl-c-hook' for more information.")
18575 (defvar org-shiftmetaup-hook nil
18576 "Hook for functions attaching themselves to `M-S-up'.
18577 See `org-ctrl-c-ctrl-c-hook' for more information.")
18578 (defvar org-shiftmetadown-hook nil
18579 "Hook for functions attaching themselves to `M-S-down'.
18580 See `org-ctrl-c-ctrl-c-hook' for more information.")
18581 (defvar org-metareturn-hook nil
18582 "Hook for functions attaching themselves to `M-RET'.
18583 See `org-ctrl-c-ctrl-c-hook' for more information.")
18584 (defvar org-shiftup-hook nil
18585 "Hook for functions attaching themselves to `S-up'.
18586 See `org-ctrl-c-ctrl-c-hook' for more information.")
18587 (defvar org-shiftup-final-hook nil
18588 "Hook for functions attaching themselves to `S-up'.
18589 This one runs after all other options except shift-select have been excluded.
18590 See `org-ctrl-c-ctrl-c-hook' for more information.")
18591 (defvar org-shiftdown-hook nil
18592 "Hook for functions attaching themselves to `S-down'.
18593 See `org-ctrl-c-ctrl-c-hook' for more information.")
18594 (defvar org-shiftdown-final-hook nil
18595 "Hook for functions attaching themselves to `S-down'.
18596 This one runs after all other options except shift-select have been excluded.
18597 See `org-ctrl-c-ctrl-c-hook' for more information.")
18598 (defvar org-shiftleft-hook nil
18599 "Hook for functions attaching themselves to `S-left'.
18600 See `org-ctrl-c-ctrl-c-hook' for more information.")
18601 (defvar org-shiftleft-final-hook nil
18602 "Hook for functions attaching themselves to `S-left'.
18603 This one runs after all other options except shift-select have been excluded.
18604 See `org-ctrl-c-ctrl-c-hook' for more information.")
18605 (defvar org-shiftright-hook nil
18606 "Hook for functions attaching themselves to `S-right'.
18607 See `org-ctrl-c-ctrl-c-hook' for more information.")
18608 (defvar org-shiftright-final-hook nil
18609 "Hook for functions attaching themselves to `S-right'.
18610 This one runs after all other options except shift-select have been excluded.
18611 See `org-ctrl-c-ctrl-c-hook' for more information.")
18613 (defun org-modifier-cursor-error ()
18614 "Throw an error, a modified cursor command was applied in wrong context."
18615 (error "This command is active in special context like tables, headlines or items"))
18617 (defun org-shiftselect-error ()
18618 "Throw an error because Shift-Cursor command was applied in wrong context."
18619 (if (and (boundp 'shift-select-mode) shift-select-mode)
18620 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18621 (error "This command works only in special context like headlines or timestamps")))
18623 (defun org-call-for-shift-select (cmd)
18624 (let ((this-command-keys-shift-translated t))
18625 (call-interactively cmd)))
18627 (defun org-shifttab (&optional arg)
18628 "Global visibility cycling or move to previous table field.
18629 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18630 on context.
18631 See the individual commands for more information."
18632 (interactive "P")
18633 (cond
18634 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18635 ((integerp arg)
18636 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18637 (message "Content view to level: %d" arg)
18638 (org-content (prefix-numeric-value arg2))
18639 (setq org-cycle-global-status 'overview)))
18640 (t (call-interactively 'org-global-cycle))))
18642 (defun org-shiftmetaleft ()
18643 "Promote subtree or delete table column.
18644 Calls `org-promote-subtree', `org-outdent-item-tree', or
18645 `org-table-delete-column', depending on context. See the
18646 individual commands for more information."
18647 (interactive)
18648 (cond
18649 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18650 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18651 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18652 ((if (not (org-region-active-p)) (org-at-item-p)
18653 (save-excursion (goto-char (region-beginning))
18654 (org-at-item-p)))
18655 (call-interactively 'org-outdent-item-tree))
18656 (t (org-modifier-cursor-error))))
18658 (defun org-shiftmetaright ()
18659 "Demote subtree or insert table column.
18660 Calls `org-demote-subtree', `org-indent-item-tree', or
18661 `org-table-insert-column', depending on context. See the
18662 individual commands for more information."
18663 (interactive)
18664 (cond
18665 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18666 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18667 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18668 ((if (not (org-region-active-p)) (org-at-item-p)
18669 (save-excursion (goto-char (region-beginning))
18670 (org-at-item-p)))
18671 (call-interactively 'org-indent-item-tree))
18672 (t (org-modifier-cursor-error))))
18674 (defun org-shiftmetaup (&optional arg)
18675 "Move subtree up or kill table row.
18676 Calls `org-move-subtree-up' or `org-table-kill-row' or
18677 `org-move-item-up' or `org-timestamp-up', depending on context.
18678 See the individual commands for more information."
18679 (interactive "P")
18680 (cond
18681 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18682 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18683 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18684 ((org-at-item-p) (call-interactively 'org-move-item-up))
18685 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18686 (call-interactively 'org-timestamp-up)))
18687 (t (org-modifier-cursor-error))))
18689 (defun org-shiftmetadown (&optional arg)
18690 "Move subtree down or insert table row.
18691 Calls `org-move-subtree-down' or `org-table-insert-row' or
18692 `org-move-item-down' or `org-timestamp-up', depending on context.
18693 See the individual commands for more information."
18694 (interactive "P")
18695 (cond
18696 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18697 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18698 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18699 ((org-at-item-p) (call-interactively 'org-move-item-down))
18700 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18701 (call-interactively 'org-timestamp-down)))
18702 (t (org-modifier-cursor-error))))
18704 (defsubst org-hidden-tree-error ()
18705 (error
18706 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18708 (defun org-metaleft (&optional arg)
18709 "Promote heading or move table column to left.
18710 Calls `org-do-promote' or `org-table-move-column', depending on context.
18711 With no specific context, calls the Emacs default `backward-word'.
18712 See the individual commands for more information."
18713 (interactive "P")
18714 (cond
18715 ((run-hook-with-args-until-success 'org-metaleft-hook))
18716 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18717 ((org-with-limited-levels
18718 (or (org-at-heading-p)
18719 (and (org-region-active-p)
18720 (save-excursion
18721 (goto-char (region-beginning))
18722 (org-at-heading-p)))))
18723 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18724 (call-interactively 'org-do-promote))
18725 ;; At an inline task.
18726 ((org-at-heading-p)
18727 (call-interactively 'org-inlinetask-promote))
18728 ((or (org-at-item-p)
18729 (and (org-region-active-p)
18730 (save-excursion
18731 (goto-char (region-beginning))
18732 (org-at-item-p))))
18733 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18734 (call-interactively 'org-outdent-item))
18735 (t (call-interactively 'backward-word))))
18737 (defun org-metaright (&optional arg)
18738 "Demote a subtree, a list item or move table column to right.
18739 In front of a drawer or a block keyword, indent it correctly.
18740 With no specific context, calls the Emacs default `forward-word'.
18741 See the individual commands for more information."
18742 (interactive "P")
18743 (cond
18744 ((run-hook-with-args-until-success 'org-metaright-hook))
18745 ((org-at-table-p) (call-interactively 'org-table-move-column))
18746 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18747 ((org-at-block-p) (call-interactively 'org-indent-block))
18748 ((org-with-limited-levels
18749 (or (org-at-heading-p)
18750 (and (org-region-active-p)
18751 (save-excursion
18752 (goto-char (region-beginning))
18753 (org-at-heading-p)))))
18754 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18755 (call-interactively 'org-do-demote))
18756 ;; At an inline task.
18757 ((org-at-heading-p)
18758 (call-interactively 'org-inlinetask-demote))
18759 ((or (org-at-item-p)
18760 (and (org-region-active-p)
18761 (save-excursion
18762 (goto-char (region-beginning))
18763 (org-at-item-p))))
18764 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18765 (call-interactively 'org-indent-item))
18766 (t (call-interactively 'forward-word))))
18768 (defun org-check-for-hidden (what)
18769 "Check if there are hidden headlines/items in the current visual line.
18770 WHAT can be either `headlines' or `items'. If the current line is
18771 an outline or item heading and it has a folded subtree below it,
18772 this function returns t, nil otherwise."
18773 (let ((re (cond
18774 ((eq what 'headlines) org-outline-regexp-bol)
18775 ((eq what 'items) (org-item-beginning-re))
18776 (t (error "This should not happen"))))
18777 beg end)
18778 (save-excursion
18779 (catch 'exit
18780 (unless (org-region-active-p)
18781 (setq beg (point-at-bol))
18782 (beginning-of-line 2)
18783 (while (and (not (eobp)) ;; this is like `next-line'
18784 (get-char-property (1- (point)) 'invisible))
18785 (beginning-of-line 2))
18786 (setq end (point))
18787 (goto-char beg)
18788 (goto-char (point-at-eol))
18789 (setq end (max end (point)))
18790 (while (re-search-forward re end t)
18791 (if (get-char-property (match-beginning 0) 'invisible)
18792 (throw 'exit t))))
18793 nil))))
18795 (autoload 'org-element-at-point "org-element")
18797 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18798 (declare-function org-element-type "org-element" (element))
18799 (declare-function org-element-context "org-element" ())
18800 (declare-function org-element-contents "org-element" (element))
18801 (declare-function org-element-property "org-element" (property element))
18802 (declare-function org-element-paragraph-parser "org-element" (limit))
18803 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18804 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18805 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18806 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18807 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18809 (defun org-metaup (&optional arg)
18810 "Move subtree up or move table row up.
18811 Calls `org-move-subtree-up' or `org-table-move-row' or
18812 `org-move-item-up', depending on context. See the individual commands
18813 for more information."
18814 (interactive "P")
18815 (cond
18816 ((run-hook-with-args-until-success 'org-metaup-hook))
18817 ((org-region-active-p)
18818 (let* ((a (min (region-beginning) (region-end)))
18819 (b (1- (max (region-beginning) (region-end))))
18820 (c (save-excursion (goto-char a)
18821 (move-beginning-of-line 0)))
18822 (d (save-excursion (goto-char a)
18823 (move-end-of-line 0) (point))))
18824 (transpose-regions a b c d)
18825 (goto-char c)))
18826 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18827 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18828 ((org-at-item-p) (call-interactively 'org-move-item-up))
18829 (t (org-drag-element-backward))))
18831 (defun org-metadown (&optional arg)
18832 "Move subtree down or move table row down.
18833 Calls `org-move-subtree-down' or `org-table-move-row' or
18834 `org-move-item-down', depending on context. See the individual
18835 commands for more information."
18836 (interactive "P")
18837 (cond
18838 ((run-hook-with-args-until-success 'org-metadown-hook))
18839 ((org-region-active-p)
18840 (let* ((a (min (region-beginning) (region-end)))
18841 (b (max (region-beginning) (region-end)))
18842 (c (save-excursion (goto-char b)
18843 (move-beginning-of-line 1)))
18844 (d (save-excursion (goto-char b)
18845 (move-end-of-line 1) (1+ (point)))))
18846 (transpose-regions a b c d)
18847 (goto-char d)))
18848 ((org-at-table-p) (call-interactively 'org-table-move-row))
18849 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18850 ((org-at-item-p) (call-interactively 'org-move-item-down))
18851 (t (org-drag-element-forward))))
18853 (defun org-shiftup (&optional arg)
18854 "Increase item in timestamp or increase priority of current headline.
18855 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18856 depending on context. See the individual commands for more information."
18857 (interactive "P")
18858 (cond
18859 ((run-hook-with-args-until-success 'org-shiftup-hook))
18860 ((and org-support-shift-select (org-region-active-p))
18861 (org-call-for-shift-select 'previous-line))
18862 ((org-at-timestamp-p t)
18863 (call-interactively (if org-edit-timestamp-down-means-later
18864 'org-timestamp-down 'org-timestamp-up)))
18865 ((and (not (eq org-support-shift-select 'always))
18866 org-enable-priority-commands
18867 (org-at-heading-p))
18868 (call-interactively 'org-priority-up))
18869 ((and (not org-support-shift-select) (org-at-item-p))
18870 (call-interactively 'org-previous-item))
18871 ((org-clocktable-try-shift 'up arg))
18872 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18873 (org-support-shift-select
18874 (org-call-for-shift-select 'previous-line))
18875 (t (org-shiftselect-error))))
18877 (defun org-shiftdown (&optional arg)
18878 "Decrease item in timestamp or decrease priority of current headline.
18879 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18880 depending on context. See the individual commands for more information."
18881 (interactive "P")
18882 (cond
18883 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18884 ((and org-support-shift-select (org-region-active-p))
18885 (org-call-for-shift-select 'next-line))
18886 ((org-at-timestamp-p t)
18887 (call-interactively (if org-edit-timestamp-down-means-later
18888 'org-timestamp-up 'org-timestamp-down)))
18889 ((and (not (eq org-support-shift-select 'always))
18890 org-enable-priority-commands
18891 (org-at-heading-p))
18892 (call-interactively 'org-priority-down))
18893 ((and (not org-support-shift-select) (org-at-item-p))
18894 (call-interactively 'org-next-item))
18895 ((org-clocktable-try-shift 'down arg))
18896 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18897 (org-support-shift-select
18898 (org-call-for-shift-select 'next-line))
18899 (t (org-shiftselect-error))))
18901 (defun org-shiftright (&optional arg)
18902 "Cycle the thing at point or in the current line, depending on context.
18903 Depending on context, this does one of the following:
18905 - switch a timestamp at point one day into the future
18906 - on a headline, switch to the next TODO keyword.
18907 - on an item, switch entire list to the next bullet type
18908 - on a property line, switch to the next allowed value
18909 - on a clocktable definition line, move time block into the future"
18910 (interactive "P")
18911 (cond
18912 ((run-hook-with-args-until-success 'org-shiftright-hook))
18913 ((and org-support-shift-select (org-region-active-p))
18914 (org-call-for-shift-select 'forward-char))
18915 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18916 ((and (not (eq org-support-shift-select 'always))
18917 (org-at-heading-p))
18918 (let ((org-inhibit-logging
18919 (not org-treat-S-cursor-todo-selection-as-state-change))
18920 (org-inhibit-blocking
18921 (not org-treat-S-cursor-todo-selection-as-state-change)))
18922 (org-call-with-arg 'org-todo 'right)))
18923 ((or (and org-support-shift-select
18924 (not (eq org-support-shift-select 'always))
18925 (org-at-item-bullet-p))
18926 (and (not org-support-shift-select) (org-at-item-p)))
18927 (org-call-with-arg 'org-cycle-list-bullet nil))
18928 ((and (not (eq org-support-shift-select 'always))
18929 (org-at-property-p))
18930 (call-interactively 'org-property-next-allowed-value))
18931 ((org-clocktable-try-shift 'right arg))
18932 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18933 (org-support-shift-select
18934 (org-call-for-shift-select 'forward-char))
18935 (t (org-shiftselect-error))))
18937 (defun org-shiftleft (&optional arg)
18938 "Cycle the thing at point or in the current line, depending on context.
18939 Depending on context, this does one of the following:
18941 - switch a timestamp at point one day into the past
18942 - on a headline, switch to the previous TODO keyword.
18943 - on an item, switch entire list to the previous bullet type
18944 - on a property line, switch to the previous allowed value
18945 - on a clocktable definition line, move time block into the past"
18946 (interactive "P")
18947 (cond
18948 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18949 ((and org-support-shift-select (org-region-active-p))
18950 (org-call-for-shift-select 'backward-char))
18951 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18952 ((and (not (eq org-support-shift-select 'always))
18953 (org-at-heading-p))
18954 (let ((org-inhibit-logging
18955 (not org-treat-S-cursor-todo-selection-as-state-change))
18956 (org-inhibit-blocking
18957 (not org-treat-S-cursor-todo-selection-as-state-change)))
18958 (org-call-with-arg 'org-todo 'left)))
18959 ((or (and org-support-shift-select
18960 (not (eq org-support-shift-select 'always))
18961 (org-at-item-bullet-p))
18962 (and (not org-support-shift-select) (org-at-item-p)))
18963 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18964 ((and (not (eq org-support-shift-select 'always))
18965 (org-at-property-p))
18966 (call-interactively 'org-property-previous-allowed-value))
18967 ((org-clocktable-try-shift 'left arg))
18968 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18969 (org-support-shift-select
18970 (org-call-for-shift-select 'backward-char))
18971 (t (org-shiftselect-error))))
18973 (defun org-shiftcontrolright ()
18974 "Switch to next TODO set."
18975 (interactive)
18976 (cond
18977 ((and org-support-shift-select (org-region-active-p))
18978 (org-call-for-shift-select 'forward-word))
18979 ((and (not (eq org-support-shift-select 'always))
18980 (org-at-heading-p))
18981 (org-call-with-arg 'org-todo 'nextset))
18982 (org-support-shift-select
18983 (org-call-for-shift-select 'forward-word))
18984 (t (org-shiftselect-error))))
18986 (defun org-shiftcontrolleft ()
18987 "Switch to previous TODO set."
18988 (interactive)
18989 (cond
18990 ((and org-support-shift-select (org-region-active-p))
18991 (org-call-for-shift-select 'backward-word))
18992 ((and (not (eq org-support-shift-select 'always))
18993 (org-at-heading-p))
18994 (org-call-with-arg 'org-todo 'previousset))
18995 (org-support-shift-select
18996 (org-call-for-shift-select 'backward-word))
18997 (t (org-shiftselect-error))))
18999 (defun org-shiftcontrolup ()
19000 "Change timestamps synchronously up in CLOCK log lines."
19001 (interactive)
19002 (cond ((and (not org-support-shift-select)
19003 (org-at-clock-log-p)
19004 (org-at-timestamp-p t))
19005 (org-clock-timestamps-up))
19006 (t (org-shiftselect-error))))
19008 (defun org-shiftcontroldown ()
19009 "Change timestamps synchronously down in CLOCK log lines."
19010 (interactive)
19011 (cond ((and (not org-support-shift-select)
19012 (org-at-clock-log-p)
19013 (org-at-timestamp-p t))
19014 (org-clock-timestamps-down))
19015 (t (org-shiftselect-error))))
19017 (defun org-ctrl-c-ret ()
19018 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19019 (interactive)
19020 (cond
19021 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19022 (t (call-interactively 'org-insert-heading))))
19024 (defun org-find-visible ()
19025 (let ((s (point)))
19026 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19027 (get-char-property s 'invisible)))
19029 (defun org-find-invisible ()
19030 (let ((s (point)))
19031 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19032 (not (get-char-property s 'invisible))))
19035 (defun org-copy-visible (beg end)
19036 "Copy the visible parts of the region."
19037 (interactive "r")
19038 (let (snippets s)
19039 (save-excursion
19040 (save-restriction
19041 (narrow-to-region beg end)
19042 (setq s (goto-char (point-min)))
19043 (while (not (= (point) (point-max)))
19044 (goto-char (org-find-invisible))
19045 (push (buffer-substring s (point)) snippets)
19046 (setq s (goto-char (org-find-visible))))))
19047 (kill-new (apply 'concat (nreverse snippets)))))
19049 (defun org-copy-special ()
19050 "Copy region in table or copy current subtree.
19051 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19052 See the individual commands for more information."
19053 (interactive)
19054 (call-interactively
19055 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19057 (defun org-cut-special ()
19058 "Cut region in table or cut current subtree.
19059 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19060 See the individual commands for more information."
19061 (interactive)
19062 (call-interactively
19063 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19065 (defun org-paste-special (arg)
19066 "Paste rectangular region into table, or past subtree relative to level.
19067 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19068 See the individual commands for more information."
19069 (interactive "P")
19070 (if (org-at-table-p)
19071 (org-table-paste-rectangle)
19072 (org-paste-subtree arg)))
19074 (defun org-edit-special (&optional arg)
19075 "Call a special editor for the stuff at point.
19076 When at a table, call the formula editor with `org-table-edit-formulas'.
19077 When at the first line of an src example, call `org-edit-src-code'.
19078 When in an #+include line, visit the include file. Otherwise call
19079 `ffap' to visit the file at point."
19080 (interactive)
19081 ;; possibly prep session before editing source
19082 (when arg
19083 (let* ((info (org-babel-get-src-block-info))
19084 (lang (nth 0 info))
19085 (params (nth 2 info))
19086 (session (cdr (assoc :session params))))
19087 (when (and info session) ;; we are in a source-code block with a session
19088 (funcall
19089 (intern (concat "org-babel-prep-session:" lang)) session params))))
19090 (cond ;; proceed with `org-edit-special'
19091 ((save-excursion
19092 (beginning-of-line 1)
19093 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19094 (find-file (org-trim (match-string 1))))
19095 ((org-edit-src-code))
19096 ((org-edit-fixed-width-region))
19097 ((org-at-table.el-p)
19098 (org-edit-src-code))
19099 ((or (org-at-table-p)
19100 (save-excursion
19101 (beginning-of-line 1)
19102 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19103 (call-interactively 'org-table-edit-formulas))
19104 (t (call-interactively 'ffap))))
19106 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19107 (defun org-ctrl-c-ctrl-c (&optional arg)
19108 "Set tags in headline, or update according to changed information at point.
19110 This command does many different things, depending on context:
19112 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19113 this is what we do.
19115 - If the cursor is on a statistics cookie, update it.
19117 - If the cursor is in a headline, prompt for tags and insert them
19118 into the current line, aligned to `org-tags-column'. When called
19119 with prefix arg, realign all tags in the current buffer.
19121 - If the cursor is in one of the special #+KEYWORD lines, this
19122 triggers scanning the buffer for these lines and updating the
19123 information.
19125 - If the cursor is inside a table, realign the table. This command
19126 works even if the automatic table editor has been turned off.
19128 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19129 the entire table.
19131 - If the cursor is at a footnote reference or definition, jump to
19132 the corresponding definition or references, respectively.
19134 - If the cursor is a the beginning of a dynamic block, update it.
19136 - If the current buffer is a capture buffer, close note and file it.
19138 - If the cursor is on a <<<target>>>, update radio targets and
19139 corresponding links in this buffer.
19141 - If the cursor is on a numbered item in a plain list, renumber the
19142 ordered list.
19144 - If the cursor is on a checkbox, toggle it.
19146 - If the cursor is on a code block, evaluate it. The variable
19147 `org-confirm-babel-evaluate' can be used to control prompting
19148 before code block evaluation, by default every code block
19149 evaluation requires confirmation. Code block evaluation can be
19150 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19151 (interactive "P")
19152 (let ((org-enable-table-editor t))
19153 (cond
19154 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19155 org-occur-highlights
19156 org-latex-fragment-image-overlays)
19157 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19158 (org-remove-occur-highlights)
19159 (org-remove-latex-fragment-image-overlays)
19160 (message "Temporary highlights/overlays removed from current buffer"))
19161 ((and (local-variable-p 'org-finish-function (current-buffer))
19162 (fboundp org-finish-function))
19163 (funcall org-finish-function))
19164 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19165 ((org-in-regexp org-ts-regexp-both)
19166 (org-timestamp-change 0 'day))
19167 ((or (looking-at org-property-start-re)
19168 (org-at-property-p))
19169 (call-interactively 'org-property-action))
19170 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19171 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19172 (or (org-at-heading-p) (org-at-item-p)))
19173 (call-interactively 'org-update-statistics-cookies))
19174 ((org-at-heading-p) (call-interactively 'org-set-tags))
19175 ((org-at-table.el-p)
19176 (message "Use C-c ' to edit table.el tables"))
19177 ((org-at-table-p)
19178 (org-table-maybe-eval-formula)
19179 (if arg
19180 (call-interactively 'org-table-recalculate)
19181 (org-table-maybe-recalculate-line))
19182 (call-interactively 'org-table-align)
19183 (orgtbl-send-table 'maybe))
19184 ((or (org-footnote-at-reference-p)
19185 (org-footnote-at-definition-p))
19186 (call-interactively 'org-footnote-action))
19187 ((org-at-item-checkbox-p)
19188 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19189 ;; list only if at top item.
19190 (let* ((cbox (match-string 1))
19191 (struct (org-list-struct))
19192 (old-struct (copy-tree struct))
19193 (parents (org-list-parents-alist struct))
19194 (orderedp (org-entry-get nil "ORDERED"))
19195 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19196 block-item)
19197 ;; Use a light version of `org-toggle-checkbox' to avoid
19198 ;; computing list structure twice.
19199 (let ((new-box (cond
19200 ((equal arg '(16)) "[-]")
19201 ((equal arg '(4)) nil)
19202 ((equal "[X]" cbox) "[ ]")
19203 (t "[X]"))))
19204 (if (and firstp arg)
19205 ;; If at first item of sub-list, remove check-box from
19206 ;; every item at the same level.
19207 (mapc
19208 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19209 (org-list-get-all-items
19210 (point-at-bol) struct (org-list-prevs-alist struct)))
19211 (org-list-set-checkbox (point-at-bol) struct new-box)))
19212 ;; Replicate `org-list-write-struct', while grabbing a return
19213 ;; value from `org-list-struct-fix-box'.
19214 (org-list-struct-fix-ind struct parents 2)
19215 (org-list-struct-fix-item-end struct)
19216 (let ((prevs (org-list-prevs-alist struct)))
19217 (org-list-struct-fix-bul struct prevs)
19218 (org-list-struct-fix-ind struct parents)
19219 (setq block-item
19220 (org-list-struct-fix-box struct parents prevs orderedp)))
19221 (org-list-struct-apply-struct struct old-struct)
19222 (org-update-checkbox-count-maybe)
19223 (when block-item
19224 (message
19225 "Checkboxes were removed due to unchecked box at line %d"
19226 (org-current-line block-item)))
19227 (when firstp (org-list-send-list 'maybe))))
19228 ((org-at-item-p)
19229 ;; Cursor at an item: repair list. Do checkbox related actions
19230 ;; only if function was called with an argument. Send list only
19231 ;; if at top item.
19232 (let* ((struct (org-list-struct))
19233 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19234 old-struct)
19235 (when arg
19236 (setq old-struct (copy-tree struct))
19237 (if firstp
19238 ;; If at first item of sub-list, add check-box to every
19239 ;; item at the same level.
19240 (mapc
19241 (lambda (pos)
19242 (unless (org-list-get-checkbox pos struct)
19243 (org-list-set-checkbox pos struct "[ ]")))
19244 (org-list-get-all-items
19245 (point-at-bol) struct (org-list-prevs-alist struct)))
19246 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19247 (org-list-write-struct
19248 struct (org-list-parents-alist struct) old-struct)
19249 (when arg (org-update-checkbox-count-maybe))
19250 (when firstp (org-list-send-list 'maybe))))
19251 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19252 ;; Dynamic block
19253 (beginning-of-line 1)
19254 (save-excursion (org-update-dblock)))
19255 ((save-excursion
19256 (let ((case-fold-search t))
19257 (beginning-of-line 1)
19258 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19259 (cond
19260 ((or (equal (match-string 1) "TBLFM")
19261 (equal (match-string 1) "tblfm"))
19262 ;; Recalculate the table before this line
19263 (save-excursion
19264 (beginning-of-line 1)
19265 (skip-chars-backward " \r\n\t")
19266 (if (org-at-table-p)
19267 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19269 (let ((org-inhibit-startup-visibility-stuff t)
19270 (org-startup-align-all-tables nil))
19271 (when (boundp 'org-table-coordinate-overlays)
19272 (mapc 'delete-overlay org-table-coordinate-overlays)
19273 (setq org-table-coordinate-overlays nil))
19274 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19275 (message "Local setup has been refreshed"))))
19276 ((org-clock-update-time-maybe))
19278 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19279 (error "C-c C-c can do nothing useful at this location"))))))
19281 (defun org-mode-restart ()
19282 "Restart Org-mode, to scan again for special lines.
19283 Also updates the keyword regular expressions."
19284 (interactive)
19285 (org-mode)
19286 (message "Org-mode restarted"))
19288 (defun org-kill-note-or-show-branches ()
19289 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19290 (interactive)
19291 (if (not org-finish-function)
19292 (progn
19293 (hide-subtree)
19294 (call-interactively 'show-branches))
19295 (let ((org-note-abort t))
19296 (funcall org-finish-function))))
19298 (defun org-return (&optional indent)
19299 "Goto next table row or insert a newline.
19300 Calls `org-table-next-row' or `newline', depending on context.
19301 See the individual commands for more information."
19302 (interactive)
19303 (let (org-ts-what)
19304 (cond
19305 ((or (bobp) (org-in-src-block-p))
19306 (if indent (newline-and-indent) (newline)))
19307 ((org-at-table-p)
19308 (org-table-justify-field-maybe)
19309 (call-interactively 'org-table-next-row))
19310 ;; when `newline-and-indent' is called within a list, make sure
19311 ;; text moved stays inside the item.
19312 ((and (org-in-item-p) indent)
19313 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19314 (progn
19315 (save-match-data (newline))
19316 (org-indent-line-to (length (match-string 0))))
19317 (let ((ind (org-get-indentation)))
19318 (newline)
19319 (if (org-looking-back org-list-end-re)
19320 (org-indent-line)
19321 (org-indent-line-to ind)))))
19322 ((and org-return-follows-link
19323 (org-at-timestamp-p t)
19324 (not (eq org-ts-what 'after)))
19325 (org-follow-timestamp-link))
19326 ((and org-return-follows-link
19327 (let ((tprop (get-text-property (point) 'face)))
19328 (or (eq tprop 'org-link)
19329 (and (listp tprop) (memq 'org-link tprop)))))
19330 (call-interactively 'org-open-at-point))
19331 ((and (org-at-heading-p)
19332 (looking-at
19333 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19334 (org-show-entry)
19335 (end-of-line 1)
19336 (newline))
19337 (t (if indent (newline-and-indent) (newline))))))
19339 (defun org-return-indent ()
19340 "Goto next table row or insert a newline and indent.
19341 Calls `org-table-next-row' or `newline-and-indent', depending on
19342 context. See the individual commands for more information."
19343 (interactive)
19344 (org-return t))
19346 (defun org-ctrl-c-star ()
19347 "Compute table, or change heading status of lines.
19348 Calls `org-table-recalculate' or `org-toggle-heading',
19349 depending on context."
19350 (interactive)
19351 (cond
19352 ((org-at-table-p)
19353 (call-interactively 'org-table-recalculate))
19355 ;; Convert all lines in region to list items
19356 (call-interactively 'org-toggle-heading))))
19358 (defun org-ctrl-c-minus ()
19359 "Insert separator line in table or modify bullet status of line.
19360 Also turns a plain line or a region of lines into list items.
19361 Calls `org-table-insert-hline', `org-toggle-item', or
19362 `org-cycle-list-bullet', depending on context."
19363 (interactive)
19364 (cond
19365 ((org-at-table-p)
19366 (call-interactively 'org-table-insert-hline))
19367 ((org-region-active-p)
19368 (call-interactively 'org-toggle-item))
19369 ((org-in-item-p)
19370 (call-interactively 'org-cycle-list-bullet))
19372 (call-interactively 'org-toggle-item))))
19374 (defun org-toggle-item (arg)
19375 "Convert headings or normal lines to items, items to normal lines.
19376 If there is no active region, only the current line is considered.
19378 If the first non blank line in the region is an headline, convert
19379 all headlines to items, shifting text accordingly.
19381 If it is an item, convert all items to normal lines.
19383 If it is normal text, change region into an item. With a prefix
19384 argument ARG, change each line in region into an item."
19385 (interactive "P")
19386 (let ((shift-text
19387 (function
19388 ;; Shift text in current section to IND, from point to END.
19389 ;; The function leaves point to END line.
19390 (lambda (ind end)
19391 (let ((min-i 1000) (end (copy-marker end)))
19392 ;; First determine the minimum indentation (MIN-I) of
19393 ;; the text.
19394 (save-excursion
19395 (catch 'exit
19396 (while (< (point) end)
19397 (let ((i (org-get-indentation)))
19398 (cond
19399 ;; Skip blank lines and inline tasks.
19400 ((looking-at "^[ \t]*$"))
19401 ((looking-at org-outline-regexp-bol))
19402 ;; We can't find less than 0 indentation.
19403 ((zerop i) (throw 'exit (setq min-i 0)))
19404 ((< i min-i) (setq min-i i))))
19405 (forward-line))))
19406 ;; Then indent each line so that a line indented to
19407 ;; MIN-I becomes indented to IND. Ignore blank lines
19408 ;; and inline tasks in the process.
19409 (let ((delta (- ind min-i)))
19410 (while (< (point) end)
19411 (unless (or (looking-at "^[ \t]*$")
19412 (looking-at org-outline-regexp-bol))
19413 (org-indent-line-to (+ (org-get-indentation) delta)))
19414 (forward-line)))))))
19415 (skip-blanks
19416 (function
19417 ;; Return beginning of first non-blank line, starting from
19418 ;; line at POS.
19419 (lambda (pos)
19420 (save-excursion
19421 (goto-char pos)
19422 (skip-chars-forward " \r\t\n")
19423 (point-at-bol)))))
19424 beg end)
19425 ;; Determine boundaries of changes.
19426 (if (org-region-active-p)
19427 (setq beg (funcall skip-blanks (region-beginning))
19428 end (copy-marker (region-end)))
19429 (setq beg (funcall skip-blanks (point-at-bol))
19430 end (copy-marker (point-at-eol))))
19431 ;; Depending on the starting line, choose an action on the text
19432 ;; between BEG and END.
19433 (org-with-limited-levels
19434 (save-excursion
19435 (goto-char beg)
19436 (cond
19437 ;; Case 1. Start at an item: de-itemize. Note that it only
19438 ;; happens when a region is active: `org-ctrl-c-minus'
19439 ;; would call `org-cycle-list-bullet' otherwise.
19440 ((org-at-item-p)
19441 (while (< (point) end)
19442 (when (org-at-item-p)
19443 (skip-chars-forward " \t")
19444 (delete-region (point) (match-end 0)))
19445 (forward-line)))
19446 ;; Case 2. Start at an heading: convert to items.
19447 ((org-at-heading-p)
19448 (let* ((bul (org-list-bullet-string "-"))
19449 (bul-len (length bul))
19450 ;; Indentation of the first heading. It should be
19451 ;; relative to the indentation of its parent, if any.
19452 (start-ind (save-excursion
19453 (cond
19454 ((not org-adapt-indentation) 0)
19455 ((not (outline-previous-heading)) 0)
19456 (t (length (match-string 0))))))
19457 ;; Level of first heading. Further headings will be
19458 ;; compared to it to determine hierarchy in the list.
19459 (ref-level (org-reduced-level (org-outline-level))))
19460 (while (< (point) end)
19461 (let* ((level (org-reduced-level (org-outline-level)))
19462 (delta (max 0 (- level ref-level))))
19463 ;; If current headline is less indented than the first
19464 ;; one, set it as reference, in order to preserve
19465 ;; subtrees.
19466 (when (< level ref-level) (setq ref-level level))
19467 (replace-match bul t t)
19468 (org-indent-line-to (+ start-ind (* delta bul-len)))
19469 ;; Ensure all text down to END (or SECTION-END) belongs
19470 ;; to the newly created item.
19471 (let ((section-end (save-excursion
19472 (or (outline-next-heading) (point)))))
19473 (forward-line)
19474 (funcall shift-text
19475 (+ start-ind (* (1+ delta) bul-len))
19476 (min end section-end)))))))
19477 ;; Case 3. Normal line with ARG: turn each non-item line into
19478 ;; an item.
19479 (arg
19480 (while (< (point) end)
19481 (unless (or (org-at-heading-p) (org-at-item-p))
19482 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19483 (replace-match
19484 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19485 (forward-line)))
19486 ;; Case 4. Normal line without ARG: make the first line of
19487 ;; region an item, and shift indentation of others
19488 ;; lines to set them as item's body.
19489 (t (let* ((bul (org-list-bullet-string "-"))
19490 (bul-len (length bul))
19491 (ref-ind (org-get-indentation)))
19492 (skip-chars-forward " \t")
19493 (insert bul)
19494 (forward-line)
19495 (while (< (point) end)
19496 ;; Ensure that lines less indented than first one
19497 ;; still get included in item body.
19498 (funcall shift-text
19499 (+ ref-ind bul-len)
19500 (min end (save-excursion (or (outline-next-heading)
19501 (point)))))
19502 (forward-line)))))))))
19504 (defun org-toggle-heading (&optional nstars)
19505 "Convert headings to normal text, or items or text to headings.
19506 If there is no active region, only the current line is considered.
19508 With a \\[universal-argument] prefix, convert the whole list at
19509 point into heading.
19511 In a region:
19513 - If the first non blank line is an headline, remove the stars
19514 from all headlines in the region.
19516 - If it is a normal line turn each and every normal line (i.e. not an
19517 heading or an item) in the region into a heading.
19519 - If it is a plain list item, turn all plain list items into headings.
19521 When converting a line into a heading, the number of stars is chosen
19522 such that the lines become children of the current entry. However,
19523 when a prefix argument is given, its value determines the number of
19524 stars to add."
19525 (interactive "P")
19526 (let ((skip-blanks
19527 (function
19528 ;; Return beginning of first non-blank line, starting from
19529 ;; line at POS.
19530 (lambda (pos)
19531 (save-excursion
19532 (goto-char pos)
19533 (while (org-at-comment-p) (forward-line))
19534 (skip-chars-forward " \r\t\n")
19535 (point-at-bol)))))
19536 beg end toggled)
19537 ;; Determine boundaries of changes. If a universal prefix has
19538 ;; been given, put the list in a region. If region ends at a bol,
19539 ;; do not consider the last line to be in the region.
19541 (when (and current-prefix-arg (org-at-item-p))
19542 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19543 (org-mark-element))
19545 (if (org-region-active-p)
19546 (setq beg (funcall skip-blanks (region-beginning))
19547 end (copy-marker (save-excursion
19548 (goto-char (region-end))
19549 (if (bolp) (point) (point-at-eol)))))
19550 (setq beg (funcall skip-blanks (point-at-bol))
19551 end (copy-marker (point-at-eol))))
19552 ;; Ensure inline tasks don't count as headings.
19553 (org-with-limited-levels
19554 (save-excursion
19555 (goto-char beg)
19556 (cond
19557 ;; Case 1. Started at an heading: de-star headings.
19558 ((org-at-heading-p)
19559 (while (< (point) end)
19560 (when (org-at-heading-p t)
19561 (looking-at org-outline-regexp) (replace-match "")
19562 (setq toggled t))
19563 (forward-line)))
19564 ;; Case 2. Started at an item: change items into headlines.
19565 ;; One star will be added by `org-list-to-subtree'.
19566 ((org-at-item-p)
19567 (let* ((stars (make-string
19568 (if nstars
19569 ;; subtract the star that will be added again by
19570 ;; `org-list-to-subtree'
19571 (1- (prefix-numeric-value current-prefix-arg))
19572 (or (org-current-level) 0))
19573 ?*))
19574 (add-stars
19575 (cond (nstars "") ; stars from prefix only
19576 ((equal stars "") "") ; before first heading
19577 (org-odd-levels-only "*") ; inside heading, odd
19578 (t "")))) ; inside heading, oddeven
19579 (while (< (point) end)
19580 (when (org-at-item-p)
19581 ;; Pay attention to cases when region ends before list.
19582 (let* ((struct (org-list-struct))
19583 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19584 (save-restriction
19585 (narrow-to-region (point) list-end)
19586 (insert
19587 (org-list-to-subtree
19588 (org-list-parse-list t)
19589 '(:istart (concat stars add-stars (funcall get-stars depth))
19590 :icount (concat stars add-stars (funcall get-stars depth)))))))
19591 (setq toggled t))
19592 (forward-line))))
19593 ;; Case 3. Started at normal text: make every line an heading,
19594 ;; skipping headlines and items.
19595 (t (let* ((stars (make-string
19596 (if nstars
19597 (prefix-numeric-value current-prefix-arg)
19598 (or (org-current-level) 0))
19599 ?*))
19600 (add-stars
19601 (cond (nstars "") ; stars from prefix only
19602 ((equal stars "") "*") ; before first heading
19603 (org-odd-levels-only "**") ; inside heading, odd
19604 (t "*"))) ; inside heading, oddeven
19605 (rpl (concat stars add-stars " ")))
19606 (while (< (point) end)
19607 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19608 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19609 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19610 (forward-line)))))))
19611 (unless toggled (message "Cannot toggle heading from here"))))
19613 (defun org-meta-return (&optional arg)
19614 "Insert a new heading or wrap a region in a table.
19615 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19616 See the individual commands for more information."
19617 (interactive "P")
19618 (cond
19619 ((run-hook-with-args-until-success 'org-metareturn-hook))
19620 ((or (org-at-drawer-p) (org-at-property-p))
19621 (newline-and-indent))
19622 ((org-at-table-p)
19623 (call-interactively 'org-table-wrap-region))
19624 (t (call-interactively 'org-insert-heading))))
19626 ;;; Menu entries
19628 (defsubst org-in-subtree-not-table-p ()
19629 "Are we in a subtree and not in a table?"
19630 (and (not (org-before-first-heading-p))
19631 (not (org-at-table-p))))
19633 ;; Define the Org-mode menus
19634 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19635 '("Tbl"
19636 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19637 ["Next Field" org-cycle (org-at-table-p)]
19638 ["Previous Field" org-shifttab (org-at-table-p)]
19639 ["Next Row" org-return (org-at-table-p)]
19640 "--"
19641 ["Blank Field" org-table-blank-field (org-at-table-p)]
19642 ["Edit Field" org-table-edit-field (org-at-table-p)]
19643 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19644 "--"
19645 ("Column"
19646 ["Move Column Left" org-metaleft (org-at-table-p)]
19647 ["Move Column Right" org-metaright (org-at-table-p)]
19648 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19649 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19650 ("Row"
19651 ["Move Row Up" org-metaup (org-at-table-p)]
19652 ["Move Row Down" org-metadown (org-at-table-p)]
19653 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19654 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19655 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19656 "--"
19657 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19658 ("Rectangle"
19659 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19660 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19661 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19662 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19663 "--"
19664 ("Calculate"
19665 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19666 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19667 ["Edit Formulas" org-edit-special (org-at-table-p)]
19668 "--"
19669 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19670 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19671 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19672 "--"
19673 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19674 "--"
19675 ["Sum Column/Rectangle" org-table-sum
19676 (or (org-at-table-p) (org-region-active-p))]
19677 ["Which Column?" org-table-current-column (org-at-table-p)])
19678 ["Debug Formulas"
19679 org-table-toggle-formula-debugger
19680 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19681 ["Show Col/Row Numbers"
19682 org-table-toggle-coordinate-overlays
19683 :style toggle
19684 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19685 "--"
19686 ["Create" org-table-create (and (not (org-at-table-p))
19687 org-enable-table-editor)]
19688 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19689 ["Import from File" org-table-import (not (org-at-table-p))]
19690 ["Export to File" org-table-export (org-at-table-p)]
19691 "--"
19692 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19694 (easy-menu-define org-org-menu org-mode-map "Org menu"
19695 '("Org"
19696 ("Show/Hide"
19697 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19698 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19699 ["Sparse Tree..." org-sparse-tree t]
19700 ["Reveal Context" org-reveal t]
19701 ["Show All" show-all t]
19702 "--"
19703 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19704 "--"
19705 ["New Heading" org-insert-heading t]
19706 ("Navigate Headings"
19707 ["Up" outline-up-heading t]
19708 ["Next" outline-next-visible-heading t]
19709 ["Previous" outline-previous-visible-heading t]
19710 ["Next Same Level" outline-forward-same-level t]
19711 ["Previous Same Level" outline-backward-same-level t]
19712 "--"
19713 ["Jump" org-goto t])
19714 ("Edit Structure"
19715 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19716 "--"
19717 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19718 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19719 "--"
19720 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19721 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19722 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19723 "--"
19724 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19725 "--"
19726 ["Copy visible text" org-copy-visible t]
19727 "--"
19728 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19729 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19730 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19731 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19732 "--"
19733 ["Sort Region/Children" org-sort t]
19734 "--"
19735 ["Convert to odd levels" org-convert-to-odd-levels t]
19736 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19737 ("Editing"
19738 ["Emphasis..." org-emphasize t]
19739 ["Edit Source Example" org-edit-special t]
19740 "--"
19741 ["Footnote new/jump" org-footnote-action t]
19742 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19743 ("Archive"
19744 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19745 "--"
19746 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19747 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19748 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19750 "--"
19751 ("Hyperlinks"
19752 ["Store Link (Global)" org-store-link t]
19753 ["Find existing link to here" org-occur-link-in-agenda-files t]
19754 ["Insert Link" org-insert-link t]
19755 ["Follow Link" org-open-at-point t]
19756 "--"
19757 ["Next link" org-next-link t]
19758 ["Previous link" org-previous-link t]
19759 "--"
19760 ["Descriptive Links"
19761 org-toggle-link-display
19762 :style radio
19763 :selected org-descriptive-links
19765 ["Literal Links"
19766 org-toggle-link-display
19767 :style radio
19768 :selected (not org-descriptive-links)])
19769 "--"
19770 ("TODO Lists"
19771 ["TODO/DONE/-" org-todo t]
19772 ("Select keyword"
19773 ["Next keyword" org-shiftright (org-at-heading-p)]
19774 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19775 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19776 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19777 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19778 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19779 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19780 "--"
19781 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19782 :selected org-enforce-todo-dependencies :style toggle :active t]
19783 "Settings for tree at point"
19784 ["Do Children sequentially" org-toggle-ordered-property :style radio
19785 :selected (org-entry-get nil "ORDERED")
19786 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19787 ["Do Children parallel" org-toggle-ordered-property :style radio
19788 :selected (not (org-entry-get nil "ORDERED"))
19789 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19790 "--"
19791 ["Set Priority" org-priority t]
19792 ["Priority Up" org-shiftup t]
19793 ["Priority Down" org-shiftdown t]
19794 "--"
19795 ["Get news from all feeds" org-feed-update-all t]
19796 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19797 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19798 ("TAGS and Properties"
19799 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19800 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19801 "--"
19802 ["Set property" org-set-property (not (org-before-first-heading-p))]
19803 ["Column view of properties" org-columns t]
19804 ["Insert Column View DBlock" org-insert-columns-dblock t])
19805 ("Dates and Scheduling"
19806 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19807 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19808 ("Change Date"
19809 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19810 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19811 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19812 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19813 ["Compute Time Range" org-evaluate-time-range t]
19814 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19815 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19816 "--"
19817 ["Custom time format" org-toggle-time-stamp-overlays
19818 :style radio :selected org-display-custom-times]
19819 "--"
19820 ["Goto Calendar" org-goto-calendar t]
19821 ["Date from Calendar" org-date-from-calendar t]
19822 "--"
19823 ["Start/Restart Timer" org-timer-start t]
19824 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19825 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19826 ["Insert Timer String" org-timer t]
19827 ["Insert Timer Item" org-timer-item t])
19828 ("Logging work"
19829 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19830 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19831 ["Clock out" org-clock-out t]
19832 ["Clock cancel" org-clock-cancel t]
19833 "--"
19834 ["Mark as default task" org-clock-mark-default-task t]
19835 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19836 ["Goto running clock" org-clock-goto t]
19837 "--"
19838 ["Display times" org-clock-display t]
19839 ["Create clock table" org-clock-report t]
19840 "--"
19841 ["Record DONE time"
19842 (progn (setq org-log-done (not org-log-done))
19843 (message "Switching to %s will %s record a timestamp"
19844 (car org-done-keywords)
19845 (if org-log-done "automatically" "not")))
19846 :style toggle :selected org-log-done])
19847 "--"
19848 ["Agenda Command..." org-agenda t]
19849 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19850 ("File List for Agenda")
19851 ("Special views current file"
19852 ["TODO Tree" org-show-todo-tree t]
19853 ["Check Deadlines" org-check-deadlines t]
19854 ["Timeline" org-timeline t]
19855 ["Tags/Property tree" org-match-sparse-tree t])
19856 "--"
19857 ["Export/Publish..." org-export t]
19858 ("LaTeX"
19859 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19860 :selected org-cdlatex-mode]
19861 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19862 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19863 ["Modify math symbol" org-cdlatex-math-modify
19864 (org-inside-LaTeX-fragment-p)]
19865 ["Insert citation" org-reftex-citation t]
19866 "--"
19867 ["Template for BEAMER" (progn (require 'org-beamer)
19868 (org-insert-beamer-options-template)) t])
19869 "--"
19870 ("MobileOrg"
19871 ["Push Files and Views" org-mobile-push t]
19872 ["Get Captured and Flagged" org-mobile-pull t]
19873 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19874 "--"
19875 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19876 "--"
19877 ("Documentation"
19878 ["Show Version" org-version t]
19879 ["Info Documentation" org-info t])
19880 ("Customize"
19881 ["Browse Org Group" org-customize t]
19882 "--"
19883 ["Expand This Menu" org-create-customize-menu
19884 (fboundp 'customize-menu-create)])
19885 ["Send bug report" org-submit-bug-report t]
19886 "--"
19887 ("Refresh/Reload"
19888 ["Refresh setup current buffer" org-mode-restart t]
19889 ["Reload Org (after update)" org-reload t]
19890 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19893 (defun org-info (&optional node)
19894 "Read documentation for Org-mode in the info system.
19895 With optional NODE, go directly to that node."
19896 (interactive)
19897 (info (format "(org)%s" (or node ""))))
19899 ;;;###autoload
19900 (defun org-submit-bug-report ()
19901 "Submit a bug report on Org-mode via mail.
19903 Don't hesitate to report any problems or inaccurate documentation.
19905 If you don't have setup sending mail from (X)Emacs, please copy the
19906 output buffer into your mail program, as it gives us important
19907 information about your Org-mode version and configuration."
19908 (interactive)
19909 (require 'reporter)
19910 (org-load-modules-maybe)
19911 (org-require-autoloaded-modules)
19912 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19913 (reporter-submit-bug-report
19914 "emacs-orgmode@gnu.org"
19915 (org-version nil 'full)
19916 (let (list)
19917 (save-window-excursion
19918 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19919 (delete-other-windows)
19920 (erase-buffer)
19921 (insert "You are about to submit a bug report to the Org-mode mailing list.
19923 We would like to add your full Org-mode and Outline configuration to the
19924 bug report. This greatly simplifies the work of the maintainer and
19925 other experts on the mailing list.
19927 HOWEVER, some variables you have customized may contain private
19928 information. The names of customers, colleagues, or friends, might
19929 appear in the form of file names, tags, todo states, or search strings.
19930 If you answer yes to the prompt, you might want to check and remove
19931 such private information before sending the email.")
19932 (add-text-properties (point-min) (point-max) '(face org-warning))
19933 (when (yes-or-no-p "Include your Org-mode configuration ")
19934 (mapatoms
19935 (lambda (v)
19936 (and (boundp v)
19937 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19938 (or (and (symbol-value v)
19939 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19940 (and
19941 (get v 'custom-type) (get v 'standard-value)
19942 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19943 (push v list)))))
19944 (kill-buffer (get-buffer "*Warn about privacy*"))
19945 list))
19946 nil nil
19947 "Remember to cover the basics, that is, what you expected to happen and
19948 what in fact did happen. You don't know how to make a good report? See
19950 http://orgmode.org/manual/Feedback.html#Feedback
19952 Your bug report will be posted to the Org-mode mailing list.
19953 ------------------------------------------------------------------------")
19954 (save-excursion
19955 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19956 (replace-match "\\1Bug: \\3 [\\2]")))))
19959 (defun org-install-agenda-files-menu ()
19960 (let ((bl (buffer-list)))
19961 (save-excursion
19962 (while bl
19963 (set-buffer (pop bl))
19964 (if (derived-mode-p 'org-mode) (setq bl nil)))
19965 (when (derived-mode-p 'org-mode)
19966 (easy-menu-change
19967 '("Org") "File List for Agenda"
19968 (append
19969 (list
19970 ["Edit File List" (org-edit-agenda-file-list) t]
19971 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19972 ["Remove Current File from List" org-remove-file t]
19973 ["Cycle through agenda files" org-cycle-agenda-files t]
19974 ["Occur in all agenda files" org-occur-in-agenda-files t]
19975 "--")
19976 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19978 ;;;; Documentation
19980 (defun org-require-autoloaded-modules ()
19981 (interactive)
19982 (mapc 'require
19983 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19984 org-docbook org-exp org-html org-icalendar
19985 org-id org-latex
19986 org-publish org-remember org-table
19987 org-timer org-xoxo)))
19989 ;;;###autoload
19990 (defun org-reload (&optional uncompiled)
19991 "Reload all org lisp files.
19992 With prefix arg UNCOMPILED, load the uncompiled versions."
19993 (interactive "P")
19994 (require 'find-func)
19995 (let* ((file-re "^org\\(-.*\\)?\\.el")
19996 (dir-org (file-name-directory (org-find-library-dir "org")))
19997 (dir-org-contrib (ignore-errors
19998 (file-name-directory
19999 (org-find-library-dir "org-contribdir"))))
20000 (babel-files
20001 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
20002 (append (list nil "comint" "eval" "exp" "keys"
20003 "lob" "ref" "table" "tangle")
20004 (delq nil
20005 (mapcar
20006 (lambda (lang)
20007 (when (cdr lang) (symbol-name (car lang))))
20008 org-babel-load-languages)))))
20009 (files
20010 (append babel-files
20011 (and dir-org-contrib
20012 (directory-files dir-org-contrib t file-re))
20013 (directory-files dir-org t file-re)))
20014 (remove-re (concat (if (featurep 'xemacs)
20015 "org-colview" "org-colview-xemacs")
20016 "\\'")))
20017 (setq files (mapcar 'file-name-sans-extension files))
20018 (setq files (mapcar
20019 (lambda (x) (if (string-match remove-re x) nil x))
20020 files))
20021 (setq files (delq nil files))
20022 (mapc
20023 (lambda (f)
20024 (when (featurep (intern (file-name-nondirectory f)))
20025 (if (and (not uncompiled)
20026 (file-exists-p (concat f ".elc")))
20027 (load (concat f ".elc") nil nil 'nosuffix)
20028 (load (concat f ".el") nil nil 'nosuffix))))
20029 files)
20030 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
20031 (org-version nil 'full 'message))
20033 ;;;###autoload
20034 (defun org-customize ()
20035 "Call the customize function with org as argument."
20036 (interactive)
20037 (org-load-modules-maybe)
20038 (org-require-autoloaded-modules)
20039 (customize-browse 'org))
20041 (defun org-create-customize-menu ()
20042 "Create a full customization menu for Org-mode, insert it into the menu."
20043 (interactive)
20044 (org-load-modules-maybe)
20045 (org-require-autoloaded-modules)
20046 (if (fboundp 'customize-menu-create)
20047 (progn
20048 (easy-menu-change
20049 '("Org") "Customize"
20050 `(["Browse Org group" org-customize t]
20051 "--"
20052 ,(customize-menu-create 'org)
20053 ["Set" Custom-set t]
20054 ["Save" Custom-save t]
20055 ["Reset to Current" Custom-reset-current t]
20056 ["Reset to Saved" Custom-reset-saved t]
20057 ["Reset to Standard Settings" Custom-reset-standard t]))
20058 (message "\"Org\"-menu now contains full customization menu"))
20059 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20061 ;;;; Miscellaneous stuff
20063 ;;; Generally useful functions
20065 (defun org-get-at-bol (property)
20066 "Get text property PROPERTY at beginning of line."
20067 (get-text-property (point-at-bol) property))
20069 (defun org-find-text-property-in-string (prop s)
20070 "Return the first non-nil value of property PROP in string S."
20071 (or (get-text-property 0 prop s)
20072 (get-text-property (or (next-single-property-change 0 prop s) 0)
20073 prop s)))
20075 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20076 "Display the given MESSAGE as a warning."
20077 (if (fboundp 'display-warning)
20078 (display-warning 'org message
20079 (if (featurep 'xemacs) 'warning :warning))
20080 (let ((buf (get-buffer-create "*Org warnings*")))
20081 (with-current-buffer buf
20082 (goto-char (point-max))
20083 (insert "Warning (Org): " message)
20084 (unless (bolp)
20085 (newline)))
20086 (display-buffer buf)
20087 (sit-for 0))))
20089 (defun org-eval (form)
20090 "Eval FORM and return result."
20091 (condition-case error
20092 (eval form)
20093 (error (format "%%![Error: %s]" error))))
20095 (defun org-in-clocktable-p ()
20096 "Check if the cursor is in a clocktable."
20097 (let ((pos (point)) start)
20098 (save-excursion
20099 (end-of-line 1)
20100 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20101 (setq start (match-beginning 0))
20102 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20103 (>= (match-end 0) pos)
20104 start))))
20106 (defun org-in-commented-line ()
20107 "Is point in a line starting with `#'?"
20108 (equal (char-after (point-at-bol)) ?#))
20110 (defun org-in-indented-comment-line ()
20111 "Is point in a line starting with `#' after some white space?"
20112 (save-excursion
20113 (save-match-data
20114 (goto-char (point-at-bol))
20115 (looking-at "[ \t]*#"))))
20117 (defun org-in-verbatim-emphasis ()
20118 (save-match-data
20119 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20121 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20122 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20123 (if (and marker (marker-buffer marker)
20124 (buffer-live-p (marker-buffer marker)))
20125 (progn
20126 (org-pop-to-buffer-same-window (marker-buffer marker))
20127 (if (or (> marker (point-max)) (< marker (point-min)))
20128 (widen))
20129 (goto-char marker)
20130 (org-show-context 'org-goto))
20131 (if bookmark
20132 (bookmark-jump bookmark)
20133 (error "Cannot find location"))))
20135 (defun org-quote-csv-field (s)
20136 "Quote field for inclusion in CSV material."
20137 (if (string-match "[\",]" s)
20138 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20141 (defun org-force-self-insert (N)
20142 "Needed to enforce self-insert under remapping."
20143 (interactive "p")
20144 (self-insert-command N))
20146 (defun org-string-width (s)
20147 "Compute width of string, ignoring invisible characters.
20148 This ignores character with invisibility property `org-link', and also
20149 characters with property `org-cwidth', because these will become invisible
20150 upon the next fontification round."
20151 (let (b l)
20152 (when (or (eq t buffer-invisibility-spec)
20153 (assq 'org-link buffer-invisibility-spec))
20154 (while (setq b (text-property-any 0 (length s)
20155 'invisible 'org-link s))
20156 (setq s (concat (substring s 0 b)
20157 (substring s (or (next-single-property-change
20158 b 'invisible s) (length s)))))))
20159 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20160 (setq s (concat (substring s 0 b)
20161 (substring s (or (next-single-property-change
20162 b 'org-cwidth s) (length s))))))
20163 (setq l (string-width s) b -1)
20164 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20165 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20168 (defun org-shorten-string (s maxlength)
20169 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20170 If the string is shorter or has length MAXLENGTH, just return the
20171 original string. If it is longer, the functions finds a space in the
20172 string, breaks this string off at that locations and adds three dots
20173 as ellipsis. Including the ellipsis, the string will not be longer
20174 than MAXLENGTH. If finding a good breaking point in the string does
20175 not work, the string is just chopped off in the middle of a word
20176 if necessary."
20177 (if (<= (length s) maxlength)
20179 (let* ((n (max (- maxlength 4) 1))
20180 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20181 (if (string-match re s)
20182 (concat (match-string 1 s) "...")
20183 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20185 (defun org-get-indentation (&optional line)
20186 "Get the indentation of the current line, interpreting tabs.
20187 When LINE is given, assume it represents a line and compute its indentation."
20188 (if line
20189 (if (string-match "^ *" (org-remove-tabs line))
20190 (match-end 0))
20191 (save-excursion
20192 (beginning-of-line 1)
20193 (skip-chars-forward " \t")
20194 (current-column))))
20196 (defun org-get-string-indentation (s)
20197 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20198 (let ((n -1) (i 0) (w tab-width) c)
20199 (catch 'exit
20200 (while (< (setq n (1+ n)) (length s))
20201 (setq c (aref s n))
20202 (cond ((= c ?\ ) (setq i (1+ i)))
20203 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20204 (t (throw 'exit t)))))
20207 (defun org-remove-tabs (s &optional width)
20208 "Replace tabulators in S with spaces.
20209 Assumes that s is a single line, starting in column 0."
20210 (setq width (or width tab-width))
20211 (while (string-match "\t" s)
20212 (setq s (replace-match
20213 (make-string
20214 (- (* width (/ (+ (match-beginning 0) width) width))
20215 (match-beginning 0)) ?\ )
20216 t t s)))
20219 (defun org-fix-indentation (line ind)
20220 "Fix indentation in LINE.
20221 IND is a cons cell with target and minimum indentation.
20222 If the current indentation in LINE is smaller than the minimum,
20223 leave it alone. If it is larger than ind, set it to the target."
20224 (let* ((l (org-remove-tabs line))
20225 (i (org-get-indentation l))
20226 (i1 (car ind)) (i2 (cdr ind)))
20227 (if (>= i i2) (setq l (substring line i2)))
20228 (if (> i1 0)
20229 (concat (make-string i1 ?\ ) l)
20230 l)))
20232 (defun org-remove-indentation (code &optional n)
20233 "Remove the maximum common indentation from the lines in CODE.
20234 N may optionally be the number of spaces to remove."
20235 (with-temp-buffer
20236 (insert code)
20237 (org-do-remove-indentation n)
20238 (buffer-string)))
20240 (defun org-do-remove-indentation (&optional n)
20241 "Remove the maximum common indentation from the buffer."
20242 (untabify (point-min) (point-max))
20243 (let ((min 10000) re)
20244 (if n
20245 (setq min n)
20246 (goto-char (point-min))
20247 (while (re-search-forward "^ *[^ \n]" nil t)
20248 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20249 (unless (or (= min 0) (= min 10000))
20250 (setq re (format "^ \\{%d\\}" min))
20251 (goto-char (point-min))
20252 (while (re-search-forward re nil t)
20253 (replace-match "")
20254 (end-of-line 1))
20255 min)))
20257 (defun org-fill-template (template alist)
20258 "Find each %key of ALIST in TEMPLATE and replace it."
20259 (let ((case-fold-search nil)
20260 entry key value)
20261 (setq alist (sort (copy-sequence alist)
20262 (lambda (a b) (< (length (car a)) (length (car b))))))
20263 (while (setq entry (pop alist))
20264 (setq template
20265 (replace-regexp-in-string
20266 (concat "%" (regexp-quote (car entry)))
20267 (or (cdr entry) "") template t t)))
20268 template))
20270 (defun org-base-buffer (buffer)
20271 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20272 (if (not buffer)
20273 buffer
20274 (or (buffer-base-buffer buffer)
20275 buffer)))
20277 (defun org-trim (s)
20278 "Remove whitespace at beginning and end of string."
20279 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20280 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20283 (defun org-wrap (string &optional width lines)
20284 "Wrap string to either a number of lines, or a width in characters.
20285 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20286 that costs. If there is a word longer than WIDTH, the text is actually
20287 wrapped to the length of that word.
20288 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20289 many lines, whatever width that takes.
20290 The return value is a list of lines, without newlines at the end."
20291 (let* ((words (org-split-string string "[ \t\n]+"))
20292 (maxword (apply 'max (mapcar 'org-string-width words)))
20293 w ll)
20294 (cond (width
20295 (org-do-wrap words (max maxword width)))
20296 (lines
20297 (setq w maxword)
20298 (setq ll (org-do-wrap words maxword))
20299 (if (<= (length ll) lines)
20301 (setq ll words)
20302 (while (> (length ll) lines)
20303 (setq w (1+ w))
20304 (setq ll (org-do-wrap words w)))
20305 ll))
20306 (t (error "Cannot wrap this")))))
20308 (defun org-do-wrap (words width)
20309 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20310 (let (lines line)
20311 (while words
20312 (setq line (pop words))
20313 (while (and words (< (+ (length line) (length (car words))) width))
20314 (setq line (concat line " " (pop words))))
20315 (setq lines (push line lines)))
20316 (nreverse lines)))
20318 (defun org-split-string (string &optional separators)
20319 "Splits STRING into substrings at SEPARATORS.
20320 No empty strings are returned if there are matches at the beginning
20321 and end of string."
20322 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20323 (start 0)
20324 notfirst
20325 (list nil))
20326 (while (and (string-match rexp string
20327 (if (and notfirst
20328 (= start (match-beginning 0))
20329 (< start (length string)))
20330 (1+ start) start))
20331 (< (match-beginning 0) (length string)))
20332 (setq notfirst t)
20333 (or (eq (match-beginning 0) 0)
20334 (and (eq (match-beginning 0) (match-end 0))
20335 (eq (match-beginning 0) start))
20336 (setq list
20337 (cons (substring string start (match-beginning 0))
20338 list)))
20339 (setq start (match-end 0)))
20340 (or (eq start (length string))
20341 (setq list
20342 (cons (substring string start)
20343 list)))
20344 (nreverse list)))
20346 (defun org-quote-vert (s)
20347 "Replace \"|\" with \"\\vert\"."
20348 (while (string-match "|" s)
20349 (setq s (replace-match "\\vert" t t s)))
20352 (defun org-uuidgen-p (s)
20353 "Is S an ID created by UUIDGEN?"
20354 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20356 (defun org-in-src-block-p nil
20357 "Whether point is in a code source block."
20358 (let (ov)
20359 (when (setq ov (overlays-at (point)))
20360 (memq 'org-block-background
20361 (overlay-properties
20362 (car ov))))))
20364 (defun org-context ()
20365 "Return a list of contexts of the current cursor position.
20366 If several contexts apply, all are returned.
20367 Each context entry is a list with a symbol naming the context, and
20368 two positions indicating start and end of the context. Possible
20369 contexts are:
20371 :headline anywhere in a headline
20372 :headline-stars on the leading stars in a headline
20373 :todo-keyword on a TODO keyword (including DONE) in a headline
20374 :tags on the TAGS in a headline
20375 :priority on the priority cookie in a headline
20376 :item on the first line of a plain list item
20377 :item-bullet on the bullet/number of a plain list item
20378 :checkbox on the checkbox in a plain list item
20379 :table in an org-mode table
20380 :table-special on a special filed in a table
20381 :table-table in a table.el table
20382 :clocktable in a clocktable
20383 :src-block in a source block
20384 :link on a hyperlink
20385 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20386 :target on a <<target>>
20387 :radio-target on a <<<radio-target>>>
20388 :latex-fragment on a LaTeX fragment
20389 :latex-preview on a LaTeX fragment with overlaid preview image
20391 This function expects the position to be visible because it uses font-lock
20392 faces as a help to recognize the following contexts: :table-special, :link,
20393 and :keyword."
20394 (let* ((f (get-text-property (point) 'face))
20395 (faces (if (listp f) f (list f)))
20396 (case-fold-search t)
20397 (p (point)) clist o)
20398 ;; First the large context
20399 (cond
20400 ((org-at-heading-p t)
20401 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20402 (when (progn
20403 (beginning-of-line 1)
20404 (looking-at org-todo-line-tags-regexp))
20405 (push (org-point-in-group p 1 :headline-stars) clist)
20406 (push (org-point-in-group p 2 :todo-keyword) clist)
20407 (push (org-point-in-group p 4 :tags) clist))
20408 (goto-char p)
20409 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20410 (if (looking-at "\\[#[A-Z0-9]\\]")
20411 (push (org-point-in-group p 0 :priority) clist)))
20413 ((org-at-item-p)
20414 (push (org-point-in-group p 2 :item-bullet) clist)
20415 (push (list :item (point-at-bol)
20416 (save-excursion (org-end-of-item) (point)))
20417 clist)
20418 (and (org-at-item-checkbox-p)
20419 (push (org-point-in-group p 0 :checkbox) clist)))
20421 ((org-at-table-p)
20422 (push (list :table (org-table-begin) (org-table-end)) clist)
20423 (if (memq 'org-formula faces)
20424 (push (list :table-special
20425 (previous-single-property-change p 'face)
20426 (next-single-property-change p 'face)) clist)))
20427 ((org-at-table-p 'any)
20428 (push (list :table-table) clist)))
20429 (goto-char p)
20431 (let ((case-fold-search t))
20432 ;; New the "medium" contexts: clocktables, source blocks
20433 (cond ((org-in-clocktable-p)
20434 (push (list :clocktable
20435 (and (or (looking-at "#\\+BEGIN: clocktable")
20436 (search-backward "#+BEGIN: clocktable" nil t))
20437 (match-beginning 0))
20438 (and (re-search-forward "#\\+END:?" nil t)
20439 (match-end 0))) clist))
20440 ((org-in-src-block-p)
20441 (push (list :src-block
20442 (and (or (looking-at "#\\+BEGIN_SRC")
20443 (search-backward "#+BEGIN_SRC" nil t))
20444 (match-beginning 0))
20445 (and (search-forward "#+END_SRC" nil t)
20446 (match-beginning 0))) clist))))
20447 (goto-char p)
20449 ;; Now the small context
20450 (cond
20451 ((org-at-timestamp-p)
20452 (push (org-point-in-group p 0 :timestamp) clist))
20453 ((memq 'org-link faces)
20454 (push (list :link
20455 (previous-single-property-change p 'face)
20456 (next-single-property-change p 'face)) clist))
20457 ((memq 'org-special-keyword faces)
20458 (push (list :keyword
20459 (previous-single-property-change p 'face)
20460 (next-single-property-change p 'face)) clist))
20461 ((org-at-target-p)
20462 (push (org-point-in-group p 0 :target) clist)
20463 (goto-char (1- (match-beginning 0)))
20464 (if (looking-at org-radio-target-regexp)
20465 (push (org-point-in-group p 0 :radio-target) clist))
20466 (goto-char p))
20467 ((setq o (car (delq nil
20468 (mapcar
20469 (lambda (x)
20470 (if (memq x org-latex-fragment-image-overlays) x))
20471 (overlays-at (point))))))
20472 (push (list :latex-fragment
20473 (overlay-start o) (overlay-end o)) clist)
20474 (push (list :latex-preview
20475 (overlay-start o) (overlay-end o)) clist))
20476 ((org-inside-LaTeX-fragment-p)
20477 ;; FIXME: positions wrong.
20478 (push (list :latex-fragment (point) (point)) clist)))
20480 (setq clist (nreverse (delq nil clist)))
20481 clist))
20483 ;; FIXME: Compare with at-regexp-p Do we need both?
20484 (defun org-in-regexp (re &optional nlines visually)
20485 "Check if point is inside a match of regexp.
20486 Normally only the current line is checked, but you can include NLINES extra
20487 lines both before and after point into the search.
20488 If VISUALLY is set, require that the cursor is not after the match but
20489 really on, so that the block visually is on the match."
20490 (catch 'exit
20491 (let ((pos (point))
20492 (eol (point-at-eol (+ 1 (or nlines 0))))
20493 (inc (if visually 1 0)))
20494 (save-excursion
20495 (beginning-of-line (- 1 (or nlines 0)))
20496 (while (re-search-forward re eol t)
20497 (if (and (<= (match-beginning 0) pos)
20498 (>= (+ inc (match-end 0)) pos))
20499 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20501 (defun org-at-regexp-p (regexp)
20502 "Is point inside a match of REGEXP in the current line?"
20503 (catch 'exit
20504 (save-excursion
20505 (let ((pos (point)) (end (point-at-eol)))
20506 (beginning-of-line 1)
20507 (while (re-search-forward regexp end t)
20508 (if (and (<= (match-beginning 0) pos)
20509 (>= (match-end 0) pos))
20510 (throw 'exit t)))
20511 nil))))
20513 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20514 "Non-nil when point is between matches of START-RE and END-RE.
20516 Also return a non-nil value when point is on one of the matches.
20518 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20519 buffer positions. Default values are the positions of headlines
20520 surrounding the point.
20522 The functions returns a cons cell whose car (resp. cdr) is the
20523 position before START-RE (resp. after END-RE)."
20524 (save-match-data
20525 (let ((pos (point))
20526 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20527 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20528 beg end)
20529 (save-excursion
20530 ;; Point is on a block when on START-RE or if START-RE can be
20531 ;; found before it...
20532 (and (or (org-at-regexp-p start-re)
20533 (re-search-backward start-re limit-up t))
20534 (setq beg (match-beginning 0))
20535 ;; ... and END-RE after it...
20536 (goto-char (match-end 0))
20537 (re-search-forward end-re limit-down t)
20538 (> (setq end (match-end 0)) pos)
20539 ;; ... without another START-RE in-between.
20540 (goto-char (match-beginning 0))
20541 (not (re-search-backward start-re (1+ beg) t))
20542 ;; Return value.
20543 (cons beg end))))))
20545 (defun org-in-block-p (names)
20546 "Non-nil when point belongs to a block whose name belongs to NAMES.
20548 NAMES is a list of strings containing names of blocks.
20550 Return first block name matched, or nil. Beware that in case of
20551 nested blocks, the returned name may not belong to the closest
20552 block from point."
20553 (save-match-data
20554 (catch 'exit
20555 (let ((case-fold-search t)
20556 (lim-up (save-excursion (outline-previous-heading)))
20557 (lim-down (save-excursion (outline-next-heading))))
20558 (mapc (lambda (name)
20559 (let ((n (regexp-quote name)))
20560 (when (org-between-regexps-p
20561 (concat "^[ \t]*#\\+begin_" n)
20562 (concat "^[ \t]*#\\+end_" n)
20563 lim-up lim-down)
20564 (throw 'exit n))))
20565 names))
20566 nil)))
20568 (defun org-occur-in-agenda-files (regexp &optional nlines)
20569 "Call `multi-occur' with buffers for all agenda files."
20570 (interactive "sOrg-files matching: \np")
20571 (let* ((files (org-agenda-files))
20572 (tnames (mapcar 'file-truename files))
20573 (extra org-agenda-text-search-extra-files)
20575 (when (eq (car extra) 'agenda-archives)
20576 (setq extra (cdr extra))
20577 (setq files (org-add-archive-files files)))
20578 (while (setq f (pop extra))
20579 (unless (member (file-truename f) tnames)
20580 (add-to-list 'files f 'append)
20581 (add-to-list 'tnames (file-truename f) 'append)))
20582 (multi-occur
20583 (mapcar (lambda (x)
20584 (with-current-buffer
20585 (or (get-file-buffer x) (find-file-noselect x))
20586 (widen)
20587 (current-buffer)))
20588 files)
20589 regexp)))
20591 (if (boundp 'occur-mode-find-occurrence-hook)
20592 ;; Emacs 23
20593 (add-hook 'occur-mode-find-occurrence-hook
20594 (lambda ()
20595 (when (derived-mode-p 'org-mode)
20596 (org-reveal))))
20597 ;; Emacs 22
20598 (defadvice occur-mode-goto-occurrence
20599 (after org-occur-reveal activate)
20600 (and (derived-mode-p 'org-mode) (org-reveal)))
20601 (defadvice occur-mode-goto-occurrence-other-window
20602 (after org-occur-reveal activate)
20603 (and (derived-mode-p 'org-mode) (org-reveal)))
20604 (defadvice occur-mode-display-occurrence
20605 (after org-occur-reveal activate)
20606 (when (derived-mode-p 'org-mode)
20607 (let ((pos (occur-mode-find-occurrence)))
20608 (with-current-buffer (marker-buffer pos)
20609 (save-excursion
20610 (goto-char pos)
20611 (org-reveal)))))))
20613 (defun org-occur-link-in-agenda-files ()
20614 "Create a link and search for it in the agendas.
20615 The link is not stored in `org-stored-links', it is just created
20616 for the search purpose."
20617 (interactive)
20618 (let ((link (condition-case nil
20619 (org-store-link nil)
20620 (error "Unable to create a link to here"))))
20621 (org-occur-in-agenda-files (regexp-quote link))))
20623 (defun org-uniquify (list)
20624 "Remove duplicate elements from LIST."
20625 (let (res)
20626 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20627 res))
20629 (defun org-delete-all (elts list)
20630 "Remove all elements in ELTS from LIST."
20631 (while elts
20632 (setq list (delete (pop elts) list)))
20633 list)
20635 (defun org-count (cl-item cl-seq)
20636 "Count the number of occurrences of ITEM in SEQ.
20637 Taken from `count' in cl-seq.el with all keyword arguments removed."
20638 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20639 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20640 (while (< cl-start cl-end)
20641 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20642 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20643 (setq cl-start (1+ cl-start)))
20644 cl-count))
20646 (defun org-remove-if (predicate seq)
20647 "Remove everything from SEQ that fulfills PREDICATE."
20648 (let (res e)
20649 (while seq
20650 (setq e (pop seq))
20651 (if (not (funcall predicate e)) (push e res)))
20652 (nreverse res)))
20654 (defun org-remove-if-not (predicate seq)
20655 "Remove everything from SEQ that does not fulfill PREDICATE."
20656 (let (res e)
20657 (while seq
20658 (setq e (pop seq))
20659 (if (funcall predicate e) (push e res)))
20660 (nreverse res)))
20662 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20663 "Reduce two-argument FUNCTION across SEQ.
20664 Taken from `reduce' in cl-seq.el with all keyword arguments but
20665 \":initial-value\" removed."
20666 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20667 (cadr (memq :initial-value cl-keys)))
20668 (cl-seq (pop cl-seq))
20669 (t (funcall cl-func)))))
20670 (while cl-seq
20671 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20672 cl-accum))
20674 (defun org-back-over-empty-lines ()
20675 "Move backwards over whitespace, to the beginning of the first empty line.
20676 Returns the number of empty lines passed."
20677 (let ((pos (point)))
20678 (if (cdr (assoc 'heading org-blank-before-new-entry))
20679 (skip-chars-backward " \t\n\r")
20680 (unless (eobp)
20681 (forward-line -1)))
20682 (beginning-of-line 2)
20683 (goto-char (min (point) pos))
20684 (count-lines (point) pos)))
20686 (defun org-skip-whitespace ()
20687 (skip-chars-forward " \t\n\r"))
20689 (defun org-point-in-group (point group &optional context)
20690 "Check if POINT is in match-group GROUP.
20691 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20692 match. If the match group does not exist or point is not inside it,
20693 return nil."
20694 (and (match-beginning group)
20695 (>= point (match-beginning group))
20696 (<= point (match-end group))
20697 (if context
20698 (list context (match-beginning group) (match-end group))
20699 t)))
20701 (defun org-switch-to-buffer-other-window (&rest args)
20702 "Switch to buffer in a second window on the current frame.
20703 In particular, do not allow pop-up frames.
20704 Returns the newly created buffer."
20705 (let (pop-up-frames special-display-buffer-names special-display-regexps
20706 special-display-function)
20707 (apply 'switch-to-buffer-other-window args)))
20709 (defun org-combine-plists (&rest plists)
20710 "Create a single property list from all plists in PLISTS.
20711 The process starts by copying the first list, and then setting properties
20712 from the other lists. Settings in the last list are the most significant
20713 ones and overrule settings in the other lists."
20714 (let ((rtn (copy-sequence (pop plists)))
20715 p v ls)
20716 (while plists
20717 (setq ls (pop plists))
20718 (while ls
20719 (setq p (pop ls) v (pop ls))
20720 (setq rtn (plist-put rtn p v))))
20721 rtn))
20723 (defun org-replace-escapes (string table)
20724 "Replace %-escapes in STRING with values in TABLE.
20725 TABLE is an association list with keys like \"%a\" and string values.
20726 The sequences in STRING may contain normal field width and padding information,
20727 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20728 so values can contain further %-escapes if they are define later in TABLE."
20729 (let ((tbl (copy-alist table))
20730 (case-fold-search nil)
20731 (pchg 0)
20732 e re rpl)
20733 (while (setq e (pop tbl))
20734 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20735 (when (and (cdr e) (string-match re (cdr e)))
20736 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20737 (safe "SREF"))
20738 (add-text-properties 0 3 (list 'sref sref) safe)
20739 (setcdr e (replace-match safe t t (cdr e)))))
20740 (while (string-match re string)
20741 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20742 (cdr e)))
20743 (setq string (replace-match rpl t t string))))
20744 (while (setq pchg (next-property-change pchg string))
20745 (let ((sref (get-text-property pchg 'sref string)))
20746 (when (and sref (string-match "SREF" string pchg))
20747 (setq string (replace-match sref t t string)))))
20748 string))
20750 (defun org-sublist (list start end)
20751 "Return a section of LIST, from START to END.
20752 Counting starts at 1."
20753 (let (rtn (c start))
20754 (setq list (nthcdr (1- start) list))
20755 (while (and list (<= c end))
20756 (push (pop list) rtn)
20757 (setq c (1+ c)))
20758 (nreverse rtn)))
20760 (defun org-find-base-buffer-visiting (file)
20761 "Like `find-buffer-visiting' but always return the base buffer and
20762 not an indirect buffer."
20763 (let ((buf (or (get-file-buffer file)
20764 (find-buffer-visiting file))))
20765 (if buf
20766 (or (buffer-base-buffer buf) buf)
20767 nil)))
20769 (defun org-image-file-name-regexp (&optional extensions)
20770 "Return regexp matching the file names of images.
20771 If EXTENSIONS is given, only match these."
20772 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20773 (image-file-name-regexp)
20774 (let ((image-file-name-extensions
20775 (or extensions
20776 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20777 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20778 (concat "\\."
20779 (regexp-opt (nconc (mapcar 'upcase
20780 image-file-name-extensions)
20781 image-file-name-extensions)
20783 "\\'"))))
20785 (defun org-file-image-p (file &optional extensions)
20786 "Return non-nil if FILE is an image."
20787 (save-match-data
20788 (string-match (org-image-file-name-regexp extensions) file)))
20790 (defun org-get-cursor-date ()
20791 "Return the date at cursor in as a time.
20792 This works in the calendar and in the agenda, anywhere else it just
20793 returns the current time."
20794 (let (date day defd)
20795 (cond
20796 ((eq major-mode 'calendar-mode)
20797 (setq date (calendar-cursor-to-date)
20798 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20799 ((eq major-mode 'org-agenda-mode)
20800 (setq day (get-text-property (point) 'day))
20801 (if day
20802 (setq date (calendar-gregorian-from-absolute day)
20803 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20804 (nth 2 date))))))
20805 (or defd (current-time))))
20807 (defun org-mark-subtree (&optional up)
20808 "Mark the current subtree.
20809 This puts point at the start of the current subtree, and mark at
20810 the end. If a numeric prefix UP is given, move up into the
20811 hierarchy of headlines by UP levels before marking the subtree."
20812 (interactive "P")
20813 (org-with-limited-levels
20814 (cond ((org-at-heading-p) (beginning-of-line))
20815 ((org-before-first-heading-p) (error "Not in a subtree"))
20816 (t (outline-previous-visible-heading 1))))
20817 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20818 (if (org-called-interactively-p 'any)
20819 (call-interactively 'org-mark-element)
20820 (org-mark-element)))
20823 ;;; Macros
20825 ;; Macros are expanded with `org-macro-replace-all', which relies
20826 ;; internally on `org-macro-expand'.
20828 ;; Templates for expansion are stored in the buffer-local variable
20829 ;; `org-macro-templates'. This variable is updated by
20830 ;; `org-macro-initialize-templates'.
20833 (defvar org-macro-templates nil
20834 "Alist containing all macro templates in current buffer.
20835 Associations are in the shape of (NAME . TEMPLATE) where NAME
20836 stands for macro's name and template for its replacement value,
20837 both as strings. This is an internal variable. Do not set it
20838 directly, use instead:
20840 #+MACRO: name template")
20841 (make-variable-buffer-local 'org-macro-templates)
20843 (defun org-macro-expand (macro)
20844 "Return expanded MACRO, as a string.
20845 MACRO is an object, obtained, for example, with
20846 `org-element-context'. Return nil if no template was found."
20847 (let ((template
20848 (cdr (assoc-string (org-element-property :key macro)
20849 org-macro-templates
20850 ;; Macro names are case-insensitive.
20851 t))))
20852 (when template
20853 (let ((value (replace-regexp-in-string
20854 "\\$[0-9]+"
20855 (lambda (arg)
20856 (or (nth (1- (string-to-number (substring arg 1)))
20857 (org-element-property :args macro))
20858 ;; No argument provided: remove
20859 ;; place-holder.
20860 ""))
20861 template)))
20862 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
20863 (when (string-match "\\`(eval\\>" value)
20864 (setq value (eval (read value))))
20865 ;; Return string.
20866 (format "%s" (or value ""))))))
20868 (defun org-macro-replace-all ()
20869 "Replace all macros in current buffer by their expansion."
20870 (save-excursion
20871 (goto-char (point-min))
20872 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
20873 (let ((object (org-element-context)))
20874 (when (eq (org-element-type object) 'macro)
20875 (let ((value (org-macro-expand object)))
20876 (when value
20877 (delete-region
20878 (org-element-property :begin object)
20879 ;; Preserve white spaces after the macro.
20880 (progn (goto-char (org-element-property :end object))
20881 (skip-chars-backward " \t")
20882 (point)))
20883 ;; Leave point before replacement in case of recursive
20884 ;; expansions.
20885 (save-excursion (insert value)))))))))
20887 (defun org-macro-initialize-templates ()
20888 "Collect macro templates defined in current buffer.
20889 Templates are stored in buffer-local variable
20890 `org-macro-templates'. In addition to buffer-defined macros, the
20891 function installs the following ones: \"property\", \"date\",
20892 \"time\". and, if appropriate, \"input-file\" and
20893 \"modification-time\"."
20894 (let ((case-fold-search t)
20895 (set-template
20896 (lambda (cell)
20897 ;; Add CELL to `org-macro-templates' if there's no
20898 ;; association matching its name already. Otherwise,
20899 ;; replace old association with the new one in that
20900 ;; variable.
20901 (let ((old-template (assoc (car cell) org-macro-templates)))
20902 (if old-template (setcdr old-template (cdr cell))
20903 (push cell org-macro-templates))))))
20904 ;; Install buffer-local macros.
20905 (org-with-wide-buffer
20906 (goto-char (point-min))
20907 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
20908 (let ((element (org-element-at-point)))
20909 (when (eq (org-element-type element) 'keyword)
20910 (let ((value (org-element-property :value element)))
20911 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
20912 (funcall set-template
20913 (cons (match-string 1 value)
20914 (or (match-string 2 value) "")))))))))
20915 ;; Install hard-coded macros.
20916 (mapc (lambda (cell) (funcall set-template cell))
20917 (list
20918 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
20919 (cons "date" "(eval (format-time-string \"$1\"))")
20920 (cons "time" "(eval (format-time-string \"$1\"))")))
20921 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
20922 (when (and visited-file (file-exists-p visited-file))
20923 (mapc (lambda (cell) (funcall set-template cell))
20924 (list
20925 (cons "input-file" (file-name-nondirectory visited-file))
20926 (cons "modification-time"
20927 (format "(eval (format-time-string \"$1\" '%s))"
20928 (prin1-to-string
20929 (nth 5 (file-attributes visited-file)))))))))))
20932 ;;; Indentation
20934 (defun org-indent-line ()
20935 "Indent line depending on context."
20936 (interactive)
20937 (let* ((pos (point))
20938 (itemp (org-at-item-p))
20939 (case-fold-search t)
20940 (org-drawer-regexp (or org-drawer-regexp "\000"))
20941 (inline-task-p (and (featurep 'org-inlinetask)
20942 (org-inlinetask-in-task-p)))
20943 (inline-re (and inline-task-p
20944 (org-inlinetask-outline-regexp)))
20945 column)
20946 (if (and orgstruct-is-++ (eq pos (point)))
20947 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20948 (indent-according-to-mode))
20949 (beginning-of-line 1)
20950 (cond
20951 ;; Headings
20952 ((looking-at org-outline-regexp) (setq column 0))
20953 ;; Included files
20954 ((looking-at "#\\+include:") (setq column 0))
20955 ;; Footnote definition
20956 ((looking-at org-footnote-definition-re) (setq column 0))
20957 ;; Literal examples
20958 ((looking-at "[ \t]*:\\( \\|$\\)")
20959 (setq column (org-get-indentation))) ; do nothing
20960 ;; Lists
20961 ((ignore-errors (goto-char (org-in-item-p)))
20962 (setq column (if itemp
20963 (org-get-indentation)
20964 (org-list-item-body-column (point))))
20965 (goto-char pos))
20966 ;; Drawers
20967 ((and (looking-at "[ \t]*:END:")
20968 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20969 (save-excursion
20970 (goto-char (1- (match-beginning 1)))
20971 (setq column (current-column))))
20972 ;; Special blocks
20973 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20974 (save-excursion
20975 (re-search-backward
20976 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20977 (setq column (org-get-indentation (match-string 0))))
20978 ((and (not (looking-at "[ \t]*#\\+begin_"))
20979 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20980 (save-excursion
20981 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20982 (setq column
20983 (cond ((equal (downcase (match-string 1)) "src")
20984 ;; src blocks: let `org-edit-src-exit' handle them
20985 (org-get-indentation))
20986 ((equal (downcase (match-string 1)) "example")
20987 (max (org-get-indentation)
20988 (org-get-indentation (match-string 0))))
20990 (org-get-indentation (match-string 0))))))
20991 ;; This line has nothing special, look at the previous relevant
20992 ;; line to compute indentation
20994 (beginning-of-line 0)
20995 (while (and (not (bobp))
20996 (not (looking-at org-drawer-regexp))
20997 ;; When point started in an inline task, do not move
20998 ;; above task starting line.
20999 (not (and inline-task-p (looking-at inline-re)))
21000 ;; Skip drawers, blocks, empty lines, verbatim,
21001 ;; comments, tables, footnotes definitions, lists,
21002 ;; inline tasks.
21003 (or (and (looking-at "[ \t]*:END:")
21004 (re-search-backward org-drawer-regexp nil t))
21005 (and (looking-at "[ \t]*#\\+end_")
21006 (re-search-backward "[ \t]*#\\+begin_"nil t))
21007 (looking-at "[ \t]*[\n:#|]")
21008 (looking-at org-footnote-definition-re)
21009 (and (ignore-errors (goto-char (org-in-item-p)))
21010 (goto-char
21011 (org-list-get-top-point (org-list-struct))))
21012 (and (not inline-task-p)
21013 (featurep 'org-inlinetask)
21014 (org-inlinetask-in-task-p)
21015 (or (org-inlinetask-goto-beginning) t))))
21016 (beginning-of-line 0))
21017 (cond
21018 ;; There was an heading above.
21019 ((looking-at "\\*+[ \t]+")
21020 (if (not org-adapt-indentation)
21021 (setq column 0)
21022 (goto-char (match-end 0))
21023 (setq column (current-column))))
21024 ;; A drawer had started and is unfinished
21025 ((looking-at org-drawer-regexp)
21026 (goto-char (1- (match-beginning 1)))
21027 (setq column (current-column)))
21028 ;; Else, nothing noticeable found: get indentation and go on.
21029 (t (setq column (org-get-indentation))))))
21030 ;; Now apply indentation and move cursor accordingly
21031 (goto-char pos)
21032 (if (<= (current-column) (current-indentation))
21033 (org-indent-line-to column)
21034 (save-excursion (org-indent-line-to column)))
21035 ;; Special polishing for properties, see `org-property-format'
21036 (setq column (current-column))
21037 (beginning-of-line 1)
21038 (if (looking-at
21039 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21040 (replace-match (concat (match-string 1)
21041 (format org-property-format
21042 (match-string 2) (match-string 3)))
21043 t t))
21044 (org-move-to-column column))))
21046 (defun org-indent-drawer ()
21047 "Indent the drawer at point."
21048 (interactive)
21049 (let ((p (point))
21050 (e (and (save-excursion (re-search-forward ":END:" nil t))
21051 (match-end 0)))
21052 (folded
21053 (save-excursion
21054 (end-of-line)
21055 (when (overlays-at (point))
21056 (member 'invisible (overlay-properties
21057 (car (overlays-at (point)))))))))
21058 (when folded (org-cycle))
21059 (indent-for-tab-command)
21060 (while (and (move-beginning-of-line 2) (< (point) e))
21061 (indent-for-tab-command))
21062 (goto-char p)
21063 (when folded (org-cycle)))
21064 (message "Drawer at point indented"))
21066 (defun org-indent-block ()
21067 "Indent the block at point."
21068 (interactive)
21069 (let ((p (point))
21070 (case-fold-search t)
21071 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21072 (match-end 0)))
21073 (folded
21074 (save-excursion
21075 (end-of-line)
21076 (when (overlays-at (point))
21077 (member 'invisible (overlay-properties
21078 (car (overlays-at (point)))))))))
21079 (when folded (org-cycle))
21080 (indent-for-tab-command)
21081 (while (and (move-beginning-of-line 2) (< (point) e))
21082 (indent-for-tab-command))
21083 (goto-char p)
21084 (when folded (org-cycle)))
21085 (message "Block at point indented"))
21087 (defun org-indent-region (start end)
21088 "Indent region."
21089 (interactive "r")
21090 (save-excursion
21091 (let ((line-end (org-current-line end)))
21092 (goto-char start)
21093 (while (< (org-current-line) line-end)
21094 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21095 (t (call-interactively 'org-indent-line)))
21096 (move-beginning-of-line 2)))))
21099 ;;; Filling
21101 ;; We use our own fill-paragraph and auto-fill functions.
21103 ;; `org-fill-paragraph' relies on adaptive filling and context
21104 ;; checking. Appropriate `fill-prefix' is computed with
21105 ;; `org-adaptive-fill-function'.
21107 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21108 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21109 ;; `org-adaptive-fill-function' value. Internally,
21110 ;; `org-comment-line-break-function' breaks the line.
21112 ;; `org-setup-filling' installs filling and auto-filling related
21113 ;; variables during `org-mode' initialization.
21115 (defun org-setup-filling ()
21116 (interactive)
21117 ;; Prevent auto-fill from inserting unwanted new items.
21118 (when (boundp 'fill-nobreak-predicate)
21119 (org-set-local
21120 'fill-nobreak-predicate
21121 (org-uniquify
21122 (append fill-nobreak-predicate
21123 '(org-fill-paragraph-separate-nobreak-p
21124 org-fill-line-break-nobreak-p)))))
21125 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21126 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21127 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21128 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21130 (defvar org-element-paragraph-separate) ; org-element.el
21131 (defun org-fill-paragraph-separate-nobreak-p ()
21132 "Non-nil when a line break at point would insert a new item."
21133 (looking-at (substring org-element-paragraph-separate 1)))
21135 (defun org-fill-line-break-nobreak-p ()
21136 "Non-nil when a line break at point would create an Org line break."
21137 (save-excursion
21138 (skip-chars-backward "[ \t]")
21139 (skip-chars-backward "\\\\")
21140 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21142 (declare-function message-in-body-p "message" ())
21143 (defvar org-element--affiliated-re) ; From org-element.el
21144 (defun org-adaptive-fill-function ()
21145 "Compute a fill prefix for the current line.
21146 Return fill prefix, as a string, or nil if current line isn't
21147 meant to be filled."
21148 (org-with-wide-buffer
21149 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21150 ;; FIXME: This is really the job of orgstruct++-mode
21151 (let* ((p (line-beginning-position))
21152 (element (save-excursion (beginning-of-line)
21153 (org-element-at-point)))
21154 (type (org-element-type element))
21155 (post-affiliated
21156 (save-excursion
21157 (goto-char (org-element-property :begin element))
21158 (while (looking-at org-element--affiliated-re) (forward-line))
21159 (point))))
21160 (unless (< p post-affiliated)
21161 (case type
21162 (comment (looking-at "[ \t]*# ?") (match-string 0))
21163 (footnote-definition "")
21164 ((item plain-list)
21165 (make-string (org-list-item-body-column post-affiliated) ? ))
21166 (paragraph
21167 ;; Fill prefix is usually the same as the current line,
21168 ;; except if the paragraph is at the beginning of an item.
21169 (let ((parent (org-element-property :parent element)))
21170 (cond ((eq (org-element-type parent) 'item)
21171 (make-string (org-list-item-body-column
21172 (org-element-property :begin parent))
21173 ? ))
21174 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21175 (match-string 0))
21176 (t ""))))
21177 (comment-block
21178 ;; Only fill contents if P is within block boundaries.
21179 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21180 (forward-line)
21181 (point)))
21182 (cend (save-excursion
21183 (goto-char (org-element-property :end element))
21184 (skip-chars-backward " \r\t\n")
21185 (line-beginning-position))))
21186 (when (and (>= p cbeg) (< p cend))
21187 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21188 (match-string 0)
21189 ""))))))))))
21191 (declare-function message-goto-body "message" ())
21192 (defvar message-cite-prefix-regexp) ; From message.el
21193 (defvar org-element-all-objects) ; From org-element.el
21194 (defun org-fill-paragraph (&optional justify)
21195 "Fill element at point, when applicable.
21197 This function only applies to comment blocks, comments, example
21198 blocks and paragraphs. Also, as a special case, re-align table
21199 when point is at one.
21201 If JUSTIFY is non-nil (interactively, with prefix argument),
21202 justify as well. If `sentence-end-double-space' is non-nil, then
21203 period followed by one space does not end a sentence, so don't
21204 break a line there. The variable `fill-column' controls the
21205 width for filling.
21207 For convenience, when point is at a plain list, an item or
21208 a footnote definition, try to fill the first paragraph within."
21209 ;; Falls back on message-fill-paragraph when necessary
21210 (interactive)
21211 (if (and (derived-mode-p 'message-mode)
21212 (or (not (message-in-body-p))
21213 (save-excursion (move-beginning-of-line 1)
21214 (looking-at message-cite-prefix-regexp))))
21215 (let ((fill-paragraph-function
21216 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21217 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21218 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21219 (paragraph-separate
21220 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21221 (fill-paragraph nil))
21222 (save-excursion
21223 ;; Move to end of line in order to get the first paragraph
21224 ;; within a plain list or a footnote definition.
21225 (end-of-line)
21226 (let ((element (org-element-at-point)))
21227 ;; First check if point is in a blank line at the beginning of
21228 ;; the buffer. In that case, ignore filling.
21229 (if (< (point) (org-element-property :begin element)) t
21230 (case (org-element-type element)
21231 ;; Align Org tables, leave table.el tables as-is.
21232 (table-row (org-table-align) t)
21233 (table
21234 (when (eq (org-element-property :type element) 'org)
21235 (org-table-align))
21237 (paragraph
21238 ;; Paragraphs may contain `line-break' type objects.
21239 (let ((beg (max (point-min)
21240 (org-element-property :contents-begin element)))
21241 (end (min (point-max)
21242 (org-element-property :contents-end element))))
21243 ;; Do nothing if point is at an affiliated keyword.
21244 (if (< (point) beg) t
21245 (when (derived-mode-p 'message-mode)
21246 ;; In `message-mode', do not fill following
21247 ;; citation in current paragraph nor text before
21248 ;; message body.
21249 (let ((body-start (save-excursion (message-goto-body))))
21250 (when body-start (setq beg (max body-start beg))))
21251 (when (save-excursion
21252 (re-search-forward
21253 (concat "^" message-cite-prefix-regexp) end t))
21254 (setq end (match-beginning 0))))
21255 ;; Fill paragraph, taking line breaks into
21256 ;; consideration. For that, slice the paragraph
21257 ;; using line breaks as separators, and fill the
21258 ;; parts in reverse order to avoid messing with
21259 ;; markers.
21260 (save-excursion
21261 (goto-char end)
21262 (mapc
21263 (lambda (pos)
21264 (fill-region-as-paragraph pos (point) justify)
21265 (goto-char pos))
21266 ;; Find the list of ending positions for line
21267 ;; breaks in the current paragraph. Add paragraph
21268 ;; beginning to include first slice.
21269 (nreverse
21270 (cons
21272 (org-element-map
21273 (org-element--parse-objects
21274 beg end nil org-element-all-objects)
21275 'line-break
21276 (lambda (lb) (org-element-property :end lb)))))))
21277 t)))
21278 ;; Contents of `comment-block' type elements should be
21279 ;; filled as plain text, but only if point is within block
21280 ;; markers.
21281 (comment-block
21282 (let* ((case-fold-search t)
21283 (beg (save-excursion
21284 (goto-char (org-element-property :begin element))
21285 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21286 (forward-line)
21287 (point)))
21288 (end (save-excursion
21289 (goto-char (org-element-property :end element))
21290 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21291 (line-beginning-position))))
21292 (when (and (>= (point) beg) (< (point) end))
21293 (fill-region-as-paragraph
21294 (save-excursion
21295 (end-of-line)
21296 (re-search-backward "^[ \t]*$" beg 'move)
21297 (line-beginning-position))
21298 (save-excursion
21299 (beginning-of-line)
21300 (re-search-forward "^[ \t]*$" end 'move)
21301 (line-beginning-position))
21302 justify)))
21304 ;; Fill comments.
21305 (comment (fill-comment-paragraph justify))
21306 ;; Ignore every other element.
21307 (otherwise t)))))))
21309 (defun org-auto-fill-function ()
21310 "Auto-fill function."
21311 ;; Check if auto-filling is meaningful.
21312 (let ((fc (current-fill-column)))
21313 (when (and fc (> (current-column) fc))
21314 (let ((fill-prefix (org-adaptive-fill-function)))
21315 (when fill-prefix (do-auto-fill))))))
21317 (defun org-comment-line-break-function (&optional soft)
21318 "Break line at point and indent, continuing comment if within one.
21319 The inserted newline is marked hard if variable
21320 `use-hard-newlines' is true, unless optional argument SOFT is
21321 non-nil."
21322 (if soft (insert-and-inherit ?\n) (newline 1))
21323 (save-excursion (forward-char -1) (delete-horizontal-space))
21324 (delete-horizontal-space)
21325 (indent-to-left-margin)
21326 (insert-before-markers-and-inherit fill-prefix))
21329 ;;; Comments
21331 ;; Org comments syntax is quite complex. It requires the entire line
21332 ;; to be just a comment. Also, even with the right syntax at the
21333 ;; beginning of line, some some elements (i.e. verse-block or
21334 ;; example-block) don't accept comments. Usual Emacs comment commands
21335 ;; cannot cope with those requirements. Therefore, Org replaces them.
21337 ;; Org still relies on `comment-dwim', but cannot trust
21338 ;; `comment-only-p'. So, `comment-region-function' and
21339 ;; `uncomment-region-function' both point
21340 ;; to`org-comment-or-uncomment-region'. Eventually,
21341 ;; `org-insert-comment' takes care of insertion of comments at the
21342 ;; beginning of line.
21344 ;; `org-setup-comments-handling' install comments related variables
21345 ;; during `org-mode' initialization.
21347 (defun org-setup-comments-handling ()
21348 (interactive)
21349 (org-set-local 'comment-use-syntax nil)
21350 (org-set-local 'comment-start "# ")
21351 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21352 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21353 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21354 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21356 (defun org-insert-comment ()
21357 "Insert an empty comment above current line.
21358 If the line is empty, insert comment at its beginning."
21359 (beginning-of-line)
21360 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21361 (org-indent-line)
21362 (insert "# "))
21364 (defvar comment-empty-lines) ; From newcomment.el.
21365 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21366 "Comment or uncomment each non-blank line in the region.
21367 Uncomment each non-blank line between BEG and END if it only
21368 contains commented lines. Otherwise, comment them."
21369 (save-restriction
21370 ;; Restrict region
21371 (narrow-to-region (save-excursion (goto-char beg)
21372 (skip-chars-forward " \r\t\n" end)
21373 (line-beginning-position))
21374 (save-excursion (goto-char end)
21375 (skip-chars-backward " \r\t\n" beg)
21376 (line-end-position)))
21377 (let ((uncommentp
21378 ;; UNCOMMENTP is non-nil when every non blank line between
21379 ;; BEG and END is a comment.
21380 (save-excursion
21381 (goto-char (point-min))
21382 (while (and (not (eobp))
21383 (let ((element (org-element-at-point)))
21384 (and (eq (org-element-type element) 'comment)
21385 (goto-char (min (point-max)
21386 (org-element-property
21387 :end element)))))))
21388 (eobp))))
21389 (if uncommentp
21390 ;; Only blank lines and comments in region: uncomment it.
21391 (save-excursion
21392 (goto-char (point-min))
21393 (while (not (eobp))
21394 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21395 (replace-match "" nil nil nil 1))
21396 (forward-line)))
21397 ;; Comment each line in region.
21398 (let ((min-indent (point-max)))
21399 ;; First find the minimum indentation across all lines.
21400 (save-excursion
21401 (goto-char (point-min))
21402 (while (and (not (eobp)) (not (zerop min-indent)))
21403 (unless (looking-at "[ \t]*$")
21404 (setq min-indent (min min-indent (current-indentation))))
21405 (forward-line)))
21406 ;; Then loop over all lines.
21407 (save-excursion
21408 (goto-char (point-min))
21409 (while (not (eobp))
21410 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21411 (org-move-to-column min-indent t)
21412 (insert comment-start))
21413 (forward-line))))))))
21416 ;;; Other stuff.
21418 (defun org-toggle-fixed-width-section (arg)
21419 "Toggle the fixed-width export.
21420 If there is no active region, the QUOTE keyword at the current headline is
21421 inserted or removed. When present, it causes the text between this headline
21422 and the next to be exported as fixed-width text, and unmodified.
21423 If there is an active region, this command adds or removes a colon as the
21424 first character of this line. If the first character of a line is a colon,
21425 this line is also exported in fixed-width font."
21426 (interactive "P")
21427 (let* ((cc 0)
21428 (regionp (org-region-active-p))
21429 (beg (if regionp (region-beginning) (point)))
21430 (end (if regionp (region-end)))
21431 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21432 (case-fold-search nil)
21433 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21434 off)
21435 (if regionp
21436 (save-excursion
21437 (goto-char beg)
21438 (setq cc (current-column))
21439 (beginning-of-line 1)
21440 (setq off (looking-at re))
21441 (while (> nlines 0)
21442 (setq nlines (1- nlines))
21443 (beginning-of-line 1)
21444 (cond
21445 (arg
21446 (org-move-to-column cc t)
21447 (insert ": \n")
21448 (forward-line -1))
21449 ((and off (looking-at re))
21450 (replace-match "" t t nil 1))
21451 ((not off) (org-move-to-column cc t) (insert ": ")))
21452 (forward-line 1)))
21453 (save-excursion
21454 (org-back-to-heading)
21455 (cond
21456 ((looking-at (format org-heading-keyword-regexp-format
21457 org-quote-string))
21458 (goto-char (match-end 1))
21459 (looking-at (concat " +" org-quote-string))
21460 (replace-match "" t t)
21461 (when (eolp) (insert " ")))
21462 ((looking-at org-outline-regexp)
21463 (goto-char (match-end 0))
21464 (insert org-quote-string " ")))))))
21466 (defun org-reftex-citation ()
21467 "Use reftex-citation to insert a citation into the buffer.
21468 This looks for a line like
21470 #+BIBLIOGRAPHY: foo plain option:-d
21472 and derives from it that foo.bib is the bibliography file relevant
21473 for this document. It then installs the necessary environment for RefTeX
21474 to work in this buffer and calls `reftex-citation' to insert a citation
21475 into the buffer.
21477 Export of such citations to both LaTeX and HTML is handled by the contributed
21478 package org-exp-bibtex by Taru Karttunen."
21479 (interactive)
21480 (let ((reftex-docstruct-symbol 'rds)
21481 (reftex-cite-format "\\cite{%l}")
21482 rds bib)
21483 (save-excursion
21484 (save-restriction
21485 (widen)
21486 (let ((case-fold-search t)
21487 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21488 (if (not (save-excursion
21489 (or (re-search-forward re nil t)
21490 (re-search-backward re nil t))))
21491 (error "No bibliography defined in file")
21492 (setq bib (concat (match-string 1) ".bib")
21493 rds (list (list 'bib bib)))))))
21494 (call-interactively 'reftex-citation)))
21496 ;;;; Functions extending outline functionality
21498 (defun org-beginning-of-line (&optional arg)
21499 "Go to the beginning of the current line. If that is invisible, continue
21500 to a visible line beginning. This makes the function of C-a more intuitive.
21501 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21502 first attempt, and only move to after the tags when the cursor is already
21503 beyond the end of the headline."
21504 (interactive "P")
21505 (let ((pos (point))
21506 (special (if (consp org-special-ctrl-a/e)
21507 (car org-special-ctrl-a/e)
21508 org-special-ctrl-a/e))
21509 refpos)
21510 (if (org-bound-and-true-p line-move-visual)
21511 (beginning-of-visual-line 1)
21512 (beginning-of-line 1))
21513 (if (and arg (fboundp 'move-beginning-of-line))
21514 (call-interactively 'move-beginning-of-line)
21515 (if (bobp)
21517 (backward-char 1)
21518 (if (org-truely-invisible-p)
21519 (while (and (not (bobp)) (org-truely-invisible-p))
21520 (backward-char 1)
21521 (beginning-of-line 1))
21522 (forward-char 1))))
21523 (when special
21524 (cond
21525 ((and (looking-at org-complex-heading-regexp)
21526 (= (char-after (match-end 1)) ?\ ))
21527 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21528 (point-at-eol)))
21529 (goto-char
21530 (if (eq special t)
21531 (cond ((> pos refpos) refpos)
21532 ((= pos (point)) refpos)
21533 (t (point)))
21534 (cond ((> pos (point)) (point))
21535 ((not (eq last-command this-command)) (point))
21536 (t refpos)))))
21537 ((org-at-item-p)
21538 ;; Being at an item and not looking at an the item means point
21539 ;; was previously moved to beginning of a visual line, which
21540 ;; doesn't contain the item. Therefore, do nothing special,
21541 ;; just stay here.
21542 (when (looking-at org-list-full-item-re)
21543 ;; Set special position at first white space character after
21544 ;; bullet, and check-box, if any.
21545 (let ((after-bullet
21546 (let ((box (match-end 3)))
21547 (if (not box) (match-end 1)
21548 (let ((after (char-after box)))
21549 (if (and after (= after ? )) (1+ box) box))))))
21550 ;; Special case: Move point to special position when
21551 ;; currently after it or at beginning of line.
21552 (if (eq special t)
21553 (when (or (> pos after-bullet) (= (point) pos))
21554 (goto-char after-bullet))
21555 ;; Reversed case: Move point to special position when
21556 ;; point was already at beginning of line and command is
21557 ;; repeated.
21558 (when (and (= (point) pos) (eq last-command this-command))
21559 (goto-char after-bullet))))))))
21560 (org-no-warnings
21561 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21563 (defun org-end-of-line (&optional arg)
21564 "Go to the end of the line.
21565 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21566 first attempt, and only move to after the tags when the cursor is already
21567 beyond the end of the headline."
21568 (interactive "P")
21569 (let ((special (if (consp org-special-ctrl-a/e)
21570 (cdr org-special-ctrl-a/e)
21571 org-special-ctrl-a/e)))
21572 (cond
21573 ((or (not special) arg
21574 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21575 (call-interactively
21576 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21577 ((fboundp 'move-end-of-line) 'move-end-of-line)
21578 (t 'end-of-line))))
21579 ((org-at-heading-p)
21580 (let ((pos (point)))
21581 (beginning-of-line 1)
21582 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21583 (if (eq special t)
21584 (if (or (< pos (match-beginning 1))
21585 (= pos (match-end 0)))
21586 (goto-char (match-beginning 1))
21587 (goto-char (match-end 0)))
21588 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21589 (goto-char (match-end 0))
21590 (goto-char (match-beginning 1))))
21591 (call-interactively (if (fboundp 'move-end-of-line)
21592 'move-end-of-line
21593 'end-of-line)))))
21594 ((org-at-drawer-p)
21595 (move-end-of-line 1)
21596 (when (overlays-at (1- (point))) (backward-char 1)))
21597 ;; At an item: Move before any hidden text.
21598 (t (call-interactively
21599 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21600 ((fboundp 'move-end-of-line) 'move-end-of-line)
21601 (t 'end-of-line)))))
21602 (org-no-warnings
21603 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21605 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21606 (define-key org-mode-map "\C-e" 'org-end-of-line)
21608 (defun org-backward-sentence (&optional arg)
21609 "Go to beginning of sentence, or beginning of table field.
21610 This will call `backward-sentence' or `org-table-beginning-of-field',
21611 depending on context."
21612 (interactive "P")
21613 (cond
21614 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21615 (t (call-interactively 'backward-sentence))))
21617 (defun org-forward-sentence (&optional arg)
21618 "Go to end of sentence, or end of table field.
21619 This will call `forward-sentence' or `org-table-end-of-field',
21620 depending on context."
21621 (interactive "P")
21622 (cond
21623 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21624 (t (call-interactively 'forward-sentence))))
21626 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21627 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21629 (defun org-kill-line (&optional arg)
21630 "Kill line, to tags or end of line."
21631 (interactive "P")
21632 (cond
21633 ((or (not org-special-ctrl-k)
21634 (bolp)
21635 (not (org-at-heading-p)))
21636 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21637 org-ctrl-k-protect-subtree)
21638 (if (or (eq org-ctrl-k-protect-subtree 'error)
21639 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21640 (error "C-k aborted - would kill hidden subtree")))
21641 (call-interactively
21642 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21643 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21644 (kill-region (point) (match-beginning 1))
21645 (org-set-tags nil t))
21646 (t (kill-region (point) (point-at-eol)))))
21648 (define-key org-mode-map "\C-k" 'org-kill-line)
21650 (defun org-yank (&optional arg)
21651 "Yank. If the kill is a subtree, treat it specially.
21652 This command will look at the current kill and check if is a single
21653 subtree, or a series of subtrees[1]. If it passes the test, and if the
21654 cursor is at the beginning of a line or after the stars of a currently
21655 empty headline, then the yank is handled specially. How exactly depends
21656 on the value of the following variables, both set by default.
21658 org-yank-folded-subtrees
21659 When set, the subtree(s) will be folded after insertion, but only
21660 if doing so would now swallow text after the yanked text.
21662 org-yank-adjusted-subtrees
21663 When set, the subtree will be promoted or demoted in order to
21664 fit into the local outline tree structure, which means that the level
21665 will be adjusted so that it becomes the smaller one of the two
21666 *visible* surrounding headings.
21668 Any prefix to this command will cause `yank' to be called directly with
21669 no special treatment. In particular, a simple \\[universal-argument] prefix \
21670 will just
21671 plainly yank the text as it is.
21673 \[1] The test checks if the first non-white line is a heading
21674 and if there are no other headings with fewer stars."
21675 (interactive "P")
21676 (org-yank-generic 'yank arg))
21678 (defun org-yank-generic (command arg)
21679 "Perform some yank-like command.
21681 This function implements the behavior described in the `org-yank'
21682 documentation. However, it has been generalized to work for any
21683 interactive command with similar behavior."
21685 ;; pretend to be command COMMAND
21686 (setq this-command command)
21688 (if arg
21689 (call-interactively command)
21691 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21692 (and (org-kill-is-subtree-p)
21693 (or (bolp)
21694 (and (looking-at "[ \t]*$")
21695 (string-match
21696 "\\`\\*+\\'"
21697 (buffer-substring (point-at-bol) (point)))))))
21698 swallowp)
21699 (cond
21700 ((and subtreep org-yank-folded-subtrees)
21701 (let ((beg (point))
21702 end)
21703 (if (and subtreep org-yank-adjusted-subtrees)
21704 (org-paste-subtree nil nil 'for-yank)
21705 (call-interactively command))
21707 (setq end (point))
21708 (goto-char beg)
21709 (when (and (bolp) subtreep
21710 (not (setq swallowp
21711 (org-yank-folding-would-swallow-text beg end))))
21712 (org-with-limited-levels
21713 (or (looking-at org-outline-regexp)
21714 (re-search-forward org-outline-regexp-bol end t))
21715 (while (and (< (point) end) (looking-at org-outline-regexp))
21716 (hide-subtree)
21717 (org-cycle-show-empty-lines 'folded)
21718 (condition-case nil
21719 (outline-forward-same-level 1)
21720 (error (goto-char end))))))
21721 (when swallowp
21722 (message
21723 "Inserted text not folded because that would swallow text"))
21725 (goto-char end)
21726 (skip-chars-forward " \t\n\r")
21727 (beginning-of-line 1)
21728 (push-mark beg 'nomsg)))
21729 ((and subtreep org-yank-adjusted-subtrees)
21730 (let ((beg (point-at-bol)))
21731 (org-paste-subtree nil nil 'for-yank)
21732 (push-mark beg 'nomsg)))
21734 (call-interactively command))))))
21736 (defun org-yank-folding-would-swallow-text (beg end)
21737 "Would hide-subtree at BEG swallow any text after END?"
21738 (let (level)
21739 (org-with-limited-levels
21740 (save-excursion
21741 (goto-char beg)
21742 (when (or (looking-at org-outline-regexp)
21743 (re-search-forward org-outline-regexp-bol end t))
21744 (setq level (org-outline-level)))
21745 (goto-char end)
21746 (skip-chars-forward " \t\r\n\v\f")
21747 (if (or (eobp)
21748 (and (bolp) (looking-at org-outline-regexp)
21749 (<= (org-outline-level) level)))
21750 nil ; Nothing would be swallowed
21751 t))))) ; something would swallow
21753 (define-key org-mode-map "\C-y" 'org-yank)
21755 (defun org-truely-invisible-p ()
21756 "Check if point is at a character currently not visible.
21757 This version does not only check the character property, but also
21758 `visible-mode'."
21759 ;; Early versions of noutline don't have `outline-invisible-p'.
21760 (if (org-bound-and-true-p visible-mode)
21762 (outline-invisible-p)))
21764 (defun org-invisible-p2 ()
21765 "Check if point is at a character currently not visible."
21766 (save-excursion
21767 (if (and (eolp) (not (bobp))) (backward-char 1))
21768 ;; Early versions of noutline don't have `outline-invisible-p'.
21769 (outline-invisible-p)))
21771 (defun org-back-to-heading (&optional invisible-ok)
21772 "Call `outline-back-to-heading', but provide a better error message."
21773 (condition-case nil
21774 (outline-back-to-heading invisible-ok)
21775 (error (error "Before first headline at position %d in buffer %s"
21776 (point) (current-buffer)))))
21778 (defun org-before-first-heading-p ()
21779 "Before first heading?"
21780 (save-excursion
21781 (end-of-line)
21782 (null (re-search-backward org-outline-regexp-bol nil t))))
21784 (defun org-at-heading-p (&optional ignored)
21785 (outline-on-heading-p t))
21786 ;; Compatibility alias with Org versions < 7.8.03
21787 (defalias 'org-on-heading-p 'org-at-heading-p)
21789 (defun org-at-comment-p nil
21790 "Is cursor in a line starting with a # character?"
21791 (save-excursion
21792 (beginning-of-line)
21793 (looking-at "^#")))
21795 (defun org-at-drawer-p nil
21796 "Is cursor at a drawer keyword?"
21797 (save-excursion
21798 (move-beginning-of-line 1)
21799 (looking-at org-drawer-regexp)))
21801 (defun org-at-block-p nil
21802 "Is cursor at a block keyword?"
21803 (save-excursion
21804 (move-beginning-of-line 1)
21805 (looking-at org-block-regexp)))
21807 (defun org-point-at-end-of-empty-headline ()
21808 "If point is at the end of an empty headline, return t, else nil.
21809 If the heading only contains a TODO keyword, it is still still considered
21810 empty."
21811 (and (looking-at "[ \t]*$")
21812 (when org-todo-line-regexp
21813 (save-excursion
21814 (beginning-of-line 1)
21815 (let ((case-fold-search nil))
21816 (looking-at org-todo-line-regexp)
21817 (string= (match-string 3) ""))))))
21819 (defun org-at-heading-or-item-p ()
21820 (or (org-at-heading-p) (org-at-item-p)))
21822 (defun org-at-target-p ()
21823 (or (org-in-regexp org-radio-target-regexp)
21824 (org-in-regexp org-target-regexp)))
21825 ;; Compatibility alias with Org versions < 7.8.03
21826 (defalias 'org-on-target-p 'org-at-target-p)
21828 (defun org-up-heading-all (arg)
21829 "Move to the heading line of which the present line is a subheading.
21830 This function considers both visible and invisible heading lines.
21831 With argument, move up ARG levels."
21832 (if (fboundp 'outline-up-heading-all)
21833 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21834 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21836 (defun org-up-heading-safe ()
21837 "Move to the heading line of which the present line is a subheading.
21838 This version will not throw an error. It will return the level of the
21839 headline found, or nil if no higher level is found.
21841 Also, this function will be a lot faster than `outline-up-heading',
21842 because it relies on stars being the outline starters. This can really
21843 make a significant difference in outlines with very many siblings."
21844 (let (start-level re)
21845 (org-back-to-heading t)
21846 (setq start-level (funcall outline-level))
21847 (if (equal start-level 1)
21849 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21850 (if (re-search-backward re nil t)
21851 (funcall outline-level)))))
21853 (defun org-first-sibling-p ()
21854 "Is this heading the first child of its parents?"
21855 (interactive)
21856 (let ((re org-outline-regexp-bol)
21857 level l)
21858 (unless (org-at-heading-p t)
21859 (error "Not at a heading"))
21860 (setq level (funcall outline-level))
21861 (save-excursion
21862 (if (not (re-search-backward re nil t))
21864 (setq l (funcall outline-level))
21865 (< l level)))))
21867 (defun org-goto-sibling (&optional previous)
21868 "Goto the next sibling, even if it is invisible.
21869 When PREVIOUS is set, go to the previous sibling instead. Returns t
21870 when a sibling was found. When none is found, return nil and don't
21871 move point."
21872 (let ((fun (if previous 're-search-backward 're-search-forward))
21873 (pos (point))
21874 (re org-outline-regexp-bol)
21875 level l)
21876 (when (condition-case nil (org-back-to-heading t) (error nil))
21877 (setq level (funcall outline-level))
21878 (catch 'exit
21879 (or previous (forward-char 1))
21880 (while (funcall fun re nil t)
21881 (setq l (funcall outline-level))
21882 (when (< l level) (goto-char pos) (throw 'exit nil))
21883 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21884 (goto-char pos)
21885 nil))))
21887 (defun org-show-siblings ()
21888 "Show all siblings of the current headline."
21889 (save-excursion
21890 (while (org-goto-sibling) (org-flag-heading nil)))
21891 (save-excursion
21892 (while (org-goto-sibling 'previous)
21893 (org-flag-heading nil))))
21895 (defun org-goto-first-child ()
21896 "Goto the first child, even if it is invisible.
21897 Return t when a child was found. Otherwise don't move point and
21898 return nil."
21899 (let (level (pos (point)) (re org-outline-regexp-bol))
21900 (when (condition-case nil (org-back-to-heading t) (error nil))
21901 (setq level (outline-level))
21902 (forward-char 1)
21903 (if (and (re-search-forward re nil t) (> (outline-level) level))
21904 (progn (goto-char (match-beginning 0)) t)
21905 (goto-char pos) nil))))
21907 (defun org-show-hidden-entry ()
21908 "Show an entry where even the heading is hidden."
21909 (save-excursion
21910 (org-show-entry)))
21912 (defun org-flag-heading (flag &optional entry)
21913 "Flag the current heading. FLAG non-nil means make invisible.
21914 When ENTRY is non-nil, show the entire entry."
21915 (save-excursion
21916 (org-back-to-heading t)
21917 ;; Check if we should show the entire entry
21918 (if entry
21919 (progn
21920 (org-show-entry)
21921 (save-excursion
21922 (and (outline-next-heading)
21923 (org-flag-heading nil))))
21924 (outline-flag-region (max (point-min) (1- (point)))
21925 (save-excursion (outline-end-of-heading) (point))
21926 flag))))
21928 (defun org-get-next-sibling ()
21929 "Move to next heading of the same level, and return point.
21930 If there is no such heading, return nil.
21931 This is like outline-next-sibling, but invisible headings are ok."
21932 (let ((level (funcall outline-level)))
21933 (outline-next-heading)
21934 (while (and (not (eobp)) (> (funcall outline-level) level))
21935 (outline-next-heading))
21936 (if (or (eobp) (< (funcall outline-level) level))
21938 (point))))
21940 (defun org-get-last-sibling ()
21941 "Move to previous heading of the same level, and return point.
21942 If there is no such heading, return nil."
21943 (let ((opoint (point))
21944 (level (funcall outline-level)))
21945 (outline-previous-heading)
21946 (when (and (/= (point) opoint) (outline-on-heading-p t))
21947 (while (and (> (funcall outline-level) level)
21948 (not (bobp)))
21949 (outline-previous-heading))
21950 (if (< (funcall outline-level) level)
21952 (point)))))
21954 (defun org-end-of-subtree (&optional invisible-ok to-heading)
21955 "Goto to the end of a subtree."
21956 ;; This contains an exact copy of the original function, but it uses
21957 ;; `org-back-to-heading', to make it work also in invisible
21958 ;; trees. And is uses an invisible-ok argument.
21959 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21960 ;; Furthermore, when used inside Org, finding the end of a large subtree
21961 ;; with many children and grandchildren etc, this can be much faster
21962 ;; than the outline version.
21963 (org-back-to-heading invisible-ok)
21964 (let ((first t)
21965 (level (funcall outline-level)))
21966 (if (and (derived-mode-p 'org-mode) (< level 1000))
21967 ;; A true heading (not a plain list item), in Org-mode
21968 ;; This means we can easily find the end by looking
21969 ;; only for the right number of stars. Using a regexp to do
21970 ;; this is so much faster than using a Lisp loop.
21971 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21972 (forward-char 1)
21973 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21974 ;; something else, do it the slow way
21975 (while (and (not (eobp))
21976 (or first (> (funcall outline-level) level)))
21977 (setq first nil)
21978 (outline-next-heading)))
21979 (unless to-heading
21980 (if (memq (preceding-char) '(?\n ?\^M))
21981 (progn
21982 ;; Go to end of line before heading
21983 (forward-char -1)
21984 (if (memq (preceding-char) '(?\n ?\^M))
21985 ;; leave blank line before heading
21986 (forward-char -1))))))
21987 (point))
21989 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21990 "Use Org version in org-mode, for dramatic speed-up."
21991 (if (derived-mode-p 'org-mode)
21992 (progn
21993 (org-end-of-subtree nil t)
21994 (unless (eobp) (backward-char 1)))
21995 ad-do-it))
21997 (defun org-end-of-meta-data-and-drawers ()
21998 "Jump to the first text after meta data and drawers in the current entry.
21999 This will move over empty lines, lines with planning time stamps,
22000 clocking lines, and drawers."
22001 (org-back-to-heading t)
22002 (let ((end (save-excursion (outline-next-heading) (point)))
22003 (re (concat "\\(" org-drawer-regexp "\\)"
22004 "\\|" "[ \t]*" org-keyword-time-regexp)))
22005 (forward-line 1)
22006 (while (re-search-forward re end t)
22007 (if (not (match-end 1))
22008 ;; empty or planning line
22009 (forward-line 1)
22010 ;; a drawer, find the end
22011 (re-search-forward "^[ \t]*:END:" end 'move)
22012 (forward-line 1)))
22013 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22014 (point)))
22016 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22017 "Move forward to the arg'th subheading at same level as this one.
22018 Stop at the first and last subheadings of a superior heading.
22019 Normally this only looks at visible headings, but when INVISIBLE-OK is
22020 non-nil it will also look at invisible ones."
22021 (interactive "p")
22022 (org-back-to-heading invisible-ok)
22023 (org-at-heading-p)
22024 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22025 (re (format "^\\*\\{1,%d\\} " level))
22027 (forward-char 1)
22028 (while (> arg 0)
22029 (while (and (re-search-forward re nil 'move)
22030 (setq l (- (match-end 0) (match-beginning 0) 1))
22031 (= l level)
22032 (not invisible-ok)
22033 (progn (backward-char 1) (outline-invisible-p)))
22034 (if (< l level) (setq arg 1)))
22035 (setq arg (1- arg)))
22036 (beginning-of-line 1)))
22038 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22039 "Move backward to the arg'th subheading at same level as this one.
22040 Stop at the first and last subheadings of a superior heading."
22041 (interactive "p")
22042 (org-back-to-heading)
22043 (org-at-heading-p)
22044 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22045 (re (format "^\\*\\{1,%d\\} " level))
22047 (while (> arg 0)
22048 (while (and (re-search-backward re nil 'move)
22049 (setq l (- (match-end 0) (match-beginning 0) 1))
22050 (= l level)
22051 (not invisible-ok)
22052 (outline-invisible-p))
22053 (if (< l level) (setq arg 1)))
22054 (setq arg (1- arg)))))
22056 (defun org-forward-element ()
22057 "Move forward by one element.
22058 Move to the next element at the same level, when possible."
22059 (interactive)
22060 (cond ((eobp) (error "Cannot move further down"))
22061 ((org-with-limited-levels (org-at-heading-p))
22062 (let ((origin (point)))
22063 (org-forward-heading-same-level 1)
22064 (unless (org-with-limited-levels (org-at-heading-p))
22065 (goto-char origin)
22066 (error "Cannot move further down"))))
22068 (let* ((elem (org-element-at-point))
22069 (end (org-element-property :end elem))
22070 (parent (org-element-property :parent elem)))
22071 (if (and parent (= (org-element-property :contents-end parent) end))
22072 (goto-char (org-element-property :end parent))
22073 (goto-char end))))))
22075 (defun org-backward-element ()
22076 "Move backward by one element.
22077 Move to the previous element at the same level, when possible."
22078 (interactive)
22079 (cond ((bobp) (error "Cannot move further up"))
22080 ((org-with-limited-levels (org-at-heading-p))
22081 ;; At an headline, move to the previous one, if any, or stay
22082 ;; here.
22083 (let ((origin (point)))
22084 (org-backward-heading-same-level 1)
22085 (unless (org-with-limited-levels (org-at-heading-p))
22086 (goto-char origin)
22087 (error "Cannot move further up"))))
22089 (let* ((trail (org-element-at-point 'keep-trail))
22090 (elem (car trail))
22091 (prev-elem (nth 1 trail))
22092 (beg (org-element-property :begin elem)))
22093 (cond
22094 ;; Move to beginning of current element if point isn't
22095 ;; there already.
22096 ((/= (point) beg) (goto-char beg))
22097 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22098 ((org-before-first-heading-p) (goto-char (point-min)))
22099 (t (org-back-to-heading)))))))
22101 (defun org-up-element ()
22102 "Move to upper element."
22103 (interactive)
22104 (if (org-with-limited-levels (org-at-heading-p))
22105 (unless (org-up-heading-safe) (error "No surrounding element"))
22106 (let* ((elem (org-element-at-point))
22107 (parent (org-element-property :parent elem)))
22108 (if parent (goto-char (org-element-property :begin parent))
22109 (if (org-with-limited-levels (org-before-first-heading-p))
22110 (error "No surrounding element")
22111 (org-with-limited-levels (org-back-to-heading)))))))
22113 (defvar org-element-greater-elements)
22114 (defun org-down-element ()
22115 "Move to inner element."
22116 (interactive)
22117 (let ((element (org-element-at-point)))
22118 (cond
22119 ((memq (org-element-type element) '(plain-list table))
22120 (goto-char (org-element-property :contents-begin element))
22121 (forward-char))
22122 ((memq (org-element-type element) org-element-greater-elements)
22123 ;; If contents are hidden, first disclose them.
22124 (when (org-element-property :hiddenp element) (org-cycle))
22125 (goto-char (or (org-element-property :contents-begin element)
22126 (error "No content for this element"))))
22127 (t (error "No inner element")))))
22129 (defun org-drag-element-backward ()
22130 "Move backward element at point."
22131 (interactive)
22132 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22133 (let* ((trail (org-element-at-point 'keep-trail))
22134 (elem (car trail))
22135 (prev-elem (nth 1 trail)))
22136 ;; Error out if no previous element or previous element is
22137 ;; a parent of the current one.
22138 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22139 (error "Cannot drag element backward")
22140 (let ((pos (point)))
22141 (org-element-swap-A-B prev-elem elem)
22142 (goto-char (+ (org-element-property :begin prev-elem)
22143 (- pos (org-element-property :begin elem)))))))))
22145 (defun org-drag-element-forward ()
22146 "Move forward element at point."
22147 (interactive)
22148 (let* ((pos (point))
22149 (elem (org-element-at-point)))
22150 (when (= (point-max) (org-element-property :end elem))
22151 (error "Cannot drag element forward"))
22152 (goto-char (org-element-property :end elem))
22153 (let ((next-elem (org-element-at-point)))
22154 (when (or (org-element-nested-p elem next-elem)
22155 (and (eq (org-element-type next-elem) 'headline)
22156 (not (eq (org-element-type elem) 'headline))))
22157 (goto-char pos)
22158 (error "Cannot drag element forward"))
22159 ;; Compute new position of point: it's shifted by NEXT-ELEM
22160 ;; body's length (without final blanks) and by the length of
22161 ;; blanks between ELEM and NEXT-ELEM.
22162 (let ((size-next (- (save-excursion
22163 (goto-char (org-element-property :end next-elem))
22164 (skip-chars-backward " \r\t\n")
22165 (forward-line)
22166 ;; Small correction if buffer doesn't end
22167 ;; with a newline character.
22168 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22169 (org-element-property :begin next-elem)))
22170 (size-blank (- (org-element-property :end elem)
22171 (save-excursion
22172 (goto-char (org-element-property :end elem))
22173 (skip-chars-backward " \r\t\n")
22174 (forward-line)
22175 (point)))))
22176 (org-element-swap-A-B elem next-elem)
22177 (goto-char (+ pos size-next size-blank))))))
22179 (defun org-mark-element ()
22180 "Put point at beginning of this element, mark at end.
22182 Interactively, if this command is repeated or (in Transient Mark
22183 mode) if the mark is active, it marks the next element after the
22184 ones already marked."
22185 (interactive)
22186 (let (deactivate-mark)
22187 (if (and (org-called-interactively-p 'any)
22188 (or (and (eq last-command this-command) (mark t))
22189 (and transient-mark-mode mark-active)))
22190 (set-mark
22191 (save-excursion
22192 (goto-char (mark))
22193 (goto-char (org-element-property :end (org-element-at-point)))))
22194 (let ((element (org-element-at-point)))
22195 (end-of-line)
22196 (push-mark (org-element-property :end element) t t)
22197 (goto-char (org-element-property :begin element))))))
22199 (defun org-narrow-to-element ()
22200 "Narrow buffer to current element."
22201 (interactive)
22202 (let ((elem (org-element-at-point)))
22203 (cond
22204 ((eq (car elem) 'headline)
22205 (narrow-to-region
22206 (org-element-property :begin elem)
22207 (org-element-property :end elem)))
22208 ((memq (car elem) org-element-greater-elements)
22209 (narrow-to-region
22210 (org-element-property :contents-begin elem)
22211 (org-element-property :contents-end elem)))
22213 (narrow-to-region
22214 (org-element-property :begin elem)
22215 (org-element-property :end elem))))))
22217 (defun org-transpose-element ()
22218 "Transpose current and previous elements, keeping blank lines between.
22219 Point is moved after both elements."
22220 (interactive)
22221 (org-skip-whitespace)
22222 (let ((end (org-element-property :end (org-element-at-point))))
22223 (org-drag-element-backward)
22224 (goto-char end)))
22226 (defun org-unindent-buffer ()
22227 "Un-indent the visible part of the buffer.
22228 Relative indentation (between items, inside blocks, etc.) isn't
22229 modified."
22230 (interactive)
22231 (unless (eq major-mode 'org-mode)
22232 (error "Cannot un-indent a buffer not in Org mode"))
22233 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22234 unindent-tree ; For byte-compiler.
22235 (unindent-tree
22236 (function
22237 (lambda (contents)
22238 (mapc
22239 (lambda (element)
22240 (if (memq (org-element-type element) '(headline section))
22241 (funcall unindent-tree (org-element-contents element))
22242 (save-excursion
22243 (save-restriction
22244 (narrow-to-region
22245 (org-element-property :begin element)
22246 (org-element-property :end element))
22247 (org-do-remove-indentation)))))
22248 (reverse contents))))))
22249 (funcall unindent-tree (org-element-contents parse-tree))))
22251 (defun org-show-subtree ()
22252 "Show everything after this heading at deeper levels."
22253 (interactive)
22254 (outline-flag-region
22255 (point)
22256 (save-excursion
22257 (org-end-of-subtree t t))
22258 nil))
22260 (defun org-show-entry ()
22261 "Show the body directly following this heading.
22262 Show the heading too, if it is currently invisible."
22263 (interactive)
22264 (save-excursion
22265 (condition-case nil
22266 (progn
22267 (org-back-to-heading t)
22268 (outline-flag-region
22269 (max (point-min) (1- (point)))
22270 (save-excursion
22271 (if (re-search-forward
22272 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22273 (match-beginning 1)
22274 (point-max)))
22275 nil)
22276 (org-cycle-hide-drawers 'children))
22277 (error nil))))
22279 (defun org-make-options-regexp (kwds &optional extra)
22280 "Make a regular expression for keyword lines."
22281 (concat
22282 "^#\\+\\("
22283 (mapconcat 'regexp-quote kwds "\\|")
22284 (if extra (concat "\\|" extra))
22285 "\\):[ \t]*\\(.*\\)"))
22287 ;; Make isearch reveal the necessary context
22288 (defun org-isearch-end ()
22289 "Reveal context after isearch exits."
22290 (when isearch-success ; only if search was successful
22291 (if (featurep 'xemacs)
22292 ;; Under XEmacs, the hook is run in the correct place,
22293 ;; we directly show the context.
22294 (org-show-context 'isearch)
22295 ;; In Emacs the hook runs *before* restoring the overlays.
22296 ;; So we have to use a one-time post-command-hook to do this.
22297 ;; (Emacs 22 has a special variable, see function `org-mode')
22298 (unless (and (boundp 'isearch-mode-end-hook-quit)
22299 isearch-mode-end-hook-quit)
22300 ;; Only when the isearch was not quitted.
22301 (org-add-hook 'post-command-hook 'org-isearch-post-command
22302 'append 'local)))))
22304 (defun org-isearch-post-command ()
22305 "Remove self from hook, and show context."
22306 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22307 (org-show-context 'isearch))
22310 ;;;; Integration with and fixes for other packages
22312 ;;; Imenu support
22314 (defvar org-imenu-markers nil
22315 "All markers currently used by Imenu.")
22316 (make-variable-buffer-local 'org-imenu-markers)
22318 (defun org-imenu-new-marker (&optional pos)
22319 "Return a new marker for use by Imenu, and remember the marker."
22320 (let ((m (make-marker)))
22321 (move-marker m (or pos (point)))
22322 (push m org-imenu-markers)
22325 (defun org-imenu-get-tree ()
22326 "Produce the index for Imenu."
22327 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22328 (setq org-imenu-markers nil)
22329 (let* ((n org-imenu-depth)
22330 (re (concat "^" (org-get-limited-outline-regexp)))
22331 (subs (make-vector (1+ n) nil))
22332 (last-level 0)
22333 m level head)
22334 (save-excursion
22335 (save-restriction
22336 (widen)
22337 (goto-char (point-max))
22338 (while (re-search-backward re nil t)
22339 (setq level (org-reduced-level (funcall outline-level)))
22340 (when (and (<= level n)
22341 (looking-at org-complex-heading-regexp))
22342 (setq head (org-link-display-format
22343 (org-match-string-no-properties 4))
22344 m (org-imenu-new-marker))
22345 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22346 (if (>= level last-level)
22347 (push (cons head m) (aref subs level))
22348 (push (cons head (aref subs (1+ level))) (aref subs level))
22349 (loop for i from (1+ level) to n do (aset subs i nil)))
22350 (setq last-level level)))))
22351 (aref subs 1)))
22353 (eval-after-load "imenu"
22354 '(progn
22355 (add-hook 'imenu-after-jump-hook
22356 (lambda ()
22357 (if (derived-mode-p 'org-mode)
22358 (org-show-context 'org-goto))))))
22360 (defun org-link-display-format (link)
22361 "Replace a link with either the description, or the link target
22362 if no description is present"
22363 (save-match-data
22364 (if (string-match org-bracket-link-analytic-regexp link)
22365 (replace-match (if (match-end 5)
22366 (match-string 5 link)
22367 (concat (match-string 1 link)
22368 (match-string 3 link)))
22369 nil t link)
22370 link)))
22372 (defun org-toggle-link-display ()
22373 "Toggle the literal or descriptive display of links."
22374 (interactive)
22375 (if org-descriptive-links
22376 (progn (org-remove-from-invisibility-spec '(org-link))
22377 (org-restart-font-lock)
22378 (setq org-descriptive-links nil))
22379 (progn (add-to-invisibility-spec '(org-link))
22380 (org-restart-font-lock)
22381 (setq org-descriptive-links t))))
22383 ;; Speedbar support
22385 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22386 "Overlay marking the agenda restriction line in speedbar.")
22387 (overlay-put org-speedbar-restriction-lock-overlay
22388 'face 'org-agenda-restriction-lock)
22389 (overlay-put org-speedbar-restriction-lock-overlay
22390 'help-echo "Agendas are currently limited to this item.")
22391 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22393 (defun org-speedbar-set-agenda-restriction ()
22394 "Restrict future agenda commands to the location at point in speedbar.
22395 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22396 (interactive)
22397 (require 'org-agenda)
22398 (let (p m tp np dir txt)
22399 (cond
22400 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22401 'org-imenu t))
22402 (setq m (get-text-property p 'org-imenu-marker))
22403 (with-current-buffer (marker-buffer m)
22404 (goto-char m)
22405 (org-agenda-set-restriction-lock 'subtree)))
22406 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22407 'speedbar-function 'speedbar-find-file))
22408 (setq tp (previous-single-property-change
22409 (1+ p) 'speedbar-function)
22410 np (next-single-property-change
22411 tp 'speedbar-function)
22412 dir (speedbar-line-directory)
22413 txt (buffer-substring-no-properties (or tp (point-min))
22414 (or np (point-max))))
22415 (with-current-buffer (find-file-noselect
22416 (let ((default-directory dir))
22417 (expand-file-name txt)))
22418 (unless (derived-mode-p 'org-mode)
22419 (error "Cannot restrict to non-Org-mode file"))
22420 (org-agenda-set-restriction-lock 'file)))
22421 (t (error "Don't know how to restrict Org-mode's agenda")))
22422 (move-overlay org-speedbar-restriction-lock-overlay
22423 (point-at-bol) (point-at-eol))
22424 (setq current-prefix-arg nil)
22425 (org-agenda-maybe-redo)))
22427 (eval-after-load "speedbar"
22428 '(progn
22429 (speedbar-add-supported-extension ".org")
22430 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22431 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22432 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22433 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22434 (add-hook 'speedbar-visiting-tag-hook
22435 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22437 ;;; Fixes and Hacks for problems with other packages
22439 ;; Make flyspell not check words in links, to not mess up our keymap
22440 (defun org-mode-flyspell-verify ()
22441 "Don't let flyspell put overlays at active buttons, or on
22442 {todo,all-time,additional-option-like}-keywords."
22443 (let ((pos (max (1- (point)) (point-min)))
22444 (word (thing-at-point 'word)))
22445 (and (not (get-text-property pos 'keymap))
22446 (not (get-text-property pos 'org-no-flyspell))
22447 (not (member word org-todo-keywords-1))
22448 (not (member word org-all-time-keywords))
22449 (not (member word org-options-keywords))
22450 (not (member word (mapcar 'car org-startup-options)))
22451 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22453 (defun org-remove-flyspell-overlays-in (beg end)
22454 "Remove flyspell overlays in region."
22455 (and (org-bound-and-true-p flyspell-mode)
22456 (fboundp 'flyspell-delete-region-overlays)
22457 (flyspell-delete-region-overlays beg end))
22458 (add-text-properties beg end '(org-no-flyspell t)))
22460 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22461 (eval-after-load "bookmark"
22462 '(if (boundp 'bookmark-after-jump-hook)
22463 ;; We can use the hook
22464 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22465 ;; Hook not available, use advice
22466 (defadvice bookmark-jump (after org-make-visible activate)
22467 "Make the position visible."
22468 (org-bookmark-jump-unhide))))
22470 ;; Make sure saveplace shows the location if it was hidden
22471 (eval-after-load "saveplace"
22472 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22473 "Make the position visible."
22474 (org-bookmark-jump-unhide)))
22476 ;; Make sure ecb shows the location if it was hidden
22477 (eval-after-load "ecb"
22478 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22479 "Make hierarchy visible when jumping into location from ECB tree buffer."
22480 (if (derived-mode-p 'org-mode)
22481 (org-show-context))))
22483 (defun org-bookmark-jump-unhide ()
22484 "Unhide the current position, to show the bookmark location."
22485 (and (derived-mode-p 'org-mode)
22486 (or (outline-invisible-p)
22487 (save-excursion (goto-char (max (point-min) (1- (point))))
22488 (outline-invisible-p)))
22489 (org-show-context 'bookmark-jump)))
22491 ;; Make session.el ignore our circular variable
22492 (eval-after-load "session"
22493 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22495 ;;;; Experimental code
22497 (defun org-closed-in-range ()
22498 "Sparse tree of items closed in a certain time range.
22499 Still experimental, may disappear in the future."
22500 (interactive)
22501 ;; Get the time interval from the user.
22502 (let* ((time1 (org-float-time
22503 (org-read-date nil 'to-time nil "Starting date: ")))
22504 (time2 (org-float-time
22505 (org-read-date nil 'to-time nil "End date:")))
22506 ;; callback function
22507 (callback (lambda ()
22508 (let ((time
22509 (org-float-time
22510 (apply 'encode-time
22511 (org-parse-time-string
22512 (match-string 1))))))
22513 ;; check if time in interval
22514 (and (>= time time1) (<= time time2))))))
22515 ;; make tree, check each match with the callback
22516 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22518 ;;;; Finish up
22520 (provide 'org)
22522 (run-hooks 'org-load-hook)
22524 ;;; org.el ends here