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.
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 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
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
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
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
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
79 (require 'format-spec
)
81 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
82 (when (fboundp 'defvaralias
)
83 (unless (boundp 'calendar-view-holidays-initially-flag
)
84 (defvaralias 'calendar-view-holidays-initially-flag
85 'view-calendar-holidays-initially
))
86 (unless (boundp 'calendar-view-diary-initially-flag
)
87 (defvaralias 'calendar-view-diary-initially-flag
88 'view-diary-entries-initially
))
89 (unless (boundp 'diary-fancy-buffer
)
90 (defvaralias 'diary-fancy-buffer
'fancy-diary-buffer
)))
92 (require 'outline
) (require 'noutline
)
93 ;; Other stuff we need.
95 (unless (fboundp 'time-subtract
) (defalias 'time-subtract
'subtract-time
))
100 (require 'org-entities
)
101 (require 'org-compat
)
104 (require 'org-pcomplete
)
106 (require 'org-footnote
)
108 (declare-function org-inlinetask-at-task-p
"org-inlinetask" ())
109 (declare-function org-inlinetask-outline-regexp
"org-inlinetask" ())
110 (declare-function org-inlinetask-toggle-visibility
"org-inlinetask" ())
111 (declare-function org-pop-to-buffer-same-window
"org-compat" (&optional buffer-or-name norecord label
))
112 (declare-function org-at-clock-log-p
"org-clock" ())
113 (declare-function org-clock-timestamps-up
"org-clock" ())
114 (declare-function org-clock-timestamps-down
"org-clock" ())
125 ;; load languages based on value of `org-babel-load-languages'
126 (defvar org-babel-load-languages
)
128 (defun org-babel-do-load-languages (sym value
)
129 "Load the languages defined in `org-babel-load-languages'."
130 (set-default sym value
)
132 (let ((active (cdr pair
)) (lang (symbol-name (car pair
))))
135 (require (intern (concat "ob-" lang
))))
137 (funcall 'fmakunbound
138 (intern (concat "org-babel-execute:" lang
)))
139 (funcall 'fmakunbound
140 (intern (concat "org-babel-expand-body:" lang
)))))))
141 org-babel-load-languages
))
143 (defcustom org-babel-load-languages
'((emacs-lisp . t
))
144 "Languages which can be evaluated in Org-mode buffers.
145 This list can be used to load support for any of the languages
146 below, note that each language will depend on a different set of
147 system executables and/or Emacs modes. When a language is
148 \"loaded\", then code blocks in that language can be evaluated
149 with `org-babel-execute-src-block' bound by default to C-c
150 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
151 be set to remove code block evaluation from the C-c C-c
152 keybinding. By default only Emacs Lisp (which has no
153 requirements) is loaded."
155 :set
'org-babel-do-load-languages
157 :type
'(alist :tag
"Babel Languages"
160 (const :tag
"Awk" awk
)
163 (const :tag
"Asymptote" asymptote
)
164 (const :tag
"Calc" calc
)
165 (const :tag
"Clojure" clojure
)
166 (const :tag
"CSS" css
)
167 (const :tag
"Ditaa" ditaa
)
168 (const :tag
"Dot" dot
)
169 (const :tag
"Emacs Lisp" emacs-lisp
)
170 (const :tag
"Fortran" fortran
)
171 (const :tag
"Gnuplot" gnuplot
)
172 (const :tag
"Haskell" haskell
)
174 (const :tag
"Java" java
)
175 (const :tag
"Javascript" js
)
176 (const :tag
"LaTeX" latex
)
177 (const :tag
"Ledger" ledger
)
178 (const :tag
"Lilypond" lilypond
)
179 (const :tag
"Maxima" maxima
)
180 (const :tag
"Matlab" matlab
)
181 (const :tag
"Mscgen" mscgen
)
182 (const :tag
"Ocaml" ocaml
)
183 (const :tag
"Octave" octave
)
184 (const :tag
"Org" org
)
185 (const :tag
"Perl" perl
)
186 (const :tag
"Pico Lisp" picolisp
)
187 (const :tag
"PlantUML" plantuml
)
188 (const :tag
"Python" python
)
189 (const :tag
"Ruby" ruby
)
190 (const :tag
"Sass" sass
)
191 (const :tag
"Scala" scala
)
192 (const :tag
"Scheme" scheme
)
193 (const :tag
"Screen" screen
)
194 (const :tag
"Shell Script" sh
)
195 (const :tag
"Shen" shen
)
196 (const :tag
"Sql" sql
)
197 (const :tag
"Sqlite" sqlite
))
198 :value-type
(boolean :tag
"Activate" :value t
)))
200 ;;;; Customization variables
201 (defcustom org-clone-delete-id nil
202 "Remove ID property of clones of a subtree.
203 When non-nil, clones of a subtree don't inherit the ID property.
204 Otherwise they inherit the ID property with a new unique
212 (defvaralias 'org-version
'org-release
)
214 (defun org-version (&optional here
)
215 "Show the org-mode version in the echo area.
216 With prefix arg HERE, insert it at point."
218 (let* ((origin default-directory
)
219 (version (if (boundp 'org-release
) org-release
"N/A"))
220 (git-version (if (boundp 'org-git-version
) org-git-version
"N/A"))
221 (org-install (ignore-errors (find-library-name "org-install")))
222 (version_ (format "Org-mode version %s (%s @ %s)"
225 (if org-install org-install
"org-install.el can not be found!"))))
226 (if (org-called-interactively-p 'interactive
)
227 (if here
(insert version_
)
231 ;;; Compatibility constants
233 ;;; The custom variables
236 "Outline-based notes management and organizer."
241 (defcustom org-mode-hook nil
242 "Mode hook for Org-mode, run after the mode was turned on."
246 (defcustom org-load-hook nil
247 "Hook that is run after org.el has been loaded."
251 (defcustom org-log-buffer-setup-hook nil
252 "Hook that is run after an Org log buffer is created."
257 (defvar org-modules
) ; defined below
258 (defvar org-modules-loaded nil
259 "Have the modules been loaded already?")
261 (defun org-load-modules-maybe (&optional force
)
262 "Load all extensions listed in `org-modules'."
263 (when (or force
(not org-modules-loaded
))
265 (condition-case nil
(require ext
)
266 (error (message "Problems while trying to load feature `%s'" ext
))))
268 (setq org-modules-loaded t
)))
270 (defun org-set-modules (var value
)
271 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
273 (when (featurep 'org
)
274 (org-load-modules-maybe 'force
)))
276 (when (org-bound-and-true-p org-modules
)
277 (let ((a (member 'org-infojs org-modules
)))
278 (and a
(setcar a
'org-jsinfo
))))
280 (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
)
281 "Modules that should always be loaded together with org.el.
282 If a description starts with <C>, the file is not part of Emacs
283 and loading it will require that you have downloaded and properly installed
284 the org-mode distribution.
286 You can also use this system to load external packages (i.e. neither Org
287 core modules, nor modules from the CONTRIB directory). Just add symbols
288 to the end of the list. If the package is called org-xyz.el, then you need
289 to add the symbol `xyz', and the package must have a call to
293 :set
'org-set-modules
296 (const :tag
" bbdb: Links to BBDB entries" org-bbdb
)
297 (const :tag
" bibtex: Links to BibTeX entries" org-bibtex
)
298 (const :tag
" crypt: Encryption of subtrees" org-crypt
)
299 (const :tag
" ctags: Access to Emacs tags with links" org-ctags
)
300 (const :tag
" docview: Links to doc-view buffers" org-docview
)
301 (const :tag
" gnus: Links to GNUS folders/messages" org-gnus
)
302 (const :tag
" id: Global IDs for identifying entries" org-id
)
303 (const :tag
" info: Links to Info nodes" org-info
)
304 (const :tag
" jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo
)
305 (const :tag
" habit: Track your consistency with habits" org-habit
)
306 (const :tag
" inlinetask: Tasks independent of outline hierarchy" org-inlinetask
)
307 (const :tag
" irc: Links to IRC/ERC chat sessions" org-irc
)
308 (const :tag
" mac-message: Links to messages in Apple Mail" org-mac-message
)
309 (const :tag
" mew Links to Mew folders/messages" org-mew
)
310 (const :tag
" mhe: Links to MHE folders/messages" org-mhe
)
311 (const :tag
" protocol: Intercept calls from emacsclient" org-protocol
)
312 (const :tag
" rmail: Links to RMAIL folders/messages" org-rmail
)
313 (const :tag
" special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks
)
314 (const :tag
" vm: Links to VM folders/messages" org-vm
)
315 (const :tag
" wl: Links to Wanderlust folders/messages" org-wl
)
316 (const :tag
" w3m: Special cut/paste from w3m to Org-mode." org-w3m
)
317 (const :tag
" mouse: Additional mouse support" org-mouse
)
318 (const :tag
" TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler
)
320 (const :tag
"C annotate-file: Annotate a file with org syntax" org-annotate-file
)
321 (const :tag
"C bookmark: Org-mode links to bookmarks" org-bookmark
)
322 (const :tag
"C checklist: Extra functions for checklists in repeated tasks" org-checklist
)
323 (const :tag
"C choose: Use TODO keywords to mark decisions states" org-choose
)
324 (const :tag
"C collector: Collect properties into tables" org-collector
)
325 (const :tag
"C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend
)
326 (const :tag
"C drill: Flashcards and spaced repetition for Org-mode" org-drill
)
327 (const :tag
"C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol
)
328 (const :tag
"C eshell Support for links to working directories in eshell" org-eshell
)
329 (const :tag
"C eval: Include command output as text" org-eval
)
330 (const :tag
"C eval-light: Evaluate inbuffer-code on demand" org-eval-light
)
331 (const :tag
"C expiry: Expiry mechanism for Org-mode entries" org-expiry
)
332 (const :tag
"C exp-bibtex: Export citations using BibTeX" org-exp-bibtex
)
333 (const :tag
"C git-link: Provide org links to specific file version" org-git-link
)
334 (const :tag
"C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query
)
336 (const :tag
"C invoice: Help manage client invoices in Org-mode" org-invoice
)
338 (const :tag
"C jira: Add a jira:ticket protocol to Org-mode" org-jira
)
339 (const :tag
"C learn: SuperMemo's incremental learning algorithm" org-learn
)
340 (const :tag
"C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix
)
341 (const :tag
"C notmuch: Provide org links to notmuch searches or messages" org-notmuch
)
342 (const :tag
"C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal
)
343 (const :tag
"C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber
)
344 (const :tag
"C man: Support for links to manpages in Org-mode" org-man
)
345 (const :tag
"C mtags: Support for muse-like tags" org-mtags
)
346 (const :tag
"C panel: Simple routines for us with bad memory" org-panel
)
347 (const :tag
"C registry: A registry for Org-mode links" org-registry
)
348 (const :tag
"C org2rem: Convert org appointments into reminders" org2rem
)
349 (const :tag
"C screen: Visit screen sessions through Org-mode links" org-screen
)
350 (const :tag
"C secretary: Team management with org-mode" org-secretary
)
351 (const :tag
"C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert
)
352 (const :tag
"C toc: Table of contents for Org-mode buffer" org-toc
)
353 (const :tag
"C track: Keep up with Org-mode development" org-track
)
354 (const :tag
"C velocity Something like Notational Velocity for Org" org-velocity
)
355 (const :tag
"C wikinodes: CamelCase wiki-like links" org-wikinodes
)
356 (repeat :tag
"External packages" :inline t
(symbol :tag
"Package"))))
358 (defcustom org-support-shift-select nil
359 "Non-nil means make shift-cursor commands select text when possible.
361 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
362 start selecting a region, or enlarge regions started in this way.
363 In Org-mode, in special contexts, these same keys are used for
364 other purposes, important enough to compete with shift selection.
365 Org tries to balance these needs by supporting `shift-select-mode'
366 outside these special contexts, under control of this variable.
368 The default of this variable is nil, to avoid confusing behavior. Shifted
369 cursor keys will then execute Org commands in the following contexts:
370 - on a headline, changing TODO state (left/right) and priority (up/down)
371 - on a time stamp, changing the time
372 - in a plain list item, changing the bullet type
373 - in a property definition line, switching between allowed values
374 - in the BEGIN line of a clock table (changing the time block).
375 Outside these contexts, the commands will throw an error.
377 When this variable is t and the cursor is not in a special
378 context, Org-mode will support shift-selection for making and
379 enlarging regions. To make this more effective, the bullet
380 cycling will no longer happen anywhere in an item line, but only
381 if the cursor is exactly on the bullet.
383 If you set this variable to the symbol `always', then the keys
384 will not be special in headlines, property lines, and item lines,
385 to make shift selection work there as well. If this is what you
386 want, you can use the following alternative commands: `C-c C-t'
387 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
388 can be used to switch TODO sets, `C-c -' to cycle item bullet
389 types, and properties can be edited by hand or in column view.
391 However, when the cursor is on a timestamp, shift-cursor commands
392 will still edit the time stamp - this is just too good to give up.
394 XEmacs user should have this variable set to nil, because
395 `shift-select-mode' is in Emacs 23 or later only."
398 (const :tag
"Never" nil
)
399 (const :tag
"When outside special context" t
)
400 (const :tag
"Everywhere except timestamps" always
)))
402 (defcustom org-loop-over-headlines-in-active-region nil
403 "Shall some commands act upon headlines in the active region?
405 When set to `t', some commands will be performed in all headlines
406 within the active region.
408 When set to `start-level', some commands will be performed in all
409 headlines within the active region, provided that these headlines
410 are of the same level than the first one.
412 When set to a string, those commands will be performed on the
413 matching headlines within the active region. Such string must be
414 a tags/property/todo match as it is used in the agenda tags view.
416 The list of commands is: `org-schedule', `org-deadline',
417 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
418 `org-archive-to-archive-sibling'. The archiving commands skip
419 already archived entries."
420 :type
'(choice (const :tag
"Don't loop" nil
)
421 (const :tag
"All headlines in active region" t
)
422 (const :tag
"In active region, headlines at the same level than the first one" 'start-level
)
423 (string :tag
"Tags/Property/Todo matcher"))
428 (defgroup org-startup nil
429 "Options concerning startup of Org-mode."
433 (defcustom org-startup-folded t
434 "Non-nil means entering Org-mode will switch to OVERVIEW.
435 This can also be configured on a per-file basis by adding one of
436 the following lines anywhere in the buffer:
438 #+STARTUP: fold (or `overview', this is equivalent)
439 #+STARTUP: nofold (or `showall', this is equivalent)
441 #+STARTUP: showeverything"
444 (const :tag
"nofold: show all" nil
)
445 (const :tag
"fold: overview" t
)
446 (const :tag
"content: all headlines" content
)
447 (const :tag
"show everything, even drawers" showeverything
)))
449 (defcustom org-startup-truncated t
450 "Non-nil means entering Org-mode will set `truncate-lines'.
451 This is useful since some lines containing links can be very long and
452 uninteresting. Also tables look terrible when wrapped."
456 (defcustom org-startup-indented nil
457 "Non-nil means turn on `org-indent-mode' on startup.
458 This can also be configured on a per-file basis by adding one of
459 the following lines anywhere in the buffer:
463 :group
'org-structure
465 (const :tag
"Not" nil
)
466 (const :tag
"Globally (slow on startup in large files)" t
)))
468 (defcustom org-use-sub-superscripts t
469 "Non-nil means interpret \"_\" and \"^\" for export.
470 When this option is turned on, you can use TeX-like syntax for sub- and
471 superscripts. Several characters after \"_\" or \"^\" will be
472 considered as a single item - so grouping with {} is normally not
473 needed. For example, the following things will be parsed as single
474 sub- or superscripts.
476 10^24 or 10^tau several digits will be considered 1 item.
477 10^-12 or 10^-tau a leading sign with digits or a word
478 x^2-y^3 will be read as x^2 - y^3, because items are
479 terminated by almost any nonword/nondigit char.
480 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
482 Still, ambiguity is possible - so when in doubt use {} to enclose the
483 sub/superscript. If you set this variable to the symbol `{}',
484 the braces are *required* in order to trigger interpretations as
485 sub/superscript. This can be helpful in documents that need \"_\"
486 frequently in plain text.
488 Not all export backends support this, but HTML does.
490 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
492 :group
'org-export-translation
495 (const :tag
"Always interpret" t
)
496 (const :tag
"Only with braces" {})
497 (const :tag
"Never interpret" nil
)))
499 (if (fboundp 'defvaralias
)
500 (defvaralias 'org-export-with-sub-superscripts
'org-use-sub-superscripts
))
503 (defcustom org-startup-with-beamer-mode nil
504 "Non-nil means turn on `org-beamer-mode' on startup.
505 This can also be configured on a per-file basis by adding one of
506 the following lines anywhere in the buffer:
513 (defcustom org-startup-align-all-tables nil
514 "Non-nil means align all tables when visiting a file.
515 This is useful when the column width in tables is forced with <N> cookies
516 in table fields. Such tables will look correct only after the first re-align.
517 This can also be configured on a per-file basis by adding one of
518 the following lines anywhere in the buffer:
524 (defcustom org-startup-with-inline-images nil
525 "Non-nil means show inline images when loading a new Org file.
526 This can also be configured on a per-file basis by adding one of
527 the following lines anywhere in the buffer:
528 #+STARTUP: inlineimages
529 #+STARTUP: noinlineimages"
534 (defcustom org-insert-mode-line-in-empty-file nil
535 "Non-nil means insert the first line setting Org-mode in empty files.
536 When the function `org-mode' is called interactively in an empty file, this
537 normally means that the file name does not automatically trigger Org-mode.
538 To ensure that the file will always be in Org-mode in the future, a
539 line enforcing Org-mode will be inserted into the buffer, if this option
544 (defcustom org-replace-disputed-keys nil
545 "Non-nil means use alternative key bindings for some keys.
546 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
547 These keys are also used by other packages like shift-selection-mode'
548 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
549 If you want to use Org-mode together with one of these other modes,
550 or more generally if you would like to move some Org-mode commands to
551 other keys, set this variable and configure the keys with the variable
554 This option is only relevant at load-time of Org-mode, and must be set
555 *before* org.el is loaded. Changing it requires a restart of Emacs to
560 (defcustom org-use-extra-keys nil
561 "Non-nil means use extra key sequence definitions for certain commands.
562 This happens automatically if you run XEmacs or if `window-system'
563 is nil. This variable lets you do the same manually. You must
564 set it before loading org.
566 Example: on Carbon Emacs 22 running graphically, with an external
567 keyboard on a Powerbook, the default way of setting M-left might
568 not work for either Alt or ESC. Setting this variable will make
573 (if (fboundp 'defvaralias
)
574 (defvaralias 'org-CUA-compatible
'org-replace-disputed-keys
))
576 (defcustom org-disputed-keys
577 '(([(shift up
)] .
[(meta p
)])
578 ([(shift down
)] .
[(meta n
)])
579 ([(shift left
)] .
[(meta -
)])
580 ([(shift right
)] .
[(meta +)])
581 ([(control shift right
)] .
[(meta shift
+)])
582 ([(control shift left
)] .
[(meta shift -
)]))
583 "Keys for which Org-mode and other modes compete.
584 This is an alist, cars are the default keys, second element specifies
585 the alternative to use when `org-replace-disputed-keys' is t.
587 Keys can be specified in any syntax supported by `define-key'.
588 The value of this option takes effect only at Org-mode's startup,
589 therefore you'll have to restart Emacs to apply it after changing."
594 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
595 Or return the original if not disputed.
596 Also apply the translations defined in `org-xemacs-key-equivalents'."
597 (when org-replace-disputed-keys
598 (let* ((nkey (key-description key
))
599 (x (org-find-if (lambda (x)
600 (equal (key-description (car x
)) nkey
))
602 (setq key
(if x
(cdr x
) key
))))
603 (when (featurep 'xemacs
)
604 (setq key
(or (cdr (assoc key org-xemacs-key-equivalents
)) key
)))
607 (defun org-find-if (predicate seq
)
610 (if (funcall predicate
(car seq
))
611 (throw 'exit
(car seq
))
614 (defun org-defkey (keymap key def
)
615 "Define a key, possibly translated, as returned by `org-key'."
616 (define-key keymap
(org-key key
) def
))
618 (defcustom org-ellipsis nil
619 "The ellipsis to use in the Org-mode outline.
620 When nil, just use the standard three dots. When a string, use that instead,
621 When a face, use the standard 3 dots, but with the specified face.
622 The change affects only Org-mode (which will then use its own display table).
623 Changing this requires executing `M-x org-mode' in a buffer to become
626 :type
'(choice (const :tag
"Default" nil
)
627 (face :tag
"Face" :value org-warning
)
628 (string :tag
"String" :value
"...#")))
630 (defvar org-display-table nil
631 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
633 (defgroup org-keywords nil
634 "Keywords in Org-mode."
638 (defcustom org-deadline-string
"DEADLINE:"
639 "String to mark deadline entries.
640 A deadline is this string, followed by a time stamp. Should be a word,
641 terminated by a colon. You can insert a schedule keyword and
642 a timestamp with \\[org-deadline].
643 Changes become only effective after restarting Emacs."
647 (defcustom org-scheduled-string
"SCHEDULED:"
648 "String to mark scheduled TODO entries.
649 A schedule is this string, followed by a time stamp. Should be a word,
650 terminated by a colon. You can insert a schedule keyword and
651 a timestamp with \\[org-schedule].
652 Changes become only effective after restarting Emacs."
656 (defcustom org-closed-string
"CLOSED:"
657 "String used as the prefix for timestamps logging closing a TODO entry."
661 (defcustom org-clock-string
"CLOCK:"
662 "String used as prefix for timestamps clocking work hours on an item."
666 (defcustom org-comment-string
"COMMENT"
667 "Entries starting with this keyword will never be exported.
668 An entry can be toggled between COMMENT and normal with
669 \\[org-toggle-comment].
670 Changes become only effective after restarting Emacs."
674 (defcustom org-quote-string
"QUOTE"
675 "Entries starting with this keyword will be exported in fixed-width font.
676 Quoting applies only to the text in the entry following the headline, and does
677 not extend beyond the next headline, even if that is lower level.
678 An entry can be toggled between QUOTE and normal with
679 \\[org-toggle-fixed-width-section]."
683 (defconst org-repeat-re
684 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
685 "Regular expression for specifying repeated events.
686 After a match, group 1 contains the repeat expression.")
688 (defgroup org-structure nil
689 "Options concerning the general structure of Org-mode files."
693 (defgroup org-reveal-location nil
694 "Options about how to make context of a location visible."
695 :tag
"Org Reveal Location"
696 :group
'org-structure
)
698 (defconst org-context-choice
700 (const :tag
"Always" t
)
701 (const :tag
"Never" nil
)
702 (repeat :greedy t
:tag
"Individual contexts"
704 (choice :tag
"Context"
711 (const bookmark-jump
)
715 "Contexts for the reveal options.")
717 (defcustom org-show-hierarchy-above
'((default . t
))
718 "Non-nil means show full hierarchy when revealing a location.
719 Org-mode often shows locations in an org-mode file which might have
720 been invisible before. When this is set, the hierarchy of headings
721 above the exposed location is shown.
722 Turning this off for example for sparse trees makes them very compact.
723 Instead of t, this can also be an alist specifying this option for different
724 contexts. Valid contexts are
725 agenda when exposing an entry from the agenda
726 org-goto when using the command `org-goto' on key C-c C-j
727 occur-tree when using the command `org-occur' on key C-c /
728 tags-tree when constructing a sparse tree based on tags matches
729 link-search when exposing search matches associated with a link
730 mark-goto when exposing the jump goal of a mark
731 bookmark-jump when exposing a bookmark location
732 isearch when exiting from an incremental search
733 default default for all contexts not set explicitly"
734 :group
'org-reveal-location
735 :type org-context-choice
)
737 (defcustom org-show-following-heading
'((default . nil
))
738 "Non-nil means show following heading when revealing a location.
739 Org-mode often shows locations in an org-mode file which might have
740 been invisible before. When this is set, the heading following the
742 Turning this off for example for sparse trees makes them very compact,
743 but makes it harder to edit the location of the match. In such a case,
744 use the command \\[org-reveal] to show more context.
745 Instead of t, this can also be an alist specifying this option for different
746 contexts. See `org-show-hierarchy-above' for valid contexts."
747 :group
'org-reveal-location
748 :type org-context-choice
)
750 (defcustom org-show-siblings
'((default . nil
) (isearch t
))
751 "Non-nil means show all sibling heading when revealing a location.
752 Org-mode often shows locations in an org-mode file which might have
753 been invisible before. When this is set, the sibling of the current entry
754 heading are all made visible. If `org-show-hierarchy-above' is t,
755 the same happens on each level of the hierarchy above the current entry.
757 By default this is on for the isearch context, off for all other contexts.
758 Turning this off for example for sparse trees makes them very compact,
759 but makes it harder to edit the location of the match. In such a case,
760 use the command \\[org-reveal] to show more context.
761 Instead of t, this can also be an alist specifying this option for different
762 contexts. See `org-show-hierarchy-above' for valid contexts."
763 :group
'org-reveal-location
764 :type org-context-choice
)
766 (defcustom org-show-entry-below
'((default . nil
))
767 "Non-nil means show the entry below a headline when revealing a location.
768 Org-mode often shows locations in an org-mode file which might have
769 been invisible before. When this is set, the text below the headline that is
770 exposed is also shown.
772 By default this is off for all contexts.
773 Instead of t, this can also be an alist specifying this option for different
774 contexts. See `org-show-hierarchy-above' for valid contexts."
775 :group
'org-reveal-location
776 :type org-context-choice
)
778 (defcustom org-indirect-buffer-display
'other-window
779 "How should indirect tree buffers be displayed?
780 This applies to indirect buffers created with the commands
781 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
783 current-window Display in the current window
784 other-window Just display in another window.
785 dedicated-frame Create one new frame, and re-use it each time.
786 new-frame Make a new frame each time. Note that in this case
787 previously-made indirect buffers are kept, and you need to
788 kill these buffers yourself."
789 :group
'org-structure
790 :group
'org-agenda-windows
792 (const :tag
"In current window" current-window
)
793 (const :tag
"In current frame, other window" other-window
)
794 (const :tag
"Each time a new frame" new-frame
)
795 (const :tag
"One dedicated frame" dedicated-frame
)))
797 (defcustom org-use-speed-commands nil
798 "Non-nil means activate single letter commands at beginning of a headline.
799 This may also be a function to test for appropriate locations where speed
800 commands should be active."
801 :group
'org-structure
803 (const :tag
"Never" nil
)
804 (const :tag
"At beginning of headline stars" t
)
807 (defcustom org-speed-commands-user nil
808 "Alist of additional speed commands.
809 This list will be checked before `org-speed-commands-default'
810 when the variable `org-use-speed-commands' is non-nil
811 and when the cursor is at the beginning of a headline.
812 The car if each entry is a string with a single letter, which must
813 be assigned to `self-insert-command' in the global map.
814 The cdr is either a command to be called interactively, a function
815 to be called, or a form to be evaluated.
816 An entry that is just a list with a single string will be interpreted
817 as a descriptive headline that will be added when listing the speed
818 commands in the Help buffer using the `?' speed command."
819 :group
'org-structure
820 :type
'(repeat :value
("k" . ignore
)
821 (choice :value
("k" . ignore
)
822 (list :tag
"Descriptive Headline" (string :tag
"Headline"))
823 (cons :tag
"Letter and Command"
824 (string :tag
"Command letter")
829 (defgroup org-cycle nil
830 "Options concerning visibility cycling in Org-mode."
832 :group
'org-structure
)
834 (defcustom org-cycle-skip-children-state-if-no-children t
835 "Non-nil means skip CHILDREN state in entries that don't have any."
839 (defcustom org-cycle-max-level nil
840 "Maximum level which should still be subject to visibility cycling.
841 Levels higher than this will, for cycling, be treated as text, not a headline.
842 When `org-odd-levels-only' is set, a value of N in this variable actually
843 means 2N-1 stars as the limiting headline.
844 When nil, cycle all levels.
845 Note that the limiting level of cycling is also influenced by
846 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
847 `org-inlinetask-min-level' is, cycling will be limited to levels one less
851 (const :tag
"No limit" nil
)
852 (integer :tag
"Maximum level")))
854 (defcustom org-drawers
'("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
855 "Names of drawers. Drawers are not opened by cycling on the headline above.
856 Drawers only open with a TAB on the drawer line itself. A drawer looks like
861 The drawer \"PROPERTIES\" is special for capturing properties through
864 Drawers can be defined on the per-file basis with a line like:
866 #+DRAWERS: HIDDEN STATE PROPERTIES"
867 :group
'org-structure
869 :type
'(repeat (string :tag
"Drawer Name")))
871 (defcustom org-hide-block-startup nil
872 "Non-nil means entering Org-mode will fold all blocks.
873 This can also be set in on a per-file basis with
875 #+STARTUP: hideblocks
876 #+STARTUP: showblocks"
881 (defcustom org-cycle-global-at-bob nil
882 "Cycle globally if cursor is at beginning of buffer and not at a headline.
883 This makes it possible to do global cycling without having to use S-TAB or
884 \\[universal-argument] TAB. For this special case to work, the first line \
886 must not be a headline - it may be empty or some other text. When used in
887 this way, `org-cycle-hook' is disables temporarily, to make sure the
888 cursor stays at the beginning of the buffer.
889 When this option is nil, don't do anything special at the beginning
894 (defcustom org-cycle-level-after-item
/entry-creation t
895 "Non-nil means cycle entry level or item indentation in new empty entries.
897 When the cursor is at the end of an empty headline, i.e with only stars
898 and maybe a TODO keyword, TAB will then switch the entry to become a child,
899 and then all possible ancestor states, before returning to the original state.
900 This makes data entry extremely fast: M-RET to create a new headline,
901 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
903 When the cursor is at the end of an empty plain list item, one TAB will
904 make it a subitem, two or more tabs will back up to make this an item
905 higher up in the item hierarchy."
909 (defcustom org-cycle-emulate-tab t
910 "Where should `org-cycle' emulate TAB.
912 white Only in completely white lines
913 whitestart Only at the beginning of lines, before the first non-white char
914 t Everywhere except in headlines
915 exc-hl-bol Everywhere except at the start of a headline
916 If TAB is used in a place where it does not emulate TAB, the current subtree
917 visibility is cycled."
919 :type
'(choice (const :tag
"Never" nil
)
920 (const :tag
"Only in completely white lines" white
)
921 (const :tag
"Before first char in a line" whitestart
)
922 (const :tag
"Everywhere except in headlines" t
)
923 (const :tag
"Everywhere except at bol in headlines" exc-hl-bol
)
926 (defcustom org-cycle-separator-lines
2
927 "Number of empty lines needed to keep an empty line between collapsed trees.
928 If you leave an empty line between the end of a subtree and the following
929 headline, this empty line is hidden when the subtree is folded.
930 Org-mode will leave (exactly) one empty line visible if the number of
931 empty lines is equal or larger to the number given in this variable.
932 So the default 2 means at least 2 empty lines after the end of a subtree
933 are needed to produce free space between a collapsed subtree and the
936 If the number is negative, and the number of empty lines is at least -N,
937 all empty lines are shown.
939 Special case: when 0, never leave empty lines in collapsed view."
942 (put 'org-cycle-separator-lines
'safe-local-variable
'integerp
)
944 (defcustom org-pre-cycle-hook nil
945 "Hook that is run before visibility cycling is happening.
946 The function(s) in this hook must accept a single argument which indicates
947 the new state that will be set right after running this hook. The
948 argument is a symbol. Before a global state change, it can have the values
949 `overview', `content', or `all'. Before a local state change, it can have
950 the values `folded', `children', or `subtree'."
954 (defcustom org-cycle-hook
'(org-cycle-hide-archived-subtrees
955 org-cycle-hide-drawers
956 org-cycle-show-empty-lines
957 org-optimize-window-after-visibility-change
)
958 "Hook that is run after `org-cycle' has changed the buffer visibility.
959 The function(s) in this hook must accept a single argument which indicates
960 the new state that was set by the most recent `org-cycle' command. The
961 argument is a symbol. After a global state change, it can have the values
962 `overview', `content', or `all'. After a local state change, it can have
963 the values `folded', `children', or `subtree'."
967 (defgroup org-edit-structure nil
968 "Options concerning structure editing in Org-mode."
969 :tag
"Org Edit Structure"
970 :group
'org-structure
)
972 (defcustom org-odd-levels-only nil
973 "Non-nil means skip even levels and only use odd levels for the outline.
974 This has the effect that two stars are being added/taken away in
975 promotion/demotion commands. It also influences how levels are
976 handled by the exporters.
977 Changing it requires restart of `font-lock-mode' to become effective
978 for fontification also in regions already fontified.
979 You may also set this on a per-file basis by adding one of the following
984 :group
'org-edit-structure
985 :group
'org-appearance
988 (defcustom org-adapt-indentation t
989 "Non-nil means adapt indentation to outline node level.
991 When this variable is set, Org assumes that you write outlines by
992 indenting text in each node to align with the headline (after the stars).
993 The following issues are influenced by this variable:
995 - When this is set and the *entire* text in an entry is indented, the
996 indentation is increased by one space in a demotion command, and
997 decreased by one in a promotion command. If any line in the entry
998 body starts with text at column 0, indentation is not changed at all.
1000 - Property drawers and planning information is inserted indented when
1001 this variable s set. When nil, they will not be indented.
1003 - TAB indents a line relative to context. The lines below a headline
1004 will be indented when this variable is set.
1006 Note that this is all about true indentation, by adding and removing
1007 space characters. See also `org-indent.el' which does level-dependent
1008 indentation in a virtual way, i.e. at display time in Emacs."
1009 :group
'org-edit-structure
1012 (defcustom org-special-ctrl-a
/e nil
1013 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1015 When t, `C-a' will bring back the cursor to the beginning of the
1016 headline text, i.e. after the stars and after a possible TODO
1017 keyword. In an item, this will be the position after bullet and
1018 check-box, if any. When the cursor is already at that position,
1019 another `C-a' will bring it to the beginning of the line.
1021 `C-e' will jump to the end of the headline, ignoring the presence
1022 of tags in the headline. A second `C-e' will then jump to the
1023 true end of the line, after any tags. This also means that, when
1024 this variable is non-nil, `C-e' also will never jump beyond the
1025 end of the heading of a folded section, i.e. not after the
1028 When set to the symbol `reversed', the first `C-a' or `C-e' works
1029 normally, going to the true line boundary first. Only a directly
1030 following, identical keypress will bring the cursor to the
1033 This may also be a cons cell where the behavior for `C-a' and
1034 `C-e' is set separately."
1035 :group
'org-edit-structure
1037 (const :tag
"off" nil
)
1038 (const :tag
"on: after stars/bullet and before tags first" t
)
1039 (const :tag
"reversed: true line boundary first" reversed
)
1040 (cons :tag
"Set C-a and C-e separately"
1041 (choice :tag
"Special C-a"
1042 (const :tag
"off" nil
)
1043 (const :tag
"on: after stars/bullet first" t
)
1044 (const :tag
"reversed: before stars/bullet first" reversed
))
1045 (choice :tag
"Special C-e"
1046 (const :tag
"off" nil
)
1047 (const :tag
"on: before tags first" t
)
1048 (const :tag
"reversed: after tags first" reversed
)))))
1049 (if (fboundp 'defvaralias
)
1050 (defvaralias 'org-special-ctrl-a
'org-special-ctrl-a
/e
))
1052 (defcustom org-special-ctrl-k nil
1053 "Non-nil means `C-k' will behave specially in headlines.
1054 When nil, `C-k' will call the default `kill-line' command.
1055 When t, the following will happen while the cursor is in the headline:
1057 - When the cursor is at the beginning of a headline, kill the entire
1058 line and possible the folded subtree below the line.
1059 - When in the middle of the headline text, kill the headline up to the tags.
1060 - When after the headline text, kill the tags."
1061 :group
'org-edit-structure
1064 (defcustom org-ctrl-k-protect-subtree nil
1065 "Non-nil means, do not delete a hidden subtree with C-k.
1066 When set to the symbol `error', simply throw an error when C-k is
1067 used to kill (part-of) a headline that has hidden text behind it.
1068 Any other non-nil value will result in a query to the user, if it is
1069 OK to kill that hidden subtree. When nil, kill without remorse."
1070 :group
'org-edit-structure
1073 (const :tag
"Do not protect hidden subtrees" nil
)
1074 (const :tag
"Protect hidden subtrees with a security query" t
)
1075 (const :tag
"Never kill a hidden subtree with C-k" error
)))
1077 (defcustom org-catch-invisible-edits nil
1078 "Check if in invisible region before inserting or deleting a character.
1081 nil Do not check, so just do invisible edits.
1082 error Throw an error and do nothing.
1083 show Make point visible, and do the requested edit.
1084 show-and-error Make point visible, then throw an error and abort the edit.
1085 smart Make point visible, and do insertion/deletion if it is
1086 adjacent to visible text and the change feels predictable.
1087 Never delete a previously invisible character or add in the
1088 middle or right after an invisible region. Basically, this
1089 allows insertion and backward-delete right before ellipses.
1090 FIXME: maybe in this case we should not even show?"
1091 :group
'org-edit-structure
1094 (const :tag
"Do not check" nil
)
1095 (const :tag
"Throw error when trying to edit" error
)
1096 (const :tag
"Unhide, but do not do the edit" show-and-error
)
1097 (const :tag
"Show invisible part and do the edit" show
)
1098 (const :tag
"Be smart and do the right thing" smart
)))
1100 (defcustom org-yank-folded-subtrees t
1101 "Non-nil means when yanking subtrees, fold them.
1102 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1103 it starts with a heading and all other headings in it are either children
1104 or siblings, then fold all the subtrees. However, do this only if no
1105 text after the yank would be swallowed into a folded tree by this action."
1106 :group
'org-edit-structure
1109 (defcustom org-yank-adjusted-subtrees nil
1110 "Non-nil means when yanking subtrees, adjust the level.
1111 With this setting, `org-paste-subtree' is used to insert the subtree, see
1112 this function for details."
1113 :group
'org-edit-structure
1116 (defcustom org-M-RET-may-split-line
'((default . t
))
1117 "Non-nil means M-RET will split the line at the cursor position.
1118 When nil, it will go to the end of the line before making a
1120 You may also set this option in a different way for different
1121 contexts. Valid contexts are:
1123 headline when creating a new headline
1124 item when creating a new item
1125 table in a table field
1126 default the value to be used for all contexts not explicitly
1128 :group
'org-structure
1131 (const :tag
"Always" t
)
1132 (const :tag
"Never" nil
)
1133 (repeat :greedy t
:tag
"Individual contexts"
1135 (choice :tag
"Context"
1143 (defcustom org-insert-heading-respect-content nil
1144 "Non-nil means insert new headings after the current subtree.
1145 When nil, the new heading is created directly after the current line.
1146 The commands \\[org-insert-heading-respect-content] and
1147 \\[org-insert-todo-heading-respect-content] turn this variable on
1148 for the duration of the command."
1149 :group
'org-structure
1152 (defcustom org-blank-before-new-entry
'((heading . auto
)
1153 (plain-list-item . auto
))
1154 "Should `org-insert-heading' leave a blank line before new heading/item?
1155 The value is an alist, with `heading' and `plain-list-item' as CAR,
1156 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1157 which case Org will look at the surrounding headings/items and try to
1158 make an intelligent decision whether to insert a blank line or not.
1160 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1161 set, the setting here is ignored and no empty line is inserted, to avoid
1162 breaking the list structure."
1163 :group
'org-edit-structure
1165 (cons (const heading
)
1166 (choice (const :tag
"Never" nil
)
1167 (const :tag
"Always" t
)
1168 (const :tag
"Auto" auto
)))
1169 (cons (const plain-list-item
)
1170 (choice (const :tag
"Never" nil
)
1171 (const :tag
"Always" t
)
1172 (const :tag
"Auto" auto
)))))
1174 (defcustom org-insert-heading-hook nil
1175 "Hook being run after inserting a new heading."
1176 :group
'org-edit-structure
1179 (defcustom org-enable-fixed-width-editor t
1180 "Non-nil means lines starting with \":\" are treated as fixed-width.
1181 This currently only means they are never auto-wrapped.
1182 When nil, such lines will be treated like ordinary lines.
1183 See also the QUOTE keyword."
1184 :group
'org-edit-structure
1187 (defcustom org-goto-auto-isearch t
1188 "Non-nil means typing characters in `org-goto' starts incremental search."
1189 :group
'org-edit-structure
1192 (defgroup org-sparse-trees nil
1193 "Options concerning sparse trees in Org-mode."
1194 :tag
"Org Sparse Trees"
1195 :group
'org-structure
)
1197 (defcustom org-highlight-sparse-tree-matches t
1198 "Non-nil means highlight all matches that define a sparse tree.
1199 The highlights will automatically disappear the next time the buffer is
1200 changed by an edit command."
1201 :group
'org-sparse-trees
1204 (defcustom org-remove-highlights-with-change t
1205 "Non-nil means any change to the buffer will remove temporary highlights.
1206 Such highlights are created by `org-occur' and `org-clock-display'.
1207 When nil, `C-c C-c needs to be used to get rid of the highlights.
1208 The highlights created by `org-preview-latex-fragment' always need
1209 `C-c C-c' to be removed."
1210 :group
'org-sparse-trees
1215 (defcustom org-occur-hook
'(org-first-headline-recenter)
1216 "Hook that is run after `org-occur' has constructed a sparse tree.
1217 This can be used to recenter the window to show as much of the structure
1219 :group
'org-sparse-trees
1222 (defgroup org-imenu-and-speedbar nil
1223 "Options concerning imenu and speedbar in Org-mode."
1224 :tag
"Org Imenu and Speedbar"
1225 :group
'org-structure
)
1227 (defcustom org-imenu-depth
2
1228 "The maximum level for Imenu access to Org-mode headlines.
1229 This also applied for speedbar access."
1230 :group
'org-imenu-and-speedbar
1233 (defgroup org-table nil
1234 "Options concerning tables in Org-mode."
1238 (defcustom org-enable-table-editor
'optimized
1239 "Non-nil means lines starting with \"|\" are handled by the table editor.
1240 When nil, such lines will be treated like ordinary lines.
1242 When equal to the symbol `optimized', the table editor will be optimized to
1244 - Automatic overwrite mode in front of whitespace in table fields.
1245 This makes the structure of the table stay in tact as long as the edited
1246 field does not exceed the column width.
1247 - Minimize the number of realigns. Normally, the table is aligned each time
1248 TAB or RET are pressed to move to another field. With optimization this
1249 happens only if changes to a field might have changed the column width.
1250 Optimization requires replacing the functions `self-insert-command',
1251 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1252 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1253 very good at guessing when a re-align will be necessary, but you can always
1254 force one with \\[org-ctrl-c-ctrl-c].
1256 If you would like to use the optimized version in Org-mode, but the
1257 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1259 This variable can be used to turn on and off the table editor during a session,
1260 but in order to toggle optimization, a restart is required.
1262 See also the variable `org-table-auto-blank-field'."
1265 (const :tag
"off" nil
)
1267 (const :tag
"on, optimized" optimized
)))
1269 (defcustom org-self-insert-cluster-for-undo t
1270 "Non-nil means cluster self-insert commands for undo when possible.
1271 If this is set, then, like in the Emacs command loop, 20 consecutive
1272 characters will be undone together.
1273 This is configurable, because there is some impact on typing performance."
1277 (defcustom org-table-tab-recognizes-table.el t
1278 "Non-nil means TAB will automatically notice a table.el table.
1279 When it sees such a table, it moves point into it and - if necessary -
1280 calls `table-recognize-table'."
1281 :group
'org-table-editing
1284 (defgroup org-link nil
1285 "Options concerning links in Org-mode."
1289 (defvar org-link-abbrev-alist-local nil
1290 "Buffer-local version of `org-link-abbrev-alist', which see.
1291 The value of this is taken from the #+LINK lines.")
1292 (make-variable-buffer-local 'org-link-abbrev-alist-local
)
1294 (defcustom org-link-abbrev-alist nil
1295 "Alist of link abbreviations.
1296 The car of each element is a string, to be replaced at the start of a link.
1297 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1298 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1300 [[linkkey:tag][description]]
1302 The 'linkkey' must be a word word, starting with a letter, followed
1303 by letters, numbers, '-' or '_'.
1305 If REPLACE is a string, the tag will simply be appended to create the link.
1306 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1307 the placeholder \"%h\" will cause a url-encoded version of the tag to
1308 be inserted at that point (see the function `url-hexify-string').
1310 REPLACE may also be a function that will be called with the tag as the
1311 only argument to create the link, which should be returned as a string.
1313 See the manual for examples."
1317 (string :tag
"Protocol")
1319 (string :tag
"Format")
1322 (defcustom org-descriptive-links t
1323 "Non-nil means Org will display descriptive links.
1324 E.g. [[http://orgmode.org][Org website]] will be displayed as
1325 \"Org Website\", hiding the link itself and just displaying its
1326 description. When set to `nil', Org will display the full links
1329 You can interactively set the value of this variable by calling
1330 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1334 (defcustom org-link-file-path-type
'adaptive
1335 "How the path name in file links should be stored.
1338 relative Relative to the current directory, i.e. the directory of the file
1339 into which the link is being inserted.
1340 absolute Absolute path, if possible with ~ for home directory.
1341 noabbrev Absolute path, no abbreviation of home directory.
1342 adaptive Use relative path for files in the current directory and sub-
1343 directories of it. For other files, use an absolute path."
1351 (defcustom org-activate-links
'(bracket angle plain radio tag date footnote
)
1352 "Types of links that should be activated in Org-mode files.
1353 This is a list of symbols, each leading to the activation of a certain link
1354 type. In principle, it does not hurt to turn on most link types - there may
1355 be a small gain when turning off unused link types. The types are:
1357 bracket The recommended [[link][description]] or [[link]] links with hiding.
1358 angle Links in angular brackets that may contain whitespace like
1359 <bbdb:Carsten Dominik>.
1360 plain Plain links in normal text, no whitespace, like http://google.com.
1361 radio Text that is matched by a radio target, see manual for details.
1362 tag Tag settings in a headline (link to tag search).
1363 date Time stamps (link to calendar).
1364 footnote Footnote labels.
1366 Changing this variable requires a restart of Emacs to become effective."
1368 :type
'(set :greedy t
1369 (const :tag
"Double bracket links" bracket
)
1370 (const :tag
"Angular bracket links" angle
)
1371 (const :tag
"Plain text links" plain
)
1372 (const :tag
"Radio target matches" radio
)
1373 (const :tag
"Tags" tag
)
1374 (const :tag
"Timestamps" date
)
1375 (const :tag
"Footnotes" footnote
)))
1377 (defcustom org-make-link-description-function nil
1378 "Function to use to generate link descriptions from links.
1379 If nil the link location will be used. This function must take
1380 two parameters; the first is the link and the second the
1381 description `org-insert-link' has generated, and should return the
1382 description to use."
1386 (defgroup org-link-store nil
1387 "Options concerning storing links in Org-mode."
1388 :tag
"Org Store Link"
1391 (defcustom org-email-link-description-format
"Email %c: %.30s"
1392 "Format of the description part of a link to an email or usenet message.
1393 The following %-escapes will be replaced by corresponding information:
1395 %F full \"From\" field
1396 %f name, taken from \"From\" field, address if no name
1397 %T full \"To\" field
1398 %t first name in \"To\" field, address if no name
1399 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1400 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1405 You may use normal field width specification between the % and the letter.
1406 This is for example useful to limit the length of the subject.
1408 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1409 :group
'org-link-store
1412 (defcustom org-from-is-user-regexp
1414 (when (and user-mail-address
(not (string= user-mail-address
"")))
1415 (setq r1
(concat "\\<" (regexp-quote user-mail-address
) "\\>")))
1416 (when (and user-full-name
(not (string= user-full-name
"")))
1417 (setq r2
(concat "\\<" (regexp-quote user-full-name
) "\\>")))
1418 (if (and r1 r2
) (concat r1
"\\|" r2
) (or r1 r2
)))
1419 "Regexp matched against the \"From:\" header of an email or usenet message.
1420 It should match if the message is from the user him/herself."
1421 :group
'org-link-store
1424 (defcustom org-link-to-org-use-id
'create-if-interactive-and-no-custom-id
1425 "Non-nil means storing a link to an Org file will use entry IDs.
1427 Note that before this variable is even considered, org-id must be loaded,
1428 so please customize `org-modules' and turn it on.
1430 The variable can have the following values:
1432 t Create an ID if needed to make a link to the current entry.
1434 create-if-interactive
1435 If `org-store-link' is called directly (interactively, as a user
1436 command), do create an ID to support the link. But when doing the
1437 job for remember, only use the ID if it already exists. The
1438 purpose of this setting is to avoid proliferation of unwanted
1439 IDs, just because you happen to be in an Org file when you
1440 call `org-remember' that automatically and preemptively
1441 creates a link. If you do want to get an ID link in a remember
1442 template to an entry not having an ID, create it first by
1443 explicitly creating a link to it, using `C-c C-l' first.
1445 create-if-interactive-and-no-custom-id
1446 Like create-if-interactive, but do not create an ID if there is
1447 a CUSTOM_ID property defined in the entry. This is the default.
1450 Use existing ID, do not create one.
1452 nil Never use an ID to make a link, instead link using a text search for
1454 :group
'org-link-store
1456 (const :tag
"Create ID to make link" t
)
1457 (const :tag
"Create if storing link interactively"
1458 create-if-interactive
)
1459 (const :tag
"Create if storing link interactively and no CUSTOM_ID is present"
1460 create-if-interactive-and-no-custom-id
)
1461 (const :tag
"Only use existing" use-existing
)
1462 (const :tag
"Do not use ID to create link" nil
)))
1464 (defcustom org-context-in-file-links t
1465 "Non-nil means file links from `org-store-link' contain context.
1466 A search string will be added to the file name with :: as separator and
1467 used to find the context when the link is activated by the command
1468 `org-open-at-point'. When this option is t, the entire active region
1469 will be placed in the search string of the file link. If set to a
1470 positive integer, only the first n lines of context will be stored.
1472 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1473 negates this setting for the duration of the command."
1474 :group
'org-link-store
1475 :type
'(choice boolean integer
))
1477 (defcustom org-keep-stored-link-after-insertion nil
1478 "Non-nil means keep link in list for entire session.
1480 The command `org-store-link' adds a link pointing to the current
1481 location to an internal list. These links accumulate during a session.
1482 The command `org-insert-link' can be used to insert links into any
1483 Org-mode file (offering completion for all stored links). When this
1484 option is nil, every link which has been inserted once using \\[org-insert-link]
1485 will be removed from the list, to make completing the unused links
1487 :group
'org-link-store
1490 (defgroup org-link-follow nil
1491 "Options concerning following links in Org-mode."
1492 :tag
"Org Follow Link"
1495 (defcustom org-link-translation-function nil
1496 "Function to translate links with different syntax to Org syntax.
1497 This can be used to translate links created for example by the Planner
1498 or emacs-wiki packages to Org syntax.
1499 The function must accept two parameters, a TYPE containing the link
1500 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1501 which is everything after the link protocol. It should return a cons
1502 with possibly modified values of type and path.
1503 Org contains a function for this, so if you set this variable to
1504 `org-translate-link-from-planner', you should be able follow many
1505 links created by planner."
1506 :group
'org-link-follow
1509 (defcustom org-follow-link-hook nil
1510 "Hook that is run after a link has been followed."
1511 :group
'org-link-follow
1514 (defcustom org-tab-follows-link nil
1515 "Non-nil means on links TAB will follow the link.
1516 Needs to be set before org.el is loaded.
1517 This really should not be used, it does not make sense, and the
1518 implementation is bad."
1519 :group
'org-link-follow
1522 (defcustom org-return-follows-link nil
1523 "Non-nil means on links RET will follow the link."
1524 :group
'org-link-follow
1527 (defcustom org-mouse-1-follows-link
1528 (if (boundp 'mouse-1-click-follows-link
) mouse-1-click-follows-link t
)
1529 "Non-nil means mouse-1 on a link will follow the link.
1530 A longer mouse click will still set point. Does not work on XEmacs.
1531 Needs to be set before org.el is loaded."
1532 :group
'org-link-follow
1535 (defcustom org-mark-ring-length
4
1536 "Number of different positions to be recorded in the ring.
1537 Changing this requires a restart of Emacs to work correctly."
1538 :group
'org-link-follow
1541 (defcustom org-link-search-must-match-exact-headline
'query-to-create
1542 "Non-nil means internal links in Org files must exactly match a headline.
1543 When nil, the link search tries to match a phrase with all words
1544 in the search text."
1545 :group
'org-link-follow
1548 (const :tag
"Use fuzzy text search" nil
)
1549 (const :tag
"Match only exact headline" t
)
1550 (const :tag
"Match exact headline or query to create it"
1553 (defcustom org-link-frame-setup
1554 '((vm . vm-visit-folder-other-frame
)
1555 (vm-imap . vm-visit-imap-folder-other-frame
)
1556 (gnus . org-gnus-no-new-news
)
1557 (file . find-file-other-window
)
1558 (wl . wl-other-frame
))
1559 "Setup the frame configuration for following links.
1560 When following a link with Emacs, it may often be useful to display
1561 this link in another window or frame. This variable can be used to
1562 set this up for the different types of links.
1565 `vm-visit-folder-other-window'
1566 `vm-visit-folder-other-frame'
1567 For Gnus, use any of
1570 `org-gnus-no-new-news'
1571 For FILE, use any of
1573 `find-file-other-window'
1574 `find-file-other-frame'
1575 For Wanderlust use any of
1578 For the calendar, use the variable `calendar-setup'.
1579 For BBDB, it is currently only possible to display the matches in
1581 :group
'org-link-follow
1585 (const vm-visit-folder
)
1586 (const vm-visit-folder-other-window
)
1587 (const vm-visit-folder-other-frame
)))
1591 (const gnus-other-frame
)
1592 (const org-gnus-no-new-news
)))
1596 (const find-file-other-window
)
1597 (const find-file-other-frame
)))
1601 (const wl-other-frame
)))))
1603 (defcustom org-display-internal-link-with-indirect-buffer nil
1604 "Non-nil means use indirect buffer to display infile links.
1605 Activating internal links (from one location in a file to another location
1606 in the same file) normally just jumps to the location. When the link is
1607 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1609 another window. When this option is set, the other window actually displays
1610 an indirect buffer clone of the current buffer, to avoid any visibility
1611 changes to the current buffer."
1612 :group
'org-link-follow
1615 (defcustom org-open-non-existing-files nil
1616 "Non-nil means `org-open-file' will open non-existing files.
1617 When nil, an error will be generated.
1618 This variable applies only to external applications because they
1619 might choke on non-existing files. If the link is to a file that
1620 will be opened in Emacs, the variable is ignored."
1621 :group
'org-link-follow
1624 (defcustom org-open-directory-means-index-dot-org nil
1625 "Non-nil means a link to a directory really means to index.org.
1626 When nil, following a directory link will run dired or open a finder/explorer
1627 window on that directory."
1628 :group
'org-link-follow
1631 (defcustom org-link-mailto-program
'(browse-url "mailto:%a?subject=%s")
1632 "Function and arguments to call for following mailto links.
1633 This is a list with the first element being a Lisp function, and the
1634 remaining elements being arguments to the function. In string arguments,
1635 %a will be replaced by the address, and %s will be replaced by the subject
1636 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1637 :group
'org-link-follow
1639 (const :tag
"browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1640 (const :tag
"compose-mail" (compose-mail "%a" "%s"))
1641 (const :tag
"message-mail" (message-mail "%a" "%s"))
1642 (cons :tag
"other" (function) (repeat :tag
"argument" sexp
))))
1644 (defcustom org-confirm-shell-link-function
'yes-or-no-p
1645 "Non-nil means ask for confirmation before executing shell links.
1646 Shell links can be dangerous: just think about a link
1648 [[shell:rm -rf ~/*][Google Search]]
1650 This link would show up in your Org-mode document as \"Google Search\",
1651 but really it would remove your entire home directory.
1652 Therefore we advise against setting this variable to nil.
1653 Just change it to `y-or-n-p' if you want to confirm with a
1654 single keystroke rather than having to type \"yes\"."
1655 :group
'org-link-follow
1657 (const :tag
"with yes-or-no (safer)" yes-or-no-p
)
1658 (const :tag
"with y-or-n (faster)" y-or-n-p
)
1659 (const :tag
"no confirmation (dangerous)" nil
)))
1660 (put 'org-confirm-shell-link-function
1661 'safe-local-variable
1662 #'(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
1664 (defcustom org-confirm-shell-link-not-regexp
""
1665 "A regexp to skip confirmation for shell links."
1666 :group
'org-link-follow
1670 (defcustom org-confirm-elisp-link-function
'yes-or-no-p
1671 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1672 Elisp links can be dangerous: just think about a link
1674 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1676 This link would show up in your Org-mode document as \"Google Search\",
1677 but really it would remove your entire home directory.
1678 Therefore we advise against setting this variable to nil.
1679 Just change it to `y-or-n-p' if you want to confirm with a
1680 single keystroke rather than having to type \"yes\"."
1681 :group
'org-link-follow
1683 (const :tag
"with yes-or-no (safer)" yes-or-no-p
)
1684 (const :tag
"with y-or-n (faster)" y-or-n-p
)
1685 (const :tag
"no confirmation (dangerous)" nil
)))
1686 (put 'org-confirm-shell-link-function
1687 'safe-local-variable
1688 #'(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
1690 (defcustom org-confirm-elisp-link-not-regexp
""
1691 "A regexp to skip confirmation for Elisp links."
1692 :group
'org-link-follow
1696 (defconst org-file-apps-defaults-gnu
1700 "Default file applications on a UNIX or GNU/Linux system.
1701 See `org-file-apps'.")
1703 (defconst org-file-apps-defaults-macosx
1706 (system .
"open %s")
1708 ("eps.gz" .
"gv %s")
1710 ("fig" .
"xfig %s"))
1711 "Default file applications on a MacOS X system.
1712 The system \"open\" is known as a default, but we use X11 applications
1713 for some files for which the OS does not have a good default.
1714 See `org-file-apps'.")
1716 (defconst org-file-apps-defaults-windowsnt
1720 (list (if (featurep 'xemacs
)
1721 'mswindows-shell-execute
1725 (list (if (featurep 'xemacs
)
1726 'mswindows-shell-execute
1729 "Default file applications on a Windows NT system.
1730 The system \"open\" is used for most files.
1731 See `org-file-apps'.")
1733 (defcustom org-file-apps
1736 ("\\.mm\\'" . default
)
1737 ("\\.x?html?\\'" . default
)
1738 ("\\.pdf\\'" . default
)
1740 "External applications for opening `file:path' items in a document.
1741 Org-mode uses system defaults for different file types, but
1742 you can use this variable to set the application for a given file
1743 extension. The entries in this list are cons cells where the car identifies
1744 files and the cdr the corresponding command. Possible values for the
1746 \"string\" A string as a file identifier can be interpreted in different
1747 ways, depending on its contents:
1749 - Alphanumeric characters only:
1750 Match links with this file extension.
1751 Example: (\"pdf\" . \"evince %s\")
1752 to open PDFs with evince.
1754 - Regular expression: Match links where the
1755 filename matches the regexp. If you want to
1756 use groups here, use shy groups.
1758 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1759 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1760 to open *.html and *.xhtml with firefox.
1762 - Regular expression which contains (non-shy) groups:
1763 Match links where the whole link, including \"::\", and
1764 anything after that, matches the regexp.
1765 In a custom command string, %1, %2, etc. are replaced with
1766 the parts of the link that were matched by the groups.
1767 For backwards compatibility, if a command string is given
1768 that does not use any of the group matches, this case is
1769 handled identically to the second one (i.e. match against
1771 In a custom lisp form, you can access the group matches with
1772 (match-string n link).
1774 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1775 to open [[file:document.pdf::5]] with evince at page 5.
1777 `directory' Matches a directory
1778 `remote' Matches a remote file, accessible through tramp or efs.
1779 Remote files most likely should be visited through Emacs
1780 because external applications cannot handle such paths.
1781 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1782 so all files Emacs knows how to handle. Using this with
1783 command `emacs' will open most files in Emacs. Beware that this
1784 will also open html files inside Emacs, unless you add
1785 (\"html\" . default) to the list as well.
1786 t Default for files not matched by any of the other options.
1787 `system' The system command to open files, like `open' on Windows
1788 and Mac OS X, and mailcap under GNU/Linux. This is the command
1789 that will be selected if you call `C-c C-o' with a double
1790 \\[universal-argument] \\[universal-argument] prefix.
1792 Possible values for the command are:
1793 `emacs' The file will be visited by the current Emacs process.
1794 `default' Use the default application for this file type, which is the
1795 association for t in the list, most likely in the system-specific
1797 This can be used to overrule an unwanted setting in the
1798 system-specific variable.
1799 `system' Use the system command for opening files, like \"open\".
1800 This command is specified by the entry whose car is `system'.
1801 Most likely, the system-specific version of this variable
1802 does define this command, but you can overrule/replace it
1804 string A command to be executed by a shell; %s will be replaced
1805 by the path to the file.
1806 sexp A Lisp form which will be evaluated. The file path will
1807 be available in the Lisp variable `file'.
1808 For more examples, see the system specific constants
1809 `org-file-apps-defaults-macosx'
1810 `org-file-apps-defaults-windowsnt'
1811 `org-file-apps-defaults-gnu'."
1812 :group
'org-link-follow
1814 (cons (choice :value
""
1815 (string :tag
"Extension")
1816 (const :tag
"System command to open files" system
)
1817 (const :tag
"Default for unrecognized files" t
)
1818 (const :tag
"Remote file" remote
)
1819 (const :tag
"Links to a directory" directory
)
1820 (const :tag
"Any files that have Emacs modes"
1823 (const :tag
"Visit with Emacs" emacs
)
1824 (const :tag
"Use default" default
)
1825 (const :tag
"Use the system command" system
)
1826 (string :tag
"Command")
1827 (sexp :tag
"Lisp form")))))
1831 (defgroup org-refile nil
1832 "Options concerning refiling entries in Org-mode."
1836 (defcustom org-directory
"~/org"
1837 "Directory with org files.
1838 This is just a default location to look for Org files. There is no need
1839 at all to put your files into this directory. It is only used in the
1840 following situations:
1842 1. When a remember template specifies a target file that is not an
1843 absolute path. The path will then be interpreted relative to
1845 2. When a remember note is filed away in an interactive way (when exiting the
1846 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1847 with `org-directory' as the default path."
1849 :group
'org-remember
1852 (defcustom org-default-notes-file
(convert-standard-filename "~/.notes")
1853 "Default target for storing notes.
1854 Used as a fall back file for org-remember.el and org-capture.el, for
1855 templates that do not specify a target file."
1857 :group
'org-remember
1859 (const :tag
"Default from remember-data-file" nil
)
1862 (defcustom org-goto-interface
'outline
1863 "The default interface to be used for `org-goto'.
1865 outline The interface shows an outline of the relevant file
1866 and the correct heading is found by moving through
1867 the outline or by searching with incremental search.
1868 outline-path-completion Headlines in the current buffer are offered via
1869 completion. This is the interface also used by
1870 the refile command."
1873 (const :tag
"Outline" outline
)
1874 (const :tag
"Outline-path-completion" outline-path-completion
)))
1876 (defcustom org-goto-max-level
5
1877 "Maximum target level when running `org-goto' with refile interface."
1881 (defcustom org-reverse-note-order nil
1882 "Non-nil means store new notes at the beginning of a file or entry.
1883 When nil, new notes will be filed to the end of a file or entry.
1884 This can also be a list with cons cells of regular expressions that
1885 are matched against file names, and values."
1886 :group
'org-remember
1889 (const :tag
"Reverse always" t
)
1890 (const :tag
"Reverse never" nil
)
1891 (repeat :tag
"By file name regexp"
1892 (cons regexp boolean
))))
1894 (defcustom org-log-refile nil
1895 "Information to record when a task is refiled.
1897 Possible values are:
1899 nil Don't add anything
1900 time Add a time stamp to the task
1901 note Prompt for a note and add it with template `org-log-note-headings'
1903 This option can also be set with on a per-file-basis with
1905 #+STARTUP: nologrefile
1906 #+STARTUP: logrefile
1907 #+STARTUP: lognoterefile
1909 You can have local logging settings for a subtree by setting the LOGGING
1910 property to one or more of these keywords.
1912 When bulk-refiling from the agenda, the value `note' is forbidden and
1913 will temporarily be changed to `time'."
1915 :group
'org-progress
1918 (const :tag
"No logging" nil
)
1919 (const :tag
"Record timestamp" time
)
1920 (const :tag
"Record timestamp with note." note
)))
1922 (defcustom org-refile-targets nil
1923 "Targets for refiling entries with \\[org-refile].
1924 This is a list of cons cells. Each cell contains:
1925 - a specification of the files to be considered, either a list of files,
1926 or a symbol whose function or variable value will be used to retrieve
1927 a file name or a list of file names. If you use `org-agenda-files' for
1928 that, all agenda files will be scanned for targets. Nil means consider
1929 headings in the current buffer.
1930 - A specification of how to find candidate refile targets. This may be
1932 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1933 This tag has to be present in all target headlines, inheritance will
1935 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1937 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1938 headlines that are refiling targets.
1939 - a cons cell (:level . N). Any headline of level N is considered a target.
1940 Note that, when `org-odd-levels-only' is set, level corresponds to
1941 order in hierarchy, not to the number of stars.
1942 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1943 Note that, when `org-odd-levels-only' is set, level corresponds to
1944 order in hierarchy, not to the number of stars.
1946 Each element of this list generates a set of possible targets.
1947 The union of these sets is presented (with completion) to
1948 the user by `org-refile'.
1950 You can set the variable `org-refile-target-verify-function' to a function
1951 to verify each headline found by the simple criteria above.
1953 When this variable is nil, all top-level headlines in the current buffer
1954 are used, equivalent to the value `((nil . (:level . 1))'."
1958 (choice :value org-agenda-files
1959 (const :tag
"All agenda files" org-agenda-files
)
1960 (const :tag
"Current buffer" nil
)
1961 (function) (variable) (file))
1962 (choice :tag
"Identify target headline by"
1963 (cons :tag
"Specific tag" (const :value
:tag
) (string))
1964 (cons :tag
"TODO keyword" (const :value
:todo
) (string))
1965 (cons :tag
"Regular expression" (const :value
:regexp
) (regexp))
1966 (cons :tag
"Level number" (const :value
:level
) (integer))
1967 (cons :tag
"Max Level number" (const :value
:maxlevel
) (integer))))))
1969 (defcustom org-refile-target-verify-function nil
1970 "Function to verify if the headline at point should be a refile target.
1971 The function will be called without arguments, with point at the
1972 beginning of the headline. It should return t and leave point
1973 where it is if the headline is a valid target for refiling.
1975 If the target should not be selected, the function must return nil.
1976 In addition to this, it may move point to a place from where the search
1977 should be continued. For example, the function may decide that the entire
1978 subtree of the current entry should be excluded and move point to the end
1983 (defcustom org-refile-use-cache nil
1984 "Non-nil means cache refile targets to speed up the process.
1985 The cache for a particular file will be updated automatically when
1986 the buffer has been killed, or when any of the marker used for flagging
1987 refile targets no longer points at a live buffer.
1988 If you have added new entries to a buffer that might themselves be targets,
1989 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1990 find that easier, `C-u C-u C-u C-c C-w'."
1995 (defcustom org-refile-use-outline-path nil
1996 "Non-nil means provide refile targets as paths.
1997 So a level 3 headline will be available as level1/level2/level3.
1999 When the value is `file', also include the file name (without directory)
2000 into the path. In this case, you can also stop the completion after
2001 the file name, to get entries inserted as top level in the file.
2003 When `full-file-path', include the full file path."
2006 (const :tag
"Not" nil
)
2007 (const :tag
"Yes" t
)
2008 (const :tag
"Start with file name" file
)
2009 (const :tag
"Start with full file path" full-file-path
)))
2011 (defcustom org-outline-path-complete-in-steps t
2012 "Non-nil means complete the outline path in hierarchical steps.
2013 When Org-mode uses the refile interface to select an outline path
2014 \(see variable `org-refile-use-outline-path'), the completion of
2015 the path can be done is a single go, or if can be done in steps down
2016 the headline hierarchy. Going in steps is probably the best if you
2017 do not use a special completion package like `ido' or `icicles'.
2018 However, when using these packages, going in one step can be very
2019 fast, while still showing the whole path to the entry."
2023 (defcustom org-refile-allow-creating-parent-nodes nil
2024 "Non-nil means allow to create new nodes as refile targets.
2025 New nodes are then created by adding \"/new node name\" to the completion
2026 of an existing node. When the value of this variable is `confirm',
2027 new node creation must be confirmed by the user (recommended)
2028 When nil, the completion must match an existing entry.
2030 Note that, if the new heading is not seen by the criteria
2031 listed in `org-refile-targets', multiple instances of the same
2032 heading would be created by trying again to file under the new
2036 (const :tag
"Never" nil
)
2037 (const :tag
"Always" t
)
2038 (const :tag
"Prompt for confirmation" confirm
)))
2040 (defcustom org-refile-active-region-within-subtree nil
2041 "Non-nil means also refile active region within a subtree.
2043 By default `org-refile' doesn't allow refiling regions if they
2044 don't contain a set of subtrees, but it might be convenient to
2045 do so sometimes: in that case, the first line of the region is
2046 converted to a headline before refiling."
2051 (defgroup org-todo nil
2052 "Options concerning TODO items in Org-mode."
2056 (defgroup org-progress nil
2057 "Options concerning Progress logging in Org-mode."
2061 (defvar org-todo-interpretation-widgets
2062 '((:tag
"Sequence (cycling hits every state)" sequence
)
2063 (:tag
"Type (cycling directly to DONE)" type
))
2064 "The available interpretation symbols for customizing `org-todo-keywords'.
2065 Interested libraries should add to this list.")
2067 (defcustom org-todo-keywords
'((sequence "TODO" "DONE"))
2068 "List of TODO entry keyword sequences and their interpretation.
2069 \\<org-mode-map>This is a list of sequences.
2071 Each sequence starts with a symbol, either `sequence' or `type',
2072 indicating if the keywords should be interpreted as a sequence of
2073 action steps, or as different types of TODO items. The first
2074 keywords are states requiring action - these states will select a headline
2075 for inclusion into the global TODO list Org-mode produces. If one of
2076 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2077 signify that no further action is necessary. If \"|\" is not found,
2078 the last keyword is treated as the only DONE state of the sequence.
2080 The command \\[org-todo] cycles an entry through these states, and one
2081 additional state where no keyword is present. For details about this
2082 cycling, see the manual.
2084 TODO keywords and interpretation can also be set on a per-file basis with
2085 the special #+SEQ_TODO and #+TYP_TODO lines.
2087 Each keyword can optionally specify a character for fast state selection
2088 \(in combination with the variable `org-use-fast-todo-selection')
2089 and specifiers for state change logging, using the same syntax
2090 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2091 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2092 indicates to record a time stamp each time this state is selected.
2094 Each keyword may also specify if a timestamp or a note should be
2095 recorded when entering or leaving the state, by adding additional
2096 characters in the parenthesis after the keyword. This looks like this:
2097 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2098 record only the time of the state change. With X and Y being either
2099 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2100 Y when leaving the state if and only if the *target* state does not
2101 define X. You may omit any of the fast-selection key or X or /Y,
2102 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2104 For backward compatibility, this variable may also be just a list
2105 of keywords - in this case the interpretation (sequence or type) will be
2106 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2108 :group
'org-keywords
2110 (repeat :tag
"Old syntax, just keywords"
2111 (string :tag
"Keyword"))
2112 (repeat :tag
"New syntax"
2115 :tag
"Interpretation"
2116 ;;Quick and dirty way to see
2117 ;;`org-todo-interpretations'. This takes the
2118 ;;place of item arguments
2126 org-todo-interpretation-widgets
))
2129 (string :tag
"Keyword"))))))
2131 (defvar org-todo-keywords-1 nil
2132 "All TODO and DONE keywords active in a buffer.")
2133 (make-variable-buffer-local 'org-todo-keywords-1
)
2134 (defvar org-todo-keywords-for-agenda nil
)
2135 (defvar org-done-keywords-for-agenda nil
)
2136 (defvar org-drawers-for-agenda nil
)
2137 (defvar org-todo-keyword-alist-for-agenda nil
)
2138 (defvar org-tag-alist-for-agenda nil
)
2139 (defvar org-agenda-contributing-files nil
)
2140 (defvar org-not-done-keywords nil
)
2141 (make-variable-buffer-local 'org-not-done-keywords
)
2142 (defvar org-done-keywords nil
)
2143 (make-variable-buffer-local 'org-done-keywords
)
2144 (defvar org-todo-heads nil
)
2145 (make-variable-buffer-local 'org-todo-heads
)
2146 (defvar org-todo-sets nil
)
2147 (make-variable-buffer-local 'org-todo-sets
)
2148 (defvar org-todo-log-states nil
)
2149 (make-variable-buffer-local 'org-todo-log-states
)
2150 (defvar org-todo-kwd-alist nil
)
2151 (make-variable-buffer-local 'org-todo-kwd-alist
)
2152 (defvar org-todo-key-alist nil
)
2153 (make-variable-buffer-local 'org-todo-key-alist
)
2154 (defvar org-todo-key-trigger nil
)
2155 (make-variable-buffer-local 'org-todo-key-trigger
)
2157 (defcustom org-todo-interpretation
'sequence
2158 "Controls how TODO keywords are interpreted.
2159 This variable is in principle obsolete and is only used for
2160 backward compatibility, if the interpretation of todo keywords is
2161 not given already in `org-todo-keywords'. See that variable for
2164 :group
'org-keywords
2165 :type
'(choice (const sequence
)
2168 (defcustom org-use-fast-todo-selection t
2169 "Non-nil means use the fast todo selection scheme with C-c C-t.
2170 This variable describes if and under what circumstances the cycling
2171 mechanism for TODO keywords will be replaced by a single-key, direct
2174 When nil, fast selection is never used.
2176 When the symbol `prefix', it will be used when `org-todo' is called with
2177 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2178 in an agenda buffer.
2180 When t, fast selection is used by default. In this case, the prefix
2181 argument forces cycling instead.
2183 In all cases, the special interface is only used if access keys have actually
2184 been assigned by the user, i.e. if keywords in the configuration are followed
2185 by a letter in parenthesis, like TODO(t)."
2188 (const :tag
"Never" nil
)
2189 (const :tag
"By default" t
)
2190 (const :tag
"Only with C-u C-c C-t" prefix
)))
2192 (defcustom org-provide-todo-statistics t
2193 "Non-nil means update todo statistics after insert and toggle.
2194 ALL-HEADLINES means update todo statistics by including headlines
2195 with no TODO keyword as well, counting them as not done.
2196 A list of TODO keywords means the same, but skip keywords that are
2199 When this is set, todo statistics is updated in the parent of the
2200 current entry each time a todo state is changed."
2203 (const :tag
"Yes, only for TODO entries" t
)
2204 (const :tag
"Yes, including all entries" 'all-headlines
)
2205 (repeat :tag
"Yes, for TODOs in this list"
2206 (string :tag
"TODO keyword"))
2207 (other :tag
"No TODO statistics" nil
)))
2209 (defcustom org-hierarchical-todo-statistics t
2210 "Non-nil means TODO statistics covers just direct children.
2211 When nil, all entries in the subtree are considered.
2212 This has only an effect if `org-provide-todo-statistics' is set.
2213 To set this to nil for only a single subtree, use a COOKIE_DATA
2214 property and include the word \"recursive\" into the value."
2218 (defcustom org-after-todo-state-change-hook nil
2219 "Hook which is run after the state of a TODO item was changed.
2220 The new state (a string with a TODO keyword, or nil) is available in the
2221 Lisp variable `org-state'."
2225 (defvar org-blocker-hook nil
2226 "Hook for functions that are allowed to block a state change.
2228 Each function gets as its single argument a property list, see
2229 `org-trigger-hook' for more information about this list.
2231 If any of the functions in this hook returns nil, the state change
2234 (defvar org-trigger-hook nil
2235 "Hook for functions that are triggered by a state change.
2237 Each function gets as its single argument a property list with at least
2238 the following elements:
2240 (:type type-of-change :position pos-at-entry-start
2241 :from old-state :to new-state)
2243 Depending on the type, more properties may be present.
2245 This mechanism is currently implemented for:
2249 :type todo-state-change
2250 :from previous state (keyword as a string), or nil, or a symbol
2251 'todo' or 'done', to indicate the general type of state.
2252 :to new state, like in :from")
2254 (defcustom org-enforce-todo-dependencies nil
2255 "Non-nil means undone TODO entries will block switching the parent to DONE.
2256 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2257 be blocked if any prior sibling is not yet done.
2258 Finally, if the parent is blocked because of ordered siblings of its own,
2259 the child will also be blocked."
2260 :set
(lambda (var val
)
2263 (add-hook 'org-blocker-hook
2264 'org-block-todo-from-children-or-siblings-or-parent
)
2265 (remove-hook 'org-blocker-hook
2266 'org-block-todo-from-children-or-siblings-or-parent
)))
2270 (defcustom org-enforce-todo-checkbox-dependencies nil
2271 "Non-nil means unchecked boxes will block switching the parent to DONE.
2272 When this is nil, checkboxes have no influence on switching TODO states.
2273 When non-nil, you first need to check off all check boxes before the TODO
2274 entry can be switched to DONE.
2275 This variable needs to be set before org.el is loaded, and you need to
2276 restart Emacs after a change to make the change effective. The only way
2277 to change is while Emacs is running is through the customize interface."
2278 :set
(lambda (var val
)
2281 (add-hook 'org-blocker-hook
2282 'org-block-todo-from-checkboxes
)
2283 (remove-hook 'org-blocker-hook
2284 'org-block-todo-from-checkboxes
)))
2288 (defcustom org-treat-insert-todo-heading-as-state-change nil
2289 "Non-nil means inserting a TODO heading is treated as state change.
2290 So when the command \\[org-insert-todo-heading] is used, state change
2291 logging will apply if appropriate. When nil, the new TODO item will
2292 be inserted directly, and no logging will take place."
2296 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2297 "Non-nil means switching TODO states with S-cursor counts as state change.
2298 This is the default behavior. However, setting this to nil allows a
2299 convenient way to select a TODO state and bypass any logging associated
2304 (defcustom org-todo-state-tags-triggers nil
2305 "Tag changes that should be triggered by TODO state changes.
2306 This is a list. Each entry is
2308 (state-change (tag . flag) .......)
2310 State-change can be a string with a state, and empty string to indicate the
2311 state that has no TODO keyword, or it can be one of the symbols `todo'
2312 or `done', meaning any not-done or done state, respectively."
2316 (cons (choice :tag
"When changing to"
2317 (const :tag
"Not-done state" todo
)
2318 (const :tag
"Done state" done
)
2319 (string :tag
"State"))
2321 (cons :tag
"Tag action"
2323 (choice (const :tag
"Add" t
) (const :tag
"Remove" nil
)))))))
2325 (defcustom org-log-done nil
2326 "Information to record when a task moves to the DONE state.
2328 Possible values are:
2330 nil Don't add anything, just change the keyword
2331 time Add a time stamp to the task
2332 note Prompt for a note and add it with template `org-log-note-headings'
2334 This option can also be set with on a per-file-basis with
2336 #+STARTUP: nologdone
2338 #+STARTUP: lognotedone
2340 You can have local logging settings for a subtree by setting the LOGGING
2341 property to one or more of these keywords."
2343 :group
'org-progress
2345 (const :tag
"No logging" nil
)
2346 (const :tag
"Record CLOSED timestamp" time
)
2347 (const :tag
"Record CLOSED timestamp with note." note
)))
2349 ;; Normalize old uses of org-log-done.
2351 ((eq org-log-done t
) (setq org-log-done
'time
))
2352 ((and (listp org-log-done
) (memq 'done org-log-done
))
2353 (setq org-log-done
'note
)))
2355 (defcustom org-log-reschedule nil
2356 "Information to record when the scheduling date of a tasks is modified.
2358 Possible values are:
2360 nil Don't add anything, just change the date
2361 time Add a time stamp to the task
2362 note Prompt for a note and add it with template `org-log-note-headings'
2364 This option can also be set with on a per-file-basis with
2366 #+STARTUP: nologreschedule
2367 #+STARTUP: logreschedule
2368 #+STARTUP: lognotereschedule"
2370 :group
'org-progress
2372 (const :tag
"No logging" nil
)
2373 (const :tag
"Record timestamp" time
)
2374 (const :tag
"Record timestamp with note." note
)))
2376 (defcustom org-log-redeadline nil
2377 "Information to record when the deadline date of a tasks is modified.
2379 Possible values are:
2381 nil Don't add anything, just change the date
2382 time Add a time stamp to the task
2383 note Prompt for a note and add it with template `org-log-note-headings'
2385 This option can also be set with on a per-file-basis with
2387 #+STARTUP: nologredeadline
2388 #+STARTUP: logredeadline
2389 #+STARTUP: lognoteredeadline
2391 You can have local logging settings for a subtree by setting the LOGGING
2392 property to one or more of these keywords."
2394 :group
'org-progress
2396 (const :tag
"No logging" nil
)
2397 (const :tag
"Record timestamp" time
)
2398 (const :tag
"Record timestamp with note." note
)))
2400 (defcustom org-log-note-clock-out nil
2401 "Non-nil means record a note when clocking out of an item.
2402 This can also be configured on a per-file basis by adding one of
2403 the following lines anywhere in the buffer:
2405 #+STARTUP: lognoteclock-out
2406 #+STARTUP: nolognoteclock-out"
2408 :group
'org-progress
2411 (defcustom org-log-done-with-time t
2412 "Non-nil means the CLOSED time stamp will contain date and time.
2413 When nil, only the date will be recorded."
2414 :group
'org-progress
2417 (defcustom org-log-note-headings
2418 '((done .
"CLOSING NOTE %t")
2419 (state .
"State %-12s from %-12S %t")
2420 (note .
"Note taken on %t")
2421 (reschedule .
"Rescheduled from %S on %t")
2422 (delschedule .
"Not scheduled, was %S on %t")
2423 (redeadline .
"New deadline from %S on %t")
2424 (deldeadline .
"Removed deadline, was %S on %t")
2425 (refile .
"Refiled on %t")
2427 "Headings for notes added to entries.
2428 The value is an alist, with the car being a symbol indicating the note
2429 context, and the cdr is the heading to be used. The heading may also be the
2431 %t in the heading will be replaced by a time stamp.
2432 %T will be an active time stamp instead the default inactive one
2433 %d will be replaced by a short-format time stamp.
2434 %D will be replaced by an active short-format time stamp.
2435 %s will be replaced by the new TODO state, in double quotes.
2436 %S will be replaced by the old TODO state, in double quotes.
2437 %u will be replaced by the user name.
2438 %U will be replaced by the full user name.
2440 In fact, it is not a good idea to change the `state' entry, because
2441 agenda log mode depends on the format of these entries."
2443 :group
'org-progress
2444 :type
'(list :greedy t
2445 (cons (const :tag
"Heading when closing an item" done
) string
)
2447 "Heading when changing todo state (todo sequence only)"
2449 (cons (const :tag
"Heading when just taking a note" note
) string
)
2450 (cons (const :tag
"Heading when clocking out" clock-out
) string
)
2451 (cons (const :tag
"Heading when an item is no longer scheduled" delschedule
) string
)
2452 (cons (const :tag
"Heading when rescheduling" reschedule
) string
)
2453 (cons (const :tag
"Heading when changing deadline" redeadline
) string
)
2454 (cons (const :tag
"Heading when deleting a deadline" deldeadline
) string
)
2455 (cons (const :tag
"Heading when refiling" refile
) string
)))
2457 (unless (assq 'note org-log-note-headings
)
2458 (push '(note .
"%t") org-log-note-headings
))
2460 (defcustom org-log-into-drawer nil
2461 "Non-nil means insert state change notes and time stamps into a drawer.
2462 When nil, state changes notes will be inserted after the headline and
2463 any scheduling and clock lines, but not inside a drawer.
2465 The value of this variable should be the name of the drawer to use.
2466 LOGBOOK is proposed as the default drawer for this purpose, you can
2467 also set this to a string to define the drawer of your choice.
2469 A value of t is also allowed, representing \"LOGBOOK\".
2471 If this variable is set, `org-log-state-notes-insert-after-drawers'
2474 You can set the property LOG_INTO_DRAWER to overrule this setting for
2477 :group
'org-progress
2479 (const :tag
"Not into a drawer" nil
)
2480 (const :tag
"LOGBOOK" t
)
2481 (string :tag
"Other")))
2483 (if (fboundp 'defvaralias
)
2484 (defvaralias 'org-log-state-notes-into-drawer
'org-log-into-drawer
))
2486 (defun org-log-into-drawer ()
2487 "Return the value of `org-log-into-drawer', but let properties overrule.
2488 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2489 used instead of the default value."
2490 (let ((p (org-entry-get nil
"LOG_INTO_DRAWER" 'inherit
)))
2492 ((or (not p
) (equal p
"nil")) org-log-into-drawer
)
2493 ((equal p
"t") "LOGBOOK")
2496 (defcustom org-log-state-notes-insert-after-drawers nil
2497 "Non-nil means insert state change notes after any drawers in entry.
2498 Only the drawers that *immediately* follow the headline and the
2499 deadline/scheduled line are skipped.
2500 When nil, insert notes right after the heading and perhaps the line
2501 with deadline/scheduling if present.
2503 This variable will have no effect if `org-log-into-drawer' is
2506 :group
'org-progress
2509 (defcustom org-log-states-order-reversed t
2510 "Non-nil means the latest state note will be directly after heading.
2511 When nil, the state change notes will be ordered according to time."
2513 :group
'org-progress
2516 (defcustom org-todo-repeat-to-state nil
2517 "The TODO state to which a repeater should return the repeating task.
2518 By default this is the first task in a TODO sequence, or the previous state
2519 in a TODO_TYP set. But you can specify another task here.
2520 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2523 :type
'(choice (const :tag
"Head of sequence" nil
)
2524 (string :tag
"Specific state")))
2526 (defcustom org-log-repeat
'time
2527 "Non-nil means record moving through the DONE state when triggering repeat.
2528 An auto-repeating task is immediately switched back to TODO when
2529 marked DONE. If you are not logging state changes (by adding \"@\"
2530 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2531 record a closing note, there will be no record of the task moving
2532 through DONE. This variable forces taking a note anyway.
2534 nil Don't force a record
2535 time Record a time stamp
2538 This option can also be set with on a per-file-basis with
2540 #+STARTUP: logrepeat
2541 #+STARTUP: lognoterepeat
2542 #+STARTUP: nologrepeat
2544 You can have local logging settings for a subtree by setting the LOGGING
2545 property to one or more of these keywords."
2547 :group
'org-progress
2549 (const :tag
"Don't force a record" nil
)
2550 (const :tag
"Force recording the DONE state" time
)
2551 (const :tag
"Force recording a note with the DONE state" note
)))
2554 (defgroup org-priorities nil
2555 "Priorities in Org-mode."
2556 :tag
"Org Priorities"
2559 (defcustom org-enable-priority-commands t
2560 "Non-nil means priority commands are active.
2561 When nil, these commands will be disabled, so that you never accidentally
2563 :group
'org-priorities
2566 (defcustom org-highest-priority ?A
2567 "The highest priority of TODO items. A character like ?A, ?B etc.
2568 Must have a smaller ASCII number than `org-lowest-priority'."
2569 :group
'org-priorities
2572 (defcustom org-lowest-priority ?C
2573 "The lowest priority of TODO items. A character like ?A, ?B etc.
2574 Must have a larger ASCII number than `org-highest-priority'."
2575 :group
'org-priorities
2578 (defcustom org-default-priority ?B
2579 "The default priority of TODO items.
2580 This is the priority an item gets if no explicit priority is given.
2581 When starting to cycle on an empty priority the first step in the cycle
2582 depends on `org-priority-start-cycle-with-default'. The resulting first
2583 step priority must not exceed the range from `org-highest-priority' to
2584 `org-lowest-priority' which means that `org-default-priority' has to be
2585 in this range exclusive or inclusive the range boundaries. Else the
2586 first step refuses to set the default and the second will fall back
2587 to (depending on the command used) the highest or lowest priority."
2588 :group
'org-priorities
2591 (defcustom org-priority-start-cycle-with-default t
2592 "Non-nil means start with default priority when starting to cycle.
2593 When this is nil, the first step in the cycle will be (depending on the
2594 command used) one higher or lower than the default priority.
2595 See also `org-default-priority'."
2596 :group
'org-priorities
2599 (defcustom org-get-priority-function nil
2600 "Function to extract the priority from a string.
2601 The string is normally the headline. If this is nil Org computes the
2602 priority from the priority cookie like [#A] in the headline. It returns
2603 an integer, increasing by 1000 for each priority level.
2604 The user can set a different function here, which should take a string
2605 as an argument and return the numeric priority."
2606 :group
'org-priorities
2610 (defgroup org-time nil
2611 "Options concerning time stamps and deadlines in Org-mode."
2615 (defcustom org-insert-labeled-timestamps-at-point nil
2616 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2617 When nil, these labeled time stamps are forces into the second line of an
2618 entry, just after the headline. When scheduling from the global TODO list,
2619 the time stamp will always be forced into the second line."
2623 (defconst org-time-stamp-formats
'("<%Y-%m-%d %a>" .
"<%Y-%m-%d %a %H:%M>")
2624 "Formats for `format-time-string' which are used for time stamps.
2625 It is not recommended to change this constant.")
2627 (defcustom org-time-stamp-rounding-minutes
'(0 5)
2628 "Number of minutes to round time stamps to.
2629 These are two values, the first applies when first creating a time stamp.
2630 The second applies when changing it with the commands `S-up' and `S-down'.
2631 When changing the time stamp, this means that it will change in steps
2632 of N minutes, as given by the second value.
2634 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2635 numbers should be factors of 60, so for example 5, 10, 15.
2637 When this is larger than 1, you can still force an exact time stamp by using
2638 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2639 and by using a prefix arg to `S-up/down' to specify the exact number
2640 of minutes to shift."
2642 :get
#'(lambda (var) ; Make sure both elements are there
2643 (if (integerp (default-value var
))
2644 (list (default-value var
) 5)
2645 (default-value var
)))
2647 (integer :tag
"when inserting times")
2648 (integer :tag
"when modifying times")))
2650 ;; Normalize old customizations of this variable.
2651 (when (integerp org-time-stamp-rounding-minutes
)
2652 (setq org-time-stamp-rounding-minutes
2653 (list org-time-stamp-rounding-minutes
2654 org-time-stamp-rounding-minutes
)))
2656 (defcustom org-display-custom-times nil
2657 "Non-nil means overlay custom formats over all time stamps.
2658 The formats are defined through the variable `org-time-stamp-custom-formats'.
2659 To turn this on on a per-file basis, insert anywhere in the file:
2660 #+STARTUP: customtime"
2664 (make-variable-buffer-local 'org-display-custom-times
)
2666 (defcustom org-time-stamp-custom-formats
2667 '("<%m/%d/%y %a>" .
"<%m/%d/%y %a %H:%M>") ; american
2668 "Custom formats for time stamps. See `format-time-string' for the syntax.
2669 These are overlaid over the default ISO format if the variable
2670 `org-display-custom-times' is set. Time like %H:%M should be at the
2671 end of the second format. The custom formats are also honored by export
2672 commands, if custom time display is turned on at the time of export."
2676 (defun org-time-stamp-format (&optional long inactive
)
2677 "Get the right format for a time string."
2678 (let ((f (if long
(cdr org-time-stamp-formats
)
2679 (car org-time-stamp-formats
))))
2681 (concat "[" (substring f
1 -
1) "]")
2684 (defcustom org-time-clocksum-format
"%d:%02d"
2685 "The format string used when creating CLOCKSUM lines.
2686 This is also used when org-mode generates a time duration."
2690 (defcustom org-time-clocksum-use-fractional nil
2691 "If non-nil, \\[org-clock-display] uses fractional times.
2692 org-mode generates a time duration."
2696 (defcustom org-time-clocksum-fractional-format
"%.2f"
2697 "The format string used when creating CLOCKSUM lines, or when
2698 org-mode generates a time duration."
2702 (defcustom org-deadline-warning-days
14
2703 "No. of days before expiration during which a deadline becomes active.
2704 This variable governs the display in sparse trees and in the agenda.
2705 When 0 or negative, it means use this number (the absolute value of it)
2706 even if a deadline has a different individual lead time specified.
2708 Custom commands can set this variable in the options section."
2710 :group
'org-agenda-daily
/weekly
2713 (defcustom org-read-date-prefer-future t
2714 "Non-nil means assume future for incomplete date input from user.
2715 This affects the following situations:
2716 1. The user gives a month but not a year.
2717 For example, if it is April and you enter \"feb 2\", this will be read
2718 as Feb 2, *next* year. \"May 5\", however, will be this year.
2719 2. The user gives a day, but no month.
2720 For example, if today is the 15th, and you enter \"3\", Org-mode will
2721 read this as the third of *next* month. However, if you enter \"17\",
2722 it will be considered as *this* month.
2724 If you set this variable to the symbol `time', then also the following
2727 3. If the user gives a time, but no day. If the time is before now,
2728 to will be interpreted as tomorrow.
2730 Currently none of this works for ISO week specifications.
2732 When this option is nil, the current day, month and year will always be
2735 See also `org-agenda-jump-prefer-future'."
2738 (const :tag
"Never" nil
)
2739 (const :tag
"Check month and day" t
)
2740 (const :tag
"Check month, day, and time" time
)))
2742 (defcustom org-agenda-jump-prefer-future
'org-read-date-prefer-future
2743 "Should the agenda jump command prefer the future for incomplete dates?
2744 The default is to do the same as configured in `org-read-date-prefer-future'.
2745 But you can also set a deviating value here.
2746 This may t or nil, or the symbol `org-read-date-prefer-future'."
2751 (const :tag
"Use org-read-date-prefer-future"
2752 org-read-date-prefer-future
)
2753 (const :tag
"Never" nil
)
2754 (const :tag
"Always" t
)))
2756 (defcustom org-read-date-force-compatible-dates t
2757 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2759 Depending on the system Emacs is running on, certain dates cannot
2760 be represented with the type used internally to represent time.
2761 Dates between 1970-1-1 and 2038-1-1 can always be represented
2762 correctly. Some systems allow for earlier dates, some for later,
2763 some for both. One way to find out it to insert any date into an
2764 Org buffer, putting the cursor on the year and hitting S-up and
2765 S-down to test the range.
2767 When this variable is set to t, the date/time prompt will not let
2768 you specify dates outside the 1970-2037 range, so it is certain that
2769 these dates will work in whatever version of Emacs you are
2770 running, and also that you can move a file from one Emacs implementation
2771 to another. WHenever Org is forcing the year for you, it will display
2774 When this variable is nil, Org will check if the date is
2775 representable in the specific Emacs implementation you are using.
2776 If not, it will force a year, usually the current year, and beep
2777 to remind you. Currently this setting is not recommended because
2778 the likelihood that you will open your Org files in an Emacs that
2779 has limited date range is not negligible.
2781 A workaround for this problem is to use diary sexp dates for time
2782 stamps outside of this range."
2787 (defcustom org-read-date-display-live t
2788 "Non-nil means display current interpretation of date prompt live.
2789 This display will be in an overlay, in the minibuffer."
2793 (defcustom org-read-date-popup-calendar t
2794 "Non-nil means pop up a calendar when prompting for a date.
2795 In the calendar, the date can be selected with mouse-1. However, the
2796 minibuffer will also be active, and you can simply enter the date as well.
2797 When nil, only the minibuffer will be available."
2800 (if (fboundp 'defvaralias
)
2801 (defvaralias 'org-popup-calendar-for-date-prompt
2802 'org-read-date-popup-calendar
))
2804 (defcustom org-read-date-minibuffer-setup-hook nil
2805 "Hook to be used to set up keys for the date/time interface.
2806 Add key definitions to `minibuffer-local-map', which will be a temporary
2811 (defcustom org-extend-today-until
0
2812 "The hour when your day really ends. Must be an integer.
2813 This has influence for the following applications:
2814 - When switching the agenda to \"today\". It it is still earlier than
2815 the time given here, the day recognized as TODAY is actually yesterday.
2816 - When a date is read from the user and it is still before the time given
2817 here, the current date and time will be assumed to be yesterday, 23:59.
2818 Also, timestamps inserted in remember templates follow this rule.
2820 IMPORTANT: This is a feature whose implementation is and likely will
2821 remain incomplete. Really, it is only here because past midnight seems to
2822 be the favorite working time of John Wiegley :-)"
2826 (defcustom org-use-effective-time nil
2827 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2828 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2829 \"effective time\" of any timestamps between midnight and 8am will be
2830 23:59 of the previous day."
2835 (defcustom org-edit-timestamp-down-means-later nil
2836 "Non-nil means S-down will increase the time in a time stamp.
2837 When nil, S-up will increase."
2841 (defcustom org-calendar-follow-timestamp-change t
2842 "Non-nil means make the calendar window follow timestamp changes.
2843 When a timestamp is modified and the calendar window is visible, it will be
2844 moved to the new date."
2848 (defgroup org-tags nil
2849 "Options concerning tags in Org-mode."
2853 (defcustom org-tag-alist nil
2854 "List of tags allowed in Org-mode files.
2855 When this list is nil, Org-mode will base TAG input on what is already in the
2857 The value of this variable is an alist, the car of each entry must be a
2858 keyword as a string, the cdr may be a character that is used to select
2859 that tag through the fast-tag-selection interface.
2860 See the manual for details."
2864 (cons (string :tag
"Tag name")
2865 (character :tag
"Access char"))
2866 (list :tag
"Start radio group"
2868 (option (string :tag
"Group description")))
2869 (list :tag
"End radio group"
2871 (option (string :tag
"Group description")))
2872 (const :tag
"New line" (:newline
)))))
2874 (defcustom org-tag-persistent-alist nil
2875 "List of tags that will always appear in all Org-mode files.
2876 This is in addition to any in buffer settings or customizations
2878 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2879 The value of this variable is an alist, the car of each entry must be a
2880 keyword as a string, the cdr may be a character that is used to select
2881 that tag through the fast-tag-selection interface.
2882 See the manual for details.
2883 To disable these tags on a per-file basis, insert anywhere in the file:
2888 (cons (string :tag
"Tag name")
2889 (character :tag
"Access char"))
2890 (const :tag
"Start radio group" (:startgroup
))
2891 (const :tag
"End radio group" (:endgroup
))
2892 (const :tag
"New line" (:newline
)))))
2894 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2895 "If non-nil, always offer completion for all tags of all agenda files.
2896 Instead of customizing this variable directly, you might want to
2897 set it locally for capture buffers, because there no list of
2898 tags in that file can be created dynamically (there are none).
2900 (add-hook 'org-capture-mode-hook
2902 (set (make-local-variable
2903 'org-complete-tags-always-offer-all-agenda-tags)
2909 (defvar org-file-tags nil
2910 "List of tags that can be inherited by all entries in the file.
2911 The tags will be inherited if the variable `org-use-tag-inheritance'
2912 says they should be.
2913 This variable is populated from #+FILETAGS lines.")
2915 (defcustom org-use-fast-tag-selection
'auto
2916 "Non-nil means use fast tag selection scheme.
2917 This is a special interface to select and deselect tags with single keys.
2918 When nil, fast selection is never used.
2919 When the symbol `auto', fast selection is used if and only if selection
2920 characters for tags have been configured, either through the variable
2921 `org-tag-alist' or through a #+TAGS line in the buffer.
2922 When t, fast selection is always used and selection keys are assigned
2923 automatically if necessary."
2926 (const :tag
"Always" t
)
2927 (const :tag
"Never" nil
)
2928 (const :tag
"When selection characters are configured" 'auto
)))
2930 (defcustom org-fast-tag-selection-single-key nil
2931 "Non-nil means fast tag selection exits after first change.
2932 When nil, you have to press RET to exit it.
2933 During fast tag selection, you can toggle this flag with `C-c'.
2934 This variable can also have the value `expert'. In this case, the window
2935 displaying the tags menu is not even shown, until you press C-c again."
2938 (const :tag
"No" nil
)
2939 (const :tag
"Yes" t
)
2940 (const :tag
"Expert" expert
)))
2942 (defvar org-fast-tag-selection-include-todo nil
2943 "Non-nil means fast tags selection interface will also offer TODO states.
2944 This is an undocumented feature, you should not rely on it.")
2946 (defcustom org-tags-column
(if (featurep 'xemacs
) -
76 -
77)
2947 "The column to which tags should be indented in a headline.
2948 If this number is positive, it specifies the column. If it is negative,
2949 it means that the tags should be flushright to that column. For example,
2950 -80 works well for a normal 80 character screen.
2951 When 0, place tags directly after headline text, with only one space in
2956 (defcustom org-auto-align-tags t
2957 "Non-nil keeps tags aligned when modifying headlines.
2958 Some operations (i.e. demoting) change the length of a headline and
2959 therefore shift the tags around. With this option turned on, after
2960 each such operation the tags are again aligned to `org-tags-column'."
2964 (defcustom org-use-tag-inheritance t
2965 "Non-nil means tags in levels apply also for sublevels.
2966 When nil, only the tags directly given in a specific line apply there.
2967 This may also be a list of tags that should be inherited, or a regexp that
2968 matches tags that should be inherited. Additional control is possible
2969 with the variable `org-tags-exclude-from-inheritance' which gives an
2970 explicit list of tags to be excluded from inheritance., even if the value of
2971 `org-use-tag-inheritance' would select it for inheritance.
2973 If this option is t, a match early-on in a tree can lead to a large
2974 number of matches in the subtree when constructing the agenda or creating
2975 a sparse tree. If you only want to see the first match in a tree during
2976 a search, check out the variable `org-tags-match-list-sublevels'."
2979 (const :tag
"Not" nil
)
2980 (const :tag
"Always" t
)
2981 (repeat :tag
"Specific tags" (string :tag
"Tag"))
2982 (regexp :tag
"Tags matched by regexp")))
2984 (defcustom org-tags-exclude-from-inheritance nil
2985 "List of tags that should never be inherited.
2986 This is a way to exclude a few tags from inheritance. For way to do
2987 the opposite, to actively allow inheritance for selected tags,
2988 see the variable `org-use-tag-inheritance'."
2990 :type
'(repeat (string :tag
"Tag")))
2992 (defun org-tag-inherit-p (tag)
2993 "Check if TAG is one that should be inherited."
2995 ((member tag org-tags-exclude-from-inheritance
) nil
)
2996 ((eq org-use-tag-inheritance t
) t
)
2997 ((not org-use-tag-inheritance
) nil
)
2998 ((stringp org-use-tag-inheritance
)
2999 (string-match org-use-tag-inheritance tag
))
3000 ((listp org-use-tag-inheritance
)
3001 (member tag org-use-tag-inheritance
))
3002 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3004 (defcustom org-tags-match-list-sublevels t
3005 "Non-nil means list also sublevels of headlines matching a search.
3006 This variable applies to tags/property searches, and also to stuck
3007 projects because this search is based on a tags match as well.
3009 When set to the symbol `indented', sublevels are indented with
3012 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3013 the sublevels of a headline matching a tag search often also match
3014 the same search. Listing all of them can create very long lists.
3015 Setting this variable to nil causes subtrees of a match to be skipped.
3017 This variable is semi-obsolete and probably should always be true. It
3018 is better to limit inheritance to certain tags using the variables
3019 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3022 (const :tag
"No, don't list them" nil
)
3023 (const :tag
"Yes, do list them" t
)
3024 (const :tag
"List them, indented with leading dots" indented
)))
3026 (defcustom org-tags-sort-function nil
3027 "When set, tags are sorted using this function as a comparator."
3030 (const :tag
"No sorting" nil
)
3031 (const :tag
"Alphabetical" string
<)
3032 (const :tag
"Reverse alphabetical" string
>)
3033 (function :tag
"Custom function" nil
)))
3035 (defvar org-tags-history nil
3036 "History of minibuffer reads for tags.")
3037 (defvar org-last-tags-completion-table nil
3038 "The last used completion table for tags.")
3039 (defvar org-after-tags-change-hook nil
3040 "Hook that is run after the tags in a line have changed.")
3042 (defgroup org-properties nil
3043 "Options concerning properties in Org-mode."
3044 :tag
"Org Properties"
3047 (defcustom org-property-format
"%-10s %s"
3048 "How property key/value pairs should be formatted by `indent-line'.
3049 When `indent-line' hits a property definition, it will format the line
3050 according to this format, mainly to make sure that the values are
3051 lined-up with respect to each other."
3052 :group
'org-properties
3055 (defcustom org-properties-postprocess-alist nil
3056 "Alist of properties and functions to adjust inserted values.
3057 Elements of this alist must be of the form
3059 ([string] [function])
3061 where [string] must be a property name and [function] must be a
3062 lambda expression: this lambda expression must take one argument,
3063 the value to adjust, and return the new value as a string.
3065 For example, this element will allow the property \"Remaining\"
3066 to be updated wrt the relation between the \"Effort\" property
3067 and the clock summary:
3069 ((\"Remaining\" (lambda(value)
3070 (let ((clocksum (org-clock-sum-current-item))
3071 (effort (org-duration-string-to-minutes
3072 (org-entry-get (point) \"Effort\"))))
3073 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3074 :group
'org-properties
3076 :type
'(alist :key-type
(string :tag
"Property")
3077 :value-type
(function :tag
"Function")))
3079 (defcustom org-use-property-inheritance nil
3080 "Non-nil means properties apply also for sublevels.
3082 This setting is chiefly used during property searches. Turning it on can
3083 cause significant overhead when doing a search, which is why it is not
3086 When nil, only the properties directly given in the current entry count.
3087 When t, every property is inherited. The value may also be a list of
3088 properties that should have inheritance, or a regular expression matching
3089 properties that should be inherited.
3091 However, note that some special properties use inheritance under special
3092 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3093 and the properties ending in \"_ALL\" when they are used as descriptor
3094 for valid values of a property.
3096 Note for programmers:
3097 When querying an entry with `org-entry-get', you can control if inheritance
3098 should be used. By default, `org-entry-get' looks only at the local
3099 properties. You can request inheritance by setting the inherit argument
3100 to t (to force inheritance) or to `selective' (to respect the setting
3102 :group
'org-properties
3104 (const :tag
"Not" nil
)
3105 (const :tag
"Always" t
)
3106 (repeat :tag
"Specific properties" (string :tag
"Property"))
3107 (regexp :tag
"Properties matched by regexp")))
3109 (defun org-property-inherit-p (property)
3110 "Check if PROPERTY is one that should be inherited."
3112 ((eq org-use-property-inheritance t
) t
)
3113 ((not org-use-property-inheritance
) nil
)
3114 ((stringp org-use-property-inheritance
)
3115 (string-match org-use-property-inheritance property
))
3116 ((listp org-use-property-inheritance
)
3117 (member property org-use-property-inheritance
))
3118 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3120 (defcustom org-columns-default-format
"%25ITEM %TODO %3PRIORITY %TAGS"
3121 "The default column format, if no other format has been defined.
3122 This variable can be set on the per-file basis by inserting a line
3124 #+COLUMNS: %25ITEM ....."
3125 :group
'org-properties
3128 (defcustom org-columns-ellipses
".."
3129 "The ellipses to be used when a field in column view is truncated.
3130 When this is the empty string, as many characters as possible are shown,
3131 but then there will be no visual indication that the field has been truncated.
3132 When this is a string of length N, the last N characters of a truncated
3133 field are replaced by this string. If the column is narrower than the
3134 ellipses string, only part of the ellipses string will be shown."
3135 :group
'org-properties
3138 (defcustom org-columns-modify-value-for-display-function nil
3139 "Function that modifies values for display in column view.
3140 For example, it can be used to cut out a certain part from a time stamp.
3141 The function must take 2 arguments:
3143 column-title The title of the column (*not* the property name)
3144 value The value that should be modified.
3146 The function should return the value that should be displayed,
3147 or nil if the normal value should be used."
3148 :group
'org-properties
3151 (defcustom org-effort-property
"Effort"
3152 "The property that is being used to keep track of effort estimates.
3153 Effort estimates given in this property need to have the format H:MM."
3154 :group
'org-properties
3155 :group
'org-progress
3156 :type
'(string :tag
"Property"))
3158 (defconst org-global-properties-fixed
3159 '(("VISIBILITY_ALL" .
"folded children content all")
3160 ("CLOCK_MODELINE_TOTAL_ALL" .
"current today repeat all auto"))
3161 "List of property/value pairs that can be inherited by any entry.
3163 These are fixed values, for the preset properties. The user variable
3164 that can be used to add to this list is `org-global-properties'.
3166 The entries in this list are cons cells where the car is a property
3167 name and cdr is a string with the value. If the value represents
3168 multiple items like an \"_ALL\" property, separate the items by
3171 (defcustom org-global-properties nil
3172 "List of property/value pairs that can be inherited by any entry.
3174 This list will be combined with the constant `org-global-properties-fixed'.
3176 The entries in this list are cons cells where the car is a property
3177 name and cdr is a string with the value.
3179 You can set buffer-local values for the same purpose in the variable
3180 `org-file-properties' this by adding lines like
3182 #+PROPERTY: NAME VALUE"
3183 :group
'org-properties
3185 (cons (string :tag
"Property")
3186 (string :tag
"Value"))))
3188 (defvar org-file-properties nil
3189 "List of property/value pairs that can be inherited by any entry.
3190 Valid for the current buffer.
3191 This variable is populated from #+PROPERTY lines.")
3192 (make-variable-buffer-local 'org-file-properties
)
3194 (defgroup org-agenda nil
3195 "Options concerning agenda views in Org-mode."
3199 (defvar org-category nil
3200 "Variable used by org files to set a category for agenda display.
3201 Such files should use a file variable to set it, for example
3203 # -*- mode: org; org-category: \"ELisp\"
3205 or contain a special line
3209 If the file does not specify a category, then file's base name
3211 (make-variable-buffer-local 'org-category
)
3212 (put 'org-category
'safe-local-variable
#'(lambda (x) (or (symbolp x
) (stringp x
))))
3214 (defcustom org-agenda-files nil
3215 "The files to be used for agenda display.
3216 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3217 \\[org-remove-file]. You can also use customize to edit the list.
3219 If an entry is a directory, all files in that directory that are matched by
3220 `org-agenda-file-regexp' will be part of the file list.
3222 If the value of the variable is not a list but a single file name, then
3223 the list of agenda files is actually stored and maintained in that file, one
3224 agenda file per line. In this file paths can be given relative to
3225 `org-directory'. Tilde expansion and environment variable substitution
3229 (repeat :tag
"List of files and directories" file
)
3230 (file :tag
"Store list in a file\n" :value
"~/.agenda_files")))
3232 (defcustom org-agenda-file-regexp
"\\`[^.].*\\.org\\'"
3233 "Regular expression to match files for `org-agenda-files'.
3234 If any element in the list in that variable contains a directory instead
3235 of a normal file, all files in that directory that are matched by this
3236 regular expression will be included."
3240 (defcustom org-agenda-text-search-extra-files nil
3241 "List of extra files to be searched by text search commands.
3242 These files will be search in addition to the agenda files by the
3243 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3244 Note that these files will only be searched for text search commands,
3245 not for the other agenda views like todo lists, tag searches or the weekly
3246 agenda. This variable is intended to list notes and possibly archive files
3247 that should also be searched by these two commands.
3248 In fact, if the first element in the list is the symbol `agenda-archives',
3249 than all archive files of all agenda files will be added to the search
3252 :type
'(set :greedy t
3253 (const :tag
"Agenda Archives" agenda-archives
)
3254 (repeat :inline t
(file))))
3256 (if (fboundp 'defvaralias
)
3257 (defvaralias 'org-agenda-multi-occur-extra-files
3258 'org-agenda-text-search-extra-files
))
3260 (defcustom org-agenda-skip-unavailable-files nil
3261 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3262 A nil value means to remove them, after a query, from the list."
3266 (defcustom org-calendar-to-agenda-key
[?c
]
3267 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3268 The command `org-calendar-goto-agenda' will be bound to this key. The
3269 default is the character `c' because then `c' can be used to switch back and
3270 forth between agenda and calendar."
3274 (defcustom org-calendar-agenda-action-key
[?k
]
3275 "The key to be installed in `calendar-mode-map' for agenda-action.
3276 The command `org-agenda-action' will be bound to this key. The
3277 default is the character `k' because we use the same key in the agenda."
3281 (defcustom org-calendar-insert-diary-entry-key
[?i
]
3282 "The key to be installed in `calendar-mode-map' for adding diary entries.
3283 This option is irrelevant until `org-agenda-diary-file' has been configured
3284 to point to an Org-mode file. When that is the case, the command
3285 `org-agenda-diary-entry' will be bound to the key given here, by default
3286 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3287 if you want to continue doing this, you need to change this to a different
3292 (defcustom org-agenda-diary-file
'diary-file
3293 "File to which to add new entries with the `i' key in agenda and calendar.
3294 When this is the symbol `diary-file', the functionality in the Emacs
3295 calendar will be used to add entries to the `diary-file'. But when this
3296 points to a file, `org-agenda-diary-entry' will be used instead."
3299 (const :tag
"The standard Emacs diary file" diary-file
)
3300 (file :tag
"Special Org file diary entries")))
3302 (eval-after-load "calendar"
3304 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3305 'org-calendar-goto-agenda
)
3306 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3308 (add-hook 'calendar-mode-hook
3310 (unless (eq org-agenda-diary-file
'diary-file
)
3311 (define-key calendar-mode-map
3312 org-calendar-insert-diary-entry-key
3313 'org-agenda-diary-entry
))))))
3315 (defgroup org-latex nil
3316 "Options for embedding LaTeX code into Org-mode."
3320 (defcustom org-format-latex-options
3321 '(:foreground default
:background default
:scale
1.0
3322 :html-foreground
"Black" :html-background
"Transparent"
3323 :html-scale
1.0 :matchers
("begin" "$1" "$" "$$" "\\(" "\\["))
3324 "Options for creating images from LaTeX fragments.
3325 This is a property list with the following properties:
3326 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3327 `default' means use the foreground of the default face.
3328 :background the background color, or \"Transparent\".
3329 `default' means use the background of the default face.
3330 :scale a scaling factor for the size of the images, to get more pixels
3331 :html-foreground, :html-background, :html-scale
3332 the same numbers for HTML export.
3333 :matchers a list indicating which matchers should be used to
3334 find LaTeX fragments. Valid members of this list are:
3335 \"begin\" find environments
3336 \"$1\" find single characters surrounded by $.$
3337 \"$\" find math expressions surrounded by $...$
3338 \"$$\" find math expressions surrounded by $$....$$
3339 \"\\(\" find math expressions surrounded by \\(...\\)
3340 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3344 (defcustom org-format-latex-signal-error t
3345 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3346 When nil, just push out a message."
3351 (defcustom org-latex-to-mathml-jar-file nil
3352 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3353 Use this to specify additional executable file say a jar file.
3355 When using MathToWeb as the converter, specify the full-path to
3356 your mathtoweb.jar file."
3360 (const :tag
"None" nil
)
3361 (file :tag
"JAR file" :must-match t
)))
3363 (defcustom org-latex-to-mathml-convert-command nil
3364 "Command to convert LaTeX fragments to MathML.
3365 Replace format-specifiers in the command as noted below and use
3366 `shell-command' to convert LaTeX to MathML.
3367 %j: Executable file in fully expanded form as specified by
3368 `org-latex-to-mathml-jar-file'.
3369 %I: Input LaTeX file in fully expanded form
3370 %o: Output MathML file
3371 This command is used by `org-create-math-formula'.
3373 When using MathToWeb as the converter, set this to
3374 \"java -jar %j -unicode -force -df %o %I\"."
3378 (const :tag
"None" nil
)
3379 (string :tag
"\nShell command")))
3381 (defcustom org-latex-create-formula-image-program
'dvipng
3382 "Program to convert LaTeX fragments with.
3384 dvipng Process the LaTeX fragments to dvi file, then convert
3385 dvi files to png files using dvipng.
3386 This will also include processing of non-math environments.
3387 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3388 to convert pdf files to png files"
3392 (const :tag
"dvipng" dvipng
)
3393 (const :tag
"imagemagick" imagemagick
)))
3395 (defun org-format-latex-mathml-available-p ()
3396 "Return t if `org-latex-to-mathml-convert-command' is usable."
3398 (when (and (boundp 'org-latex-to-mathml-convert-command
)
3399 org-latex-to-mathml-convert-command
)
3400 (let ((executable (car (split-string
3401 org-latex-to-mathml-convert-command
))))
3402 (when (executable-find executable
)
3404 "%j" org-latex-to-mathml-convert-command
)
3405 (file-readable-p org-latex-to-mathml-jar-file
)
3408 (defcustom org-format-latex-header
"\\documentclass{article}
3409 \\usepackage[usenames]{color}
3410 \\usepackage{amsmath}
3411 \\usepackage[mathscr]{eucal}
3412 \\pagestyle{empty} % do not remove
3415 % The settings below are copied from fullpage.sty
3416 \\setlength{\\textwidth}{\\paperwidth}
3417 \\addtolength{\\textwidth}{-3cm}
3418 \\setlength{\\oddsidemargin}{1.5cm}
3419 \\addtolength{\\oddsidemargin}{-2.54cm}
3420 \\setlength{\\evensidemargin}{\\oddsidemargin}
3421 \\setlength{\\textheight}{\\paperheight}
3422 \\addtolength{\\textheight}{-\\headheight}
3423 \\addtolength{\\textheight}{-\\headsep}
3424 \\addtolength{\\textheight}{-\\footskip}
3425 \\addtolength{\\textheight}{-3cm}
3426 \\setlength{\\topmargin}{1.5cm}
3427 \\addtolength{\\topmargin}{-2.54cm}"
3428 "The document header used for processing LaTeX fragments.
3429 It is imperative that this header make sure that no page number
3430 appears on the page. The package defined in the variables
3431 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3432 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3437 (defvar org-format-latex-header-extra nil
)
3439 (defun org-set-packages-alist (var val
)
3440 "Set the packages alist and make sure it has 3 elements per entry."
3441 (set var
(mapcar (lambda (x)
3442 (if (and (consp x
) (= (length x
) 2))
3443 (list (car x
) (nth 1 x
) t
)
3447 (defun org-get-packages-alist (var)
3449 "Get the packages alist and make sure it has 3 elements per entry."
3451 (if (and (consp x
) (= (length x
) 2))
3452 (list (car x
) (nth 1 x
) t
)
3454 (default-value var
)))
3456 ;; The following variables are defined here because is it also used
3457 ;; when formatting latex fragments. Originally it was part of the
3458 ;; LaTeX exporter, which is why the name includes "export".
3459 (defcustom org-export-latex-default-packages-alist
3460 '(("AUTO" "inputenc" t
)
3464 ("" "longtable" nil
)
3476 "Alist of default packages to be inserted in the header.
3477 Change this only if one of the packages here causes an incompatibility
3478 with another package you are using.
3479 The packages in this list are needed by one part or another of Org-mode
3480 to function properly.
3482 - inputenc, fontenc: for basic font and character selection
3483 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3484 for interpreting the entities in `org-entities'. You can skip some of these
3485 packages if you don't use any of the symbols in it.
3486 - graphicx: for including images
3487 - float, wrapfig: for figure placement
3488 - longtable: for long tables
3489 - hyperref: for cross references
3491 Therefore you should not modify this variable unless you know what you
3492 are doing. The one reason to change it anyway is that you might be loading
3493 some other package that conflicts with one of the default packages.
3494 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3495 If SNIPPET-FLAG is t, the package also needs to be included when
3496 compiling LaTeX snippets into images for inclusion into HTML."
3497 :group
'org-export-latex
3498 :set
'org-set-packages-alist
3499 :get
'org-get-packages-alist
3503 (list :tag
"options/package pair"
3504 (string :tag
"options")
3505 (string :tag
"package")
3506 (boolean :tag
"Snippet"))
3507 (string :tag
"A line of LaTeX"))))
3509 (defcustom org-export-latex-packages-alist nil
3510 "Alist of packages to be inserted in every LaTeX header.
3511 These will be inserted after `org-export-latex-default-packages-alist'.
3512 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3513 SNIPPET-FLAG, when t, indicates that this package is also needed when
3514 turning LaTeX snippets into images for inclusion into HTML.
3515 Make sure that you only list packages here which:
3516 - you want in every file
3517 - do not conflict with the default packages in
3518 `org-export-latex-default-packages-alist'
3519 - do not conflict with the setup in `org-format-latex-header'."
3520 :group
'org-export-latex
3521 :set
'org-set-packages-alist
3522 :get
'org-get-packages-alist
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"))))
3532 (defgroup org-appearance nil
3533 "Settings for Org-mode appearance."
3534 :tag
"Org Appearance"
3537 (defcustom org-level-color-stars-only nil
3538 "Non-nil means fontify only the stars in each headline.
3539 When nil, the entire headline is fontified.
3540 Changing it requires restart of `font-lock-mode' to become effective
3541 also in regions already fontified."
3542 :group
'org-appearance
3545 (defcustom org-hide-leading-stars nil
3546 "Non-nil means hide the first N-1 stars in a headline.
3547 This works by using the face `org-hide' for these stars. This
3548 face is white for a light background, and black for a dark
3549 background. You may have to customize the face `org-hide' to
3551 Changing it requires restart of `font-lock-mode' to become effective
3552 also in regions already fontified.
3553 You may also set this on a per-file basis by adding one of the following
3554 lines to the buffer:
3556 #+STARTUP: hidestars
3557 #+STARTUP: showstars"
3558 :group
'org-appearance
3561 (defcustom org-hidden-keywords nil
3562 "List of symbols corresponding to keywords to be hidden the org buffer.
3563 For example, a value '(title) for this list will make the document's title
3564 appear in the buffer without the initial #+TITLE: keyword."
3565 :group
'org-appearance
3567 :type
'(set (const :tag
"#+AUTHOR" author
)
3568 (const :tag
"#+DATE" date
)
3569 (const :tag
"#+EMAIL" email
)
3570 (const :tag
"#+TITLE" title
)))
3572 (defcustom org-fontify-done-headline nil
3573 "Non-nil means change the face of a headline if it is marked DONE.
3574 Normally, only the TODO/DONE keyword indicates the state of a headline.
3575 When this is non-nil, the headline after the keyword is set to the
3576 `org-headline-done' as an additional indication."
3577 :group
'org-appearance
3580 (defcustom org-fontify-emphasized-text t
3581 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3582 Changing this variable requires a restart of Emacs to take effect."
3583 :group
'org-appearance
3586 (defcustom org-fontify-whole-heading-line nil
3587 "Non-nil means fontify the whole line for headings.
3588 This is useful when setting a background color for the
3590 :group
'org-appearance
3593 (defcustom org-highlight-latex-fragments-and-specials nil
3594 "Non-nil means fontify what is treated specially by the exporters."
3595 :group
'org-appearance
3598 (defcustom org-hide-emphasis-markers nil
3599 "Non-nil mean font-lock should hide the emphasis marker characters."
3600 :group
'org-appearance
3603 (defcustom org-pretty-entities nil
3604 "Non-nil means show entities as UTF8 characters.
3605 When nil, the \\name form remains in the buffer."
3606 :group
'org-appearance
3610 (defcustom org-pretty-entities-include-sub-superscripts t
3611 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3612 :group
'org-appearance
3616 (defvar org-emph-re nil
3617 "Regular expression for matching emphasis.
3618 After a match, the match groups contain these elements:
3619 0 The match of the full regular expression, including the characters
3620 before and after the proper match
3621 1 The character before the proper match, or empty at beginning of line
3622 2 The proper match, including the leading and trailing markers
3623 3 The leading marker like * or /, indicating the type of highlighting
3624 4 The text between the emphasis markers, not including the markers
3625 5 The character after the match, empty at the end of a line")
3626 (defvar org-verbatim-re nil
3627 "Regular expression for matching verbatim text.")
3628 (defvar org-emphasis-regexp-components
) ; defined just below
3629 (defvar org-emphasis-alist
) ; defined just below
3630 (defun org-set-emph-re (var val
)
3631 "Set variable and compute the emphasis regular expression."
3633 (when (and (boundp 'org-emphasis-alist
)
3634 (boundp 'org-emphasis-regexp-components
)
3635 org-emphasis-alist org-emphasis-regexp-components
)
3636 (let* ((e org-emphasis-regexp-components
)
3642 (body1 (concat body
"*?"))
3643 (markers (mapconcat 'car org-emphasis-alist
""))
3644 (vmarkers (mapconcat
3645 (lambda (x) (if (eq (nth 4 x
) 'verbatim
) (car x
) ""))
3646 org-emphasis-alist
"")))
3647 ;; make sure special characters appear at the right position in the class
3648 (if (string-match "\\^" markers
)
3649 (setq markers
(concat (replace-match "" t t markers
) "^")))
3650 (if (string-match "-" markers
)
3651 (setq markers
(concat (replace-match "" t t markers
) "-")))
3652 (if (string-match "\\^" vmarkers
)
3653 (setq vmarkers
(concat (replace-match "" t t vmarkers
) "^")))
3654 (if (string-match "-" vmarkers
)
3655 (setq vmarkers
(concat (replace-match "" t t vmarkers
) "-")))
3657 (setq body1
(concat body1
"\\(?:\n" body
"*?\\)\\{0,"
3658 (int-to-string nl
) "\\}")))
3661 (concat "\\([" pre
"]\\|^\\)"
3663 "\\([" markers
"]\\)"
3671 "\\([" post
"]\\|$\\)"))
3672 (setq org-verbatim-re
3673 (concat "\\([" pre
"]\\|^\\)"
3675 "\\([" vmarkers
"]\\)"
3683 "\\([" post
"]\\|$\\)")))))
3685 (defcustom org-emphasis-regexp-components
3686 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3687 "Components used to build the regular expression for emphasis.
3688 This is a list with five entries. Terminology: In an emphasis string
3689 like \" *strong word* \", we call the initial space PREMATCH, the final
3690 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3691 and \"trong wor\" is the body. The different components in this variable
3692 specify what is allowed/forbidden in each part:
3694 pre Chars allowed as prematch. Beginning of line will be allowed too.
3695 post Chars allowed as postmatch. End of line will be allowed too.
3696 border The chars *forbidden* as border characters.
3697 body-regexp A regexp like \".\" to match a body character. Don't use
3698 non-shy groups here, and don't allow newline here.
3699 newline The maximum number of newlines allowed in an emphasis exp.
3701 Use customize to modify this, or restart Emacs after changing it."
3702 :group
'org-appearance
3703 :set
'org-set-emph-re
3705 (sexp :tag
"Allowed chars in pre ")
3706 (sexp :tag
"Allowed chars in post ")
3707 (sexp :tag
"Forbidden chars in border ")
3708 (sexp :tag
"Regexp for body ")
3709 (integer :tag
"number of newlines allowed")
3710 (option (boolean :tag
"Please ignore this button"))))
3712 (defcustom org-emphasis-alist
3713 `(("*" bold
"<b>" "</b>")
3714 ("/" italic
"<i>" "</i>")
3715 ("_" underline
"<span style=\"text-decoration:underline;\">" "</span>")
3716 ("=" org-code
"<code>" "</code>" verbatim
)
3717 ("~" org-verbatim
"<code>" "</code>" verbatim
)
3718 ("+" ,(if (featurep 'xemacs
) 'org-table
'(:strike-through t
))
3721 "Special syntax for emphasized text.
3722 Text starting and ending with a special character will be emphasized, for
3723 example *bold*, _underlined_ and /italic/. This variable sets the marker
3724 characters, the face to be used by font-lock for highlighting in Org-mode
3725 Emacs buffers, and the HTML tags to be used for this.
3726 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3727 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3728 Use customize to modify this, or restart Emacs after changing it."
3729 :group
'org-appearance
3730 :set
'org-set-emph-re
3733 (string :tag
"Marker character")
3735 (face :tag
"Font-lock-face")
3736 (plist :tag
"Face property list"))
3737 (string :tag
"HTML start tag")
3738 (string :tag
"HTML end tag")
3739 (option (const verbatim
)))))
3741 (defvar org-protecting-blocks
3742 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3743 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3744 This is needed for font-lock setup.")
3746 ;;; Miscellaneous options
3748 (defgroup org-completion nil
3749 "Completion in Org-mode."
3750 :tag
"Org Completion"
3753 (defcustom org-completion-use-ido nil
3754 "Non-nil means use ido completion wherever possible.
3755 Note that `ido-mode' must be active for this variable to be relevant.
3756 If you decide to turn this variable on, you might well want to turn off
3757 `org-outline-path-complete-in-steps'.
3758 See also `org-completion-use-iswitchb'."
3759 :group
'org-completion
3762 (defcustom org-completion-use-iswitchb nil
3763 "Non-nil means use iswitchb completion wherever possible.
3764 Note that `iswitchb-mode' must be active for this variable to be relevant.
3765 If you decide to turn this variable on, you might well want to turn off
3766 `org-outline-path-complete-in-steps'.
3767 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3768 :group
'org-completion
3771 (defcustom org-completion-fallback-command
'hippie-expand
3772 "The expansion command called by \\[pcomplete] in normal context.
3773 Normal means, no org-mode-specific context."
3774 :group
'org-completion
3777 ;;; Functions and variables from their packages
3778 ;; Declared here to avoid compiler warnings
3781 (defvar outline-mode-menu-heading
)
3782 (defvar outline-mode-menu-show
)
3783 (defvar outline-mode-menu-hide
)
3784 (defvar zmacs-regions
) ; XEmacs regions
3787 (defvar mark-active
)
3790 (declare-function calendar-absolute-from-iso
"cal-iso" (date))
3791 (declare-function calendar-forward-day
"cal-move" (arg))
3792 (declare-function calendar-goto-date
"cal-move" (date))
3793 (declare-function calendar-goto-today
"cal-move" ())
3794 (declare-function calendar-iso-from-absolute
"cal-iso" (date))
3795 (defvar calc-embedded-close-formula
)
3796 (defvar calc-embedded-open-formula
)
3797 (declare-function cdlatex-tab
"ext:cdlatex" ())
3798 (declare-function cdlatex-compute-tables
"ext:cdlatex" ())
3799 (declare-function dired-get-filename
"dired" (&optional localp no-error-if-not-filep
))
3800 (defvar font-lock-unfontify-region-function
)
3801 (declare-function iswitchb-read-buffer
"iswitchb"
3802 (prompt &optional default require-match start matches-set
))
3803 (defvar iswitchb-temp-buflist
)
3804 (declare-function org-gnus-follow-link
"org-gnus" (&optional group article
))
3805 (defvar org-agenda-tags-todo-honor-ignore-options
)
3806 (declare-function org-agenda-skip
"org-agenda" ())
3808 org-agenda-format-item
"org-agenda"
3809 (extra txt
&optional category tags dotime noprefix remove-re habitp
))
3810 (declare-function org-agenda-new-marker
"org-agenda" (&optional pos
))
3811 (declare-function org-agenda-change-all-lines
"org-agenda"
3812 (newhead hdmarker
&optional fixface just-this
))
3813 (declare-function org-agenda-set-restriction-lock
"org-agenda" (&optional type
))
3814 (declare-function org-agenda-maybe-redo
"org-agenda" ())
3815 (declare-function org-agenda-save-markers-for-cut-and-paste
"org-agenda"
3817 (declare-function org-agenda-copy-local-variable
"org-agenda" (var))
3818 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3819 "org-agenda" (&optional end
))
3820 (declare-function org-inlinetask-remove-END-maybe
"org-inlinetask" ())
3821 (declare-function org-inlinetask-in-task-p
"org-inlinetask" ())
3822 (declare-function org-inlinetask-goto-beginning
"org-inlinetask" ())
3823 (declare-function org-inlinetask-goto-end
"org-inlinetask" ())
3824 (declare-function org-indent-mode
"org-indent" (&optional arg
))
3825 (declare-function parse-time-string
"parse-time" (string))
3826 (declare-function org-attach-reveal
"org-attach" (&optional if-exists
))
3827 (declare-function org-export-latex-fix-inputenc
"org-latex" ())
3828 (declare-function orgtbl-send-table
"org-table" (&optional maybe
))
3829 (defvar remember-data-file
)
3830 (defvar texmathp-why
)
3831 (declare-function speedbar-line-directory
"speedbar" (&optional depth
))
3832 (declare-function table--at-cell-p
"table" (position &optional object at-column
))
3834 (defvar w3m-current-url
)
3835 (defvar w3m-current-title
)
3837 (defvar org-latex-regexps
)
3839 ;;; Autoload and prepare some org modules
3841 ;; Some table stuff that needs to be defined here, because it is used
3842 ;; by the functions setting up org-mode or checking for table context.
3844 (defconst org-table-any-line-regexp
"^[ \t]*\\(|\\|\\+-[-+]\\)"
3845 "Detect an org-type or table-type table.")
3846 (defconst org-table-line-regexp
"^[ \t]*|"
3847 "Detect an org-type table line.")
3848 (defconst org-table-dataline-regexp
"^[ \t]*|[^-]"
3849 "Detect an org-type table line.")
3850 (defconst org-table-hline-regexp
"^[ \t]*|-"
3851 "Detect an org-type table hline.")
3852 (defconst org-table1-hline-regexp
"^[ \t]*\\+-[-+]"
3853 "Detect a table-type table hline.")
3854 (defconst org-table-any-border-regexp
"^[ \t]*[^|+ \t]"
3855 "Detect the first line outside a table when searching from within it.
3856 This works for both table types.")
3858 ;; Autoload the functions in org-table.el that are needed by functions here.
3861 (org-autoload "org-table"
3862 '(org-table-align org-table-begin org-table-blank-field
3863 org-table-convert org-table-convert-region org-table-copy-down
3864 org-table-copy-region org-table-create
3865 org-table-create-or-convert-from-region
3866 org-table-create-with-table.el org-table-current-dline
3867 org-table-cut-region org-table-delete-column org-table-edit-field
3868 org-table-edit-formulas org-table-end org-table-eval-formula
3869 org-table-export org-table-field-info
3870 org-table-get-stored-formulas org-table-goto-column
3871 org-table-hline-and-move org-table-import org-table-insert-column
3872 org-table-insert-hline org-table-insert-row org-table-iterate
3873 org-table-justify-field-maybe org-table-kill-row
3874 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3875 org-table-move-column org-table-move-column-left
3876 org-table-move-column-right org-table-move-row
3877 org-table-move-row-down org-table-move-row-up
3878 org-table-next-field org-table-next-row org-table-paste-rectangle
3879 org-table-previous-field org-table-recalculate
3880 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3881 org-table-toggle-coordinate-overlays
3882 org-table-toggle-formula-debugger org-table-wrap-region
3883 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3884 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3885 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo
)))
3887 (defun org-at-table-p (&optional table-type
)
3888 "Return t if the cursor is inside an org-type table.
3889 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3890 (if org-enable-table-editor
3892 (beginning-of-line 1)
3893 (looking-at (if table-type org-table-any-line-regexp
3894 org-table-line-regexp
)))
3896 (defsubst org-table-p
() (org-at-table-p))
3898 (defun org-at-table.el-p
()
3899 "Return t if and only if we are at a table.el table."
3900 (and (org-at-table-p 'any
)
3902 (goto-char (org-table-begin 'any
))
3903 (looking-at org-table1-hline-regexp
))))
3904 (defun org-table-recognize-table.el
()
3905 "If there is a table.el table nearby, recognize it and move into it."
3906 (if org-table-tab-recognizes-table.el
3907 (if (org-at-table.el-p
)
3909 (beginning-of-line 1)
3910 (if (looking-at org-table-dataline-regexp
)
3912 (if (looking-at org-table1-hline-regexp
)
3914 (beginning-of-line 2)
3915 (if (looking-at org-table-any-border-regexp
)
3916 (beginning-of-line -
1)))))
3917 (if (re-search-forward "|" (org-table-end t
) t
)
3920 (if (table--at-cell-p (point))
3922 (message "recognizing table.el table...")
3923 (table-recognize-table)
3924 (message "recognizing table.el table...done")))
3925 (error "This should not happen"))
3930 (defun org-at-table-hline-p ()
3931 "Return t if the cursor is inside a hline in a table."
3932 (if org-enable-table-editor
3934 (beginning-of-line 1)
3935 (looking-at org-table-hline-regexp
))
3938 (defvar org-table-clean-did-remove-column nil
)
3940 (defun org-table-map-tables (function &optional quietly
)
3941 "Apply FUNCTION to the start of all tables in the buffer."
3945 (goto-char (point-min))
3946 (while (re-search-forward org-table-any-line-regexp nil t
)
3948 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3949 (beginning-of-line 1)
3950 (when (and (looking-at org-table-line-regexp
)
3951 ;; Exclude tables in src/example/verbatim/clocktable blocks
3952 (not (org-in-block-p '("src" "example"))))
3953 (save-excursion (funcall function
))
3954 (or (looking-at org-table-line-regexp
)
3956 (re-search-forward org-table-any-border-regexp nil
1))))
3957 (unless quietly
(message "Mapping tables: done")))
3959 ;; Declare and autoload functions from org-exp.el & Co
3961 (declare-function org-default-export-plist
"org-exp")
3962 (declare-function org-infile-export-plist
"org-exp")
3963 (declare-function org-get-current-options
"org-exp")
3965 (org-autoload "org-exp"
3966 '(org-export org-export-visible
3967 org-insert-export-options-template
3968 org-table-clean-before-export
))
3969 (org-autoload "org-ascii"
3970 '(org-export-as-ascii org-export-ascii-preprocess
3971 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3972 org-export-region-as-ascii
))
3973 (org-autoload "org-latex"
3974 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3975 org-replace-region-by-latex org-export-region-as-latex
3976 org-export-as-latex org-export-as-pdf
3977 org-export-as-pdf-and-open
))
3978 (org-autoload "org-html"
3979 '(org-export-as-html-and-open
3980 org-export-as-html-batch org-export-as-html-to-buffer
3981 org-replace-region-by-html org-export-region-as-html
3982 org-export-as-html
))
3983 (org-autoload "org-docbook"
3984 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3985 org-replace-region-by-docbook org-export-region-as-docbook
3986 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3987 org-export-as-docbook
))
3988 (org-autoload "org-icalendar"
3989 '(org-export-icalendar-this-file
3990 org-export-icalendar-all-agenda-files
3991 org-export-icalendar-combine-agenda-files
))
3992 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3993 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning
)))
3995 ;; Declare and autoload functions from org-agenda.el
3998 (org-autoload "org-agenda"
3999 '(org-agenda org-agenda-list org-search-view
4000 org-todo-list org-tags-view org-agenda-list-stuck-projects
4001 org-diary org-agenda-to-appt
4002 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
)))
4004 ;; Autoload org-remember
4007 (org-autoload "org-remember"
4008 '(org-remember-insinuate org-remember-annotation
4009 org-remember-apply-template org-remember org-remember-handler
)))
4012 (org-autoload "org-capture"
4013 '(org-capture org-capture-insert-template-here
4014 org-capture-import-remember-templates
)))
4016 ;; Autoload org-clock.el
4018 (declare-function org-clock-save-markers-for-cut-and-paste
"org-clock"
4020 (declare-function org-clock-update-mode-line
"org-clock" ())
4021 (declare-function org-resolve-clocks
"org-clock"
4022 (&optional also-non-dangling-p prompt last-valid
))
4023 (defvar org-clock-start-time
)
4024 (defvar org-clock-marker
(make-marker)
4025 "Marker recording the last clock-in.")
4026 (defvar org-clock-hd-marker
(make-marker)
4027 "Marker recording the last clock-in, but the headline position.")
4028 (defvar org-clock-heading
""
4029 "The heading of the current clock entry.")
4030 (defun org-clock-is-active ()
4031 "Return non-nil if clock is currently running.
4032 The return value is actually the clock marker."
4033 (marker-buffer org-clock-marker
))
4038 '(org-clock-in org-clock-out org-clock-cancel
4039 org-clock-goto org-clock-sum org-clock-display
4040 org-clock-remove-overlays org-clock-report
4041 org-clocktable-shift org-dblock-write
:clocktable
4042 org-get-clocktable org-resolve-clocks
)))
4044 (defun org-clock-update-time-maybe ()
4045 "If this is a CLOCK line, update it and return t.
4046 Otherwise, return nil."
4049 (beginning-of-line 1)
4050 (skip-chars-forward " \t")
4051 (when (looking-at org-clock-string
)
4052 (let ((re (concat "[ \t]*" org-clock-string
4053 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4054 "\\([ \t]*=>.*\\)?\\)?"))
4057 ((not (looking-at re
))
4059 ((not (match-end 2))
4060 (when (and (equal (marker-buffer org-clock-marker
) (current-buffer))
4061 (> org-clock-marker
(point))
4062 (<= org-clock-marker
(point-at-eol)))
4063 ;; The clock is running here
4064 (setq org-clock-start-time
4066 (org-parse-time-string (match-string 1))))
4067 (org-clock-update-mode-line)))
4069 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4071 (setq ts
(match-string 1)
4072 te
(match-string 3))
4073 (setq s
(- (org-float-time
4074 (apply 'encode-time
(org-parse-time-string te
)))
4076 (apply 'encode-time
(org-parse-time-string ts
))))
4079 h
(floor (/ s
3600))
4083 (insert " => " (format (if neg
"-%d:%02d" "%2d:%02d") h m
))
4086 (defun org-check-running-clock ()
4087 "Check if the current buffer contains the running clock.
4088 If yes, offer to stop it and to save the buffer with the changes."
4089 (when (and (equal (marker-buffer org-clock-marker
) (current-buffer))
4090 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4093 (when (y-or-n-p "Save changed buffer?")
4096 (defun org-clocktable-try-shift (dir n
)
4097 "Check if this line starts a clock table, if yes, shift the time block."
4098 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4099 (org-clocktable-shift dir n
)))
4101 ;; Autoload org-timer.el
4106 '(org-timer-start org-timer org-timer-item
4107 org-timer-change-times-in-region
4109 org-timer-reset-timers
4110 org-timer-show-remaining-time
)))
4112 ;; Autoload org-feed.el
4117 '(org-feed-update org-feed-update-all org-feed-goto-inbox
)))
4120 ;; Autoload org-indent.el
4122 ;; Define the variable already here, to make sure we have it.
4123 (defvar org-indent-mode nil
4124 "Non-nil if Org-Indent mode is enabled.
4125 Use the command `org-indent-mode' to change this variable.")
4130 '(org-indent-mode)))
4132 ;; Autoload org-mobile.el
4137 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda
)))
4139 ;; Autoload archiving code
4140 ;; The stuff that is needed for cycling and tags has to be defined here.
4142 (defgroup org-archive nil
4143 "Options concerning archiving in Org-mode."
4145 :group
'org-structure
)
4147 (defcustom org-archive-location
"%s_archive::"
4148 "The location where subtrees should be archived.
4150 The value of this variable is a string, consisting of two parts,
4151 separated by a double-colon. The first part is a filename and
4152 the second part is a headline.
4154 When the filename is omitted, archiving happens in the same file.
4155 %s in the filename will be replaced by the current file
4156 name (without the directory part). Archiving to a different file
4157 is useful to keep archived entries from contributing to the
4160 The archived entries will be filed as subtrees of the specified
4161 headline. When the headline is omitted, the subtrees are simply
4162 filed away at the end of the file, as top-level entries. Also in
4163 the heading you can use %s to represent the file name, this can be
4164 useful when using the same archive for a number of different files.
4166 Here are a few examples:
4168 If the current file is Projects.org, archive in file
4169 Projects.org_archive, as top-level trees. This is the default.
4171 \"::* Archived Tasks\"
4172 Archive in the current file, under the top-level headline
4173 \"* Archived Tasks\".
4175 \"~/org/archive.org::\"
4176 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4178 \"~/org/archive.org::* From %s\"
4179 Archive in file ~/org/archive.org (absolute path), under headlines
4180 \"From FILENAME\" where file name is the current file name.
4182 \"~/org/datetree.org::datetree/* Finished Tasks\"
4183 The \"datetree/\" string is special, signifying to archive
4184 items to the datetree. Items are placed in either the CLOSED
4185 date of the item, or the current date if there is no CLOSED date.
4186 The heading will be a subentry to the current date. There doesn't
4187 need to be a heading, but there always needs to be a slash after
4188 datetree. For example, to store archived items directly in the
4189 datetree, use \"~/org/datetree.org::datetree/\".
4191 \"basement::** Finished Tasks\"
4192 Archive in file ./basement (relative path), as level 3 trees
4193 below the level 2 heading \"** Finished Tasks\".
4195 You may set this option on a per-file basis by adding to the buffer a
4198 #+ARCHIVE: basement::** Finished Tasks
4200 You may also define it locally for a subtree by setting an ARCHIVE property
4201 in the entry. If such a property is found in an entry, or anywhere up
4202 the hierarchy, it will be used."
4206 (defcustom org-archive-tag
"ARCHIVE"
4207 "The tag that marks a subtree as archived.
4208 An archived subtree does not open during visibility cycling, and does
4209 not contribute to the agenda listings.
4210 After changing this, font-lock must be restarted in the relevant buffers to
4211 get the proper fontification."
4213 :group
'org-keywords
4216 (defcustom org-agenda-skip-archived-trees t
4217 "Non-nil means the agenda will skip any items located in archived trees.
4218 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4219 variable is no longer recommended, you should leave it at the value t.
4220 Instead, use the key `v' to cycle the archives-mode in the agenda."
4222 :group
'org-agenda-skip
4225 (defcustom org-columns-skip-archived-trees t
4226 "Non-nil means ignore archived trees when creating column view."
4228 :group
'org-properties
4231 (defcustom org-cycle-open-archived-trees nil
4232 "Non-nil means `org-cycle' will open archived trees.
4233 An archived tree is a tree marked with the tag ARCHIVE.
4234 When nil, archived trees will stay folded. You can still open them with
4235 normal outline commands like `show-all', but not with the cycling commands."
4240 (defcustom org-sparse-tree-open-archived-trees nil
4241 "Non-nil means sparse tree construction shows matches in archived trees.
4242 When nil, matches in these trees are highlighted, but the trees are kept in
4245 :group
'org-sparse-trees
4248 (defun org-cycle-hide-archived-subtrees (state)
4249 "Re-hide all archived subtrees after a visibility state change."
4250 (when (and (not org-cycle-open-archived-trees
)
4251 (not (memq state
'(overview folded
))))
4253 (let* ((globalp (memq state
'(contents all
)))
4254 (beg (if globalp
(point-min) (point)))
4255 (end (if globalp
(point-max) (org-end-of-subtree t
))))
4256 (org-hide-archived-subtrees beg end
)
4258 (if (looking-at (concat ".*:" org-archive-tag
":"))
4259 (message "%s" (substitute-command-keys
4260 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4262 (defun org-force-cycle-archived ()
4263 "Cycle subtree even if it is archived."
4265 (setq this-command
'org-cycle
)
4266 (let ((org-cycle-open-archived-trees t
))
4267 (call-interactively 'org-cycle
)))
4269 (defun org-hide-archived-subtrees (beg end
)
4270 "Re-hide all archived subtrees after a visibility state change."
4272 (let* ((re (concat ":" org-archive-tag
":")))
4274 (while (re-search-forward re end t
)
4275 (when (org-at-heading-p)
4276 (org-flag-subtree t
)
4277 (org-end-of-subtree t
))))))
4279 (defun org-flag-subtree (flag)
4281 (org-back-to-heading t
)
4282 (outline-end-of-heading)
4283 (outline-flag-region (point)
4284 (progn (org-end-of-subtree t
) (point))
4287 (defalias 'org-advertized-archive-subtree
'org-archive-subtree
)
4290 (org-autoload "org-archive"
4291 '(org-add-archive-files org-archive-subtree
4292 org-archive-to-archive-sibling org-toggle-archive-tag
4293 org-archive-subtree-default
4294 org-archive-subtree-default-with-confirmation
)))
4296 ;; Autoload Column View Code
4298 (declare-function org-columns-number-to-string
"org-colview")
4299 (declare-function org-columns-get-format-and-top-level
"org-colview")
4300 (declare-function org-columns-compute
"org-colview")
4302 (org-autoload (if (featurep 'xemacs
) "org-colview-xemacs" "org-colview")
4303 '(org-columns-number-to-string org-columns-get-format-and-top-level
4304 org-columns-compute org-agenda-columns org-columns-remove-overlays
4305 org-columns org-insert-columns-dblock org-dblock-write
:columnview
))
4309 (declare-function org-id-store-link
"org-id")
4310 (declare-function org-id-locations-load
"org-id")
4311 (declare-function org-id-locations-save
"org-id")
4312 (defvar org-id-track-globally
)
4313 (org-autoload "org-id"
4314 '(org-id-get-create org-id-new org-id-copy org-id-get
4315 org-id-get-with-outline-path-completion
4316 org-id-get-with-outline-drilling org-id-store-link
4317 org-id-goto org-id-find org-id-store-link
))
4319 ;; Autoload Plotting Code
4321 (org-autoload "org-plot"
4322 '(org-plot/gnuplot
))
4324 ;;; Variables for pre-computed regular expressions, all buffer local
4326 (defvar org-drawer-regexp nil
4327 "Matches first line of a hidden block.")
4328 (make-variable-buffer-local 'org-drawer-regexp
)
4329 (defvar org-todo-regexp nil
4330 "Matches any of the TODO state keywords.")
4331 (make-variable-buffer-local 'org-todo-regexp
)
4332 (defvar org-not-done-regexp nil
4333 "Matches any of the TODO state keywords except the last one.")
4334 (make-variable-buffer-local 'org-not-done-regexp
)
4335 (defvar org-not-done-heading-regexp nil
4336 "Matches a TODO headline that is not done.")
4337 (make-variable-buffer-local 'org-not-done-regexp
)
4338 (defvar org-todo-line-regexp nil
4339 "Matches a headline and puts TODO state into group 2 if present.")
4340 (make-variable-buffer-local 'org-todo-line-regexp
)
4341 (defvar org-complex-heading-regexp nil
4342 "Matches a headline and puts everything into groups:
4344 group 2: The todo keyword, maybe
4345 group 3: Priority cookie
4346 group 4: True headline
4348 (make-variable-buffer-local 'org-complex-heading-regexp
)
4349 (defvar org-complex-heading-regexp-format nil
4350 "Printf format to make regexp to match an exact headline.
4351 This regexp will match the headline of any node which has the
4352 exact headline text that is put into the format, but may have any
4353 TODO state, priority and tags.")
4354 (make-variable-buffer-local 'org-complex-heading-regexp-format
)
4355 (defvar org-todo-line-tags-regexp nil
4356 "Matches a headline and puts TODO state into group 2 if present.
4357 Also put tags into group 4 if tags are present.")
4358 (make-variable-buffer-local 'org-todo-line-tags-regexp
)
4359 (defvar org-ds-keyword-length
12
4360 "Maximum length of the Deadline and SCHEDULED keywords.")
4361 (make-variable-buffer-local 'org-ds-keyword-length
)
4362 (defvar org-deadline-regexp nil
4363 "Matches the DEADLINE keyword.")
4364 (make-variable-buffer-local 'org-deadline-regexp
)
4365 (defvar org-deadline-time-regexp nil
4366 "Matches the DEADLINE keyword together with a time stamp.")
4367 (make-variable-buffer-local 'org-deadline-time-regexp
)
4368 (defvar org-deadline-line-regexp nil
4369 "Matches the DEADLINE keyword and the rest of the line.")
4370 (make-variable-buffer-local 'org-deadline-line-regexp
)
4371 (defvar org-scheduled-regexp nil
4372 "Matches the SCHEDULED keyword.")
4373 (make-variable-buffer-local 'org-scheduled-regexp
)
4374 (defvar org-scheduled-time-regexp nil
4375 "Matches the SCHEDULED keyword together with a time stamp.")
4376 (make-variable-buffer-local 'org-scheduled-time-regexp
)
4377 (defvar org-closed-time-regexp nil
4378 "Matches the CLOSED keyword together with a time stamp.")
4379 (make-variable-buffer-local 'org-closed-time-regexp
)
4381 (defvar org-keyword-time-regexp nil
4382 "Matches any of the 4 keywords, together with the time stamp.")
4383 (make-variable-buffer-local 'org-keyword-time-regexp
)
4384 (defvar org-keyword-time-not-clock-regexp nil
4385 "Matches any of the 3 keywords, together with the time stamp.")
4386 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp
)
4387 (defvar org-maybe-keyword-time-regexp nil
4388 "Matches a timestamp, possibly preceded by a keyword.")
4389 (make-variable-buffer-local 'org-maybe-keyword-time-regexp
)
4390 (defvar org-planning-or-clock-line-re nil
4391 "Matches a line with planning or clock info.")
4392 (make-variable-buffer-local 'org-planning-or-clock-line-re
)
4393 (defvar org-all-time-keywords nil
4394 "List of time keywords.")
4395 (make-variable-buffer-local 'org-all-time-keywords
)
4397 (defconst org-plain-time-of-day-regexp
4400 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4403 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4405 "Regular expression to match a plain time or time range.
4406 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4407 groups carry important information:
4409 1 the first time, range or not
4410 8 the second time, if it is a range.")
4412 (defconst org-plain-time-extension-regexp
4415 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4416 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4417 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4418 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4419 groups carry important information:
4422 9 minutes of duration")
4424 (defconst org-stamp-time-of-day-regexp
4426 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4427 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4429 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4430 "Regular expression to match a timestamp time or time range.
4431 After a match, the following groups carry important information:
4433 1 date plus weekday, for back referencing to make sure both times are on the same day
4434 2 the first time, range or not
4435 4 the second time, if it is a range.")
4437 (defconst org-startup-options
4438 '(("fold" org-startup-folded t
)
4439 ("overview" org-startup-folded t
)
4440 ("nofold" org-startup-folded nil
)
4441 ("showall" org-startup-folded nil
)
4442 ("showeverything" org-startup-folded showeverything
)
4443 ("content" org-startup-folded content
)
4444 ("indent" org-startup-indented t
)
4445 ("noindent" org-startup-indented nil
)
4446 ("hidestars" org-hide-leading-stars t
)
4447 ("showstars" org-hide-leading-stars nil
)
4448 ("odd" org-odd-levels-only t
)
4449 ("oddeven" org-odd-levels-only nil
)
4450 ("align" org-startup-align-all-tables t
)
4451 ("noalign" org-startup-align-all-tables nil
)
4452 ("inlineimages" org-startup-with-inline-images t
)
4453 ("noinlineimages" org-startup-with-inline-images nil
)
4454 ("customtime" org-display-custom-times t
)
4455 ("logdone" org-log-done time
)
4456 ("lognotedone" org-log-done note
)
4457 ("nologdone" org-log-done nil
)
4458 ("lognoteclock-out" org-log-note-clock-out t
)
4459 ("nolognoteclock-out" org-log-note-clock-out nil
)
4460 ("logrepeat" org-log-repeat state
)
4461 ("lognoterepeat" org-log-repeat note
)
4462 ("nologrepeat" org-log-repeat nil
)
4463 ("logreschedule" org-log-reschedule time
)
4464 ("lognotereschedule" org-log-reschedule note
)
4465 ("nologreschedule" org-log-reschedule nil
)
4466 ("logredeadline" org-log-redeadline time
)
4467 ("lognoteredeadline" org-log-redeadline note
)
4468 ("nologredeadline" org-log-redeadline nil
)
4469 ("logrefile" org-log-refile time
)
4470 ("lognoterefile" org-log-refile note
)
4471 ("nologrefile" org-log-refile nil
)
4472 ("fninline" org-footnote-define-inline t
)
4473 ("nofninline" org-footnote-define-inline nil
)
4474 ("fnlocal" org-footnote-section nil
)
4475 ("fnauto" org-footnote-auto-label t
)
4476 ("fnprompt" org-footnote-auto-label nil
)
4477 ("fnconfirm" org-footnote-auto-label confirm
)
4478 ("fnplain" org-footnote-auto-label plain
)
4479 ("fnadjust" org-footnote-auto-adjust t
)
4480 ("nofnadjust" org-footnote-auto-adjust nil
)
4481 ("constcgs" constants-unit-system cgs
)
4482 ("constSI" constants-unit-system SI
)
4483 ("noptag" org-tag-persistent-alist nil
)
4484 ("hideblocks" org-hide-block-startup t
)
4485 ("nohideblocks" org-hide-block-startup nil
)
4486 ("beamer" org-startup-with-beamer-mode t
)
4487 ("entitiespretty" org-pretty-entities t
)
4488 ("entitiesplain" org-pretty-entities nil
))
4489 "Variable associated with STARTUP options for org-mode.
4490 Each element is a list of three items: The startup options as written
4491 in the #+STARTUP line, the corresponding variable, and the value to
4492 set this variable to if the option is found. An optional forth element PUSH
4493 means to push this value onto the list in the variable.")
4495 (defun org-update-property-plist (key val props
)
4496 "Update PROPS with KEY and VAL."
4497 (let* ((appending (string= "+" (substring key
(- (length key
) 1))))
4498 (key (if appending
(substring key
0 (- (length key
) 1)) key
))
4499 (remainder (org-remove-if (lambda (p) (string= (car p
) key
)) props
))
4500 (previous (cdr (assoc key props
))))
4502 (cons (cons key
(if previous
(concat previous
" " val
) val
)) remainder
)
4503 (cons (cons key val
) remainder
))))
4505 (defconst org-block-regexp
4506 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4507 "Regular expression for hiding blocks.")
4508 (defconst org-heading-keyword-regexp-format
4509 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4510 "Printf format for a regexp matching an headline with some keyword.
4511 This regexp will match the headline of any node which has the
4512 exact keyword that is put into the format. The keyword isn't in
4513 any group by default, but the stars and the body are.")
4514 (defconst org-heading-keyword-maybe-regexp-format
4515 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4516 "Printf format for a regexp matching an headline, possibly with some keyword.
4517 This regexp can match any headline with the specified keyword, or
4518 without a keyword. The keyword isn't in any group by default,
4519 but the stars and the body are.")
4521 (defun org-set-regexps-and-options ()
4522 "Precompute regular expressions for current buffer."
4523 (when (derived-mode-p 'org-mode
)
4524 (org-set-local 'org-todo-kwd-alist nil
)
4525 (org-set-local 'org-todo-key-alist nil
)
4526 (org-set-local 'org-todo-key-trigger nil
)
4527 (org-set-local 'org-todo-keywords-1 nil
)
4528 (org-set-local 'org-done-keywords nil
)
4529 (org-set-local 'org-todo-heads nil
)
4530 (org-set-local 'org-todo-sets nil
)
4531 (org-set-local 'org-todo-log-states nil
)
4532 (org-set-local 'org-file-properties nil
)
4533 (org-set-local 'org-file-tags nil
)
4534 (let ((re (org-make-options-regexp
4535 '("CATEGORY" "TODO" "COLUMNS"
4536 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4537 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4539 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4541 (scripts org-use-sub-superscripts
)
4542 kwds kws0 kwsa key log value cat arch tags const links hw dws
4543 tail sep kws1 prio props ftags drawers beamer-p
4544 ext-setup-or-nil setup-contents
(start 0))
4548 (goto-char (point-min))
4549 (while (or (and ext-setup-or-nil
4550 (string-match re ext-setup-or-nil start
)
4551 (setq start
(match-end 0)))
4552 (and (setq ext-setup-or-nil nil start
0)
4553 (re-search-forward re nil t
)))
4554 (setq key
(upcase (match-string 1 ext-setup-or-nil
))
4555 value
(org-match-string-no-properties 2 ext-setup-or-nil
))
4556 (if (stringp value
) (setq value
(org-trim value
)))
4558 ((equal key
"CATEGORY")
4560 ((member key
'("SEQ_TODO" "TODO"))
4561 (push (cons 'sequence
(org-split-string value splitre
)) kwds
))
4562 ((equal key
"TYP_TODO")
4563 (push (cons 'type
(org-split-string value splitre
)) kwds
))
4564 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key
)
4565 ;; general TODO-like setup
4566 (push (cons (intern (downcase (match-string 1 key
)))
4567 (org-split-string value splitre
)) kwds
))
4569 (setq tags
(append tags
(if tags
'("\\n") nil
)
4570 (org-split-string value splitre
))))
4571 ((equal key
"COLUMNS")
4572 (org-set-local 'org-columns-default-format value
))
4574 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value
)
4575 (push (cons (match-string 1 value
)
4576 (org-trim (match-string 2 value
)))
4578 ((equal key
"PRIORITIES")
4579 (setq prio
(org-split-string value
" +")))
4580 ((equal key
"PROPERTY")
4581 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value
)
4582 (setq props
(org-update-property-plist (match-string 1 value
)
4583 (match-string 2 value
)
4585 ((equal key
"FILETAGS")
4586 (when (string-match "\\S-" value
)
4591 (mapcar (lambda (x) (org-split-string x
":"))
4592 (org-split-string value
)))))))
4593 ((equal key
"DRAWERS")
4594 (setq drawers
(delete-dups (append org-drawers
(org-split-string value splitre
)))))
4595 ((equal key
"CONSTANTS")
4596 (setq const
(append const
(org-split-string value splitre
))))
4597 ((equal key
"STARTUP")
4598 (let ((opts (org-split-string value splitre
))
4600 (while (setq l
(pop opts
))
4601 (when (setq l
(assoc l org-startup-options
))
4602 (setq var
(nth 1 l
) val
(nth 2 l
))
4604 (set (make-local-variable var
) val
)
4605 (if (not (listp (symbol-value var
)))
4606 (set (make-local-variable var
) nil
))
4607 (set (make-local-variable var
) (symbol-value var
))
4608 (add-to-list var val
))))))
4609 ((equal key
"ARCHIVE")
4611 (remove-text-properties 0 (length arch
)
4612 '(face t fontified t
) arch
))
4613 ((equal key
"LATEX_CLASS")
4614 (setq beamer-p
(equal value
"beamer")))
4615 ((equal key
"OPTIONS")
4616 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value
)
4617 (setq scripts
(read (match-string 2 value
)))))
4618 ((equal key
"SETUPFILE")
4619 (setq setup-contents
(org-file-contents
4621 (org-remove-double-quotes value
))
4623 (if (not ext-setup-or-nil
)
4624 (setq ext-setup-or-nil setup-contents start
0)
4625 (setq ext-setup-or-nil
4626 (concat (substring ext-setup-or-nil
0 start
)
4627 "\n" setup-contents
"\n"
4628 (substring ext-setup-or-nil start
)))))))
4629 ;; search for property blocks
4630 (goto-char (point-min))
4631 (while (re-search-forward org-block-regexp nil t
)
4632 (when (equal "PROPERTY" (upcase (match-string 1)))
4633 (setq value
(replace-regexp-in-string
4634 "[\n\r]" " " (match-string 4)))
4635 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value
)
4636 (setq props
(org-update-property-plist (match-string 1 value
)
4637 (match-string 2 value
)
4639 (org-set-local 'org-use-sub-superscripts scripts
)
4641 (org-set-local 'org-category
(intern cat
))
4642 (push (cons "CATEGORY" cat
) props
))
4644 (if (< (length prio
) 3) (setq prio
'("A" "C" "B")))
4645 (setq prio
(mapcar 'string-to-char prio
))
4646 (org-set-local 'org-highest-priority
(nth 0 prio
))
4647 (org-set-local 'org-lowest-priority
(nth 1 prio
))
4648 (org-set-local 'org-default-priority
(nth 2 prio
)))
4649 (and props
(org-set-local 'org-file-properties
(nreverse props
)))
4650 (and ftags
(org-set-local 'org-file-tags
4651 (mapcar 'org-add-prop-inherited ftags
)))
4652 (and drawers
(org-set-local 'org-drawers drawers
))
4653 (and arch
(org-set-local 'org-archive-location arch
))
4654 (and links
(setq org-link-abbrev-alist-local
(nreverse links
)))
4655 ;; Process the TODO keywords
4657 ;; Use the global values as if they had been given locally.
4658 (setq kwds
(default-value 'org-todo-keywords
))
4659 (if (stringp (car kwds
))
4660 (setq kwds
(list (cons org-todo-interpretation
4661 (default-value 'org-todo-keywords
)))))
4662 (setq kwds
(reverse kwds
)))
4663 (setq kwds
(nreverse kwds
))
4665 (while (setq kws
(pop kwds
))
4667 (run-hook-with-args-until-success
4668 'org-todo-setup-filter-hook kws
)
4670 (setq inter
(pop kws
) sep
(member "|" kws
)
4671 kws0
(delete "|" (copy-sequence kws
))
4676 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x
)
4678 (setq kw
(match-string 1 x
)
4679 key
(and (match-end 2) (match-string 2 x
))
4680 log
(org-extract-log-state-settings x
))
4681 (push (cons kw
(and key
(string-to-char key
))) kwsa
)
4682 (and log
(push log org-todo-log-states
))
4684 (error "Invalid TODO keyword %s" x
)))
4686 kwsa
(if kwsa
(append '((:startgroup
))
4690 dws
(if sep
(org-remove-keyword-keys (cdr sep
)) (last kws1
))
4691 tail
(list inter hw
(car dws
) (org-last dws
))))
4692 (add-to-list 'org-todo-heads hw
'append
)
4693 (push kws1 org-todo-sets
)
4694 (setq org-done-keywords
(append org-done-keywords dws nil
))
4695 (setq org-todo-key-alist
(append org-todo-key-alist kwsa
))
4696 (mapc (lambda (x) (push (cons x tail
) org-todo-kwd-alist
)) kws1
)
4697 (setq org-todo-keywords-1
(append org-todo-keywords-1 kws1 nil
)))
4698 (setq org-todo-sets
(nreverse org-todo-sets
)
4699 org-todo-kwd-alist
(nreverse org-todo-kwd-alist
)
4700 org-todo-key-trigger
(delq nil
(mapcar 'cdr org-todo-key-alist
))
4701 org-todo-key-alist
(org-assign-fast-keys org-todo-key-alist
)))
4702 ;; Process the constants
4705 (while (setq e
(pop const
))
4706 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e
)
4707 (push (cons (match-string 1 e
) (match-string 2 e
)) cst
)))
4708 (setq org-table-formula-constants-local cst
)))
4710 ;; Process the tags.
4713 (while (setq e
(pop tags
))
4715 ((equal e
"{") (push '(:startgroup
) tgs
))
4716 ((equal e
"}") (push '(:endgroup
) tgs
))
4717 ((equal e
"\\n") (push '(:newline
) tgs
))
4718 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e
)
4719 (push (cons (match-string 1 e
)
4720 (string-to-char (match-string 2 e
)))
4722 (t (push (list e
) tgs
))))
4723 (org-set-local 'org-tag-alist nil
)
4724 (while (setq e
(pop tgs
))
4725 (or (and (stringp (car e
))
4726 (assoc (car e
) org-tag-alist
))
4727 (push e org-tag-alist
)))))
4729 ;; Compute the regular expressions and other local variables.
4730 ;; Using `org-outline-regexp-bol' would complicate them much,
4731 ;; because of the fixed white space at the end of that string.
4732 (if (not org-done-keywords
)
4733 (setq org-done-keywords
(and org-todo-keywords-1
4734 (list (org-last org-todo-keywords-1
)))))
4735 (setq org-ds-keyword-length
(+ 2 (max (length org-deadline-string
)
4736 (length org-scheduled-string
)
4737 (length org-clock-string
)
4738 (length org-closed-string
)))
4740 (concat "^[ \t]*:\\("
4741 (mapconcat 'regexp-quote org-drawers
"\\|")
4743 org-not-done-keywords
4744 (org-delete-all org-done-keywords
(copy-sequence org-todo-keywords-1
))
4747 (mapconcat 'regexp-quote org-todo-keywords-1
"\\|")
4751 (mapconcat 'regexp-quote org-not-done-keywords
"\\|")
4753 org-not-done-heading-regexp
4754 (format org-heading-keyword-regexp-format org-not-done-regexp
)
4755 org-todo-line-regexp
4756 (format org-heading-keyword-maybe-regexp-format org-todo-regexp
)
4757 org-complex-heading-regexp
4758 (concat "^\\(\\*+\\)"
4759 "\\(?: +" org-todo-regexp
"\\)?"
4760 "\\(?: +\\(\\[#.\\]\\)\\)?"
4761 "\\(?: +\\(.*?\\)\\)?"
4762 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4764 org-complex-heading-regexp-format
4765 (concat "^\\(\\*+\\)"
4766 "\\(?: +" org-todo-regexp
"\\)?"
4767 "\\(?: +\\(\\[#.\\]\\)\\)?"
4769 ;; Stats cookies can be stuck to body.
4770 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4772 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4774 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4776 org-todo-line-tags-regexp
4777 (concat "^\\(\\*+\\)"
4778 "\\(?: +" org-todo-regexp
"\\)?"
4779 "\\(?: +\\(.*?\\)\\)?"
4780 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4782 org-deadline-regexp
(concat "\\<" org-deadline-string
)
4783 org-deadline-time-regexp
4784 (concat "\\<" org-deadline-string
" *<\\([^>]+\\)>")
4785 org-deadline-line-regexp
4786 (concat "\\<\\(" org-deadline-string
"\\).*")
4787 org-scheduled-regexp
4788 (concat "\\<" org-scheduled-string
)
4789 org-scheduled-time-regexp
4790 (concat "\\<" org-scheduled-string
" *<\\([^>]+\\)>")
4791 org-closed-time-regexp
4792 (concat "\\<" org-closed-string
" *\\[\\([^]]+\\)\\]")
4793 org-keyword-time-regexp
4794 (concat "\\<\\(" org-scheduled-string
4795 "\\|" org-deadline-string
4796 "\\|" org-closed-string
4797 "\\|" org-clock-string
"\\)"
4798 " *[[<]\\([^]>]+\\)[]>]")
4799 org-keyword-time-not-clock-regexp
4800 (concat "\\<\\(" org-scheduled-string
4801 "\\|" org-deadline-string
4802 "\\|" org-closed-string
4804 " *[[<]\\([^]>]+\\)[]>]")
4805 org-maybe-keyword-time-regexp
4806 (concat "\\(\\<\\(" org-scheduled-string
4807 "\\|" org-deadline-string
4808 "\\|" org-closed-string
4809 "\\|" org-clock-string
"\\)\\)?"
4810 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4811 org-planning-or-clock-line-re
4812 (concat "^[ \t]*\\("
4813 org-scheduled-string
"\\|"
4814 org-deadline-string
"\\|"
4815 org-closed-string
"\\|"
4816 org-clock-string
"\\)")
4817 org-all-time-keywords
4818 (mapcar (lambda (w) (substring w
0 -
1))
4819 (list org-scheduled-string org-deadline-string
4820 org-clock-string org-closed-string
))
4822 (org-compute-latex-and-specials-regexp)
4823 (org-set-font-lock-defaults))))
4825 (defun org-file-contents (file &optional noerror
)
4826 "Return the contents of FILE, as a string."
4828 (not (file-readable-p file
)))
4831 (message "Cannot read file \"%s\"" file
)
4834 (error "Cannot read file \"%s\"" file
))
4836 (insert-file-contents file
)
4839 (defun org-extract-log-state-settings (x)
4840 "Extract the log state setting from a TODO keyword string.
4841 This will extract info from a string like \"WAIT(w@/!)\"."
4842 (let (kw key log1 log2
)
4843 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x
)
4844 (setq kw
(match-string 1 x
)
4845 key
(and (match-end 2) (match-string 2 x
))
4846 log1
(and (match-end 3) (match-string 3 x
))
4847 log2
(and (match-end 4) (match-string 4 x
)))
4850 (and log1
(if (equal log1
"!") 'time
'note
))
4851 (and log2
(if (equal log2
"!") 'time
'note
)))))))
4853 (defun org-remove-keyword-keys (list)
4854 "Remove a pair of parenthesis at the end of each string in LIST."
4856 (if (string-match "(.*)$" x
)
4857 (substring x
0 (match-beginning 0))
4861 (defun org-assign-fast-keys (alist)
4862 "Assign fast keys to a keyword-key alist.
4863 Respect keys that are already there."
4864 (let (new e
(alt ?
0))
4865 (while (setq e
(pop alist
))
4866 (if (or (memq (car e
) '(:newline
:endgroup
:startgroup
))
4867 (cdr e
)) ;; Key already assigned.
4869 (let ((clist (string-to-list (downcase (car e
))))
4870 (used (append new alist
)))
4871 (when (= (car clist
) ?
@)
4873 (while (and clist
(rassoc (car clist
) used
))
4876 (while (rassoc alt used
)
4878 (push (cons (car e
) (or (car clist
) alt
)) new
))))
4881 ;;; Some variables used in various places
4883 (defvar org-window-configuration nil
4884 "Used in various places to store a window configuration.")
4885 (defvar org-selected-window nil
4886 "Used in various places to store a window configuration.")
4887 (defvar org-finish-function nil
4888 "Function to be called when `C-c C-c' is used.
4889 This is for getting out of special buffers like remember.")
4892 ;; FIXME: Occasionally check by commenting these, to make sure
4893 ;; no other functions uses these, forgetting to let-bind them.
4895 (defvar org-last-state
)
4898 ;; Defined somewhere in this file, but used before definition.
4899 (defvar org-entities
) ;; defined in org-entities.el
4900 (defvar org-struct-menu
)
4901 (defvar org-org-menu
)
4902 (defvar org-tbl-menu
)
4904 ;;;; Define the Org-mode
4906 (if (and (not (keymapp outline-mode-map
)) (featurep 'allout
))
4907 (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"))
4910 ;; We use a before-change function to check if a table might need
4912 (defvar org-table-may-need-update t
4913 "Indicates that a table might need an update.
4914 This variable is set by `org-before-change-function'.
4915 `org-table-align' sets it back to nil.")
4916 (defun org-before-change-function (beg end
)
4917 "Every change indicates that a table might need an update."
4918 (setq org-table-may-need-update t
))
4919 (defvar org-mode-map
)
4920 (defvar org-inhibit-startup nil
) ; Dynamically-scoped param.
4921 (defvar org-inhibit-startup-visibility-stuff nil
) ; Dynamically-scoped param.
4922 (defvar org-agenda-keep-modes nil
) ; Dynamically-scoped param.
4923 (defvar org-inhibit-logging nil
) ; Dynamically-scoped param.
4924 (defvar org-inhibit-blocking nil
) ; Dynamically-scoped param.
4925 (defvar org-table-buffer-is-an nil
)
4927 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4928 ;; some places -- e.g. see the macro org-with-limited-levels.
4930 ;; In Org buffers, the value of `outline-regexp' is that of
4931 ;; `org-outline-regexp'. The only function still directly relying on
4932 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4933 ;; job when `orgstruct-mode' is active.
4934 (defvar org-outline-regexp
"\\*+ "
4935 "Regexp to match Org headlines.")
4936 (defconst org-outline-regexp-bol
"^\\*+ "
4937 "Regexp to match Org headlines.
4938 This is similar to `org-outline-regexp' but additionally makes
4939 sure that we are at the beginning of the line.")
4941 (defconst org-heading-regexp
"^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4942 "Matches an headline, putting stars and text into groups.
4943 Stars are put in group 1 and the trimmed body in group 2.")
4945 (defvar bidi-paragraph-direction
)
4946 (defvar buffer-face-mode-face
)
4949 (define-derived-mode org-mode outline-mode
"Org"
4950 "Outline-based notes management and organizer, alias
4951 \"Carsten's outline-mode for keeping track of everything.\"
4953 Org-mode develops organizational tasks around a NOTES file which
4954 contains information about projects as plain text. Org-mode is
4955 implemented on top of outline-mode, which is ideal to keep the content
4956 of large files well structured. It supports ToDo items, deadlines and
4957 time stamps, which magically appear in the diary listing of the Emacs
4958 calendar. Tables are easily created with a built-in table editor.
4959 Plain text URL-like links connect to websites, emails (VM), Usenet
4960 messages (Gnus), BBDB entries, and any files related to the project.
4961 For printing and sharing of notes, an Org-mode file (or a part of it)
4962 can be exported as a structured ASCII or HTML file.
4964 The following commands are available:
4968 ;; Get rid of Outline menus, they are not needed
4969 ;; Need to do this here because define-derived-mode sets up
4970 ;; the keymap so late. Still, it is a waste to call this each time
4971 ;; we switch another buffer into org-mode.
4972 (if (featurep 'xemacs
)
4973 (when (boundp 'outline-mode-menu-heading
)
4974 ;; Assume this is Greg's port, it uses easymenu
4975 (easy-menu-remove outline-mode-menu-heading
)
4976 (easy-menu-remove outline-mode-menu-show
)
4977 (easy-menu-remove outline-mode-menu-hide
))
4978 (define-key org-mode-map
[menu-bar headings
] 'undefined
)
4979 (define-key org-mode-map
[menu-bar hide
] 'undefined
)
4980 (define-key org-mode-map
[menu-bar show
] 'undefined
))
4982 (org-load-modules-maybe)
4983 (easy-menu-add org-org-menu
)
4984 (easy-menu-add org-tbl-menu
)
4985 (org-install-agenda-files-menu)
4986 (if org-descriptive-links
(add-to-invisibility-spec '(org-link)))
4987 (add-to-invisibility-spec '(org-cwidth))
4988 (add-to-invisibility-spec '(org-hide-block . t
))
4989 (when (featurep 'xemacs
)
4990 (org-set-local 'line-move-ignore-invisible t
))
4991 (org-set-local 'outline-regexp org-outline-regexp
)
4992 (org-set-local 'outline-level
'org-outline-level
)
4993 (setq bidi-paragraph-direction
'left-to-right
)
4994 (when (and org-ellipsis
4995 (fboundp 'set-display-table-slot
) (boundp 'buffer-display-table
)
4996 (fboundp 'make-glyph-code
))
4997 (unless org-display-table
4998 (setq org-display-table
(make-display-table)))
4999 (set-display-table-slot
5002 (lambda (c) (make-glyph-code c
(and (not (stringp org-ellipsis
))
5004 (if (stringp org-ellipsis
) org-ellipsis
"..."))))
5005 (setq buffer-display-table org-display-table
))
5006 (org-set-regexps-and-options)
5007 (when (and org-tag-faces
(not org-tags-special-faces-re
))
5008 ;; tag faces set outside customize.... force initialization.
5009 (org-set-tag-faces 'org-tag-faces org-tag-faces
))
5011 (org-set-local 'calc-embedded-open-mode
"# ")
5012 (modify-syntax-entry ?
@ "w")
5013 (if org-startup-truncated
(setq truncate-lines t
))
5014 (org-set-local 'font-lock-unfontify-region-function
5015 'org-unfontify-region
)
5016 ;; Activate before-change-function
5017 (org-set-local 'org-table-may-need-update t
)
5018 (org-add-hook 'before-change-functions
'org-before-change-function nil
5020 ;; Check for running clock before killing a buffer
5021 (org-add-hook 'kill-buffer-hook
'org-check-running-clock nil
'local
)
5022 ;; Paragraphs and auto-filling
5023 (org-set-autofill-regexps)
5024 (setq indent-line-function
'org-indent-line-function
)
5025 (org-update-radio-target-regexp)
5026 ;; Beginning/end of defun
5027 (org-set-local 'beginning-of-defun-function
'org-beginning-of-defun
)
5028 (org-set-local 'end-of-defun-function
'org-end-of-defun
)
5029 ;; Next error for sparse trees
5030 (org-set-local 'next-error-function
'org-occur-next-match
)
5031 ;; Make sure dependence stuff works reliably, even for users who set it
5033 (if org-enforce-todo-dependencies
5034 (add-hook 'org-blocker-hook
5035 'org-block-todo-from-children-or-siblings-or-parent
)
5036 (remove-hook 'org-blocker-hook
5037 'org-block-todo-from-children-or-siblings-or-parent
))
5038 (if org-enforce-todo-checkbox-dependencies
5039 (add-hook 'org-blocker-hook
5040 'org-block-todo-from-checkboxes
)
5041 (remove-hook 'org-blocker-hook
5042 'org-block-todo-from-checkboxes
))
5044 ;; Comment characters
5045 (org-set-local 'comment-start
"#")
5046 (org-set-local 'comment-padding
" ")
5048 ;; Align options lines
5050 'align-mode-rules-list
5051 '((org-in-buffer-settings
5052 (regexp .
"^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5053 (modes .
'(org-mode)))))
5056 (org-set-local 'imenu-create-index-function
5057 'org-imenu-get-tree
)
5059 ;; Make isearch reveal context
5060 (if (or (featurep 'xemacs
)
5061 (not (boundp 'outline-isearch-open-invisible-function
)))
5062 ;; Emacs 21 and XEmacs make use of the hook
5063 (org-add-hook 'isearch-mode-end-hook
'org-isearch-end
'append
'local
)
5064 ;; Emacs 22 deals with this through a special variable
5065 (org-set-local 'outline-isearch-open-invisible-function
5066 (lambda (&rest ignore
) (org-show-context 'isearch
))))
5068 ;; Turn on org-beamer-mode?
5069 (and org-startup-with-beamer-mode
(org-beamer-mode 1))
5071 ;; Setup the pcomplete hooks
5072 (set (make-local-variable 'pcomplete-command-completion-function
)
5073 'org-pcomplete-initial
)
5074 (set (make-local-variable 'pcomplete-command-name-function
)
5075 'org-command-at-point
)
5076 (set (make-local-variable 'pcomplete-default-completion-function
)
5078 (set (make-local-variable 'pcomplete-parse-arguments-function
)
5079 'org-parse-arguments
)
5080 (set (make-local-variable 'pcomplete-termination-string
) "")
5081 (when (>= emacs-major-version
23)
5082 (set (make-local-variable 'buffer-face-mode-face
) 'org-default
))
5084 ;; If empty file that did not turn on org-mode automatically, make it to.
5085 (if (and org-insert-mode-line-in-empty-file
5086 (org-called-interactively-p 'any
)
5087 (= (point-min) (point-max)))
5088 (insert "# -*- mode: org -*-\n\n"))
5089 (unless org-inhibit-startup
5090 (when org-startup-align-all-tables
5091 (let ((bmp (buffer-modified-p)))
5092 (org-table-map-tables 'org-table-align
'quietly
)
5093 (set-buffer-modified-p bmp
)))
5094 (when org-startup-with-inline-images
5095 (org-display-inline-images))
5096 (when org-startup-indented
5097 (require 'org-indent
)
5098 (org-indent-mode 1))
5099 (unless org-inhibit-startup-visibility-stuff
5100 (org-set-startup-visibility))))
5102 (when (fboundp 'abbrev-table-put
)
5103 (abbrev-table-put org-mode-abbrev-table
5104 :parents
(list text-mode-abbrev-table
)))
5106 (put 'org-mode
'flyspell-mode-predicate
'org-mode-flyspell-verify
)
5108 (defun org-current-time ()
5109 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5110 (if (> (car org-time-stamp-rounding-minutes
) 1)
5111 (let ((r (car org-time-stamp-rounding-minutes
))
5112 (time (decode-time)))
5114 (append (list 0 (* r
(floor (+ .5 (/ (float (nth 1 time
)) r
)))))
5119 "Return today date, considering `org-extend-today-until'."
5121 (time-subtract (current-time)
5122 (list 0 (* 3600 org-extend-today-until
) 0))))
5124 ;;;; Font-Lock stuff, including the activators
5126 (defvar org-mouse-map
(make-sparse-keymap))
5127 (org-defkey org-mouse-map
[mouse-2
] 'org-open-at-mouse
)
5128 (org-defkey org-mouse-map
[mouse-3
] 'org-find-file-at-mouse
)
5129 (when org-mouse-1-follows-link
5130 (org-defkey org-mouse-map
[follow-link
] 'mouse-face
))
5131 (when org-tab-follows-link
5132 (org-defkey org-mouse-map
[(tab)] 'org-open-at-point
)
5133 (org-defkey org-mouse-map
"\C-i" 'org-open-at-point
))
5135 (require 'font-lock
)
5137 (defconst org-non-link-chars
"]\t\n\r<>")
5138 (defvar org-link-types
'("http" "https" "ftp" "mailto" "file" "news"
5139 "shell" "elisp" "doi" "message"))
5140 (defvar org-link-types-re nil
5141 "Matches a link that has a url-like prefix like \"http:\"")
5142 (defvar org-link-re-with-space nil
5143 "Matches a link with spaces, optional angular brackets around it.")
5144 (defvar org-link-re-with-space2 nil
5145 "Matches a link with spaces, optional angular brackets around it.")
5146 (defvar org-link-re-with-space3 nil
5147 "Matches a link with spaces, only for internal part in bracket links.")
5148 (defvar org-angle-link-re nil
5149 "Matches link with angular brackets, spaces are allowed.")
5150 (defvar org-plain-link-re nil
5151 "Matches plain link, without spaces.")
5152 (defvar org-bracket-link-regexp nil
5153 "Matches a link in double brackets.")
5154 (defvar org-bracket-link-analytic-regexp nil
5155 "Regular expression used to analyze links.
5156 Here is what the match groups contain after a match:
5162 (defvar org-bracket-link-analytic-regexp
++ nil
5163 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5164 (defvar org-any-link-re nil
5165 "Regular expression matching any link.")
5167 (defcustom org-match-sexp-depth
3
5168 "Number of stacked braces for sub/superscript matching.
5169 This has to be set before loading org.el to be effective."
5170 :group
'org-export-translation
; ??????????????????????????/
5173 (defun org-create-multibrace-regexp (left right n
)
5174 "Create a regular expression which will match a balanced sexp.
5175 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5176 as single character strings.
5177 The regexp returned will match the entire expression including the
5178 delimiters. It will also define a single group which contains the
5179 match except for the outermost delimiters. The maximum depth of
5180 stacked delimiters is N. Escaping delimiters is not possible."
5181 (let* ((nothing (concat "[^" left right
"]*?"))
5184 (next (concat "\\(?:" nothing left nothing right
"\\)+" nothing
)))
5187 re
(concat re or next
)
5188 next
(concat "\\(?:" nothing left next right
"\\)+" nothing
)))
5189 (concat left
"\\(" re
"\\)" right
)))
5191 (defvar org-match-substring-regexp
5193 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5194 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth
) "\\)"
5196 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth
) "\\)"
5198 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5199 "The regular expression matching a sub- or superscript.")
5201 (defvar org-match-substring-with-braces-regexp
5203 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5204 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth
) "\\)"
5206 "The regular expression matching a sub- or superscript, forcing braces.")
5208 (defun org-make-link-regexps ()
5209 "Update the link regular expressions.
5210 This should be called after the variable `org-link-types' has changed."
5211 (setq org-link-types-re
5213 "\\`\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):")
5214 org-link-re-with-space
5216 "<?\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):"
5217 "\\([^" org-non-link-chars
" ]"
5218 "[^" org-non-link-chars
"]*"
5219 "[^" org-non-link-chars
" ]\\)>?")
5220 org-link-re-with-space2
5222 "<?\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):"
5223 "\\([^" org-non-link-chars
" ]"
5225 "[^" org-non-link-chars
" ]\\)>?")
5226 org-link-re-with-space3
5228 "<?\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):"
5229 "\\([^" org-non-link-chars
" ]"
5233 "<\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):"
5234 "\\([^" org-non-link-chars
" ]"
5235 "[^" org-non-link-chars
"]*"
5239 "\\<\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):"
5240 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5241 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5242 org-bracket-link-regexp
5243 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5244 org-bracket-link-analytic-regexp
5247 "\\(\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):\\)?"
5250 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5252 org-bracket-link-analytic-regexp
++
5255 "\\(\\(" (mapconcat 'regexp-quote
(cons "coderef" org-link-types
) "\\|") "\\):\\)?"
5258 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5261 (concat "\\(" org-bracket-link-regexp
"\\)\\|\\("
5262 org-angle-link-re
"\\)\\|\\("
5263 org-plain-link-re
"\\)")))
5265 (org-make-link-regexps)
5267 (defconst org-ts-regexp
"<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5268 "Regular expression for fast time stamp matching.")
5269 (defconst org-ts-regexp-both
"[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5270 "Regular expression for fast time stamp matching.")
5271 (defconst org-ts-regexp0
5272 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5273 "Regular expression matching time strings for analysis.
5274 This one does not require the space after the date, so it can be used
5275 on a string that terminates immediately after the date.")
5276 (defconst org-ts-regexp1
"\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5277 "Regular expression matching time strings for analysis.")
5278 (defconst org-ts-regexp2
(concat "<" org-ts-regexp1
"[^>\n]\\{0,16\\}>")
5279 "Regular expression matching time stamps, with groups.")
5280 (defconst org-ts-regexp3
(concat "[[<]" org-ts-regexp1
"[^]>\n]\\{0,16\\}[]>]")
5281 "Regular expression matching time stamps (also [..]), with groups.")
5282 (defconst org-tr-regexp
(concat org-ts-regexp
"--?-?" org-ts-regexp
)
5283 "Regular expression matching a time stamp range.")
5284 (defconst org-tr-regexp-both
5285 (concat org-ts-regexp-both
"--?-?" org-ts-regexp-both
)
5286 "Regular expression matching a time stamp range.")
5287 (defconst org-tsr-regexp
(concat org-ts-regexp
"\\(--?-?"
5288 org-ts-regexp
"\\)?")
5289 "Regular expression matching a time stamp or time stamp range.")
5290 (defconst org-tsr-regexp-both
(concat org-ts-regexp-both
"\\(--?-?"
5291 org-ts-regexp-both
"\\)?")
5292 "Regular expression matching a time stamp or time stamp range.
5293 The time stamps may be either active or inactive.")
5295 (defvar org-emph-face nil
)
5297 (defun org-do-emphasis-faces (limit)
5298 "Run through the buffer and add overlays to emphasized strings."
5300 (while (and (not rtn
) (re-search-forward org-emph-re limit t
))
5301 (if (not (= (char-after (match-beginning 3))
5302 (char-after (match-beginning 4))))
5305 (setq a
(assoc (match-string 3) org-emphasis-alist
))
5306 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5310 (org-remove-flyspell-overlays-in
5311 (match-beginning 0) (match-end 0)))
5312 (add-text-properties (match-beginning 2) (match-end 2)
5313 '(font-lock-multiline t org-emphasis t
))
5314 (when org-hide-emphasis-markers
5315 (add-text-properties (match-end 4) (match-beginning 5)
5316 '(invisible org-link
))
5317 (add-text-properties (match-beginning 3) (match-end 3)
5318 '(invisible org-link
)))))
5322 (defun org-emphasize (&optional char
)
5323 "Insert or change an emphasis, i.e. a font like bold or italic.
5324 If there is an active region, change that region to a new emphasis.
5325 If there is no region, just insert the marker characters and position
5326 the cursor between them.
5327 CHAR should be either the marker character, or the first character of the
5328 HTML tag associated with that emphasis. If CHAR is a space, the means
5329 to remove the emphasis of the selected region.
5330 If char is not given (for example in an interactive call) it
5331 will be prompted for."
5333 (let ((eal org-emphasis-alist
) e det
5334 (erc org-emphasis-regexp-components
)
5336 (string "") beg end move tag c s
)
5337 (if (org-region-active-p)
5338 (setq beg
(region-beginning) end
(region-end)
5339 string
(buffer-substring beg end
))
5342 (while (setq e
(pop eal
))
5343 (setq tag
(car (org-split-string (nth 2 e
) "[ <>/]+"))
5345 (push (cons c
(string-to-char (car e
))) det
)
5346 (setq prompt
(concat prompt
(format " [%s%c]%s" (car e
) c
5347 (substring tag
1)))))
5348 (setq det
(nreverse det
))
5350 (message "%s" (concat "Emphasis marker or tag:" prompt
))
5351 (setq char
(read-char-exclusive)))
5352 (setq char
(or (cdr (assoc char det
)) char
))
5353 (if (equal char ?\
)
5354 (setq s
"" move nil
)
5355 (unless (assoc (char-to-string char
) org-emphasis-alist
)
5356 (error "No such emphasis marker: \"%c\"" char
))
5357 (setq s
(char-to-string char
)))
5358 (while (and (> (length string
) 1)
5359 (equal (substring string
0 1) (substring string -
1))
5360 (assoc (substring string
0 1) org-emphasis-alist
))
5361 (setq string
(substring string
1 -
1)))
5362 (setq string
(concat s string s
))
5363 (if beg
(delete-region beg end
))
5365 (string-match (concat "[" (nth 0 erc
) "\n]")
5366 (char-to-string (char-before (point)))))
5369 (string-match (concat "[" (nth 1 erc
) "\n]")
5370 (char-to-string (char-after (point)))))
5371 (insert " ") (backward-char 1))
5373 (and move
(backward-char 1))))
5375 (defconst org-nonsticky-props
5376 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text
))
5378 (defsubst org-rear-nonsticky-at
(pos)
5379 (add-text-properties (1- pos
) pos
(list 'rear-nonsticky org-nonsticky-props
)))
5381 (defun org-activate-plain-links (limit)
5382 "Run through the buffer and add overlays to links."
5385 (if (re-search-forward org-plain-link-re limit t
)
5387 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5388 (setq f
(get-text-property (match-beginning 0) 'face
))
5389 (if (or (eq f
'org-tag
)
5390 (and (listp f
) (memq 'org-tag f
)))
5392 (add-text-properties (match-beginning 0) (match-end 0)
5393 (list 'mouse-face
'highlight
5395 'keymap org-mouse-map
))
5396 (org-rear-nonsticky-at (match-end 0)))
5399 (defun org-activate-code (limit)
5400 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t
)
5402 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5403 (remove-text-properties (match-beginning 0) (match-end 0)
5404 '(display t invisible t intangible t
))
5407 (defcustom org-src-fontify-natively nil
5408 "When non-nil, fontify code in code blocks."
5411 :group
'org-appearance
5414 (defcustom org-src-prevent-auto-filling nil
5415 "When non-nil, prevent auto-filling in src blocks."
5418 :group
'org-appearance
5421 (defun org-fontify-meta-lines-and-blocks (limit)
5423 (org-fontify-meta-lines-and-blocks-1 limit
)
5424 (error (message "org-mode fontification error"))))
5426 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5427 "Fontify #+ lines and blocks, in the correct ways."
5428 (let ((case-fold-search t
))
5429 (if (re-search-forward
5430 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5432 (let ((beg (match-beginning 0))
5433 (block-start (match-end 0))
5435 (lang (match-string 7))
5436 (beg1 (line-beginning-position 2))
5437 (dc1 (downcase (match-string 2)))
5438 (dc3 (downcase (match-string 3)))
5439 end end1 quoting block-type ovl
)
5441 ((member dc1
'("html:" "ascii:" "latex:" "docbook:"))
5442 ;; a single line of backend-specific content
5443 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5444 (remove-text-properties (match-beginning 0) (match-end 0)
5445 '(display t invisible t intangible t
))
5446 (add-text-properties (match-beginning 1) (match-end 3)
5447 '(font-lock-fontified t face org-meta-line
))
5448 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5449 '(font-lock-fontified t face org-block
))
5450 ; for backend-specific code
5452 ((and (match-end 4) (equal dc3
"begin"))
5454 (setq block-type
(downcase (match-string 5))
5455 quoting
(member block-type org-protecting-blocks
))
5456 (when (re-search-forward
5457 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5458 nil t
) ;; on purpose, we look further than LIMIT
5459 (setq end
(min (point-max) (match-end 0))
5460 end1
(min (point-max) (1- (match-beginning 0))))
5461 (setq block-end
(match-beginning 0))
5463 (remove-text-properties beg end
5464 '(display t invisible t intangible t
)))
5465 (add-text-properties
5467 '(font-lock-fontified t font-lock-multiline t
))
5468 (add-text-properties beg beg1
'(face org-meta-line
))
5469 (add-text-properties end1
(min (point-max) (1+ end
))
5470 '(face org-meta-line
)) ; for end_src
5472 ((and lang
(not (string= lang
"")) org-src-fontify-natively
)
5473 (org-src-font-lock-fontify-block lang block-start block-end
)
5474 ;; remove old background overlays
5476 (if (eq (overlay-get ov
'face
) 'org-block-background
)
5477 (delete-overlay ov
)))
5478 (overlays-at (/ (+ beg1 block-end
) 2)))
5479 ;; add a background overlay
5480 (setq ovl
(make-overlay beg1 block-end
))
5481 (overlay-put ovl
'face
'org-block-background
)
5482 (overlay-put ovl
'evaporate t
)) ;; make it go away when empty
5484 (add-text-properties beg1
(min (point-max) (1+ end1
))
5485 '(face org-block
))) ; end of source block
5486 ((not org-fontify-quote-and-verse-blocks
))
5487 ((string= block-type
"quote")
5488 (add-text-properties beg1
(min (point-max) (1+ end1
)) '(face org-quote
)))
5489 ((string= block-type
"verse")
5490 (add-text-properties beg1
(min (point-max) (1+ end1
)) '(face org-verse
))))
5491 (add-text-properties beg beg1
'(face org-block-begin-line
))
5492 (add-text-properties (min (point-max) (1+ end
)) (min (point-max) (1+ end1
))
5493 '(face org-block-end-line
))
5495 ((member dc1
'("title:" "author:" "email:" "date:"))
5496 (add-text-properties
5498 (if (member (intern (substring dc1
0 -
1)) org-hidden-keywords
)
5499 '(font-lock-fontified t invisible t
)
5500 '(font-lock-fontified t face org-document-info-keyword
)))
5501 (add-text-properties
5502 (match-beginning 6) (match-end 6)
5503 (if (string-equal dc1
"title:")
5504 '(font-lock-fontified t face org-document-title
)
5505 '(font-lock-fontified t face org-document-info
))))
5506 ((not (member (char-after beg
) '(?\ ?
\t)))
5507 ;; just any other in-buffer setting, but not indented
5508 (add-text-properties
5510 '(font-lock-fontified t face org-meta-line
))
5512 ((or (member dc1
'("begin:" "end:" "caption:" "label:"
5513 "orgtbl:" "tblfm:" "tblname:" "results:"
5514 "call:" "header:" "headers:" "name:"))
5515 (and (match-end 4) (equal dc3
"attr")))
5516 (add-text-properties
5518 '(font-lock-fontified t face org-meta-line
))
5520 ((member dc3
'(" " ""))
5521 (add-text-properties
5523 '(font-lock-fontified t face font-lock-comment-face
)))
5526 (defun org-strip-protective-commas (beg end
)
5527 "Strip protective commas between BEG and END in the current buffer."
5532 (let ((front-line (save-excursion
5534 "[^[:space:]]" end t
)
5535 (goto-char (match-beginning 0))
5537 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\+\\)" end t
)
5538 (goto-char (match-beginning 1))
5539 (when (= (current-column) front-line
)
5540 (replace-match "" nil nil nil
1)))))))
5542 (defun org-activate-angle-links (limit)
5543 "Run through the buffer and add overlays to links."
5544 (if (re-search-forward org-angle-link-re limit t
)
5546 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5547 (add-text-properties (match-beginning 0) (match-end 0)
5548 (list 'mouse-face
'highlight
5549 'keymap org-mouse-map
))
5550 (org-rear-nonsticky-at (match-end 0))
5553 (defun org-activate-footnote-links (limit)
5554 "Run through the buffer and add overlays to footnotes."
5555 (let ((fn (org-footnote-next-reference-or-definition limit
)))
5557 (let ((beg (nth 1 fn
)) (end (nth 2 fn
)))
5558 (org-remove-flyspell-overlays-in beg end
)
5559 (add-text-properties beg end
5560 (list 'mouse-face
'highlight
5561 'keymap org-mouse-map
5563 (if (= (point-at-bol) beg
)
5564 "Footnote definition"
5565 "Footnote reference")
5566 'font-lock-fontified t
5567 'font-lock-multiline t
5568 'face
'org-footnote
))))))
5570 (defun org-activate-bracket-links (limit)
5571 "Run through the buffer and add overlays to bracketed links."
5572 (if (re-search-forward org-bracket-link-regexp limit t
)
5573 (let* ((help (concat "LINK: "
5574 (org-match-string-no-properties 1)))
5575 ;; FIXME: above we should remove the escapes.
5576 ;; but that requires another match, protecting match data,
5577 ;; a lot of overhead for font-lock.
5578 (ip (org-maybe-intangible
5579 (list 'invisible
'org-link
5580 'keymap org-mouse-map
'mouse-face
'highlight
5581 'font-lock-multiline t
'help-echo help
)))
5582 (vp (list 'keymap org-mouse-map
'mouse-face
'highlight
5583 'font-lock-multiline t
'help-echo help
)))
5584 ;; We need to remove the invisible property here. Table narrowing
5585 ;; may have made some of this invisible.
5586 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5587 (remove-text-properties (match-beginning 0) (match-end 0)
5591 (add-text-properties (match-beginning 0) (match-beginning 3) ip
)
5592 (org-rear-nonsticky-at (match-beginning 3))
5593 (add-text-properties (match-beginning 3) (match-end 3) vp
)
5594 (org-rear-nonsticky-at (match-end 3))
5595 (add-text-properties (match-end 3) (match-end 0) ip
)
5596 (org-rear-nonsticky-at (match-end 0)))
5597 (add-text-properties (match-beginning 0) (match-beginning 1) ip
)
5598 (org-rear-nonsticky-at (match-beginning 1))
5599 (add-text-properties (match-beginning 1) (match-end 1) vp
)
5600 (org-rear-nonsticky-at (match-end 1))
5601 (add-text-properties (match-end 1) (match-end 0) ip
)
5602 (org-rear-nonsticky-at (match-end 0)))
5605 (defun org-activate-dates (limit)
5606 "Run through the buffer and add overlays to dates."
5607 (if (re-search-forward org-tsr-regexp-both limit t
)
5609 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5610 (add-text-properties (match-beginning 0) (match-end 0)
5611 (list 'mouse-face
'highlight
5612 'keymap org-mouse-map
))
5613 (org-rear-nonsticky-at (match-end 0))
5614 (when org-display-custom-times
5616 (org-display-custom-time (match-beginning 3) (match-end 3)))
5617 (org-display-custom-time (match-beginning 1) (match-end 1)))
5620 (defvar org-target-link-regexp nil
5621 "Regular expression matching radio targets in plain text.")
5622 (make-variable-buffer-local 'org-target-link-regexp
)
5623 (defvar org-target-regexp
"<<\\([^<>\n\r]+\\)>>"
5624 "Regular expression matching a link target.")
5625 (defvar org-radio-target-regexp
"<<<\\([^<>\n\r]+\\)>>>"
5626 "Regular expression matching a radio target.")
5627 (defvar org-any-target-regexp
"<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5628 "Regular expression matching any target.")
5630 (defun org-activate-target-links (limit)
5631 "Run through the buffer and add overlays to target matches."
5632 (when org-target-link-regexp
5633 (let ((case-fold-search t
))
5634 (if (re-search-forward org-target-link-regexp limit t
)
5636 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5637 (add-text-properties (match-beginning 0) (match-end 0)
5638 (list 'mouse-face
'highlight
5639 'keymap org-mouse-map
5640 'help-echo
"Radio target link"
5641 'org-linked-text t
))
5642 (org-rear-nonsticky-at (match-end 0))
5645 (defun org-update-radio-target-regexp ()
5646 "Find all radio targets in this file and update the regular expression."
5648 (when (memq 'radio org-activate-links
)
5649 (setq org-target-link-regexp
5650 (org-make-target-link-regexp (org-all-targets 'radio
)))
5651 (org-restart-font-lock)))
5653 (defun org-hide-wide-columns (limit)
5655 (setq s
(text-property-any (point) (or limit
(point-max))
5658 (setq e
(next-single-property-change s
'org-cwidth
))
5659 (add-text-properties s e
(org-maybe-intangible '(invisible org-cwidth
)))
5663 (defvar org-latex-and-specials-regexp nil
5664 "Regular expression for highlighting export special stuff.")
5665 (defvar org-match-substring-regexp
)
5666 (defvar org-match-substring-with-braces-regexp
)
5668 ;; This should be with the exporter code, but we also use if for font-locking
5669 (defconst org-export-html-special-string-regexps
5670 '(("\\\\-" .
"­")
5671 ("---\\([^-]\\)" .
"—\\1")
5672 ("--\\([^-]\\)" .
"–\\1")
5673 ("\\.\\.\\." .
"…"))
5674 "Regular expressions for special string conversion.")
5677 (defun org-compute-latex-and-specials-regexp ()
5678 "Compute regular expression for stuff treated specially by exporters."
5679 (if (not org-highlight-latex-fragments-and-specials
)
5680 (org-set-local 'org-latex-and-specials-regexp nil
)
5683 ((matchers (plist-get org-format-latex-options
:matchers
))
5684 (latexs (delq nil
(mapcar (lambda (x) (if (member (car x
) matchers
) x
))
5685 org-latex-regexps
)))
5686 (org-export-allow-BIND nil
)
5687 (options (org-combine-plists (org-default-export-plist)
5688 (org-infile-export-plist)))
5689 (org-export-with-sub-superscripts (plist-get options
:sub-superscript
))
5690 (org-export-with-LaTeX-fragments (plist-get options
:LaTeX-fragments
))
5691 (org-export-with-TeX-macros (plist-get options
:TeX-macros
))
5692 (org-export-html-expand (plist-get options
:expand-quoted-html
))
5693 (org-export-with-special-strings (plist-get options
:special-strings
))
5696 ((equal org-export-with-sub-superscripts
'{})
5697 (list org-match-substring-with-braces-regexp
))
5698 (org-export-with-sub-superscripts
5699 (list org-match-substring-regexp
))
5702 (if org-export-with-LaTeX-fragments
5703 (mapcar (lambda (x) (nth 1 x
)) latexs
)))
5705 (if org-export-with-TeX-macros
5706 (list (concat "\\\\"
5712 (append org-entities-user
5714 (if (boundp 'org-latex-entities
)
5716 (or (car-safe x
) x
))
5721 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5722 (re-special (if org-export-with-special-strings
5723 (mapcar (lambda (x) (car x
))
5724 org-export-html-special-string-regexps
)))
5728 (if org-export-html-expand
"@<[^>\n]+>")
5731 'org-latex-and-specials-regexp
5732 (mapconcat 'identity
(append re-latex re-sub re-macros re-special
5735 (defun org-do-latex-and-special-faces (limit)
5736 "Run through the buffer and add overlays to links."
5737 (when org-latex-and-specials-regexp
5739 (while (and (not rtn
) (re-search-forward org-latex-and-specials-regexp
5741 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5743 '(org-code org-verbatim underline
)))
5746 d
(cond ((member (char-after (1+ (match-beginning 0)))
5749 (font-lock-prepend-text-property
5750 (+ d
(match-beginning 0)) (match-end 0)
5751 'face
'org-latex-and-export-specials
)
5752 (add-text-properties (+ d
(match-beginning 0)) (match-end 0)
5753 '(font-lock-multiline t
)))))
5756 (defun org-restart-font-lock ()
5757 "Restart `font-lock-mode', to force refontification."
5758 (when (and (boundp 'font-lock-mode
) font-lock-mode
)
5760 (font-lock-mode 1)))
5762 (defun org-all-targets (&optional radio
)
5763 "Return a list of all targets in this file.
5764 With optional argument RADIO, only find radio targets."
5765 (let ((re (if radio org-radio-target-regexp org-target-regexp
))
5768 (goto-char (point-min))
5769 (while (re-search-forward re nil t
)
5770 (add-to-list 'rtn
(downcase (org-match-string-no-properties 1))))
5773 (defun org-make-target-link-regexp (targets)
5774 "Make regular expression matching all strings in TARGETS.
5775 The regular expression finds the targets also if there is a line break
5782 (setq x
(regexp-quote x
))
5783 (while (string-match " +" x
)
5784 (setq x
(replace-match "\\s-+" t t x
)))
5790 (defun org-activate-tags (limit)
5791 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t
)
5793 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5794 (add-text-properties (match-beginning 1) (match-end 1)
5795 (list 'mouse-face
'highlight
5796 'keymap org-mouse-map
))
5797 (org-rear-nonsticky-at (match-end 1))
5800 (defun org-outline-level ()
5801 "Compute the outline level of the heading at point.
5802 This function assumes that the cursor is at the beginning of a line matched
5803 by `outline-regexp'. Otherwise it returns garbage.
5804 If this is called at a normal headline, the level is the number of stars.
5805 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5807 (looking-at org-outline-regexp
)
5808 (1- (- (match-end 0) (match-beginning 0)))))
5810 (defvar org-font-lock-keywords nil
)
5812 (defconst org-property-re
(org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5813 "Regular expression matching a property line.")
5815 (defvar org-font-lock-hook nil
5816 "Functions to be called for special font lock stuff.")
5818 (defvar org-font-lock-set-keywords-hook nil
5819 "Functions that can manipulate `org-font-lock-extra-keywords'.
5820 This is called after `org-font-lock-extra-keywords' is defined, but before
5821 it is installed to be used by font lock. This can be useful if something
5822 needs to be inserted at a specific position in the font-lock sequence.")
5824 (defun org-font-lock-hook (limit)
5825 (run-hook-with-args 'org-font-lock-hook limit
))
5827 (defun org-set-font-lock-defaults ()
5828 (let* ((em org-fontify-emphasized-text
)
5829 (lk org-activate-links
)
5830 (org-font-lock-extra-keywords
5833 '(org-font-lock-hook)
5835 `(,(if org-fontify-whole-heading-line
5836 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5837 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5838 (1 (org-get-level-face 1))
5839 (2 (org-get-level-face 2))
5840 (3 (org-get-level-face 3)))
5842 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5845 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t
))
5846 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t
))
5847 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t
))
5848 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t
))
5850 (list org-drawer-regexp
'(0 'org-special-keyword t
))
5851 (list "^[ \t]*:END:" '(0 'org-special-keyword t
))
5853 (list org-property-re
5854 '(1 'org-special-keyword t
)
5855 '(3 'org-property-value t
))
5857 (if (memq 'tag lk
) '(org-activate-tags (1 'org-tag prepend
)))
5858 (if (memq 'angle lk
) '(org-activate-angle-links (0 'org-link t
)))
5859 (if (memq 'plain lk
) '(org-activate-plain-links))
5860 (if (memq 'bracket lk
) '(org-activate-bracket-links (0 'org-link t
)))
5861 (if (memq 'radio lk
) '(org-activate-target-links (0 'org-link t
)))
5862 (if (memq 'date lk
) '(org-activate-dates (0 'org-date t
)))
5863 (if (memq 'footnote lk
) '(org-activate-footnote-links))
5864 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t
))
5865 '(org-hide-wide-columns (0 nil append
))
5867 (list (format org-heading-keyword-regexp-format
5869 '(2 (org-get-todo-face 2) t
))
5871 (if org-fontify-done-headline
5872 (list (format org-heading-keyword-regexp-format
5875 (mapconcat 'regexp-quote org-done-keywords
"\\|")
5877 '(2 'org-headline-done t
))
5880 '(org-font-lock-add-priority-faces)
5882 '(org-font-lock-add-tag-faces)
5884 (list (concat "\\<" org-deadline-string
) '(0 'org-special-keyword t
))
5885 (list (concat "\\<" org-scheduled-string
) '(0 'org-special-keyword t
))
5886 (list (concat "\\<" org-closed-string
) '(0 'org-special-keyword t
))
5887 (list (concat "\\<" org-clock-string
) '(0 'org-special-keyword t
))
5890 (if (featurep 'xemacs
)
5891 '(org-do-emphasis-faces (0 nil append
))
5892 '(org-do-emphasis-faces)))
5894 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5895 1 'org-checkbox prepend
)
5896 (if (cdr (assq 'checkbox org-list-automatic-rules
))
5897 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5898 (0 (org-get-checkbox-statistics-face) t
)))
5899 ;; Description list items
5900 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5901 1 'org-list-dt prepend
)
5902 ;; ARCHIVEd headings
5904 org-outline-regexp-bol
5905 "\\(.*:" org-archive-tag
":.*\\)")
5906 '(1 'org-archived prepend
))
5908 '(org-do-latex-and-special-faces)
5909 '(org-fontify-entities)
5910 '(org-raise-scripts)
5912 '(org-activate-code (1 'org-code t
))
5914 (list (format org-heading-keyword-regexp-format
5916 org-comment-string
"\\|" org-quote-string
5918 '(2 'org-special-keyword t
))
5919 '("^#.*" (0 'font-lock-comment-face t
))
5920 ;; Blocks and meta lines
5921 '(org-fontify-meta-lines-and-blocks)
5923 (setq org-font-lock-extra-keywords
(delq nil org-font-lock-extra-keywords
))
5924 (run-hooks 'org-font-lock-set-keywords-hook
)
5925 ;; Now set the full font-lock-keywords
5926 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords
)
5927 (org-set-local 'font-lock-defaults
5928 '(org-font-lock-keywords t nil nil backward-paragraph
))
5929 (kill-local-variable 'font-lock-keywords
) nil
))
5931 (defun org-toggle-pretty-entities ()
5932 "Toggle the composition display of entities as UTF8 characters."
5934 (org-set-local 'org-pretty-entities
(not org-pretty-entities
))
5935 (org-restart-font-lock)
5936 (if org-pretty-entities
5937 (message "Entities are displayed as UTF8 characters")
5940 (org-decompose-region (point-min) (point-max))
5941 (message "Entities are displayed plain"))))
5943 (defun org-fontify-entities (limit)
5944 "Find an entity to fontify."
5946 (when org-pretty-entities
5948 (while (re-search-forward
5949 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5951 (if (and (not (org-in-indented-comment-line))
5952 (setq ee
(org-entity-get (match-string 1)))
5953 (= (length (nth 6 ee
)) 1))
5955 ((end (if (equal (match-string 2) "{}")
5958 (add-text-properties
5959 (match-beginning 0) end
5960 (list 'font-lock-fontified t
))
5961 (compose-region (match-beginning 0) end
5967 (defun org-fontify-like-in-org-mode (s &optional odd-levels
)
5968 "Fontify string S like in Org-mode."
5971 (let ((org-odd-levels-only odd-levels
))
5973 (font-lock-fontify-buffer)
5979 (defun org-get-level-face (n)
5980 "Get the right face for match N in font-lock matching of headlines."
5981 (setq org-l
(- (match-end 2) (match-beginning 1) 1))
5982 (if org-odd-levels-only
(setq org-l
(1+ (/ org-l
2))))
5983 (if org-cycle-level-faces
5984 (setq org-f
(nth (%
(1- org-l
) org-n-level-faces
) org-level-faces
))
5985 (setq org-f
(nth (1- (min org-l org-n-level-faces
)) org-level-faces
)))
5987 ((eq n
1) (if org-hide-leading-stars
'org-hide org-f
))
5989 (t (if org-level-color-stars-only nil org-f
))))
5992 (defun org-get-todo-face (kwd)
5993 "Get the right face for a TODO keyword KWD.
5994 If KWD is a number, get the corresponding match group."
5995 (if (numberp kwd
) (setq kwd
(match-string kwd
)))
5996 (or (org-face-from-face-or-color
5997 'todo
'org-todo
(cdr (assoc kwd org-todo-keyword-faces
)))
5998 (and (member kwd org-done-keywords
) 'org-done
)
6001 (defun org-face-from-face-or-color (context inherit face-or-color
)
6002 "Create a face list that inherits INHERIT, but sets the foreground color.
6003 When FACE-OR-COLOR is not a string, just return it."
6004 (if (stringp face-or-color
)
6005 (list :inherit inherit
6006 (cdr (assoc context org-faces-easy-properties
))
6010 (defun org-font-lock-add-tag-faces (limit)
6011 "Add the special tag faces."
6012 (when (and org-tag-faces org-tags-special-faces-re
)
6013 (while (re-search-forward org-tags-special-faces-re limit t
)
6014 (add-text-properties (match-beginning 1) (match-end 1)
6015 (list 'face
(org-get-tag-face 1)
6016 'font-lock-fontified t
))
6017 (backward-char 1))))
6019 (defun org-font-lock-add-priority-faces (limit)
6020 "Add the special priority faces."
6021 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t
)
6022 (add-text-properties
6023 (match-beginning 0) (match-end 0)
6024 (list 'face
(or (org-face-from-face-or-color
6025 'priority
'org-special-keyword
6026 (cdr (assoc (char-after (match-beginning 1))
6027 org-priority-faces
)))
6028 'org-special-keyword
)
6029 'font-lock-fontified t
))))
6031 (defun org-get-tag-face (kwd)
6032 "Get the right face for a TODO keyword KWD.
6033 If KWD is a number, get the corresponding match group."
6034 (if (numberp kwd
) (setq kwd
(match-string kwd
)))
6035 (or (org-face-from-face-or-color
6036 'tag
'org-tag
(cdr (assoc kwd org-tag-faces
)))
6039 (defun org-unfontify-region (beg end
&optional maybe_loudly
)
6040 "Remove fontification and activation overlays from links."
6041 (font-lock-default-unfontify-region beg end
)
6042 (let* ((buffer-undo-list t
)
6043 (inhibit-read-only t
) (inhibit-point-motion-hooks t
)
6044 (inhibit-modification-hooks t
)
6045 deactivate-mark buffer-file-name buffer-file-truename
)
6046 (org-decompose-region beg end
)
6047 (remove-text-properties beg end
6048 '(mouse-face t keymap t org-linked-text t
6049 invisible t intangible t
6050 org-no-flyspell t org-emphasis t
))
6051 (org-remove-font-lock-display-properties beg end
)))
6053 (defconst org-script-display
'(((raise -
0.3) (height 0.7))
6054 ((raise 0.3) (height 0.7))
6057 "Display properties for showing superscripts and subscripts.")
6059 (defun org-remove-font-lock-display-properties (beg end
)
6060 "Remove specific display properties that have been added by font lock.
6061 The will remove the raise properties that are used to show superscripts
6065 (setq next
(next-single-property-change beg
'display nil end
)
6066 prop
(get-text-property beg
'display
))
6067 (if (member prop org-script-display
)
6068 (put-text-property beg next
'display nil
))
6071 (defun org-raise-scripts (limit)
6072 "Add raise properties to sub/superscripts."
6073 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
)
6074 (if (re-search-forward
6075 (if (eq org-use-sub-superscripts t
)
6076 org-match-substring-regexp
6077 org-match-substring-with-braces-regexp
)
6079 (let* ((pos (point)) table-p comment-p
6080 (mpos (match-beginning 3))
6081 (emph-p (get-text-property mpos
'org-emphasis
))
6082 (link-p (get-text-property mpos
'mouse-face
))
6083 (keyw-p (eq 'org-special-keyword
(get-text-property mpos
'face
))))
6084 (goto-char (point-at-bol))
6085 (setq table-p
(org-looking-at-p org-table-dataline-regexp
)
6086 comment-p
(org-looking-at-p "[ \t]*#"))
6088 ;; FIXME: Should we go back one character here, for a_b^c
6089 ;; (goto-char (1- pos)) ;????????????????????
6090 (if (or comment-p emph-p link-p keyw-p
)
6092 (put-text-property (match-beginning 3) (match-end 0)
6094 (if (equal (char-after (match-beginning 2)) ?^
)
6095 (nth (if table-p
3 1) org-script-display
)
6096 (nth (if table-p
2 0) org-script-display
)))
6097 (add-text-properties (match-beginning 2) (match-end 2)
6099 'org-dwidth t
'org-dwidth-n
1))
6100 (if (and (eq (char-after (match-beginning 3)) ?
{)
6101 (eq (char-before (match-end 3)) ?
}))
6103 (add-text-properties
6104 (match-beginning 3) (1+ (match-beginning 3))
6105 (list 'invisible t
'org-dwidth t
'org-dwidth-n
1))
6106 (add-text-properties
6107 (1- (match-end 3)) (match-end 3)
6108 (list 'invisible t
'org-dwidth t
'org-dwidth-n
1))))
6111 ;;;; Visibility cycling, including org-goto and indirect buffer
6115 (defvar org-cycle-global-status nil
)
6116 (make-variable-buffer-local 'org-cycle-global-status
)
6117 (defvar org-cycle-subtree-status nil
)
6118 (make-variable-buffer-local 'org-cycle-subtree-status
)
6122 (defvar org-inlinetask-min-level
)
6124 (defun org-cycle (&optional arg
)
6125 "TAB-action and visibility cycling for Org-mode.
6127 This is the command invoked in Org-mode by the TAB key. Its main purpose
6128 is outline visibility cycling, but it also invokes other actions
6129 in special contexts.
6131 - When this function is called with a prefix argument, rotate the entire
6132 buffer through 3 states (global cycling)
6133 1. OVERVIEW: Show only top-level headlines.
6134 2. CONTENTS: Show all headlines of all levels, but no body text.
6135 3. SHOW ALL: Show everything.
6136 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6137 determined by the variable `org-startup-folded', and by any VISIBILITY
6138 properties in the buffer.
6139 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6140 including any drawers.
6142 - When inside a table, re-align the table and move to the next field.
6144 - When point is at the beginning of a headline, rotate the subtree started
6145 by this line through 3 different states (local cycling)
6146 1. FOLDED: Only the main headline is shown.
6147 2. CHILDREN: The main headline and the direct children are shown.
6148 From this state, you can move to one of the children
6149 and zoom in further.
6150 3. SUBTREE: Show the entire subtree, including body text.
6151 If there is no subtree, switch directly from CHILDREN to FOLDED.
6153 - When point is at the beginning of an empty headline and the variable
6154 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6155 of the headline by demoting and promoting it to likely levels. This
6156 speeds up creation document structure by pressing TAB once or several
6157 times right after creating a new headline.
6159 - When there is a numeric prefix, go up to a heading with level ARG, do
6160 a `show-subtree' and return to the previous cursor position. If ARG
6161 is negative, go up that many levels.
6163 - When point is not at the beginning of a headline, execute the global
6164 binding for TAB, which is re-indenting the line. See the option
6165 `org-cycle-emulate-tab' for details.
6167 - Special case: if point is at the beginning of the buffer and there is
6168 no headline in line 1, this function will act as if called with prefix arg
6169 (C-u TAB, same as S-TAB) also when called without prefix arg.
6170 But only if also the variable `org-cycle-global-at-bob' is t."
6172 (org-load-modules-maybe)
6173 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook
)
6174 (and org-cycle-level-after-item
/entry-creation
6175 (or (org-cycle-level)
6176 (org-cycle-item-indentation))))
6178 (or org-cycle-max-level
6179 (and (boundp 'org-inlinetask-min-level
)
6180 org-inlinetask-min-level
6181 (1- org-inlinetask-min-level
))))
6182 (nstars (and limit-level
6183 (if org-odd-levels-only
6184 (and limit-level
(1- (* limit-level
2)))
6187 (if (not (derived-mode-p 'org-mode
))
6189 (concat "\\*" (if nstars
(format "\\{1,%d\\} " nstars
) "+ "))))
6190 (bob-special (and org-cycle-global-at-bob
(not arg
) (bobp)
6191 (not (looking-at org-outline-regexp
))))
6194 (delq 'org-optimize-window-after-visibility-change
6195 (copy-sequence org-cycle-hook
))
6199 (if (or bob-special
(equal arg
'(4)))
6200 ;; special case: use global cycling
6206 (setq last-command
'dummy
)
6207 (org-set-startup-visibility)
6208 (message "Startup visibility, plus VISIBILITY properties"))
6212 (message "Entire buffer visible, including drawers"))
6214 ;; Table: enter it or move to the next field.
6215 ((org-at-table-p 'any
)
6216 (if (org-at-table.el-p
)
6217 (message "Use C-c ' to edit table.el tables")
6218 (if arg
(org-table-edit-field t
)
6219 (org-table-justify-field-maybe)
6220 (call-interactively 'org-table-next-field
))))
6222 ((run-hook-with-args-until-success
6223 'org-tab-after-check-for-table-hook
))
6225 ;; Global cycling: delegate to `org-cycle-internal-global'.
6226 ((eq arg t
) (org-cycle-internal-global))
6228 ;; Drawers: delegate to `org-flag-drawer'.
6229 ((and org-drawers org-drawer-regexp
6231 (beginning-of-line 1)
6232 (looking-at org-drawer-regexp
)))
6233 (org-flag-drawer ; toggle block visibility
6234 (not (get-char-property (match-end 0) 'invisible
))))
6236 ;; Show-subtree, ARG levels up from here.
6239 (org-back-to-heading)
6240 (outline-up-heading (if (< arg
0) (- arg
)
6241 (- (funcall outline-level
) arg
)))
6242 (org-show-subtree)))
6244 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6245 ((and (featurep 'org-inlinetask
)
6246 (org-inlinetask-at-task-p)
6247 (or (bolp) (not (eq org-cycle-emulate-tab
'exc-hl-bol
))))
6248 (org-inlinetask-toggle-visibility))
6250 ((org-try-cdlatex-tab))
6252 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6253 ((and (or (and org-cycle-include-plain-lists
(org-at-item-p))
6254 (save-excursion (beginning-of-line 1)
6255 (looking-at org-outline-regexp
)))
6256 (or (bolp) (not (eq org-cycle-emulate-tab
'exc-hl-bol
))))
6257 (org-cycle-internal-local))
6259 ;; From there: TAB emulation and template completion.
6260 (buffer-read-only (org-back-to-heading))
6262 ((run-hook-with-args-until-success
6263 'org-tab-after-check-for-cycling-hook
))
6265 ((org-try-structure-completion))
6267 ((run-hook-with-args-until-success
6268 'org-tab-before-tab-emulation-hook
))
6270 ((and (eq org-cycle-emulate-tab
'exc-hl-bol
)
6272 (not (looking-at org-outline-regexp
))))
6273 (call-interactively (global-key-binding "\t")))
6275 ((if (and (memq org-cycle-emulate-tab
'(white whitestart
))
6276 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6277 (or (and (eq org-cycle-emulate-tab
'white
)
6278 (= (match-end 0) (point-at-eol)))
6279 (and (eq org-cycle-emulate-tab
'whitestart
)
6280 (>= (match-end 0) pos
))))
6282 (eq org-cycle-emulate-tab t
))
6283 (call-interactively (global-key-binding "\t")))
6286 (org-back-to-heading)
6289 (defun org-cycle-internal-global ()
6290 "Do the global cycling action."
6291 ;; Hack to avoid display of messages for .org attachments in Gnus
6292 (let ((ga (string-match "\\*fontification" (buffer-name))))
6294 ((and (eq last-command this-command
)
6295 (eq org-cycle-global-status
'overview
))
6296 ;; We just created the overview - now do table of contents
6297 ;; This can be slow in very large buffers, so indicate action
6298 (run-hook-with-args 'org-pre-cycle-hook
'contents
)
6299 (unless ga
(message "CONTENTS..."))
6301 (unless ga
(message "CONTENTS...done"))
6302 (setq org-cycle-global-status
'contents
)
6303 (run-hook-with-args 'org-cycle-hook
'contents
))
6305 ((and (eq last-command this-command
)
6306 (eq org-cycle-global-status
'contents
))
6307 ;; We just showed the table of contents - now show everything
6308 (run-hook-with-args 'org-pre-cycle-hook
'all
)
6310 (unless ga
(message "SHOW ALL"))
6311 (setq org-cycle-global-status
'all
)
6312 (run-hook-with-args 'org-cycle-hook
'all
))
6315 ;; Default action: go to overview
6316 (run-hook-with-args 'org-pre-cycle-hook
'overview
)
6318 (unless ga
(message "OVERVIEW"))
6319 (setq org-cycle-global-status
'overview
)
6320 (run-hook-with-args 'org-cycle-hook
'overview
)))))
6322 (defun org-cycle-internal-local ()
6323 "Do the local cycling action."
6324 (let ((goal-column 0) eoh eol eos has-children children-skipped struct
)
6325 ;; First, determine end of headline (EOH), end of subtree or item
6326 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6331 (setq struct
(org-list-struct))
6332 (setq eoh
(point-at-eol))
6333 (setq eos
(org-list-get-item-end-before-blank (point) struct
))
6334 (setq has-children
(org-list-has-child-p (point) struct
)))
6335 (org-back-to-heading)
6336 (setq eoh
(save-excursion (outline-end-of-heading) (point)))
6337 (setq eos
(save-excursion
6338 (org-end-of-subtree t
)
6340 (skip-chars-forward " \t\n"))
6341 (if (eobp) (point) (1- (point)))))
6344 (let ((level (funcall outline-level
)))
6345 (outline-next-heading)
6346 (and (org-at-heading-p t
)
6347 (> (funcall outline-level
) level
))))
6349 (org-list-search-forward (org-item-beginning-re) eos t
)))))
6350 ;; Determine end invisible part of buffer (EOL)
6351 (beginning-of-line 2)
6352 ;; XEmacs doesn't have `next-single-char-property-change'
6353 (if (featurep 'xemacs
)
6354 (while (and (not (eobp)) ;; this is like `next-line'
6355 (get-char-property (1- (point)) 'invisible
))
6356 (beginning-of-line 2))
6357 (while (and (not (eobp)) ;; this is like `next-line'
6358 (get-char-property (1- (point)) 'invisible
))
6359 (goto-char (next-single-char-property-change (point) 'invisible
))
6360 (and (eolp) (beginning-of-line 2))))
6362 ;; Find out what to do next and set `this-command'
6365 ;; Nothing is hidden behind this heading
6366 (run-hook-with-args 'org-pre-cycle-hook
'empty
)
6367 (message "EMPTY ENTRY")
6368 (setq org-cycle-subtree-status nil
)
6371 (outline-next-heading)
6372 (if (outline-invisible-p) (org-flag-heading nil
))))
6373 ((and (or (>= eol eos
)
6374 (not (string-match "\\S-" (buffer-substring eol eos
))))
6376 (not (setq children-skipped
6377 org-cycle-skip-children-state-if-no-children
))))
6378 ;; Entire subtree is hidden in one line: children view
6379 (run-hook-with-args 'org-pre-cycle-hook
'children
)
6381 (org-list-set-item-visibility (point-at-bol) struct
'children
)
6383 (org-with-limited-levels (show-children))
6384 ;; FIXME: This slows down the func way too much.
6385 ;; How keep drawers hidden in subtree anyway?
6386 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6387 ;; (org-cycle-hide-drawers 'subtree))
6389 ;; Fold every list in subtree to top-level items.
6390 (when (eq org-cycle-include-plain-lists
'integrate
)
6392 (org-back-to-heading)
6393 (while (org-list-search-forward (org-item-beginning-re) eos t
)
6394 (beginning-of-line 1)
6395 (let* ((struct (org-list-struct))
6396 (prevs (org-list-prevs-alist struct
))
6397 (end (org-list-get-bottom-point struct
)))
6398 (mapc (lambda (e) (org-list-set-item-visibility e struct
'folded
))
6399 (org-list-get-all-items (point) struct prevs
))
6400 (goto-char end
))))))
6401 (message "CHILDREN")
6404 (outline-next-heading)
6405 (if (outline-invisible-p) (org-flag-heading nil
)))
6406 (setq org-cycle-subtree-status
'children
)
6407 (run-hook-with-args 'org-cycle-hook
'children
))
6408 ((or children-skipped
6409 (and (eq last-command this-command
)
6410 (eq org-cycle-subtree-status
'children
)))
6411 ;; We just showed the children, or no children are there,
6412 ;; now show everything.
6413 (run-hook-with-args 'org-pre-cycle-hook
'subtree
)
6414 (outline-flag-region eoh eos nil
)
6415 (message (if children-skipped
"SUBTREE (NO CHILDREN)" "SUBTREE"))
6416 (setq org-cycle-subtree-status
'subtree
)
6417 (run-hook-with-args 'org-cycle-hook
'subtree
))
6419 ;; Default action: hide the subtree.
6420 (run-hook-with-args 'org-pre-cycle-hook
'folded
)
6421 (outline-flag-region eoh eos t
)
6423 (setq org-cycle-subtree-status
'folded
)
6424 (run-hook-with-args 'org-cycle-hook
'folded
)))))
6427 (defun org-global-cycle (&optional arg
)
6428 "Cycle the global visibility. For details see `org-cycle'.
6429 With \\[universal-argument] prefix arg, switch to startup visibility.
6430 With a numeric prefix, show all headlines up to that level."
6432 (let ((org-cycle-include-plain-lists
6433 (if (derived-mode-p 'org-mode
) org-cycle-include-plain-lists nil
)))
6437 (hide-sublevels arg
)
6438 (setq org-cycle-global-status
'contents
))
6440 (org-set-startup-visibility)
6441 (message "Startup visibility, plus VISIBILITY properties."))
6443 (org-cycle '(4))))))
6445 (defun org-set-startup-visibility ()
6446 "Set the visibility required by startup options and properties."
6448 ((eq org-startup-folded t
)
6450 ((eq org-startup-folded
'content
)
6451 (let ((this-command 'org-cycle
) (last-command 'org-cycle
))
6452 (org-cycle '(4)) (org-cycle '(4)))))
6453 (unless (eq org-startup-folded
'showeverything
)
6454 (if org-hide-block-startup
(org-hide-block-all))
6455 (org-set-visibility-according-to-property 'no-cleanup
)
6456 (org-cycle-hide-archived-subtrees 'all
)
6457 (org-cycle-hide-drawers 'all
)
6458 (org-cycle-show-empty-lines t
)))
6460 (defun org-set-visibility-according-to-property (&optional no-cleanup
)
6461 "Switch subtree visibilities according to :VISIBILITY: property."
6463 (let (org-show-entry-below state
)
6465 (goto-char (point-min))
6466 (while (re-search-forward
6467 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6469 (setq state
(match-string 1))
6471 (org-back-to-heading t
)
6475 ((equal state
'("fold" "folded"))
6477 ((equal state
"children")
6478 (org-show-hidden-entry)
6480 ((equal state
"content")
6483 (org-narrow-to-subtree)
6485 ((member state
'("all" "showall"))
6488 (org-cycle-hide-archived-subtrees 'all
)
6489 (org-cycle-hide-drawers 'all
)
6490 (org-cycle-show-empty-lines 'all
)))))
6492 ;; This function uses outline-regexp instead of the more fundamental
6493 ;; org-outline-regexp so that org-cycle-global works outside of Org
6494 ;; buffers, where outline-regexp is needed.
6495 (defun org-overview ()
6496 "Switch to overview mode, showing only top-level headlines.
6497 Really, this shows all headlines with level equal or greater than the level
6498 of the first headline in the buffer. This is important, because if the
6499 first headline is not level one, then (hide-sublevels 1) gives confusing
6502 (let ((level (save-excursion
6503 (goto-char (point-min))
6504 (if (re-search-forward (concat "^" outline-regexp
) nil t
)
6506 (goto-char (match-beginning 0))
6507 (funcall outline-level
))))))
6508 (and level
(hide-sublevels level
))))
6510 (defun org-content (&optional arg
)
6511 "Show all headlines in the buffer, like a table of contents.
6512 With numerical argument N, show content up to level N."
6515 ;; Visit all headings and show their offspring
6516 (and (integerp arg
) (org-overview))
6517 (goto-char (point-max))
6519 (while (and (progn (condition-case nil
6520 (outline-previous-visible-heading 1)
6521 (error (goto-char (point-min))))
6523 (looking-at org-outline-regexp
))
6525 (show-children (1- arg
))
6527 (if (bobp) (throw 'exit nil
))))))
6530 (defun org-optimize-window-after-visibility-change (state)
6531 "Adjust the window after a change in outline visibility.
6532 This function is the default value of the hook `org-cycle-hook'."
6533 (when (get-buffer-window (current-buffer))
6535 ((eq state
'content
) nil
)
6536 ((eq state
'all
) nil
)
6537 ((eq state
'folded
) nil
)
6538 ((eq state
'children
) (or (org-subtree-end-visible-p) (recenter 1)))
6539 ((eq state
'subtree
) (or (org-subtree-end-visible-p) (recenter 1))))))
6541 (defun org-remove-empty-overlays-at (pos)
6542 "Remove outline overlays that do not contain non-white stuff."
6545 (and (eq 'outline
(overlay-get o
'invisible
))
6546 (not (string-match "\\S-" (buffer-substring (overlay-start o
)
6548 (delete-overlay o
)))
6551 (defun org-clean-visibility-after-subtree-move ()
6552 "Fix visibility issues after moving a subtree."
6553 ;; First, find a reasonable region to look at:
6554 ;; Start two siblings above, end three below
6555 (let* ((beg (save-excursion
6556 (and (org-get-last-sibling)
6557 (org-get-last-sibling))
6559 (end (save-excursion
6560 (and (org-get-next-sibling)
6561 (org-get-next-sibling)
6562 (org-get-next-sibling))
6563 (if (org-at-heading-p)
6566 (level (looking-at "\\*+"))
6567 (re (if level
(concat "^" (regexp-quote (match-string 0)) " "))))
6570 (narrow-to-region beg end
)
6572 ;; Properly fold already folded siblings
6573 (goto-char (point-min))
6574 (while (re-search-forward re nil t
)
6575 (if (and (not (outline-invisible-p))
6577 (goto-char (point-at-eol)) (outline-invisible-p)))
6579 (org-cycle-show-empty-lines 'overview
)
6580 (org-cycle-hide-drawers 'overview
)))))
6582 (defun org-cycle-show-empty-lines (state)
6583 "Show empty lines above all visible headlines.
6584 The region to be covered depends on STATE when called through
6585 `org-cycle-hook'. Lisp program can use t for STATE to get the
6586 entire buffer covered. Note that an empty line is only shown if there
6587 are at least `org-cycle-separator-lines' empty lines before the headline."
6588 (when (not (= org-cycle-separator-lines
0))
6590 (let* ((n (abs org-cycle-separator-lines
))
6592 ((= n
1) "\\(\n[ \t]*\n\\*+\\) ")
6593 ((= n
2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6594 (t (let ((ns (number-to-string (- n
2))))
6595 (concat "^\\(?:[ \t]*\n\\)\\{" ns
"," ns
"\\}"
6596 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6599 ((memq state
'(overview contents t
))
6600 (setq beg
(point-min) end
(point-max)))
6601 ((memq state
'(children folded
))
6602 (setq beg
(point) end
(progn (org-end-of-subtree t t
)
6603 (beginning-of-line 2)
6607 (while (re-search-forward re end t
)
6608 (unless (get-char-property (match-end 1) 'invisible
)
6609 (setq e
(match-end 1))
6610 (if (< org-cycle-separator-lines
0)
6611 (setq b
(save-excursion
6612 (goto-char (match-beginning 0))
6613 (org-back-over-empty-lines)
6615 (goto-char (max (point-min) (1- (point))))
6619 (setq b
(match-beginning 1)))
6620 (outline-flag-region b e nil
)))))))
6621 ;; Never hide empty lines at the end of the file.
6623 (goto-char (point-max))
6624 (outline-previous-heading)
6625 (outline-end-of-heading)
6626 (if (and (looking-at "[ \t\n]+")
6627 (= (match-end 0) (point-max)))
6628 (outline-flag-region (point) (match-end 0) nil
))))
6630 (defun org-show-empty-lines-in-parent ()
6631 "Move to the parent and re-show empty lines before visible headlines."
6633 (let ((context (if (org-up-heading-safe) 'children
'overview
)))
6634 (org-cycle-show-empty-lines context
))))
6636 (defun org-files-list ()
6637 "Return `org-agenda-files' list, plus all open org-mode files.
6638 This is useful for operations that need to scan all of a user's
6639 open and agenda-wise Org files."
6640 (let ((files (mapcar 'expand-file-name
(org-agenda-files))))
6641 (dolist (buf (buffer-list))
6642 (with-current-buffer buf
6643 (if (and (derived-mode-p 'org-mode
) (buffer-file-name))
6644 (let ((file (expand-file-name (buffer-file-name))))
6645 (unless (member file files
)
6646 (push file files
))))))
6649 (defsubst org-entry-beginning-position
()
6650 "Return the beginning position of the current entry."
6651 (save-excursion (outline-back-to-heading t
) (point)))
6653 (defsubst org-entry-end-position
()
6654 "Return the end position of the current entry."
6655 (save-excursion (outline-next-heading) (point)))
6657 (defun org-cycle-hide-drawers (state)
6658 "Re-hide all drawers after a visibility state change."
6659 (when (and (derived-mode-p 'org-mode
)
6660 (not (memq state
'(overview folded contents
))))
6662 (let* ((globalp (memq state
'(contents all
)))
6663 (beg (if globalp
(point-min) (point)))
6664 (end (if globalp
(point-max)
6665 (if (eq state
'children
)
6666 (save-excursion (outline-next-heading) (point))
6667 (org-end-of-subtree t
)))))
6669 (while (re-search-forward org-drawer-regexp end t
)
6670 (org-flag-drawer t
))))))
6672 (defun org-flag-drawer (flag)
6674 (beginning-of-line 1)
6675 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6676 (let ((b (match-end 0)))
6677 (if (re-search-forward
6679 (save-excursion (outline-next-heading) (point)) t
)
6680 (outline-flag-region b
(point-at-eol) flag
)
6681 (error ":END: line missing at position %s" b
))))))
6683 (defun org-subtree-end-visible-p ()
6684 "Is the end of the current subtree visible?"
6685 (pos-visible-in-window-p
6686 (save-excursion (org-end-of-subtree t
) (point))))
6688 (defun org-first-headline-recenter (&optional N
)
6689 "Move cursor to the first headline and recenter the headline.
6690 Optional argument N means put the headline into the Nth line of the window."
6691 (goto-char (point-min))
6692 (when (re-search-forward (concat "^\\(" org-outline-regexp
"\\)") nil t
)
6694 (recenter (prefix-numeric-value N
))))
6696 ;;; Saving and restoring visibility
6698 (defun org-outline-overlay-data (&optional use-markers
)
6699 "Return a list of the locations of all outline overlays.
6700 These are overlays with the `invisible' property value `outline'.
6701 The return value is a list of cons cells, with start and stop
6702 positions for each overlay.
6703 If USE-MARKERS is set, return the positions as markers."
6710 (when (eq (overlay-get o
'invisible
) 'outline
)
6711 (setq beg
(overlay-start o
)
6712 end
(overlay-end o
))
6713 (and beg end
(> end beg
)
6715 (cons (move-marker (make-marker) beg
)
6716 (move-marker (make-marker) end
))
6718 (overlays-in (point-min) (point-max))))))))
6720 (defun org-set-outline-overlay-data (data)
6721 "Create visibility overlays for all positions in DATA.
6722 DATA should have been made by `org-outline-overlay-data'."
6729 (outline-flag-region (car c
) (cdr c
) t
))
6732 ;;; Folding of blocks
6734 (defvar org-hide-block-overlays nil
6735 "Overlays hiding blocks.")
6736 (make-variable-buffer-local 'org-hide-block-overlays
)
6738 (defun org-block-map (function &optional start end
)
6739 "Call FUNCTION at the head of all source blocks in the current buffer.
6740 Optional arguments START and END can be used to limit the range."
6741 (let ((start (or start
(point-min)))
6742 (end (or end
(point-max))))
6745 (while (and (< (point) end
) (re-search-forward org-block-regexp end t
))
6748 (goto-char (match-beginning 0))
6749 (funcall function
)))))))
6751 (defun org-hide-block-toggle-all ()
6752 "Toggle the visibility of all blocks in the current buffer."
6753 (org-block-map #'org-hide-block-toggle
))
6755 (defun org-hide-block-all ()
6756 "Fold all blocks in the current buffer."
6758 (org-show-block-all)
6759 (org-block-map #'org-hide-block-toggle-maybe
))
6761 (defun org-show-block-all ()
6762 "Unfold all blocks in the current buffer."
6764 (mapc 'delete-overlay org-hide-block-overlays
)
6765 (setq org-hide-block-overlays nil
))
6767 (defun org-hide-block-toggle-maybe ()
6768 "Toggle visibility of block at point."
6770 (let ((case-fold-search t
))
6772 (beginning-of-line 1)
6773 (looking-at org-block-regexp
))
6774 (progn (org-hide-block-toggle)
6775 t
) ;; to signal that we took action
6776 nil
))) ;; to signal that we did not
6778 (defun org-hide-block-toggle (&optional force
)
6779 "Toggle the visibility of the current block."
6783 (if (re-search-forward org-block-regexp nil t
)
6784 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6785 (end (match-end 0)) ;; end of entire body
6787 (if (memq t
(mapcar (lambda (overlay)
6788 (eq (overlay-get overlay
'invisible
)
6790 (overlays-at start
)))
6791 (if (or (not force
) (eq force
'off
))
6793 (when (member ov org-hide-block-overlays
)
6794 (setq org-hide-block-overlays
6795 (delq ov org-hide-block-overlays
)))
6796 (when (eq (overlay-get ov
'invisible
)
6798 (delete-overlay ov
)))
6799 (overlays-at start
)))
6800 (setq ov
(make-overlay start end
))
6801 (overlay-put ov
'invisible
'org-hide-block
)
6802 ;; make the block accessible to isearch
6804 ov
'isearch-open-invisible
6806 (when (member ov org-hide-block-overlays
)
6807 (setq org-hide-block-overlays
6808 (delq ov org-hide-block-overlays
)))
6809 (when (eq (overlay-get ov
'invisible
)
6811 (delete-overlay ov
))))
6812 (push ov org-hide-block-overlays
)))
6813 (error "Not looking at a source block"))))
6815 ;; org-tab-after-check-for-cycling-hook
6816 (add-hook 'org-tab-first-hook
'org-hide-block-toggle-maybe
)
6817 ;; Remove overlays when changing major mode
6818 (add-hook 'org-mode-hook
6819 (lambda () (org-add-hook 'change-major-mode-hook
6820 'org-show-block-all
'append
'local
)))
6824 (defvar org-goto-window-configuration nil
)
6825 (defvar org-goto-marker nil
)
6826 (defvar org-goto-map
6827 (let ((map (make-sparse-keymap)))
6828 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur
)) cmd
)
6829 (while (setq cmd
(pop cmds
))
6830 (substitute-key-definition cmd cmd map global-map
)))
6831 (suppress-keymap map
)
6832 (org-defkey map
"\C-m" 'org-goto-ret
)
6833 (org-defkey map
[(return)] 'org-goto-ret
)
6834 (org-defkey map
[(left)] 'org-goto-left
)
6835 (org-defkey map
[(right)] 'org-goto-right
)
6836 (org-defkey map
[(control ?g
)] 'org-goto-quit
)
6837 (org-defkey map
"\C-i" 'org-cycle
)
6838 (org-defkey map
[(tab)] 'org-cycle
)
6839 (org-defkey map
[(down)] 'outline-next-visible-heading
)
6840 (org-defkey map
[(up)] 'outline-previous-visible-heading
)
6841 (if org-goto-auto-isearch
6842 (if (fboundp 'define-key-after
)
6843 (define-key-after map
[t] 'org-goto-local-auto-isearch)
6845 (org-defkey map "q" 'org-goto-quit)
6846 (org-defkey map "n" 'outline-next-visible-heading)
6847 (org-defkey map "p" 'outline-previous-visible-heading)
6848 (org-defkey map "f" 'outline-forward-same-level)
6849 (org-defkey map "b" 'outline-backward-same-level)
6850 (org-defkey map "u" 'outline-up-heading))
6851 (org-defkey map "/" 'org-occur)
6852 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6853 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6854 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6855 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6856 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6859 (defconst org-goto-help
6860 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6861 RET=jump to location [Q]uit and return to previous location
6862 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6864 (defvar org-goto-start-pos) ; dynamically scoped parameter
6866 ;; FIXME: Docstring does not mention both interfaces
6867 (defun org-goto (&optional alternative-interface)
6868 "Look up a different location in the current file, keeping current visibility.
6870 When you want look-up or go to a different location in a
6871 document, the fastest way is often to fold the entire buffer and
6872 then dive into the tree. This method has the disadvantage, that
6873 the previous location will be folded, which may not be what you
6876 This command works around this by showing a copy of the current
6877 buffer in an indirect buffer, in overview mode. You can dive
6878 into the tree in that copy, use org-occur and incremental search
6879 to find a location. When pressing RET or `Q', the command
6880 returns to the original buffer in which the visibility is still
6881 unchanged. After RET it will also jump to the location selected
6882 in the indirect buffer and expose the headline hierarchy above.
6884 With a prefix argument, use the alternative interface: e.g. if
6885 `org-goto-interface' is 'outline use 'outline-path-completion."
6887 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6888 (org-refile-use-outline-path t)
6889 (org-refile-target-verify-function nil)
6891 (if (not alternative-interface)
6893 (if (eq org-goto-interface 'outline)
6894 'outline-path-completion
6896 (org-goto-start-pos (point))
6898 (if (eq interface 'outline)
6899 (car (org-get-location (current-buffer) org-goto-help))
6900 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6901 (org-refile-check-position pa)
6905 (org-mark-ring-push org-goto-start-pos)
6906 (goto-char selected-point)
6907 (if (or (outline-invisible-p) (org-invisible-p2))
6908 (org-show-context 'org-goto)))
6911 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6912 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6913 (defvar org-goto-local-auto-isearch-map) ; defined below
6915 (defun org-get-location (buf help)
6916 "Let the user select a location in the Org-mode buffer BUF.
6917 This function uses a recursive edit. It returns the selected position
6919 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6920 (isearch-hide-immediately nil)
6921 (isearch-search-fun-function
6922 (lambda () 'org-goto-local-search-headings))
6923 (org-goto-selected-point org-goto-exit-command)
6925 (special-display-buffer-names nil)
6926 (special-display-regexps nil)
6927 (special-display-function nil))
6929 (save-window-excursion
6930 (delete-other-windows)
6931 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6932 (org-pop-to-buffer-same-window
6934 (make-indirect-buffer (current-buffer) "*org-goto*")
6935 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6936 (with-output-to-temp-buffer "*Help*"
6938 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6939 (setq buffer-read-only nil)
6940 (let ((org-startup-truncated t)
6941 (org-startup-folded nil)
6942 (org-startup-align-all-tables nil))
6945 (setq buffer-read-only t)
6946 (if (and (boundp 'org-goto-start-pos)
6947 (integer-or-marker-p org-goto-start-pos))
6948 (let ((org-show-hierarchy-above t)
6949 (org-show-siblings t)
6950 (org-show-following-heading t))
6951 (goto-char org-goto-start-pos)
6952 (and (outline-invisible-p) (org-show-context)))
6953 (goto-char (point-min)))
6954 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6955 (message "Select location and press RET")
6956 (use-local-map org-goto-map)
6959 (kill-buffer "*org-goto*")
6960 (cons org-goto-selected-point org-goto-exit-command)))
6962 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6963 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6964 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6965 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6967 (defun org-goto-local-search-headings (string bound noerror)
6968 "Search and make sure that any matches are in headlines."
6970 (while (if isearch-forward
6971 (search-forward string bound noerror)
6972 (search-backward string bound noerror))
6973 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6974 (and (member :headline context)
6975 (not (member :tags context))))
6976 (throw 'return (point))))))
6978 (defun org-goto-local-auto-isearch ()
6981 (goto-char (point-min))
6982 (let ((keys (this-command-keys)))
6983 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6985 (isearch-process-search-char (string-to-char keys)))))
6987 (defun org-goto-ret (&optional arg)
6988 "Finish `org-goto' by going to the new location."
6990 (setq org-goto-selected-point (point)
6991 org-goto-exit-command 'return)
6994 (defun org-goto-left ()
6995 "Finish `org-goto' by going to the new location."
6997 (if (org-at-heading-p)
6999 (beginning-of-line 1)
7000 (setq org-goto-selected-point (point)
7001 org-goto-exit-command 'left)
7003 (error "Not on a heading")))
7005 (defun org-goto-right ()
7006 "Finish `org-goto' by going to the new location."
7008 (if (org-at-heading-p)
7010 (setq org-goto-selected-point (point)
7011 org-goto-exit-command 'right)
7013 (error "Not on a heading")))
7015 (defun org-goto-quit ()
7016 "Finish `org-goto' without cursor motion."
7018 (setq org-goto-selected-point nil)
7019 (setq org-goto-exit-command 'quit)
7022 ;;; Indirect buffer display of subtrees
7024 (defvar org-indirect-dedicated-frame nil
7025 "This is the frame being used for indirect tree display.")
7026 (defvar org-last-indirect-buffer nil)
7028 (defun org-tree-to-indirect-buffer (&optional arg)
7029 "Create indirect buffer and narrow it to current subtree.
7030 With numerical prefix ARG, go up to this level and then take that tree.
7031 If ARG is negative, go up that many levels.
7032 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7033 indirect buffer previously made with this command, to avoid proliferation of
7034 indirect buffers. However, when you call the command with a \
7035 \\[universal-argument] prefix, or
7036 when `org-indirect-buffer-display' is `new-frame', the last buffer
7037 is kept so that you can work with several indirect buffers at the same time.
7038 If `org-indirect-buffer-display' is `dedicated-frame', the \
7039 \\[universal-argument] prefix also
7040 requests that a new frame be made for the new buffer, so that the dedicated
7041 frame is not changed."
7043 (let ((cbuf (current-buffer))
7044 (cwin (selected-window))
7046 beg end level heading ibuf)
7048 (org-back-to-heading t)
7050 (setq level (org-outline-level))
7051 (if (< arg 0) (setq arg (+ level arg)))
7052 (while (> (setq level (org-outline-level)) arg)
7053 (outline-up-heading 1 t)))
7055 heading (org-get-heading))
7056 (org-end-of-subtree t t)
7057 (if (org-at-heading-p) (backward-char 1))
7059 (if (and (buffer-live-p org-last-indirect-buffer)
7060 (not (eq org-indirect-buffer-display 'new-frame))
7062 (kill-buffer org-last-indirect-buffer))
7063 (setq ibuf (org-get-indirect-buffer cbuf)
7064 org-last-indirect-buffer ibuf)
7066 ((or (eq org-indirect-buffer-display 'new-frame)
7067 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7068 (select-frame (make-frame))
7069 (delete-other-windows)
7070 (org-pop-to-buffer-same-window ibuf)
7071 (org-set-frame-title heading))
7072 ((eq org-indirect-buffer-display 'dedicated-frame)
7074 (select-frame (or (and org-indirect-dedicated-frame
7075 (frame-live-p org-indirect-dedicated-frame)
7076 org-indirect-dedicated-frame)
7077 (setq org-indirect-dedicated-frame (make-frame)))))
7078 (delete-other-windows)
7079 (org-pop-to-buffer-same-window ibuf)
7080 (org-set-frame-title (concat "Indirect: " heading)))
7081 ((eq org-indirect-buffer-display 'current-window)
7082 (org-pop-to-buffer-same-window ibuf))
7083 ((eq org-indirect-buffer-display 'other-window)
7084 (pop-to-buffer ibuf))
7085 (t (error "Invalid value")))
7086 (if (featurep 'xemacs)
7087 (save-excursion (org-mode) (turn-on-font-lock)))
7088 (narrow-to-region beg end)
7091 (run-hook-with-args 'org-cycle-hook 'all)
7092 (and (window-live-p cwin) (select-window cwin))))
7094 (defun org-get-indirect-buffer (&optional buffer)
7095 (setq buffer (or buffer (current-buffer)))
7096 (let ((n 1) (base (buffer-name buffer)) bname)
7097 (while (buffer-live-p
7098 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7101 (make-indirect-buffer buffer bname 'clone)
7102 (error (make-indirect-buffer buffer bname)))))
7104 (defun org-set-frame-title (title)
7105 "Set the title of the current frame to the string TITLE."
7106 ;; FIXME: how to name a single frame in XEmacs???
7107 (unless (featurep 'xemacs)
7108 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7110 ;;;; Structure editing
7112 ;;; Inserting headlines
7114 (defun org-previous-line-empty-p ()
7117 (or (beginning-of-line 0) t)
7119 (looking-at "[ \t]*$")))))
7121 (defun org-insert-heading (&optional force-heading invisible-ok)
7122 "Insert a new heading or item with same depth at point.
7123 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7124 If point is at the beginning of a headline, insert a sibling before the
7125 current headline. If point is not at the beginning, split the line,
7126 create the new headline with the text in the current line after point
7127 \(but see also the variable `org-M-RET-may-split-line').
7129 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7130 This is important for non-interactive uses of the command."
7132 (if (or (= (buffer-size) 0)
7133 (and (not (save-excursion
7134 (and (ignore-errors (org-back-to-heading invisible-ok))
7135 (org-at-heading-p))))
7136 (or force-heading (not (org-in-item-p)))))
7139 (run-hooks 'org-insert-heading-hook))
7140 (when (or force-heading (not (org-insert-item)))
7141 (let* ((empty-line-p nil)
7143 (on-heading (org-at-heading-p))
7144 (head (save-excursion
7147 (org-back-to-heading invisible-ok)
7148 (when (and (not on-heading)
7149 (featurep 'org-inlinetask)
7150 (integerp org-inlinetask-min-level)
7151 (>= (length (match-string 0))
7152 org-inlinetask-min-level))
7153 ;; Find a heading level before the inline task
7154 (while (and (setq level (org-up-heading-safe))
7155 (>= level org-inlinetask-min-level)))
7156 (if (org-at-heading-p)
7157 (org-back-to-heading invisible-ok)
7158 (error "This should not happen")))
7159 (setq empty-line-p (org-previous-line-empty-p))
7162 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7163 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7164 pos hide-previous previous-pos)
7166 ((and (org-at-heading-p) (bolp)
7168 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7169 ;; insert before the current line
7170 (open-line (if blank 2 1)))
7172 (not org-insert-heading-respect-content)
7175 (backward-char 1) (not (outline-invisible-p)))))
7176 ;; insert right here
7179 ;; somewhere in the line
7181 (setq previous-pos (point-at-bol))
7183 (setq hide-previous (outline-invisible-p)))
7184 (and org-insert-heading-respect-content (org-show-subtree))
7186 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7189 (goto-char (point-at-bol))
7190 (and (looking-at org-complex-heading-regexp)
7192 (> p (match-beginning 4)))))))
7195 (org-insert-heading-respect-content
7196 (org-end-of-subtree nil t)
7197 (when (featurep 'org-inlinetask)
7198 (while (and (not (eobp))
7199 (looking-at "\\(\\*+\\)[ \t]+")
7200 (>= (length (match-string 1))
7201 org-inlinetask-min-level))
7202 (org-end-of-subtree nil t)))
7203 (or (bolp) (newline))
7204 (or (org-previous-line-empty-p)
7205 (and blank (newline)))
7211 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7212 (setq tags (and (match-end 2) (match-string 2)))
7214 (delete-region (match-beginning 1) (match-end 1)))
7215 (setq pos (point-at-bol))
7216 (or split (end-of-line 1))
7217 (delete-horizontal-space)
7218 (if (string-match "\\`\\*+\\'"
7219 (buffer-substring (point-at-bol) (point)))
7221 (newline (if blank 2 1))
7227 (org-set-tags nil 'align))))
7229 (or split (end-of-line 1))
7230 (newline (if blank 2 1)))))))
7231 (insert head) (just-one-space)
7234 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7235 (when (and org-insert-heading-respect-content hide-previous)
7237 (goto-char previous-pos)
7239 (run-hooks 'org-insert-heading-hook)))))
7241 (defun org-get-heading (&optional no-tags no-todo)
7242 "Return the heading of the current entry, without the stars.
7243 When NO-TAGS is non-nil, don't include tags.
7244 When NO-TODO is non-nil, don't include TODO keywords."
7246 (org-back-to-heading t)
7248 ((and no-tags no-todo)
7249 (looking-at org-complex-heading-regexp)
7252 (looking-at (concat org-outline-regexp
7254 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7257 (looking-at org-todo-line-regexp)
7259 (t (looking-at org-heading-regexp)
7260 (match-string 2)))))
7262 (defun org-heading-components ()
7263 "Return the components of the current heading.
7264 This is a list with the following elements:
7265 - the level as an integer
7266 - the reduced level, different if `org-odd-levels-only' is set.
7267 - the TODO keyword, or nil
7268 - the priority character, like ?A, or nil if no priority is given
7269 - the headline text itself, or the tags string if no headline text
7270 - the tags string, or nil."
7272 (org-back-to-heading t)
7273 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7274 (list (length (match-string 1))
7275 (org-reduced-level (length (match-string 1)))
7276 (org-match-string-no-properties 2)
7277 (and (match-end 3) (aref (match-string 3) 2))
7278 (org-match-string-no-properties 4)
7279 (org-match-string-no-properties 5)))))
7281 (defun org-get-entry ()
7282 "Get the entry text, after heading, entire subtree."
7284 (org-back-to-heading t)
7285 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7287 (defun org-insert-heading-after-current ()
7288 "Insert a new heading with same level as current, after current subtree."
7290 (org-back-to-heading)
7291 (org-insert-heading)
7292 (org-move-subtree-down)
7295 (defun org-insert-heading-respect-content ()
7297 (let ((org-insert-heading-respect-content t))
7298 (org-insert-heading t)))
7300 (defun org-insert-todo-heading-respect-content (&optional force-state)
7302 (let ((org-insert-heading-respect-content t))
7303 (org-insert-todo-heading force-state t)))
7305 (defun org-insert-todo-heading (arg &optional force-heading)
7306 "Insert a new heading with the same level and TODO state as current heading.
7307 If the heading has no TODO state, or if the state is DONE, use the first
7308 state (TODO by default). Also with prefix arg, force first state."
7310 (when (or force-heading (not (org-insert-item 'checkbox)))
7311 (org-insert-heading force-heading)
7313 (org-back-to-heading)
7314 (outline-previous-heading)
7315 (looking-at org-todo-line-regexp))
7319 (not (match-beginning 2))
7320 (member (match-string 2) org-done-keywords))
7321 (car org-todo-keywords-1)
7325 (run-hook-with-args-until-success
7326 'org-todo-get-default-hook new-mark-x nil)
7328 (beginning-of-line 1)
7329 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7330 (if org-treat-insert-todo-heading-as-state-change
7332 (insert new-mark " "))))
7333 (when org-provide-todo-statistics
7334 (org-update-parent-todo-statistics))))
7336 (defun org-insert-subheading (arg)
7337 "Insert a new subheading and demote it.
7338 Works for outline headings and for plain lists alike."
7340 (org-insert-heading arg)
7342 ((org-at-heading-p) (org-do-demote))
7343 ((org-at-item-p) (org-indent-item))))
7345 (defun org-insert-todo-subheading (arg)
7346 "Insert a new subheading with TODO keyword or checkbox and demote it.
7347 Works for outline headings and for plain lists alike."
7349 (org-insert-todo-heading arg)
7351 ((org-at-heading-p) (org-do-demote))
7352 ((org-at-item-p) (org-indent-item))))
7354 ;;; Promotion and Demotion
7356 (defvar org-after-demote-entry-hook nil
7357 "Hook run after an entry has been demoted.
7358 The cursor will be at the beginning of the entry.
7359 When a subtree is being demoted, the hook will be called for each node.")
7361 (defvar org-after-promote-entry-hook nil
7362 "Hook run after an entry has been promoted.
7363 The cursor will be at the beginning of the entry.
7364 When a subtree is being promoted, the hook will be called for each node.")
7366 (defun org-promote-subtree ()
7367 "Promote the entire subtree.
7368 See also `org-promote'."
7371 (org-with-limited-levels (org-map-tree 'org-promote)))
7372 (org-fix-position-after-promote))
7374 (defun org-demote-subtree ()
7375 "Demote the entire subtree. See `org-demote'.
7376 See also `org-promote'."
7379 (org-with-limited-levels (org-map-tree 'org-demote)))
7380 (org-fix-position-after-promote))
7383 (defun org-do-promote ()
7384 "Promote the current heading higher up the tree.
7385 If the region is active in `transient-mark-mode', promote all headings
7389 (if (org-region-active-p)
7390 (org-map-region 'org-promote (region-beginning) (region-end))
7392 (org-fix-position-after-promote))
7394 (defun org-do-demote ()
7395 "Demote the current heading lower down the tree.
7396 If the region is active in `transient-mark-mode', demote all headings
7400 (if (org-region-active-p)
7401 (org-map-region 'org-demote (region-beginning) (region-end))
7403 (org-fix-position-after-promote))
7405 (defun org-fix-position-after-promote ()
7406 "Make sure that after pro/demotion cursor position is right."
7407 (let ((pos (point)))
7408 (when (save-excursion
7409 (beginning-of-line 1)
7410 (looking-at org-todo-line-regexp)
7411 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7412 (cond ((eobp) (insert " "))
7413 ((eolp) (insert " "))
7414 ((equal (char-after) ?\ ) (forward-char 1))))))
7416 (defun org-current-level ()
7417 "Return the level of the current entry, or nil if before the first headline.
7418 The level is the number of stars at the beginning of the headline."
7420 (org-with-limited-levels
7421 (if (ignore-errors (org-back-to-heading t))
7422 (funcall outline-level)))))
7424 (defun org-get-previous-line-level ()
7425 "Return the outline depth of the last headline before the current line.
7426 Returns 0 for the first headline in the buffer, and nil if before the
7428 (let ((current-level (org-current-level))
7429 (prev-level (when (> (line-number-at-pos) 1)
7431 (beginning-of-line 0)
7432 (org-current-level)))))
7433 (cond ((null current-level) nil) ; Before first headline
7434 ((null prev-level) 0) ; At first headline
7437 (defun org-reduced-level (l)
7438 "Compute the effective level of a heading.
7439 This takes into account the setting of `org-odd-levels-only'."
7442 (org-odd-levels-only (1+ (floor (/ l 2))))
7445 (defun org-level-increment ()
7446 "Return the number of stars that will be added or removed at a
7447 time to headlines when structure editing, based on the value of
7448 `org-odd-levels-only'."
7449 (if org-odd-levels-only 2 1))
7451 (defun org-get-valid-level (level &optional change)
7452 "Rectify a level change under the influence of `org-odd-levels-only'
7453 LEVEL is a current level, CHANGE is by how much the level should be
7454 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7455 even level numbers will become the next higher odd number."
7456 (if org-odd-levels-only
7457 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7458 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7459 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7460 (max 1 (+ level (or change 0)))))
7462 (if (boundp 'define-obsolete-function-alias)
7463 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7464 (define-obsolete-function-alias 'org-get-legal-level
7465 'org-get-valid-level)
7466 (define-obsolete-function-alias 'org-get-legal-level
7467 'org-get-valid-level "23.1")))
7469 (defun org-promote ()
7470 "Promote the current heading higher up the tree.
7471 If the region is active in `transient-mark-mode', promote all headings
7473 (org-back-to-heading t)
7474 (let* ((level (save-match-data (funcall outline-level)))
7475 (after-change-functions (remove 'flyspell-after-change-function
7476 after-change-functions))
7477 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7478 (diff (abs (- level (length up-head) -1))))
7479 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7480 (replace-match up-head nil t)
7481 ;; Fixup tag positioning
7482 (and org-auto-align-tags (org-set-tags nil t))
7483 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7484 (run-hooks 'org-after-promote-entry-hook)))
7486 (defun org-demote ()
7487 "Demote the current heading lower down the tree.
7488 If the region is active in `transient-mark-mode', demote all headings
7490 (org-back-to-heading t)
7491 (let* ((level (save-match-data (funcall outline-level)))
7492 (after-change-functions (remove 'flyspell-after-change-function
7493 after-change-functions))
7494 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7495 (diff (abs (- level (length down-head) -1))))
7496 (replace-match down-head nil t)
7497 ;; Fixup tag positioning
7498 (and org-auto-align-tags (org-set-tags nil t))
7499 (if org-adapt-indentation (org-fixup-indentation diff))
7500 (run-hooks 'org-after-demote-entry-hook)))
7502 (defun org-cycle-level ()
7503 "Cycle the level of an empty headline through possible states.
7504 This goes first to child, then to parent, level, then up the hierarchy.
7505 After top level, it switches back to sibling level."
7507 (let ((org-adapt-indentation nil))
7508 (when (org-point-at-end-of-empty-headline)
7509 (setq this-command 'org-cycle-level) ; Only needed for caching
7510 (let ((cur-level (org-current-level))
7511 (prev-level (org-get-previous-line-level)))
7513 ;; If first headline in file, promote to top-level.
7515 (loop repeat (/ (- cur-level 1) (org-level-increment))
7516 do (org-do-promote)))
7517 ;; If same level as prev, demote one.
7518 ((= prev-level cur-level)
7520 ;; If parent is top-level, promote to top level if not already.
7522 (loop repeat (/ (- cur-level 1) (org-level-increment))
7523 do (org-do-promote)))
7524 ;; If top-level, return to prev-level.
7526 (loop repeat (/ (- prev-level 1) (org-level-increment))
7527 do (org-do-demote)))
7528 ;; If less than prev-level, promote one.
7529 ((< cur-level prev-level)
7531 ;; If deeper than prev-level, promote until higher than
7533 ((> cur-level prev-level)
7534 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7535 do (org-do-promote))))
7538 (defun org-map-tree (fun)
7539 "Call FUN for every heading underneath the current one."
7540 (org-back-to-heading)
7541 (let ((level (funcall outline-level)))
7545 (outline-next-heading)
7546 (> (funcall outline-level) level))
7550 (defun org-map-region (fun beg end)
7551 "Call FUN for every heading between BEG and END."
7552 (let ((org-ignore-region t))
7554 (setq end (copy-marker end))
7556 (if (and (re-search-forward org-outline-regexp-bol nil t)
7560 (outline-next-heading)
7565 (defvar org-property-end-re) ; silence byte-compiler
7566 (defun org-fixup-indentation (diff)
7567 "Change the indentation in the current entry by DIFF.
7568 However, if any line in the current entry has no indentation, or if it
7569 would end up with no indentation after the change, nothing at all is done."
7571 (let ((end (save-excursion (outline-next-heading)
7573 (prohibit (if (> diff 0)
7575 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7577 (unless (save-excursion (end-of-line 1)
7578 (re-search-forward prohibit end t))
7579 (while (and (< (point) end)
7580 (re-search-forward "^[ \t]+" end t))
7581 (goto-char (match-end 0))
7582 (setq col (current-column))
7583 (if (< diff 0) (replace-match ""))
7584 (org-indent-to-column (+ diff col))))
7585 (move-marker end nil))))
7587 (defun org-convert-to-odd-levels ()
7588 "Convert an org-mode file with all levels allowed to one with odd levels.
7589 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7592 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7593 (let ((outline-level 'org-outline-level)
7594 (org-odd-levels-only nil) n)
7596 (goto-char (point-min))
7597 (while (re-search-forward "^\\*\\*+ " nil t)
7598 (setq n (- (length (match-string 0)) 2))
7599 (while (>= (setq n (1- n)) 0)
7601 (end-of-line 1))))))
7603 (defun org-convert-to-oddeven-levels ()
7604 "Convert an org-mode file with only odd levels to one with odd/even levels.
7605 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7606 file contains a section with an even level, conversion would
7607 destroy the structure of the file. An error is signaled in this
7610 (goto-char (point-min))
7611 ;; First check if there are no even levels
7612 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7613 (org-show-context t)
7614 (error "Not all levels are odd in this file. Conversion not possible"))
7615 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7616 (let ((outline-regexp org-outline-regexp)
7617 (outline-level 'org-outline-level)
7618 (org-odd-levels-only nil) n)
7620 (goto-char (point-min))
7621 (while (re-search-forward "^\\*\\*+ " nil t)
7622 (setq n (/ (1- (length (match-string 0))) 2))
7623 (while (>= (setq n (1- n)) 0)
7625 (end-of-line 1))))))
7627 (defun org-tr-level (n)
7628 "Make N odd if required."
7629 (if org-odd-levels-only (1+ (/ n 2)) n))
7631 ;;; Vertical tree motion, cutting and pasting of subtrees
7633 (defun org-move-subtree-up (&optional arg)
7634 "Move the current subtree up past ARG headlines of the same level."
7636 (org-move-subtree-down (- (prefix-numeric-value arg))))
7638 (defun org-move-subtree-down (&optional arg)
7639 "Move the current subtree down past ARG headlines of the same level."
7641 (setq arg (prefix-numeric-value arg))
7642 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7643 'org-get-last-sibling))
7644 (ins-point (make-marker))
7646 (col (current-column))
7647 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7649 (org-back-to-heading)
7652 (setq ne-beg (org-back-over-empty-lines))
7655 (save-excursion (outline-end-of-heading)
7656 (setq folded (outline-invisible-p)))
7657 (outline-end-of-subtree))
7658 (outline-next-heading)
7659 (setq ne-end (org-back-over-empty-lines))
7662 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7663 ;; include less whitespace
7666 (forward-line (- ne-beg ne-end))
7667 (setq beg (point))))
7668 ;; Find insertion point, with error handling
7670 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7671 (progn (goto-char beg0)
7672 (error "Cannot move past superior level or buffer limit")))
7673 (setq cnt (1- cnt)))
7675 ;; Moving forward - still need to move over subtree
7676 (progn (org-end-of-subtree t t)
7678 (org-back-over-empty-lines)
7679 (or (bolp) (newline)))))
7680 (setq ne-ins (org-back-over-empty-lines))
7681 (move-marker ins-point (point))
7682 (setq txt (buffer-substring beg end))
7683 (org-save-markers-in-region beg end)
7684 (delete-region beg end)
7685 (org-remove-empty-overlays-at beg)
7686 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7687 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7688 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7689 (let ((bbb (point)))
7690 (insert-before-markers txt)
7691 (org-reinstall-markers-in-region bbb)
7692 (move-marker ins-point bbb))
7693 (or (bolp) (insert "\n"))
7694 (setq ins-end (point))
7695 (goto-char ins-point)
7696 (org-skip-whitespace)
7697 (when (and (< arg 0)
7698 (org-first-sibling-p)
7700 ;; Move whitespace back to beginning
7703 (let ((kill-whole-line t))
7704 (kill-line (- ne-ins ne-beg)) (point)))
7705 (insert (make-string (- ne-ins ne-beg) ?\n)))
7706 (move-marker ins-point nil)
7711 (org-cycle-hide-drawers 'children))
7712 (org-clean-visibility-after-subtree-move)
7713 ;; move back to the initial column we were at
7714 (move-to-column col)))
7716 (defvar org-subtree-clip ""
7717 "Clipboard for cut and paste of subtrees.
7718 This is actually only a copy of the kill, because we use the normal kill
7719 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7721 (defvar org-subtree-clip-folded nil
7722 "Was the last copied subtree folded?
7723 This is used to fold the tree back after pasting.")
7725 (defun org-cut-subtree (&optional n)
7726 "Cut the current subtree into the clipboard.
7727 With prefix arg N, cut this many sequential subtrees.
7728 This is a short-hand for marking the subtree and then cutting it."
7730 (org-copy-subtree n 'cut))
7732 (defun org-copy-subtree (&optional n cut force-store-markers)
7733 "Cut the current subtree into the clipboard.
7734 With prefix arg N, cut this many sequential subtrees.
7735 This is a short-hand for marking the subtree and then copying it.
7736 If CUT is non-nil, actually cut the subtree.
7737 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7738 of some markers in the region, even if CUT is non-nil. This is
7739 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7741 (let (beg end folded (beg0 (point)))
7742 (if (org-called-interactively-p 'any)
7743 (org-back-to-heading nil) ; take what looks like a subtree
7744 (org-back-to-heading t)) ; take what is really there
7745 (org-back-over-empty-lines)
7747 (skip-chars-forward " \t\r\n")
7749 (save-excursion (outline-end-of-heading)
7750 (setq folded (outline-invisible-p)))
7752 (org-forward-same-level (1- n) t)
7754 (org-end-of-subtree t t))
7755 (org-back-over-empty-lines)
7759 (setq org-subtree-clip-folded folded)
7760 (when (or cut force-store-markers)
7761 (org-save-markers-in-region beg end))
7762 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7763 (setq org-subtree-clip (current-kill 0))
7764 (message "%s: Subtree(s) with %d characters"
7765 (if cut "Cut" "Copied")
7766 (length org-subtree-clip)))))
7768 (defun org-paste-subtree (&optional level tree for-yank)
7769 "Paste the clipboard as a subtree, with modification of headline level.
7770 The entire subtree is promoted or demoted in order to match a new headline
7773 If the cursor is at the beginning of a headline, the same level as
7774 that headline is used to paste the tree
7776 If not, the new level is derived from the *visible* headings
7777 before and after the insertion point, and taken to be the inferior headline
7778 level of the two. So if the previous visible heading is level 3 and the
7779 next is level 4 (or vice versa), level 4 will be used for insertion.
7780 This makes sure that the subtree remains an independent subtree and does
7781 not swallow low level entries.
7783 You can also force a different level, either by using a numeric prefix
7784 argument, or by inserting the heading marker by hand. For example, if the
7785 cursor is after \"*****\", then the tree will be shifted to level 5.
7787 If optional TREE is given, use this text instead of the kill ring.
7789 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7790 move back over whitespace before inserting, and move point to the end of
7791 the inserted text when done."
7793 (setq tree (or tree (and kill-ring (current-kill 0))))
7794 (unless (org-kill-is-subtree-p tree)
7796 (substitute-command-keys
7797 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7798 (org-with-limited-levels
7799 (let* ((visp (not (outline-invisible-p)))
7801 (^re_ "\\(\\*+\\)[ \t]*")
7802 (old-level (if (string-match org-outline-regexp-bol txt)
7803 (- (match-end 0) (match-beginning 0) 1)
7805 (force-level (cond (level (prefix-numeric-value level))
7806 ((and (looking-at "[ \t]*$")
7808 "^\\*+$" (buffer-substring
7809 (point-at-bol) (point))))
7810 (- (match-end 1) (match-beginning 1)))
7812 (looking-at org-outline-regexp))
7813 (- (match-end 0) (point) 1))
7815 (previous-level (save-excursion
7818 (outline-previous-visible-heading 1)
7819 (if (looking-at ^re_)
7820 (- (match-end 0) (match-beginning 0) 1)
7823 (next-level (save-excursion
7826 (or (looking-at org-outline-regexp)
7827 (outline-next-visible-heading 1))
7828 (if (looking-at ^re_)
7829 (- (match-end 0) (match-beginning 0) 1)
7832 (new-level (or force-level (max previous-level next-level)))
7833 (shift (if (or (= old-level -1)
7835 (= old-level new-level))
7837 (- new-level old-level)))
7838 (delta (if (> shift 0) -1 1))
7839 (func (if (> shift 0) 'org-demote 'org-promote))
7840 (org-odd-levels-only nil)
7842 ;; Remove the forced level indicator
7844 (delete-region (point-at-bol) (point)))
7846 (beginning-of-line (if (bolp) 1 2))
7847 (unless for-yank (org-back-over-empty-lines))
7849 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7850 (insert-before-markers txt)
7851 (unless (string-match "\n\\'" txt) (insert "\n"))
7852 (setq newend (point))
7853 (org-reinstall-markers-in-region beg)
7856 (skip-chars-forward " \t\n\r")
7858 (if (and (outline-invisible-p) visp)
7859 (save-excursion (outline-show-heading)))
7860 ;; Shift if necessary
7863 (narrow-to-region beg end)
7864 (while (not (= shift 0))
7865 (org-map-region func (point-min) (point-max))
7866 (setq shift (+ delta shift)))
7867 (goto-char (point-min))
7868 (setq newend (point-max))))
7869 (when (or (org-called-interactively-p 'interactive) for-yank)
7870 (message "Clipboard pasted as level %d subtree" new-level))
7871 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7873 (eq org-subtree-clip (current-kill 0))
7874 org-subtree-clip-folded)
7875 ;; The tree was folded before it was killed/copied
7877 (and for-yank (goto-char newend)))))
7879 (defun org-kill-is-subtree-p (&optional txt)
7880 "Check if the current kill is an outline subtree, or a set of trees.
7881 Returns nil if kill does not start with a headline, or if the first
7882 headline level is not the largest headline level in the tree.
7883 So this will actually accept several entries of equal levels as well,
7884 which is OK for `org-paste-subtree'.
7885 If optional TXT is given, check this string instead of the current kill."
7886 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7887 (re (org-get-limited-outline-regexp))
7888 (^re (concat "^" re))
7889 (start-level (and kill
7891 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7893 (- (match-end 2) (match-beginning 2) 1)))
7894 (start (1+ (or (match-beginning 2) -1))))
7895 (if (not start-level)
7897 nil) ;; does not even start with a heading
7899 (while (setq start (string-match ^re kill (1+ start)))
7900 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7904 (defvar org-markers-to-move nil
7905 "Markers that should be moved with a cut-and-paste operation.
7906 Those markers are stored together with their positions relative to
7907 the start of the region.")
7909 (defun org-save-markers-in-region (beg end)
7910 "Check markers in region.
7911 If these markers are between BEG and END, record their position relative
7912 to BEG, so that after moving the block of text, we can put the markers back
7914 This function gets called just before an entry or tree gets cut from the
7915 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7916 called immediately, to move the markers with the entries."
7917 (setq org-markers-to-move nil)
7918 (when (featurep 'org-clock)
7919 (org-clock-save-markers-for-cut-and-paste beg end))
7920 (when (featurep 'org-agenda)
7921 (org-agenda-save-markers-for-cut-and-paste beg end)))
7923 (defun org-check-and-save-marker (marker beg end)
7924 "Check if MARKER is between BEG and END.
7925 If yes, remember the marker and the distance to BEG."
7926 (when (and (marker-buffer marker)
7927 (equal (marker-buffer marker) (current-buffer)))
7928 (if (and (>= marker beg) (< marker end))
7929 (push (cons marker (- marker beg)) org-markers-to-move))))
7931 (defun org-reinstall-markers-in-region (beg)
7932 "Move all remembered markers to their position relative to BEG."
7934 (move-marker (car x) (+ beg (cdr x))))
7935 org-markers-to-move)
7936 (setq org-markers-to-move nil))
7938 (defun org-narrow-to-subtree ()
7939 "Narrow buffer to the current subtree."
7943 (org-with-limited-levels
7945 (progn (org-back-to-heading t) (point))
7946 (progn (org-end-of-subtree t t)
7947 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7950 (defun org-narrow-to-block ()
7951 "Narrow buffer to the current block."
7953 (let* ((case-fold-search t)
7954 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7955 "^[ \t]*#\\+end_.*")))
7957 (narrow-to-region (car blockp) (cdr blockp))
7958 (error "Not in a block"))))
7961 (defvar org-property-drawer-re))
7963 (defvar org-property-start-re) ;; defined below
7964 (defun org-clone-subtree-with-time-shift (n &optional shift)
7965 "Clone the task (subtree) at point N times.
7966 The clones will be inserted as siblings.
7968 In interactive use, the user will be prompted for the number of
7969 clones to be produced, and for a time SHIFT, which may be a
7970 repeater as used in time stamps, for example `+3d'.
7972 When a valid repeater is given and the entry contains any time
7973 stamps, the clones will become a sequence in time, with time
7974 stamps in the subtree shifted for each clone produced. If SHIFT
7975 is nil or the empty string, time stamps will be left alone. The
7976 ID property of the original subtree is removed.
7978 If the original subtree did contain time stamps with a repeater,
7979 the following will happen:
7980 - the repeater will be removed in each clone
7981 - an additional clone will be produced, with the current, unshifted
7982 date(s) in the entry.
7983 - the original entry will be placed *after* all the clones, with
7985 - the start days in the repeater in the original entry will be shifted
7986 to past the last clone.
7987 In this way you can spell out a number of instances of a repeating task,
7988 and still retain the repeater to cover future instances of the task."
7989 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7990 (let (beg end template task idprop
7991 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7992 (drawer-re org-drawer-regexp))
7993 (if (not (and (integerp n) (> n 0)))
7994 (error "Invalid number of replications %s" n))
7995 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7996 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
7998 (error "Invalid shift specification %s" shift))
8000 (setq shift-n (string-to-number (match-string 1 shift))
8001 shift-what (cdr (assoc (match-string 2 shift)
8002 '(("d" . day) ("w" . week)
8003 ("m" . month) ("y" . year))))))
8004 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8005 (setq nmin 1 nmax n)
8006 (org-back-to-heading t)
8008 (setq idprop (org-entry-get nil "ID"))
8009 (org-end-of-subtree t t)
8010 (or (bolp) (insert "\n"))
8012 (setq template (buffer-substring beg end))
8014 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8015 (delete-region beg end)
8017 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8019 (loop for n from nmin to nmax do
8024 (goto-char (point-min))
8026 (and idprop (if org-clone-delete-id
8027 (org-entry-delete nil "ID")
8028 (org-id-get-create t)))
8030 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8032 (goto-char (point-min))
8033 (while (re-search-forward drawer-re nil t)
8035 (org-remove-empty-drawer-at d (point))) org-drawers)))
8036 (goto-char (point-min))
8038 (while (re-search-forward org-ts-regexp-both nil t)
8039 (org-timestamp-change (* n shift-n) shift-what))
8040 (unless (= n n-no-remove)
8041 (goto-char (point-min))
8042 (while (re-search-forward org-ts-regexp nil t)
8044 (goto-char (match-beginning 0))
8045 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8046 (delete-region (match-beginning 1) (match-end 1)))))))
8047 (setq task (buffer-string)))
8053 (defun org-sort (with-case)
8054 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8055 Optional argument WITH-CASE means sort case-sensitively."
8058 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8059 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8061 (org-call-with-arg 'org-sort-entries with-case))))
8063 (defun org-sort-remove-invisible (s)
8064 (remove-text-properties 0 (length s) org-rm-props s)
8065 (while (string-match org-bracket-link-regexp s)
8066 (setq s (replace-match (if (match-end 2)
8068 (match-string 1 s)) t t s)))
8071 (defvar org-priority-regexp) ; defined later in the file
8073 (defvar org-after-sorting-entries-or-items-hook nil
8074 "Hook that is run after a bunch of entries or items have been sorted.
8075 When children are sorted, the cursor is in the parent line when this
8076 hook gets called. When a region or a plain list is sorted, the cursor
8077 will be in the first entry of the sorted region/list.")
8079 (defun org-sort-entries
8080 (&optional with-case sorting-type getkey-func compare-func property)
8081 "Sort entries on a certain level of an outline tree.
8082 If there is an active region, the entries in the region are sorted.
8083 Else, if the cursor is before the first entry, sort the top-level items.
8084 Else, the children of the entry at point are sorted.
8086 Sorting can be alphabetically, numerically, by date/time as given by
8087 a time stamp, by a property or by priority.
8089 The command prompts for the sorting type unless it has been given to the
8090 function through the SORTING-TYPE argument, which needs to be a character,
8091 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8092 precise meaning of each character:
8094 n Numerically, by converting the beginning of the entry/item to a number.
8095 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8096 t By date/time, either the first active time stamp in the entry, or, if
8097 none exist, by the first inactive one.
8098 s By the scheduled date/time.
8099 d By deadline date/time.
8100 c By creation time, which is assumed to be the first inactive time stamp
8101 at the beginning of a line.
8102 p By priority according to the cookie.
8103 r By the value of a property.
8105 Capital letters will reverse the sort order.
8107 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8108 called with point at the beginning of the record. It must return either
8109 a string or a number that should serve as the sorting key for that record.
8111 Comparing entries ignores case by default. However, with an optional argument
8112 WITH-CASE, the sorting considers case as well."
8114 (let ((case-func (if with-case 'identity 'downcase))
8115 start beg end stars re re2
8117 ;; Find beginning and end of region to sort
8119 ((org-region-active-p)
8120 ;; we will sort the region
8121 (setq end (region-end)
8123 (goto-char (region-beginning))
8124 (if (not (org-at-heading-p)) (outline-next-heading))
8125 (setq start (point)))
8126 ((or (org-at-heading-p)
8127 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8128 ;; we will sort the children of the current headline
8129 (org-back-to-heading)
8131 end (progn (org-end-of-subtree t t)
8132 (or (bolp) (insert "\n"))
8133 (org-back-over-empty-lines)
8138 (outline-next-heading))
8140 ;; we will sort the top-level entries in this file
8141 (goto-char (point-min))
8142 (or (org-at-heading-p) (outline-next-heading))
8143 (setq start (point))
8144 (goto-char (point-max))
8145 (beginning-of-line 1)
8146 (when (looking-at ".*?\\S-")
8147 ;; File ends in a non-white line
8150 (setq end (point-max))
8151 (setq what "top-level")
8156 (if (>= beg end) (error "Nothing to sort"))
8158 (looking-at "\\(\\*+\\)")
8159 (setq stars (match-string 1)
8160 re (concat "^" (regexp-quote stars) " +")
8161 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8162 txt (buffer-substring beg end))
8163 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8164 (if (and (not (equal stars "*")) (string-match re2 txt))
8165 (error "Region to sort contains a level above the first entry"))
8167 (unless sorting-type
8169 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8170 [t]ime
[s]cheduled [d]eadline [c]reated
8171 A/N/T/S/D/C/P/O/F means reversed:"
8173 (setq sorting-type (read-char-exclusive))
8175 (and (= (downcase sorting-type) ?f)
8177 (org-icompleting-read "Sort using function: "
8178 obarray 'fboundp t nil nil))
8179 (setq getkey-func (intern getkey-func)))
8181 (and (= (downcase sorting-type) ?r)
8183 (org-icompleting-read "Property: "
8184 (mapcar 'list (org-buffer-property-keys t))
8187 (message "Sorting entries...")
8190 (narrow-to-region start end)
8191 (let ((dcst (downcase sorting-type))
8192 (case-fold-search nil)
8193 (now (current-time)))
8195 (/= dcst sorting-type)
8196 ;; This function moves to the beginning character of the "record" to
8199 (if (re-search-forward re nil t)
8200 (goto-char (match-beginning 0))
8201 (goto-char (point-max))))
8202 ;; This function moves to the last character of the "record" being
8207 (outline-forward-same-level 1)
8209 (goto-char (point-max))))))
8210 ;; This function returns the value that gets sorted against.
8214 (if (looking-at org-complex-heading-regexp)
8215 (string-to-number (match-string 4))
8218 (if (looking-at org-complex-heading-regexp)
8219 (funcall case-func (match-string 4))
8222 (let ((end (save-excursion (outline-next-heading) (point))))
8223 (if (or (re-search-forward org-ts-regexp end t)
8224 (re-search-forward org-ts-regexp-both end t))
8225 (org-time-string-to-seconds (match-string 0))
8226 (org-float-time now))))
8228 (let ((end (save-excursion (outline-next-heading) (point))))
8229 (if (re-search-forward
8230 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8232 (org-time-string-to-seconds (match-string 0))
8233 (org-float-time now))))
8235 (let ((end (save-excursion (outline-next-heading) (point))))
8236 (if (re-search-forward org-scheduled-time-regexp end t)
8237 (org-time-string-to-seconds (match-string 1))
8238 (org-float-time now))))
8240 (let ((end (save-excursion (outline-next-heading) (point))))
8241 (if (re-search-forward org-deadline-time-regexp end t)
8242 (org-time-string-to-seconds (match-string 1))
8243 (org-float-time now))))
8245 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8246 (string-to-char (match-string 2))
8247 org-default-priority))
8249 (or (org-entry-get nil property) ""))
8251 (if (looking-at org-complex-heading-regexp)
8252 (- 9999 (length (member (match-string 2)
8253 org-todo-keywords-1)))))
8257 (setq tmp (funcall getkey-func))
8258 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8260 (error "Invalid key function `%s'" getkey-func)))
8261 (t (error "Invalid sorting type `%c'" sorting-type))))
8264 ((= dcst ?a) 'string<)
8265 ((= dcst ?f) compare-func)
8266 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8268 (run-hooks 'org-after-sorting-entries-or-items-hook)
8269 (message "Sorting entries...done")))
8271 (defun org-do-sort (table what &optional with-case sorting-type)
8272 "Sort TABLE of WHAT according to SORTING-TYPE.
8273 The user will be prompted for the SORTING-TYPE if the call to this
8274 function does not specify it. WHAT is only for the prompt, to indicate
8275 what is being sorted. The sorting key will be extracted from
8276 the car of the elements of the table.
8277 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8278 (unless sorting-type
8280 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8282 (setq sorting-type (read-char-exclusive)))
8283 (let ((dcst (downcase sorting-type))
8284 extractfun comparefun)
8285 ;; Define the appropriate functions
8288 (setq extractfun 'string-to-number
8289 comparefun (if (= dcst sorting-type) '< '>)))
8291 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8292 (lambda(x) (downcase (org-sort-remove-invisible x))))
8293 comparefun (if (= dcst sorting-type)
8295 (lambda (a b) (and (not (string< a b))
8296 (not (string= a b)))))))
8300 (if (or (string-match org-ts-regexp x)
8301 (string-match org-ts-regexp-both x))
8303 (org-time-string-to-time (match-string 0 x)))
8305 comparefun (if (= dcst sorting-type) '< '>)))
8306 (t (error "Invalid sorting type `%c'" sorting-type)))
8308 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8310 (lambda (a b) (funcall comparefun (car a) (car b))))))
8313 ;;; The orgstruct minor mode
8315 ;; Define a minor mode which can be used in other modes in order to
8316 ;; integrate the org-mode structure editing commands.
8318 ;; This is really a hack, because the org-mode structure commands use
8319 ;; keys which normally belong to the major mode. Here is how it
8320 ;; works: The minor mode defines all the keys necessary to operate the
8321 ;; structure commands, but wraps the commands into a function which
8322 ;; tests if the cursor is currently at a headline or a plain list
8323 ;; item. If that is the case, the structure command is used,
8324 ;; temporarily setting many Org-mode variables like regular
8325 ;; expressions for filling etc. However, when any of those keys is
8326 ;; used at a different location, function uses `key-binding' to look
8327 ;; up if the key has an associated command in another currently active
8328 ;; keymap (minor modes, major mode, global), and executes that
8329 ;; command. There might be problems if any of the keys is otherwise
8330 ;; used as a prefix key.
8332 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8333 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8334 ;; addresses this by checking explicitly for both bindings.
8336 (defvar orgstruct-mode-map (make-sparse-keymap)
8337 "Keymap for the minor `orgstruct-mode'.")
8339 (defvar org-local-vars nil
8340 "List of local variables, for use by `orgstruct-mode'.")
8343 (define-minor-mode orgstruct-mode
8344 "Toggle the minor mode `orgstruct-mode'.
8345 This mode is for using Org-mode structure commands in other
8346 modes. The following keys behave as if Org-mode were active, if
8347 the cursor is on a headline, or on a plain list item (both as
8348 defined by Org-mode).
8350 M-up Move entry/item up
8351 M-down Move entry/item down
8354 M-S-up Move entry/item up
8355 M-S-down Move entry/item down
8356 M-S-left Promote subtree
8357 M-S-right Demote subtree
8358 M-q Fill paragraph and items like in Org-mode
8360 C-c - Cycle list bullet
8361 TAB Cycle item visibility
8362 M-RET Insert new heading/item
8363 S-M-RET Insert new TODO heading / Checkbox item
8364 C-c C-c Set tags / toggle checkbox"
8365 nil " OrgStruct" nil
8366 (org-load-modules-maybe)
8367 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8370 (defun turn-on-orgstruct ()
8371 "Unconditionally turn on `orgstruct-mode'."
8374 (defvar org-fb-vars nil)
8375 (make-variable-buffer-local 'org-fb-vars)
8376 (defun orgstruct++-mode (&optional arg)
8377 "Toggle `orgstruct-mode', the enhanced version of it.
8378 In addition to setting orgstruct-mode, this also exports all indentation
8379 and autofilling variables from org-mode into the buffer. It will also
8380 recognize item context in multiline items.
8381 Note that turning off orgstruct-mode will *not* remove the
8382 indentation/paragraph settings. This can only be done by refreshing the
8383 major mode, for example with \\[normal-mode]."
8385 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8387 (progn (orgstruct-mode -1)
8389 (org-set-local (car v)
8390 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8393 (setq org-fb-vars nil)
8398 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8399 (symbol-name (car x)))
8400 (setq var (car x) val (nth 1 x))
8401 (push (list var `(quote ,(eval var))) org-fb-vars)
8402 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8404 (org-set-local 'orgstruct-is-++ t))))
8406 (defvar orgstruct-is-++ nil
8407 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8408 (make-variable-buffer-local 'orgstruct-is-++)
8411 (defun turn-on-orgstruct++ ()
8412 "Unconditionally turn on `orgstruct++-mode'."
8413 (orgstruct++-mode 1))
8415 (defun orgstruct-error ()
8416 "Error when there is no default binding for a structure key."
8418 (error "This key has no function outside structure elements"))
8420 (defun orgstruct-setup ()
8421 "Setup orgstruct keymaps."
8425 '([(meta up)] org-metaup)
8426 '([(meta down)] org-metadown)
8427 '([(meta left)] org-metaleft)
8428 '([(meta right)] org-metaright)
8429 '([(meta shift up)] org-shiftmetaup)
8430 '([(meta shift down)] org-shiftmetadown)
8431 '([(meta shift left)] org-shiftmetaleft)
8432 '([(meta shift right)] org-shiftmetaright)
8433 '([?\e (up)] org-metaup)
8434 '([?\e (down)] org-metadown)
8435 '([?\e (left)] org-metaleft)
8436 '([?\e (right)] org-metaright)
8437 '([?\e (shift up)] org-shiftmetaup)
8438 '([?\e (shift down)] org-shiftmetadown)
8439 '([?\e (shift left)] org-shiftmetaleft)
8440 '([?\e (shift right)] org-shiftmetaright)
8441 '([(shift up)] org-shiftup)
8442 '([(shift down)] org-shiftdown)
8443 '([(shift left)] org-shiftleft)
8444 '([(shift right)] org-shiftright)
8445 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8446 '("\M-q" fill-paragraph)
8448 '("\C-c-" org-cycle-list-bullet)))
8450 (while (setq elt (pop bindings))
8451 (setq nfunc (1+ nfunc))
8452 (setq key (org-key (car elt))
8454 cmd (orgstruct-make-binding fun nfunc key))
8455 (org-defkey orgstruct-mode-map key cmd))
8457 ;; Special treatment needed for TAB and RET
8458 (org-defkey orgstruct-mode-map [(tab)]
8459 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8460 (org-defkey orgstruct-mode-map "\C-i"
8461 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8463 (org-defkey orgstruct-mode-map "\M-\C-m"
8464 (orgstruct-make-binding 'org-insert-heading 105
8465 "\M-\C-m" [(meta return)]))
8466 (org-defkey orgstruct-mode-map [(meta return)]
8467 (orgstruct-make-binding 'org-insert-heading 106
8468 [(meta return)] "\M-\C-m"))
8470 (org-defkey orgstruct-mode-map [(shift meta return)]
8471 (orgstruct-make-binding 'org-insert-todo-heading 107
8472 [(meta return)] "\M-\C-m"))
8474 (org-defkey orgstruct-mode-map "\e\C-m"
8475 (orgstruct-make-binding 'org-insert-heading 108
8476 "\e\C-m" [?\e (return)]))
8477 (org-defkey orgstruct-mode-map [?\e (return)]
8478 (orgstruct-make-binding 'org-insert-heading 109
8479 [?\e (return)] "\e\C-m"))
8480 (org-defkey orgstruct-mode-map [?\e (shift return)]
8481 (orgstruct-make-binding 'org-insert-todo-heading 110
8482 [?\e (return)] "\e\C-m"))
8484 (unless org-local-vars
8485 (setq org-local-vars (org-get-local-variables)))
8489 (defun orgstruct-make-binding (fun n &rest keys)
8490 "Create a function for binding in the structure minor mode.
8491 FUN is the command to call inside a table. N is used to create a unique
8492 command name. KEYS are keys that should be checked in for a command
8493 to execute outside of tables."
8496 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8498 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8499 "Outside of structure, run the binding of `"
8500 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8504 `(org-context-p 'headline 'item
8505 (and orgstruct-is-++
8506 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8508 (list 'org-run-like-in-org-mode (list 'quote fun))
8509 (list 'let '(orgstruct-mode)
8510 (list 'call-interactively
8513 (list 'key-binding k))
8515 '('orgstruct-error))))))))
8517 (defun org-context-p (&rest contexts)
8518 "Check if local context is any of CONTEXTS.
8519 Possible values in the list of contexts are `table', `headline', and `item'."
8520 (let ((pos (point)))
8521 (goto-char (point-at-bol))
8522 (prog1 (or (and (memq 'table contexts)
8523 (looking-at "[ \t]*|"))
8524 (and (memq 'headline contexts)
8525 (looking-at org-outline-regexp))
8526 (and (memq 'item contexts)
8527 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8528 (and (memq 'item-body contexts)
8532 (defun org-get-local-variables ()
8533 "Return a list of all local variables in an org-mode buffer."
8535 (with-current-buffer (get-buffer-create "*Org tmp*")
8538 (setq varlist (buffer-local-variables)))
8539 (kill-buffer "*Org tmp*")
8546 (list (car x) (list 'quote (cdr x)))))
8548 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8549 (symbol-name (car x)))
8553 (defun org-clone-local-variables (from-buffer &optional regexp)
8554 "Clone local variables from FROM-BUFFER.
8555 Optional argument REGEXP selects variables to clone."
8558 (and (symbolp (car pair))
8560 (string-match regexp (symbol-name (car pair))))
8561 (set (make-local-variable (car pair))
8563 (buffer-local-variables from-buffer)))
8566 (defun org-run-like-in-org-mode (cmd)
8567 "Run a command, pretending that the current buffer is in Org-mode.
8568 This will temporarily bind local variables that are typically bound in
8569 Org-mode to the values they have in Org-mode, and then interactively
8571 (org-load-modules-maybe)
8572 (unless org-local-vars
8573 (setq org-local-vars (org-get-local-variables)))
8574 (eval (list 'let org-local-vars
8575 (list 'call-interactively (list 'quote cmd)))))
8579 (defun org-get-category (&optional pos force-refresh)
8580 "Get the category applying to position POS."
8582 (if force-refresh (org-refresh-category-properties))
8583 (let ((pos (or pos (point))))
8584 (or (get-text-property pos 'org-category)
8585 (progn (org-refresh-category-properties)
8586 (get-text-property pos 'org-category))))))
8588 (defun org-refresh-category-properties ()
8589 "Refresh category text properties in the buffer."
8590 (let ((inhibit-read-only t)
8592 ((null org-category)
8593 (if buffer-file-name
8594 (file-name-sans-extension
8595 (file-name-nondirectory buffer-file-name))
8597 ((symbolp org-category) (symbol-name org-category))
8599 beg end cat pos optionp)
8604 (goto-char (point-min))
8605 (put-text-property (point) (point-max) 'org-category def-cat)
8606 (while (re-search-forward
8607 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8608 (setq pos (match-end 0)
8609 optionp (equal (char-after (match-beginning 0)) ?#)
8610 cat (org-trim (match-string 2)))
8612 (setq beg (point-at-bol) end (point-max))
8613 (org-back-to-heading t)
8614 (setq beg (point) end (org-end-of-subtree t t)))
8615 (put-text-property beg end 'org-category cat)
8616 (put-text-property beg end 'org-category-position beg)
8617 (goto-char pos)))))))
8622 ;;; Link abbreviations
8624 (defun org-link-expand-abbrev (link)
8625 "Apply replacements as defined in `org-link-abbrev-alist'."
8626 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8627 (let* ((key (match-string 1 link))
8628 (as (or (assoc key org-link-abbrev-alist-local)
8629 (assoc key org-link-abbrev-alist)))
8630 (tag (and (match-end 2) (match-string 3 link)))
8636 ((symbolp rpl) (funcall rpl tag))
8637 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8638 ((string-match "%h" rpl)
8639 (replace-match (url-hexify-string (or tag "")) t t rpl))
8640 (t (concat rpl tag)))))
8643 ;;; Storing and inserting links
8645 (defvar org-insert-link-history nil
8646 "Minibuffer history for links inserted with `org-insert-link'.")
8648 (defvar org-stored-links nil
8649 "Contains the links stored with `org-store-link'.")
8651 (defvar org-store-link-plist nil
8652 "Plist with info about the most recently link created with `org-store-link'.")
8654 (defvar org-link-protocols nil
8655 "Link protocols added to Org-mode using `org-add-link-type'.")
8657 (defvar org-store-link-functions nil
8658 "List of functions that are called to create and store a link.
8659 Each function will be called in turn until one returns a non-nil
8660 value. Each function should check if it is responsible for creating
8661 this link (for example by looking at the major mode).
8662 If not, it must exit and return nil.
8663 If yes, it should return a non-nil value after a calling
8664 `org-store-link-props' with a list of properties and values.
8665 Special properties are:
8667 :type The link prefix, like \"http\". This must be given.
8668 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8669 This is obligatory as well.
8670 :description Optional default description for the second pair
8671 of brackets in an Org-mode link. The user can still change
8672 this when inserting this link into an Org-mode buffer.
8674 In addition to these, any additional properties can be specified
8675 and then used in remember templates.")
8677 (defun org-add-link-type (type &optional follow export)
8678 "Add TYPE to the list of `org-link-types'.
8679 Re-compute all regular expressions depending on `org-link-types'
8681 FOLLOW and EXPORT are two functions.
8683 FOLLOW should take the link path as the single argument and do whatever
8684 is necessary to follow the link, for example find a file or display
8687 EXPORT should format the link path for export to one of the export formats.
8688 It should be a function accepting three arguments:
8690 path the path of the link, the text after the prefix (like \"http:\")
8691 desc the description of the link, if any, or a description added by
8692 org-export-normalize-links if there is none
8693 format the export format, a symbol like `html' or `latex' or `ascii'..
8695 The function may use the FORMAT information to return different values
8696 depending on the format. The return value will be put literally into
8697 the exported file. If the return value is nil, this means Org should
8698 do what it normally does with links which do not have EXPORT defined.
8700 Org-mode has a built-in default for exporting links. If you are happy with
8701 this default, there is no need to define an export function for the link
8702 type. For a simple example of an export function, see `org-bbdb.el'."
8703 (add-to-list 'org-link-types type t)
8704 (org-make-link-regexps)
8705 (if (assoc type org-link-protocols)
8706 (setcdr (assoc type org-link-protocols) (list follow export))
8707 (push (list type follow export) org-link-protocols)))
8709 (defvar org-agenda-buffer-name)
8712 (defun org-store-link (arg)
8713 "\\<org-mode-map>Store an org-link to the current location.
8714 This link is added to `org-stored-links' and can later be inserted
8715 into an org-buffer with \\[org-insert-link].
8717 For some link types, a prefix arg is interpreted:
8718 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8719 For file links, arg negates `org-context-in-file-links'."
8721 (org-load-modules-maybe)
8722 (setq org-store-link-plist nil) ; reset
8723 (org-with-limited-levels
8724 (let (link cpltxt desc description search txt custom-id agenda-link)
8727 ((run-hook-with-args-until-success 'org-store-link-functions)
8728 (setq link (plist-get org-store-link-plist :link)
8729 desc (or (plist-get org-store-link-plist :description) link)))
8731 ((org-src-edit-buffer-p)
8733 (while (or (not label)
8737 (goto-char (point-min))
8739 (regexp-quote (format org-coderef-label-format label))
8741 (when label (message "Label exists already") (sit-for 2))
8742 (setq label (read-string "Code line label: " label)))
8744 (setq link (format org-coderef-label-format label))
8745 (setq gc (- 79 (length link)))
8746 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8748 (setq link (concat "(" label ")") desc nil)))
8750 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8751 ;; We are in the agenda, link to referenced location
8752 (let ((m (or (get-text-property (point) 'org-hd-marker)
8753 (get-text-property (point) 'org-marker))))
8755 (org-with-point-at m
8757 (if (org-called-interactively-p 'any)
8758 (call-interactively 'org-store-link)
8759 (org-store-link nil)))))))
8761 ((eq major-mode 'calendar-mode)
8762 (let ((cd (calendar-cursor-to-date)))
8765 (car org-time-stamp-formats)
8767 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8769 (org-store-link-props :type "calendar" :date cd)))
8771 ((eq major-mode 'w3-mode)
8772 (setq cpltxt (if (and (buffer-name)
8773 (not (string-match "Untitled" (buffer-name))))
8776 link (org-make-link (url-view-url t)))
8777 (org-store-link-props :type "w3" :url (url-view-url t)))
8779 ((eq major-mode 'w3m-mode)
8780 (setq cpltxt (or w3m-current-title w3m-current-url)
8781 link (org-make-link w3m-current-url))
8782 (org-store-link-props :type "w3m" :url (url-view-url t)))
8784 ((setq search (run-hook-with-args-until-success
8785 'org-create-file-search-functions))
8786 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8788 (setq cpltxt (or description link)))
8790 ((eq major-mode 'image-mode)
8791 (setq cpltxt (concat "file:"
8792 (abbreviate-file-name buffer-file-name))
8793 link (org-make-link cpltxt))
8794 (org-store-link-props :type "image" :file buffer-file-name))
8796 ((eq major-mode 'dired-mode)
8797 ;; link to the file in the current line
8798 (let ((file (dired-get-filename nil t)))
8800 (abbreviate-file-name
8801 (expand-file-name (dired-get-filename nil t)))
8802 ;; otherwise, no file so use current directory.
8804 (setq cpltxt (concat "file:" file)
8805 link (org-make-link cpltxt))))
8807 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8808 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8810 ((org-in-regexp "<<\\(.*?\\)>>")
8813 (abbreviate-file-name
8814 (buffer-file-name (buffer-base-buffer)))
8815 "::" (match-string 1))
8816 link (org-make-link cpltxt)))
8817 ((and (featurep 'org-id)
8818 (or (eq org-link-to-org-use-id t)
8819 (and (eq org-link-to-org-use-id 'create-if-interactive)
8820 (org-called-interactively-p 'any))
8821 (and (eq org-link-to-org-use-id
8822 'create-if-interactive-and-no-custom-id)
8823 (org-called-interactively-p 'any)
8825 (and org-link-to-org-use-id
8826 (org-entry-get nil "ID"))))
8827 ;; We can make a link using the ID.
8828 (setq link (condition-case nil
8829 (prog1 (org-id-store-link)
8830 (setq desc (plist-get org-store-link-plist
8833 ;; probably before first headline, link to file only
8835 (abbreviate-file-name
8836 (buffer-file-name (buffer-base-buffer))))))))
8838 ;; Just link to current headline
8839 (setq cpltxt (concat "file:"
8840 (abbreviate-file-name
8841 (buffer-file-name (buffer-base-buffer)))))
8842 ;; Add a context search string
8843 (when (org-xor org-context-in-file-links arg)
8845 ((org-at-heading-p) nil)
8846 ((org-region-active-p)
8847 (buffer-substring (region-beginning) (region-end)))
8849 (when (or (null txt) (string-match "\\S-" txt))
8853 (org-make-org-heading-search-string txt)
8855 desc (or (nth 4 (ignore-errors
8856 (org-heading-components))) "NONE"))))
8857 (if (string-match "::\\'" cpltxt)
8858 (setq cpltxt (substring cpltxt 0 -2)))
8859 (setq link (org-make-link cpltxt)))))
8861 ((buffer-file-name (buffer-base-buffer))
8862 ;; Just link to this file here.
8863 (setq cpltxt (concat "file:"
8864 (abbreviate-file-name
8865 (buffer-file-name (buffer-base-buffer)))))
8866 ;; Add a context string
8867 (when (org-xor org-context-in-file-links arg)
8868 (setq txt (if (org-region-active-p)
8869 (buffer-substring (region-beginning) (region-end))
8870 (buffer-substring (point-at-bol) (point-at-eol))))
8871 ;; Only use search option if there is some text.
8872 (when (string-match "\\S-" txt)
8874 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8876 (setq link (org-make-link cpltxt)))
8878 ((org-called-interactively-p 'interactive)
8879 (error "Cannot link to a buffer which is not visiting a file"))
8881 (t (setq link nil)))
8883 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8884 (setq link (or link cpltxt)
8885 desc (or desc cpltxt))
8886 (if (equal desc "NONE") (setq desc nil))
8888 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8890 (setq org-stored-links
8891 (cons (list link desc) org-stored-links))
8892 (message "Stored: %s" (or desc link))
8894 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8896 (setq org-stored-links
8897 (cons (list link desc) org-stored-links))))
8898 (or agenda-link (and link (org-make-link-string link desc)))))))
8900 (defun org-store-link-props (&rest plist)
8901 "Store link properties, extract names and addresses."
8903 (when (setq x (plist-get plist :from))
8904 (setq adr (mail-extract-address-components x))
8905 (setq plist (plist-put plist :fromname (car adr)))
8906 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8907 (when (setq x (plist-get plist :to))
8908 (setq adr (mail-extract-address-components x))
8909 (setq plist (plist-put plist :toname (car adr)))
8910 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8911 (let ((from (plist-get plist :from))
8912 (to (plist-get plist :to)))
8913 (when (and from to org-from-is-user-regexp)
8915 (plist-put plist :fromto
8916 (if (string-match org-from-is-user-regexp from)
8918 (concat "from %f"))))))
8919 (setq org-store-link-plist plist))
8921 (defun org-add-link-props (&rest plist)
8922 "Add these properties to the link property list."
8925 (setq key (pop plist) value (pop plist))
8926 (setq org-store-link-plist
8927 (plist-put org-store-link-plist key value)))))
8929 (defun org-email-link-description (&optional fmt)
8930 "Return the description part of an email link.
8931 This takes information from `org-store-link-plist' and formats it
8932 according to FMT (default from `org-email-link-description-format')."
8933 (setq fmt (or fmt org-email-link-description-format))
8934 (let* ((p org-store-link-plist)
8935 (to (plist-get p :toaddress))
8936 (from (plist-get p :fromaddress))
8939 (cons "%c" (plist-get p :fromto))
8940 (cons "%F" (plist-get p :from))
8941 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8942 (cons "%T" (plist-get p :to))
8943 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8944 (cons "%s" (plist-get p :subject))
8945 (cons "%d" (plist-get p :date))
8946 (cons "%m" (plist-get p :message-id)))))
8947 (when (string-match "%c" fmt)
8948 ;; Check if the user wrote this message
8949 (if (and org-from-is-user-regexp from to
8950 (save-match-data (string-match org-from-is-user-regexp from)))
8951 (setq fmt (replace-match "to %t" t t fmt))
8952 (setq fmt (replace-match "from %f" t t fmt))))
8953 (org-replace-escapes fmt table)))
8955 (defun org-make-org-heading-search-string (&optional string heading)
8956 "Make search string for STRING or current headline."
8958 (let ((s (or string (org-get-heading)))
8959 (lines org-context-in-file-links))
8960 (unless (and string (not heading))
8961 ;; We are using a headline, clean up garbage in there.
8962 (if (string-match org-todo-regexp s)
8963 (setq s (replace-match "" t t s)))
8964 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8965 (setq s (replace-match "" t t s)))
8966 (setq s (org-trim s))
8967 (if (string-match (concat "^\\(" org-quote-string "\\|"
8968 org-comment-string "\\)") s)
8969 (setq s (replace-match "" t t s)))
8970 (while (string-match org-ts-regexp s)
8971 (setq s (replace-match "" t t s))))
8972 (or string (setq s (concat "*" s))) ; Add * for headlines
8973 (when (and string (integerp lines) (> lines 0))
8974 (let ((slines (org-split-string s "\n")))
8975 (when (< lines (length slines))
8978 (reverse (nthcdr (- (length slines) lines)
8979 (reverse slines))) "\n")))))
8980 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8982 (defun org-make-link (&rest strings)
8983 "Concatenate STRINGS."
8984 (apply 'concat strings))
8986 (defun org-make-link-string (link &optional description)
8987 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8988 (unless (string-match "\\S-" link)
8989 (error "Empty link"))
8990 (when (and description
8991 (stringp description)
8992 (not (string-match "\\S-" description)))
8993 (setq description nil))
8994 (when (stringp description)
8995 ;; Remove brackets from the description, they are fatal.
8996 (while (string-match "\\[" description)
8997 (setq description (replace-match "{" t t description)))
8998 (while (string-match "\\]" description)
8999 (setq description (replace-match "}" t t description))))
9000 (when (equal link description)
9001 ;; No description needed, it is identical
9002 (setq description nil))
9003 (when (and (not description)
9004 (not (string-match (org-image-file-name-regexp) link))
9005 (not (equal link (org-link-escape link))))
9006 (setq description (org-extract-attributes link)))
9008 (cond ((string-match (org-image-file-name-regexp) link) link)
9009 ((string-match org-link-types-re link)
9010 (concat (match-string 1 link)
9011 (org-link-escape (substring link (match-end 1)))))
9012 (t (org-link-escape link))))
9013 (concat "[[" link "]"
9014 (if description (concat "[" description "]") "")
9017 (defconst org-link-escape-chars
9018 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9019 "List of characters that should be escaped in link.
9020 This is the list that is used for internal purposes.")
9022 (defvar org-url-encoding-use-url-hexify nil)
9024 (defconst org-link-escape-chars-browser
9026 "List of escapes for characters that are problematic in links.
9027 This is the list that is used before handing over to the browser.")
9029 (defun org-link-escape (text &optional table merge)
9030 "Return percent escaped representation of TEXT.
9031 TEXT is a string with the text to escape.
9032 Optional argument TABLE is a list with characters that should be
9033 escaped. When nil, `org-link-escape-chars' is used.
9034 If optional argument MERGE is set, merge TABLE into
9035 `org-link-escape-chars'."
9036 (if (and org-url-encoding-use-url-hexify (not table))
9037 (url-hexify-string text)
9040 (mapc (lambda (defchr)
9041 (unless (member defchr table)
9042 (setq table (cons defchr table)))) org-link-escape-chars))
9044 (setq table org-link-escape-chars)))
9047 (if (or (member char table)
9048 (< char 32) (= char 37) (> char 126))
9049 (mapconcat (lambda (sequence-element)
9050 (format "%%%.2X" sequence-element))
9051 (or (encode-coding-char char 'utf-8)
9052 (error "Unable to percent escape character: %s"
9053 (char-to-string char))) "")
9054 (char-to-string char))) text "")))
9056 (defun org-link-unescape (str)
9057 "Unhex hexified Unicode strings as returned from the JavaScript function
9058 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9059 (unless (and (null str) (string= "" str))
9060 (let ((pos 0) (case-fold-search t) unhexed)
9061 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9062 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9063 (setq str (replace-match unhexed t t str))
9064 (setq pos (+ pos (length unhexed))))))
9067 (defun org-link-unescape-compound (hex)
9068 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9069 Note: this function also decodes single byte encodings like
9070 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9072 (let* ((bytes (cdr (split-string hex "%")))
9077 (let* ((val (string-to-number (pop bytes) 16))
9081 ((>= val 252) (cons 6 252))
9082 ((>= val 248) (cons 5 248))
9083 ((>= val 240) (cons 4 240))
9084 ((>= val 224) (cons 3 224))
9085 ((>= val 192) (cons 2 192))
9088 (if (>= val 192) (setq eat (car shift-xor)))
9089 (setq val (logxor val (cdr shift-xor)))
9090 (setq sum (+ (lsh sum (car shift-xor)) val))
9091 (if (> eat 0) (setq eat (- eat 1)))
9093 ((= 0 eat) ;multi byte
9094 (setq ret (concat ret (org-char-to-string sum)))
9096 ((not bytes) ; single byte(s)
9097 (setq ret (org-link-unescape-single-byte-sequence hex))))
9098 )) ;; end (while bytes
9101 (defun org-link-unescape-single-byte-sequence (hex)
9102 "Unhexify hex-encoded single byte character sequences."
9103 (mapconcat (lambda (byte)
9104 (char-to-string (string-to-number byte 16)))
9105 (cdr (split-string hex "%")) ""))
9107 (defun org-xor (a b)
9111 (defun org-fixup-message-id-for-http (s)
9112 "Replace special characters in a message id, so it can be used in an http query."
9113 (when (string-match "%" s)
9114 (setq s (mapconcat (lambda (c)
9117 (char-to-string c)))
9119 (while (string-match "<" s)
9120 (setq s (replace-match "%3C" t t s)))
9121 (while (string-match ">" s)
9122 (setq s (replace-match "%3E" t t s)))
9123 (while (string-match "@" s)
9124 (setq s (replace-match "%40" t t s)))
9127 (defun org-link-prettify (link)
9128 "Return a human-readable representation of LINK.
9129 The car of LINK must be a raw link the cdr of LINK must be either
9130 a link description or nil."
9131 (let ((desc (or (cadr link) "<no description>")))
9132 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9133 "[[" (car link) "]]")))
9136 (defun org-insert-link-global ()
9137 "Insert a link like Org-mode does.
9138 This command can be called in any mode to insert a link in Org-mode syntax."
9140 (org-load-modules-maybe)
9141 (org-run-like-in-org-mode 'org-insert-link))
9143 (defun org-insert-link (&optional complete-file link-location default-description)
9144 "Insert a link. At the prompt, enter the link.
9146 Completion can be used to insert any of the link protocol prefixes like
9149 The history can be used to select a link previously stored with
9150 `org-store-link'. When the empty string is entered (i.e. if you just
9151 press RET at the prompt), the link defaults to the most recently
9152 stored link. As SPC triggers completion in the minibuffer, you need to
9153 use M-SPC or C-q SPC to force the insertion of a space character.
9155 You will also be prompted for a description, and if one is given, it will
9156 be displayed in the buffer instead of the link.
9158 If there is already a link at point, this command will allow you to edit link
9159 and description parts.
9161 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9162 be selected using completion. The path to the file will be relative to the
9163 current directory if the file is in the current directory or a subdirectory.
9164 Otherwise, the link will be the absolute path as completed in the minibuffer
9165 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9166 option `org-link-file-path-type'.
9168 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9169 the current directory or below.
9171 With three \\[universal-argument] prefixes, negate the meaning of
9172 `org-keep-stored-link-after-insertion'.
9174 If `org-make-link-description-function' is non-nil, this function will be
9175 called with the link target, and the result will be the default
9178 If the LINK-LOCATION parameter is non-nil, this value will be
9179 used as the link location instead of reading one interactively.
9181 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9182 be used as the default description."
9184 (let* ((wcf (current-window-configuration))
9185 (region (if (org-region-active-p)
9186 (buffer-substring (region-beginning) (region-end))))
9187 (remove (and region (list (region-beginning) (region-end))))
9189 tmphist ; byte-compile incorrectly complains about this
9190 (link link-location)
9191 entry file all-prefixes)
9193 (link-location) ; specified by arg, just use it.
9194 ((org-in-regexp org-bracket-link-regexp 1)
9195 ;; We do have a link at point, and we are going to edit it.
9196 (setq remove (list (match-beginning 0) (match-end 0)))
9197 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9198 (setq link (read-string "Link: "
9200 (org-match-string-no-properties 1)))))
9201 ((or (org-in-regexp org-angle-link-re)
9202 (org-in-regexp org-plain-link-re))
9203 ;; Convert to bracket link
9204 (setq remove (list (match-beginning 0) (match-end 0))
9205 link (read-string "Link: "
9206 (org-remove-angle-brackets (match-string 0)))))
9207 ((member complete-file '((4) (16)))
9208 ;; Completing read for file names.
9209 (setq link (org-file-complete-link complete-file)))
9211 ;; Read link, with completion for stored links.
9212 (with-output-to-temp-buffer "*Org Links*"
9213 (princ "Insert a link.
9214 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9215 (when org-stored-links
9216 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9217 (princ (mapconcat 'org-link-prettify
9218 (reverse org-stored-links) "\n"))))
9219 (let ((cw (selected-window)))
9220 (select-window (get-buffer-window "*Org Links*" 'visible))
9221 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9222 (unless (pos-visible-in-window-p (point-max))
9223 (org-fit-window-to-buffer))
9224 (and (window-live-p cw) (select-window cw)))
9225 ;; Fake a link history, containing the stored links.
9226 (setq tmphist (append (mapcar 'car org-stored-links)
9227 org-insert-link-history))
9228 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9229 (mapcar 'car org-link-abbrev-alist)
9234 (let ((org-completion-use-ido nil)
9235 (org-completion-use-iswitchb nil))
9236 (org-completing-read
9239 (mapcar (lambda (x) (list (concat x ":")))
9241 (mapcar 'car org-stored-links))
9244 (car (car org-stored-links)))))
9245 (if (not (string-match "\\S-" link))
9246 (error "No link selected"))
9247 (if (or (member link all-prefixes)
9248 (and (equal ":" (substring link -1))
9249 (member (substring link 0 -1) all-prefixes)
9250 (setq link (substring link 0 -1))))
9251 (setq link (org-link-try-special-completion link))))
9252 (set-window-configuration wcf)
9253 (kill-buffer "*Org Links*"))
9254 (setq entry (assoc link org-stored-links))
9255 (or entry (push link org-insert-link-history))
9256 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9257 (not org-keep-stored-link-after-insertion))
9258 (setq org-stored-links (delq (assoc link org-stored-links)
9260 (setq desc (or desc (nth 1 entry)))))
9262 (if (string-match org-plain-link-re link)
9263 ;; URL-like link, normalize the use of angular brackets.
9264 (setq link (org-make-link (org-remove-angle-brackets link))))
9266 ;; Check if we are linking to the current file with a search option
9267 ;; If yes, simplify the link by using only the search option.
9268 (when (and buffer-file-name
9269 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9270 (let* ((path (match-string 1 link))
9271 (case-fold-search nil)
9272 (search (match-string 2 link)))
9274 (if (equal (file-truename buffer-file-name) (file-truename path))
9275 ;; We are linking to this same file, with a search option
9276 (setq link search)))))
9278 ;; Check if we can/should use a relative path. If yes, simplify the link
9279 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9280 (let* ((type (match-string 1 link))
9281 (path (match-string 2 link))
9283 (case-fold-search nil))
9285 ((or (eq org-link-file-path-type 'absolute)
9286 (equal complete-file '(16)))
9287 (setq path (abbreviate-file-name (expand-file-name path))))
9288 ((eq org-link-file-path-type 'noabbrev)
9289 (setq path (expand-file-name path)))
9290 ((eq org-link-file-path-type 'relative)
9291 (setq path (file-relative-name path)))
9294 (if (string-match (concat "^" (regexp-quote
9296 (file-name-as-directory
9297 default-directory))))
9298 (expand-file-name path))
9299 ;; We are linking a file with relative path name.
9300 (setq path (substring (expand-file-name path)
9302 (setq path (abbreviate-file-name (expand-file-name path)))))))
9303 (setq link (concat type path))
9304 (if (equal desc origpath)
9307 (if org-make-link-description-function
9308 (setq desc (funcall org-make-link-description-function link desc))
9309 (if default-description (setq desc default-description)))
9311 (setq desc (read-string "Description: " desc))
9312 (unless (string-match "\\S-" desc) (setq desc nil))
9313 (if remove (apply 'delete-region remove))
9314 (insert (org-make-link-string link desc))))
9316 (defun org-link-try-special-completion (type)
9317 "If there is completion support for link type TYPE, offer it."
9318 (let ((fun (intern (concat "org-" type "-complete-link"))))
9321 (read-string "Link (no completion support): " (concat type ":")))))
9323 (defun org-file-complete-link (&optional arg)
9324 "Create a file link using completion."
9326 (setq file (read-file-name "File: "))
9327 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9328 (pwd1 (file-name-as-directory (abbreviate-file-name
9329 (expand-file-name ".")))))
9332 (setq link (org-make-link
9334 (abbreviate-file-name (expand-file-name file)))))
9335 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9336 (setq link (org-make-link "file:" (match-string 1 file))))
9337 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9338 (expand-file-name file))
9339 (setq link (org-make-link
9340 "file:" (match-string 1 (expand-file-name file)))))
9341 (t (setq link (org-make-link "file:" file)))))
9344 (defun org-completing-read (&rest args)
9345 "Completing-read with SPACE being a normal character."
9346 (let ((enable-recursive-minibuffers t)
9347 (minibuffer-local-completion-map
9348 (copy-keymap minibuffer-local-completion-map)))
9349 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9350 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9351 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9352 (apply 'org-icompleting-read args)))
9354 (defun org-completing-read-no-i (&rest args)
9355 (let (org-completion-use-ido org-completion-use-iswitchb)
9356 (apply 'org-completing-read args)))
9358 (defun org-iswitchb-completing-read (prompt choices &rest args)
9359 "Use iswitch as a completing-read replacement to choose from choices.
9360 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9362 (let* ((iswitchb-use-virtual-buffers nil)
9363 (iswitchb-make-buflist-hook
9365 (setq iswitchb-temp-buflist choices))))
9366 (iswitchb-read-buffer prompt)))
9368 (defun org-icompleting-read (&rest args)
9369 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9370 (org-without-partial-completion
9371 (if (and org-completion-use-ido
9372 (fboundp 'ido-completing-read)
9373 (boundp 'ido-mode) ido-mode
9374 (listp (second args)))
9375 (let ((ido-enter-matching-directory nil))
9376 (apply 'ido-completing-read (concat (car args))
9377 (if (consp (car (nth 1 args)))
9378 (mapcar 'car (nth 1 args))
9381 (if (and org-completion-use-iswitchb
9382 (boundp 'iswitchb-mode) iswitchb-mode
9383 (listp (second args)))
9384 (apply 'org-iswitchb-completing-read (concat (car args))
9385 (if (consp (car (nth 1 args)))
9386 (mapcar 'car (nth 1 args))
9389 (apply 'completing-read args)))))
9391 (defun org-extract-attributes (s)
9392 "Extract the attributes cookie from a string and set as text property."
9393 (let (a attr (start 0) key value)
9395 (when (string-match "{{\\([^}]+\\)}}$" s)
9396 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9397 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9398 (setq key (match-string 1 a) value (match-string 2 a)
9400 attr (plist-put attr (intern key) value))))
9401 (org-add-props s nil 'org-attr attr))
9404 (defun org-extract-attributes-from-string (tag)
9405 (let (key value attr)
9406 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9407 (setq key (match-string 1 tag) value (match-string 2 tag)
9408 tag (replace-match "" t t tag)
9409 attr (plist-put attr (intern key) value)))
9412 (defun org-attributes-to-string (plist)
9413 "Format a property list into an HTML attribute list."
9414 (let ((s "") key value)
9416 (setq key (pop plist) value (pop plist))
9418 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9421 ;;; Opening/following a link
9423 (defvar org-link-search-failed nil)
9425 (defvar org-open-link-functions nil
9426 "Hook for functions finding a plain text link.
9427 These functions must take a single argument, the link content.
9428 They will be called for links that look like [[link text][description]]
9429 when LINK TEXT does not have a protocol like \"http:\" and does not look
9430 like a filename (e.g. \"./blue.png\").
9432 These functions will be called *before* Org attempts to resolve the
9433 link by doing text searches in the current buffer - so if you want a
9434 link \"[[target]]\" to still find \"<<target>>\", your function should
9435 handle this as a special case.
9437 When the function does handle the link, it must return a non-nil value.
9438 If it decides that it is not responsible for this link, it must return
9439 nil to indicate that that Org-mode can continue with other options
9440 like exact and fuzzy text search.")
9442 (defun org-next-link ()
9443 "Move forward to the next link.
9444 If the link is in hidden text, expose it."
9446 (when (and org-link-search-failed (eq this-command last-command))
9447 (goto-char (point-min))
9448 (message "Link search wrapped back to beginning of buffer"))
9449 (setq org-link-search-failed nil)
9450 (let* ((pos (point))
9452 (a (assoc :link ct)))
9453 (if a (goto-char (nth 2 a)))
9454 (if (re-search-forward org-any-link-re nil t)
9456 (goto-char (match-beginning 0))
9457 (if (outline-invisible-p) (org-show-context)))
9459 (setq org-link-search-failed t)
9460 (error "No further link found"))))
9462 (defun org-previous-link ()
9463 "Move backward to the previous link.
9464 If the link is in hidden text, expose it."
9466 (when (and org-link-search-failed (eq this-command last-command))
9467 (goto-char (point-max))
9468 (message "Link search wrapped back to end of buffer"))
9469 (setq org-link-search-failed nil)
9470 (let* ((pos (point))
9472 (a (assoc :link ct)))
9473 (if a (goto-char (nth 1 a)))
9474 (if (re-search-backward org-any-link-re nil t)
9476 (goto-char (match-beginning 0))
9477 (if (outline-invisible-p) (org-show-context)))
9479 (setq org-link-search-failed t)
9480 (error "No further link found"))))
9482 (defun org-translate-link (s)
9483 "Translate a link string if a translation function has been defined."
9484 (if (and org-link-translation-function
9485 (fboundp org-link-translation-function)
9486 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9488 (setq s (funcall org-link-translation-function
9489 (match-string 1 s) (match-string 2 s)))
9490 (concat (car s) ":" (cdr s)))
9493 (defun org-translate-link-from-planner (type path)
9494 "Translate a link from Emacs Planner syntax so that Org can follow it.
9495 This is still an experimental function, your mileage may vary."
9497 ((member type '("http" "https" "news" "ftp"))
9498 ;; standard Internet links are the same.
9500 ((and (equal type "irc") (string-match "^//" path))
9501 ;; Planner has two / at the beginning of an irc link, we have 1.
9502 ;; We should have zero, actually....
9503 (setq path (substring path 1)))
9504 ((and (equal type "lisp") (string-match "^/" path))
9505 ;; Planner has a slash, we do not.
9506 (setq type "elisp" path (substring path 1)))
9507 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9508 ;; A typical message link. Planner has the id after the final slash,
9509 ;; we separate it with a hash mark
9510 (setq path (concat (match-string 1 path) "#"
9511 (org-remove-angle-brackets (match-string 2 path)))))
9515 (defun org-find-file-at-mouse (ev)
9516 "Open file link or URL at mouse."
9518 (mouse-set-point ev)
9519 (org-open-at-point 'in-emacs))
9521 (defun org-open-at-mouse (ev)
9522 "Open file link or URL at mouse.
9523 See the docstring of `org-open-file' for details."
9525 (mouse-set-point ev)
9526 (if (eq major-mode 'org-agenda-mode)
9527 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9528 (org-open-at-point))
9530 (defvar org-window-config-before-follow-link nil
9531 "The window configuration before following a link.
9532 This is saved in case the need arises to restore it.")
9534 (defvar org-open-link-marker (make-marker)
9535 "Marker pointing to the location where `org-open-at-point; was called.")
9538 (defun org-open-at-point-global ()
9539 "Follow a link like Org-mode does.
9540 This command can be called in any mode to follow a link that has
9543 (org-run-like-in-org-mode 'org-open-at-point))
9546 (defun org-open-link-from-string (s &optional arg reference-buffer)
9547 "Open a link in the string S, as if it was in Org-mode."
9548 (interactive "sLink: \nP")
9549 (let ((reference-buffer (or reference-buffer (current-buffer))))
9551 (let ((org-inhibit-startup (not reference-buffer)))
9554 (goto-char (point-min))
9555 (when reference-buffer
9556 (setq org-link-abbrev-alist-local
9557 (with-current-buffer reference-buffer
9558 org-link-abbrev-alist-local)))
9559 (org-open-at-point arg reference-buffer)))))
9561 (defvar org-open-at-point-functions nil
9562 "Hook that is run when following a link at point.
9564 Functions in this hook must return t if they identify and follow
9565 a link at point. If they don't find anything interesting at point,
9566 they must return nil.")
9568 (defun org-open-at-point (&optional arg reference-buffer)
9569 "Open link at or after point.
9570 If there is no link at point, this function will search forward up to
9571 the end of the current line.
9572 Normally, files will be opened by an appropriate application. If the
9573 optional prefix argument ARG is non-nil, Emacs will visit the file.
9574 With a double prefix argument, try to open outside of Emacs, in the
9575 application the system uses for this file type."
9577 ;; if in a code block, then open the block's results
9578 (unless (call-interactively #'org-babel-open-src-block-result)
9579 (org-load-modules-maybe)
9580 (move-marker org-open-link-marker (point))
9581 (setq org-window-config-before-follow-link (current-window-configuration))
9582 (org-remove-occur-highlights nil nil t)
9584 ((and (org-at-heading-p)
9586 (concat org-plain-link-re "\\|"
9587 org-bracket-link-regexp "\\|"
9588 org-angle-link-re "\\|"
9589 "[ \t]:[^ \t\n]+:[ \t]*$")))
9590 (not (get-text-property (point) 'org-linked-text)))
9591 (or (org-offer-links-in-entry arg)
9592 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9593 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9594 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9595 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9596 (not (org-in-regexp org-bracket-link-regexp)))
9597 (org-footnote-action))
9599 (let (type path link line search (pos (point)))
9602 (skip-chars-forward "^]\n\r")
9603 (when (org-in-regexp org-bracket-link-regexp 1)
9604 (setq link (org-extract-attributes
9605 (org-link-unescape (org-match-string-no-properties 1))))
9606 (while (string-match " *\n *" link)
9607 (setq link (replace-match " " t t link)))
9608 (setq link (org-link-expand-abbrev link))
9610 ((or (file-name-absolute-p link)
9611 (string-match "^\\.\\.?/" link))
9612 (setq type "file" path link))
9613 ((string-match org-link-re-with-space3 link)
9614 (setq type (match-string 1 link) path (match-string 2 link)))
9615 (t (setq type "thisfile" path link)))
9618 (when (get-text-property (point) 'org-linked-text)
9619 (setq type "thisfile"
9620 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9621 (1+ (point)) (point))
9622 path (buffer-substring
9623 (or (previous-single-property-change pos 'org-linked-text)
9625 (or (next-single-property-change pos 'org-linked-text)
9630 (when (or (org-in-regexp org-angle-link-re)
9631 (org-in-regexp org-plain-link-re))
9632 (setq type (match-string 1)
9633 path (org-link-unescape (match-string 2)))
9636 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9638 path (match-string 1))
9639 (while (string-match ":" path)
9640 (setq path (replace-match "+" t t path)))
9642 (when (org-in-regexp "<\\([^><\n]+\\)>")
9643 (setq type "tree-match"
9644 path (match-string 1))
9647 (error "No link found"))
9649 ;; switch back to reference buffer
9650 ;; needed when if called in a temporary buffer through
9651 ;; org-open-link-from-string
9652 (with-current-buffer (or reference-buffer (current-buffer))
9654 ;; Remove any trailing spaces in path
9655 (if (string-match " +\\'" path)
9656 (setq path (replace-match "" t t path)))
9657 (if (and org-link-translation-function
9658 (fboundp org-link-translation-function))
9659 ;; Check if we need to translate the link
9660 (let ((tmp (funcall org-link-translation-function type path)))
9661 (setq type (car tmp) path (cdr tmp))))
9665 ((assoc type org-link-protocols)
9666 (funcall (nth 1 (assoc type org-link-protocols)) path))
9668 ((equal type "mailto")
9669 (let ((cmd (car org-link-mailto-program))
9670 (args (cdr org-link-mailto-program)) args1
9671 (address path) (subject "") a)
9672 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9673 (setq address (match-string 1 path)
9674 subject (org-link-escape (match-string 2 path))))
9677 ((not (stringp (car args))) (push (pop args) args1))
9678 (t (setq a (pop args))
9679 (if (string-match "%a" a)
9680 (setq a (replace-match address t t a)))
9681 (if (string-match "%s" a)
9682 (setq a (replace-match subject t t a)))
9684 (apply cmd (nreverse args1))))
9686 ((member type '("http" "https" "ftp" "news"))
9687 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9689 path org-link-escape-chars-browser)
9692 ((string= type "doi")
9693 (browse-url (concat "http://dx.doi.org/" (if (org-string-match-p "[[:nonascii:] ]" path)
9695 path org-link-escape-chars-browser)
9698 ((member type '("message"))
9699 (browse-url (concat type ":" path)))
9701 ((string= type "tags")
9702 (org-tags-view arg path))
9704 ((string= type "tree-match")
9705 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9707 ((string= type "file")
9708 (if (string-match "::\\([0-9]+\\)\\'" path)
9709 (setq line (string-to-number (match-string 1 path))
9710 path (substring path 0 (match-beginning 0)))
9711 (if (string-match "::\\(.+\\)\\'" path)
9712 (setq search (match-string 1 path)
9713 path (substring path 0 (match-beginning 0)))))
9714 (if (string-match "[*?{]" (file-name-nondirectory path))
9716 (org-open-file path arg line search)))
9718 ((string= type "shell")
9720 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9721 (string-match org-confirm-shell-link-not-regexp cmd))
9722 (not org-confirm-shell-link-function)
9723 (funcall org-confirm-shell-link-function
9724 (format "Execute \"%s\" in shell? "
9725 (org-add-props cmd nil
9726 'face 'org-warning))))
9728 (message "Executing %s" cmd)
9729 (shell-command cmd))
9732 ((string= type "elisp")
9734 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9735 (string-match org-confirm-elisp-link-not-regexp cmd))
9736 (not org-confirm-elisp-link-function)
9737 (funcall org-confirm-elisp-link-function
9738 (format "Execute \"%s\" as elisp? "
9739 (org-add-props cmd nil
9740 'face 'org-warning))))
9741 (message "%s => %s" cmd
9742 (if (equal (string-to-char cmd) ?\()
9744 (call-interactively (read cmd))))
9747 ((and (string= type "thisfile")
9748 (run-hook-with-args-until-success
9749 'org-open-link-functions path)))
9751 ((string= type "thisfile")
9753 (switch-to-buffer-other-window
9754 (org-get-buffer-for-internal-link (current-buffer)))
9755 (org-mark-ring-push))
9756 (let ((cmd `(org-link-search
9758 ,(cond ((equal arg '(4)) ''occur)
9759 ((equal arg '(16)) ''org-occur)
9762 (condition-case nil (let ((org-link-search-inhibit-query t))
9764 (error (progn (widen) (eval cmd))))))
9767 (browse-url-at-point)))))))
9768 (move-marker org-open-link-marker nil)
9769 (run-hook-with-args 'org-follow-link-hook)))
9771 (defun org-offer-links-in-entry (&optional nth zero)
9772 "Offer links in the current entry and follow the selected link.
9773 If there is only one link, follow it immediately as well.
9774 If NTH is an integer, immediately pick the NTH link found.
9775 If ZERO is a string, check also this string for a link, and if
9776 there is one, offer it as link number zero."
9777 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9778 "\\(" org-angle-link-re "\\)\\|"
9779 "\\(" org-plain-link-re "\\)"))
9781 (in-emacs (if (integerp nth) nil nth))
9782 have-zero end links link c)
9783 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9784 (push (match-string 0 zero) links)
9785 (setq cnt (1- cnt) have-zero t))
9787 (org-back-to-heading t)
9788 (setq end (save-excursion (outline-next-heading) (point)))
9789 (while (re-search-forward re end t)
9790 (push (match-string 0) links))
9791 (setq links (org-uniquify (reverse links))))
9795 (message "No links"))
9796 ((equal (length links) 1)
9797 (setq link (list (car links))))
9798 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9799 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9800 (t ; we have to select a link
9802 (save-window-excursion
9803 (delete-other-windows)
9804 (with-output-to-temp-buffer "*Select Link*"
9806 (if (not (string-match org-bracket-link-regexp l))
9807 (princ (format "[%c] %s\n" (incf cnt)
9808 (org-remove-angle-brackets l)))
9810 (princ (format "[%c] %s (%s)\n" (incf cnt)
9811 (match-string 3 l) (match-string 1 l)))
9812 (princ (format "[%c] %s\n" (incf cnt)
9813 (match-string 1 l))))))
9815 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9816 (message "Select link to open, RET to open all:")
9817 (setq c (read-char-exclusive))
9818 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9819 (when (equal c ?q) (error "Abort"))
9823 (if have-zero (setq nth (1+ nth)))
9824 (unless (and (integerp nth) (>= (length links) nth))
9825 (error "Invalid link selection"))
9826 (setq link (list (nth (1- nth) links))))))
9828 (let ((buf (current-buffer)))
9830 (org-open-link-from-string l in-emacs buf))
9834 ;; Add special file links that specify the way of opening
9836 (org-add-link-type "file+sys" 'org-open-file-with-system)
9837 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9838 (defun org-open-file-with-system (path)
9839 "Open file at PATH using the system way of opening it."
9840 (org-open-file path 'system))
9841 (defun org-open-file-with-emacs (path)
9842 "Open file at PATH in Emacs."
9843 (org-open-file path 'emacs))
9844 (defun org-remove-file-link-modifiers ()
9845 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9846 (goto-char (point-min))
9847 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9849 (replace-match "file:" t t))))
9850 (eval-after-load "org-exp"
9851 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9852 'org-remove-file-link-modifiers))
9856 (defun org-get-effort (&optional pom)
9857 "Get the effort estimate for the current entry."
9858 (org-entry-get pom org-effort-property))
9862 (defvar org-create-file-search-functions nil
9863 "List of functions to construct the right search string for a file link.
9864 These functions are called in turn with point at the location to
9865 which the link should point.
9867 A function in the hook should first test if it would like to
9868 handle this file type, for example by checking the `major-mode'
9869 or the file extension. If it decides not to handle this file, it
9870 should just return nil to give other functions a chance. If it
9871 does handle the file, it must return the search string to be used
9872 when following the link. The search string will be part of the
9873 file link, given after a double colon, and `org-open-at-point'
9874 will automatically search for it. If special measures must be
9875 taken to make the search successful, another function should be
9876 added to the companion hook `org-execute-file-search-functions',
9879 A function in this hook may also use `setq' to set the variable
9880 `description' to provide a suggestion for the descriptive text to
9881 be used for this link when it gets inserted into an Org-mode
9882 buffer with \\[org-insert-link].")
9884 (defvar org-execute-file-search-functions nil
9885 "List of functions to execute a file search triggered by a link.
9887 Functions added to this hook must accept a single argument, the
9888 search string that was part of the file link, the part after the
9889 double colon. The function must first check if it would like to
9890 handle this search, for example by checking the `major-mode' or
9891 the file extension. If it decides not to handle this search, it
9892 should just return nil to give other functions a chance. If it
9893 does handle the search, it must return a non-nil value to keep
9894 other functions from trying.
9896 Each function can access the current prefix argument through the
9897 variable `current-prefix-argument'. Note that a single prefix is
9898 used to force opening a link in Emacs, so it may be good to only
9899 use a numeric or double prefix to guide the search function.
9901 In case this is needed, a function in this hook can also restore
9902 the window configuration before `org-open-at-point' was called using:
9904 (set-window-configuration org-window-config-before-follow-link)")
9906 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9907 (defun org-link-search (s &optional type avoid-pos stealth)
9908 "Search for a link search option.
9909 If S is surrounded by forward slashes, it is interpreted as a
9910 regular expression. In org-mode files, this will create an `org-occur'
9911 sparse tree. In ordinary files, `occur' will be used to list matches.
9912 If the current buffer is in `dired-mode', grep will be used to search
9913 in all files. If AVOID-POS is given, ignore matches near that position.
9915 When optional argument STEALTH is non-nil, do not modify
9916 visibility around point, thus ignoring
9917 `org-show-hierarchy-above', `org-show-following-heading' and
9918 `org-show-siblings' variables."
9919 (let ((case-fold-search t)
9920 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9921 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9922 (append '(("") (" ") ("\t") ("\n"))
9926 (pre nil) (post nil)
9927 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9929 ;; First check if there are any special search functions
9930 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9931 ;; Now try the builtin stuff
9932 ((and (equal (string-to-char s0) ?#)
9935 (goto-char (point-min))
9938 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9939 (setq type 'dedicated
9940 pos (match-beginning 0))))
9941 ;; There is an exact target for this
9943 (org-back-to-heading t)))
9945 (goto-char (point-min))
9948 (concat "<<" (regexp-quote s0) ">>") nil t)
9949 (setq type 'dedicated
9950 pos (match-beginning 0))))
9951 ;; There is an exact target for this
9954 (goto-char (point-min))
9957 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
9958 (setq type 'dedicated pos (match-beginning 0))))
9959 ;; Found an invisible target.
9962 (goto-char (point-min))
9965 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
9966 (setq type 'dedicated pos (match-beginning 0))))
9967 ;; Found an element with a matching #+name affiliated keyword.
9969 ((and (string-match "^(\\(.*\\))$" s0)
9971 (goto-char (point-min))
9974 (concat "[^[]" (regexp-quote
9975 (format org-coderef-label-format
9976 (match-string 1 s0))))
9978 (setq type 'dedicated
9979 pos (1+ (match-beginning 0))))))
9980 ;; There is a coderef target for this
9982 ((string-match "^/\\(.*\\)/$" s)
9983 ;; A regular expression
9985 ((derived-mode-p 'org-mode)
9986 (org-occur (match-string 1 s)))
9987 ;;((eq major-mode 'dired-mode)
9988 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9989 (t (org-do-occur (match-string 1 s)))))
9990 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
9991 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9992 (goto-char (point-min))
9994 ((let (case-fold-search)
9995 (re-search-forward (format org-complex-heading-regexp-format
9998 ;; OK, found a match
9999 (setq type 'dedicated)
10000 (goto-char (match-beginning 0)))
10001 ((and (not org-link-search-inhibit-query)
10002 (eq org-link-search-must-match-exact-headline 'query-to-create)
10003 (y-or-n-p "No match - create this as a new heading? "))
10004 (goto-char (point-max))
10005 (or (bolp) (newline))
10006 (insert "* " s "\n")
10007 (beginning-of-line 0))
10010 (error "No match"))))
10012 ;; A normal search string
10013 (when (equal (string-to-char s) ?*)
10014 ;; Anchor on headlines, post may include tags.
10015 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10016 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10017 s (substring s 1)))
10018 (remove-text-properties
10020 '(face nil mouse-face nil keymap nil fontified nil) s)
10021 ;; Make a series of regular expressions to find a match
10022 (setq words (org-split-string s "[ \n\r\t]+")
10024 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10025 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10027 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10028 re2a (concat "[ \t\r\n]" re2a_)
10029 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10030 re4 (concat "[^a-zA-Z_]" re4_)
10032 re1 (concat pre re2 post)
10033 re3 (concat pre (if pre re4_ re4) post)
10034 re5 (concat pre ".*" re4)
10035 re2 (concat pre re2)
10036 re2a (concat pre (if pre re2a_ re2a))
10037 re4 (concat pre (if pre re4_ re4))
10038 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10039 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10043 ((eq type 'org-occur) (org-occur reall))
10044 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10045 (t (goto-char (point-min))
10047 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10048 (org-search-not-self 1 re1 nil t)
10049 (org-search-not-self 1 re2 nil t)
10050 (org-search-not-self 1 re2a nil t)
10051 (org-search-not-self 1 re3 nil t)
10052 (org-search-not-self 1 re4 nil t)
10053 (org-search-not-self 1 re5 nil t)
10055 (goto-char (match-beginning 1))
10057 (error "No match"))))))
10058 (and (derived-mode-p 'org-mode)
10060 (org-show-context 'link-search))
10063 (defun org-search-not-self (group &rest args)
10064 "Execute `re-search-forward', but only accept matches that do not
10065 enclose the position of `org-open-link-marker'."
10066 (let ((m org-open-link-marker))
10068 (while (apply 're-search-forward args)
10069 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10070 (goto-char (match-end group))
10071 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10072 (> (match-beginning 0) (marker-position m))
10073 (< (match-end 0) (marker-position m)))
10075 (or (not (org-in-regexp
10076 org-bracket-link-analytic-regexp 1))
10077 (not (match-end 4)) ; no description
10078 (and (<= (match-beginning 4) (point))
10079 (>= (match-end 4) (point))))))
10080 (throw 'exit (point))))))))
10082 (defun org-get-buffer-for-internal-link (buffer)
10083 "Return a buffer to be used for displaying the link target of internal links."
10085 ((not org-display-internal-link-with-indirect-buffer)
10087 ((string-match "(Clone)$" (buffer-name buffer))
10088 (message "Buffer is already a clone, not making another one")
10089 ;; we also do not modify visibility in this case
10091 (t ; make a new indirect buffer for displaying the link
10092 (let* ((bn (buffer-name buffer))
10093 (ibn (concat bn "(Clone)"))
10094 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10095 (with-current-buffer ib (org-overview))
10098 (defun org-do-occur (regexp &optional cleanup)
10099 "Call the Emacs command `occur'.
10100 If CLEANUP is non-nil, remove the printout of the regular expression
10101 in the *Occur* buffer. This is useful if the regex is long and not useful
10105 (let ((cwin (selected-window)) win beg end)
10106 (when (setq win (get-buffer-window "*Occur*"))
10107 (select-window win))
10108 (goto-char (point-min))
10109 (when (re-search-forward "match[a-z]+" nil t)
10110 (setq beg (match-end 0))
10111 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10112 (setq end (1- (match-beginning 0)))))
10113 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10114 (goto-char (point-min))
10115 (select-window cwin))))
10117 ;;; The mark ring for links jumps
10119 (defvar org-mark-ring nil
10120 "Mark ring for positions before jumps in Org-mode.")
10121 (defvar org-mark-ring-last-goto nil
10122 "Last position in the mark ring used to go back.")
10123 ;; Fill and close the ring
10124 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10125 (loop for i from 1 to org-mark-ring-length do
10126 (push (make-marker) org-mark-ring))
10127 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10130 (defun org-mark-ring-push (&optional pos buffer)
10131 "Put the current position or POS into the mark ring and rotate it."
10133 (setq pos (or pos (point)))
10134 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10135 (move-marker (car org-mark-ring)
10137 (or buffer (current-buffer)))
10139 (substitute-command-keys
10140 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10142 (defun org-mark-ring-goto (&optional n)
10143 "Jump to the previous position in the mark ring.
10144 With prefix arg N, jump back that many stored positions. When
10145 called several times in succession, walk through the entire ring.
10146 Org-mode commands jumping to a different position in the current file,
10147 or to another Org-mode file, automatically push the old position
10151 (if (eq last-command this-command)
10152 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10153 (setq p org-mark-ring))
10154 (setq org-mark-ring-last-goto p)
10156 (org-pop-to-buffer-same-window (marker-buffer m))
10158 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10160 (defun org-remove-angle-brackets (s)
10161 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10162 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10164 (defun org-add-angle-brackets (s)
10165 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10166 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10168 (defun org-remove-double-quotes (s)
10169 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10170 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10173 ;;; Following specific links
10175 (defun org-follow-timestamp-link ()
10177 ((org-at-date-range-p t)
10178 (let ((org-agenda-start-on-weekday)
10179 (t1 (match-string 1))
10180 (t2 (match-string 2)))
10181 (setq t1 (time-to-days (org-time-string-to-time t1))
10182 t2 (time-to-days (org-time-string-to-time t2)))
10183 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10184 ((org-at-timestamp-p t)
10185 (org-agenda-list nil (time-to-days (org-time-string-to-time
10186 (substring (match-string 1) 0 10)))
10188 (t (error "This should not happen"))))
10191 ;;; Following file links
10192 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10193 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10194 (declare-function mailcap-mime-info
10195 "mailcap" (string &optional request no-decode))
10196 (defvar org-wait nil)
10197 (defun org-open-file (path &optional in-emacs line search)
10198 "Open the file at PATH.
10199 First, this expands any special file name abbreviations. Then the
10200 configuration variable `org-file-apps' is checked if it contains an
10201 entry for this file type, and if yes, the corresponding command is launched.
10203 If no application is found, Emacs simply visits the file.
10205 With optional prefix argument IN-EMACS, Emacs will visit the file.
10206 With a double \\[universal-argument] \\[universal-argument] \
10207 prefix arg, Org tries to avoid opening in Emacs
10208 and to use an external application to visit the file.
10210 Optional LINE specifies a line to go to, optional SEARCH a string
10211 to search for. If LINE or SEARCH is given, the file will be
10212 opened in Emacs, unless an entry from org-file-apps that makes
10213 use of groups in a regexp matches.
10215 If you want to change the way frames are used when following a
10216 link, please customize `org-link-frame-setup'.
10218 If the file does not exist, an error is thrown."
10219 (let* ((file (if (equal path "")
10221 (substitute-in-file-name (expand-file-name path))))
10222 (file-apps (append org-file-apps (org-default-apps)))
10223 (apps (org-remove-if
10224 'org-file-apps-entry-match-against-dlink-p file-apps))
10225 (apps-dlink (org-remove-if-not
10226 'org-file-apps-entry-match-against-dlink-p file-apps))
10227 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10228 (dirp (if remp nil (file-directory-p file)))
10229 (file (if (and dirp org-open-directory-means-index-dot-org)
10230 (concat (file-name-as-directory file) "index.org")
10232 (a-m-a-p (assq 'auto-mode apps))
10233 (dfile (downcase file))
10234 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10235 (link (cond ((and (eq line nil)
10239 (concat file "::" (number-to-string line)))
10241 (concat file "::" search))))
10242 (dlink (downcase link))
10243 (old-buffer (current-buffer))
10245 (old-mode major-mode)
10246 ext cmd link-match-data)
10247 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10248 (setq ext (match-string 1 dfile))
10249 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10250 (setq ext (match-string 1 dfile))))
10252 ((member in-emacs '((16) system))
10253 (setq cmd (cdr (assoc 'system apps))))
10254 (in-emacs (setq cmd 'emacs))
10256 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10257 (and dirp (cdr (assoc 'directory apps)))
10258 ; first, try matching against apps-dlink
10259 ; if we get a match here, store the match data for later
10260 (let ((match (assoc-default dlink apps-dlink
10263 (progn (setq link-match-data (match-data))
10265 (progn (setq in-emacs (or in-emacs line search))
10266 nil))) ; if we have no match in apps-dlink,
10267 ; always open the file in emacs if line or search
10268 ; is given (for backwards compatibility)
10269 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10271 (cdr (assoc ext apps))
10272 (cdr (assoc t apps))))))
10273 (when (eq cmd 'system)
10274 (setq cmd (cdr (assoc 'system apps))))
10275 (when (eq cmd 'default)
10276 (setq cmd (cdr (assoc t apps))))
10277 (when (eq cmd 'mailcap)
10279 (mailcap-parse-mailcaps)
10280 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10281 (command (mailcap-mime-info mime-type)))
10282 (if (stringp command)
10284 (setq cmd 'emacs))))
10285 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10286 (not (file-exists-p file))
10287 (not org-open-non-existing-files))
10288 (error "No such file: %s" file))
10290 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10291 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10292 (while (string-match "['\"]%s['\"]" cmd)
10293 (setq cmd (replace-match "%s" t t cmd)))
10294 (while (string-match "%s" cmd)
10295 (setq cmd (replace-match
10297 (shell-quote-argument
10298 (convert-standard-filename file)))
10301 ;; Replace "%1", "%2" etc. in command with group matches from regex
10303 (let ((match-index 1)
10304 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10305 (set-match-data link-match-data)
10306 (while (<= match-index number-of-groups)
10307 (let ((regex (concat "%" (number-to-string match-index)))
10308 (replace-with (match-string match-index dlink)))
10309 (while (string-match regex cmd)
10310 (setq cmd (replace-match replace-with t t cmd))))
10311 (setq match-index (+ match-index 1)))))
10313 (save-window-excursion
10314 (start-process-shell-command cmd nil cmd)
10315 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10319 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10321 (if line (org-goto-line line)
10322 (if search (org-link-search search))))
10324 (let ((file (convert-standard-filename file)))
10326 (set-match-data link-match-data)
10328 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10329 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10330 (or (not (equal old-buffer (current-buffer)))
10331 (not (equal old-pos (point))))
10332 (org-mark-ring-push old-pos old-buffer))))
10334 (defun org-file-apps-entry-match-against-dlink-p (entry)
10335 "This function returns non-nil if `entry' uses a regular
10336 expression which should be matched against the whole link by
10339 It assumes that is the case when the entry uses a regular
10340 expression which has at least one grouping construct and the
10341 action is either a lisp form or a command string containing
10342 '%1', i.e. using at least one subexpression match as a
10344 (let ((selector (car entry))
10345 (action (cdr entry)))
10346 (if (stringp selector)
10347 (and (> (regexp-opt-depth selector) 0)
10348 (or (and (stringp action)
10349 (string-match "%[0-9]" action))
10353 (defun org-default-apps ()
10354 "Return the default applications for this operating system."
10356 ((eq system-type 'darwin)
10357 org-file-apps-defaults-macosx)
10358 ((eq system-type 'windows-nt)
10359 org-file-apps-defaults-windowsnt)
10360 (t org-file-apps-defaults-gnu)))
10362 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10363 "Convert extensions to regular expressions in the cars of LIST.
10364 Also, weed out any non-string entries, because the return value is used
10365 only for regexp matching.
10366 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10367 point to the symbol `emacs', indicating that the file should
10368 be opened in Emacs."
10371 (mapcar (lambda (x)
10372 (if (not (stringp (car x)))
10374 (if (string-match "\\W" (car x))
10376 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10379 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10381 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10382 (defun org-file-remote-p (file)
10383 "Test whether FILE specifies a location on a remote system.
10384 Return non-nil if the location is indeed remote.
10386 For example, the filename \"/user@host:/foo\" specifies a location
10387 on the system \"/user@host:\"."
10388 (cond ((fboundp 'file-remote-p)
10389 (file-remote-p file))
10390 ((fboundp 'tramp-handle-file-remote-p)
10391 (tramp-handle-file-remote-p file))
10392 ((and (boundp 'ange-ftp-name-format)
10393 (string-match (car ange-ftp-name-format) file))
10400 (defun org-get-org-file ()
10401 "Read a filename, with default directory `org-directory'."
10402 (let ((default (or org-default-notes-file remember-data-file)))
10403 (read-file-name (format "File name [%s]: " default)
10404 (file-name-as-directory org-directory)
10407 (defun org-notes-order-reversed-p ()
10408 "Check if the current file should receive notes in reversed order."
10410 ((not org-reverse-note-order) nil)
10411 ((eq t org-reverse-note-order) t)
10412 ((not (listp org-reverse-note-order)) nil)
10414 (let ((all org-reverse-note-order)
10416 (while (setq entry (pop all))
10417 (if (string-match (car entry) buffer-file-name)
10418 (throw 'exit (cdr entry))))
10421 (defvar org-refile-target-table nil
10422 "The list of refile targets, created by `org-refile'.")
10424 (defvar org-agenda-new-buffers nil
10425 "Buffers created to visit agenda files.")
10427 (defvar org-refile-cache nil
10428 "Cache for refile targets.")
10430 (defvar org-refile-markers nil
10431 "All the markers used for caching refile locations.")
10433 (defun org-refile-marker (pos)
10434 "Get a new refile marker, but only if caching is in use."
10435 (if (not org-refile-use-cache)
10437 (let ((m (make-marker)))
10438 (move-marker m pos)
10439 (push m org-refile-markers)
10442 (defun org-refile-cache-clear ()
10443 "Clear the refile cache and disable all the markers."
10444 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10445 (setq org-refile-markers nil)
10446 (setq org-refile-cache nil)
10447 (message "Refile cache has been cleared"))
10449 (defun org-refile-cache-check-set (set)
10450 "Check if all the markers in the cache still have live buffers."
10453 (while (and set (setq marker (nth 3 (pop set))))
10454 ;; if org-refile-use-outline-path is 'file, marker may be nil
10455 (when (and marker (null (marker-buffer marker)))
10456 (message "not found") (sit-for 3)
10457 (throw 'exit nil)))
10460 (defun org-refile-cache-put (set &rest identifiers)
10461 "Push the refile targets SET into the cache, under IDENTIFIERS."
10462 (let* ((key (sha1 (prin1-to-string identifiers)))
10463 (entry (assoc key org-refile-cache)))
10466 (push (cons key set) org-refile-cache))))
10468 (defun org-refile-cache-get (&rest identifiers)
10469 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10471 ((not org-refile-cache) nil)
10472 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10474 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10475 org-refile-cache))))
10476 (and set (org-refile-cache-check-set set) set)))))
10478 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10479 "Produce a table with refile targets."
10480 (let ((case-fold-search nil)
10481 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10482 (entries (or org-refile-targets '((nil . (:level . 1)))))
10483 targets tgs txt re files f desc descre fast-path-p level pos0)
10484 (message "Getting targets...")
10485 (with-current-buffer (or default-buffer (current-buffer))
10486 (while (setq entry (pop entries))
10487 (setq files (car entry) desc (cdr entry))
10488 (setq fast-path-p nil)
10490 ((null files) (setq files (list (current-buffer))))
10491 ((eq files 'org-agenda-files)
10492 (setq files (org-agenda-files 'unrestricted)))
10493 ((and (symbolp files) (fboundp files))
10494 (setq files (funcall files)))
10495 ((and (symbolp files) (boundp files))
10496 (setq files (symbol-value files))))
10497 (if (stringp files) (setq files (list files)))
10499 ((eq (car desc) :tag)
10500 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10501 ((eq (car desc) :todo)
10502 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10503 ((eq (car desc) :regexp)
10504 (setq descre (cdr desc)))
10505 ((eq (car desc) :level)
10506 (setq descre (concat "^\\*\\{" (number-to-string
10507 (if org-odd-levels-only
10508 (1- (* 2 (cdr desc)))
10511 ((eq (car desc) :maxlevel)
10512 (setq fast-path-p t)
10513 (setq descre (concat "^\\*\\{1," (number-to-string
10514 (if org-odd-levels-only
10515 (1- (* 2 (cdr desc)))
10518 (t (error "Bad refiling target description %s" desc)))
10519 (while (setq f (pop files))
10520 (with-current-buffer
10521 (if (bufferp f) f (org-get-agenda-file-buffer f))
10523 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10525 (if (bufferp f) (setq f (buffer-file-name
10526 (buffer-base-buffer f))))
10527 (setq f (and f (expand-file-name f)))
10528 (if (eq org-refile-use-outline-path 'file)
10529 (push (list (file-name-nondirectory f) f nil nil) tgs))
10533 (goto-char (point-min))
10534 (while (re-search-forward descre nil t)
10535 (goto-char (setq pos0 (point-at-bol)))
10537 (when org-refile-target-verify-function
10539 (or (funcall org-refile-target-verify-function)
10541 (when (and (looking-at org-complex-heading-regexp)
10542 (not (member (match-string 4) excluded-entries))
10544 (setq level (org-reduced-level
10545 (- (match-end 1) (match-beginning 1)))
10546 txt (org-link-display-format (match-string 4))
10547 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10548 re (format org-complex-heading-regexp-format
10549 (regexp-quote (match-string 4))))
10550 (when org-refile-use-outline-path
10551 (setq txt (mapconcat
10554 (if (eq org-refile-use-outline-path
10556 (list (file-name-nondirectory
10558 (buffer-base-buffer))))
10559 (if (eq org-refile-use-outline-path
10561 (list (buffer-file-name
10562 (buffer-base-buffer)))))
10563 (org-get-outline-path fast-path-p
10567 (push (list txt f re (org-refile-marker (point)))
10569 (when (= (point) pos0)
10570 ;; verification function has not moved point
10571 (goto-char (point-at-eol))))))))
10572 (when org-refile-use-cache
10573 (org-refile-cache-put tgs (buffer-file-name) descre))
10574 (setq targets (append tgs targets))
10576 (message "Getting targets...done")
10577 (nreverse targets)))
10579 (defun org-protect-slash (s)
10580 (while (string-match "/" s)
10581 (setq s (replace-match "\\" t t s)))
10584 (defvar org-olpa (make-vector 20 nil))
10586 (defun org-get-outline-path (&optional fastp level heading)
10587 "Return the outline path to the current entry, as a list.
10589 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10590 routine which makes outline path derivations for an entire file,
10591 avoiding backtracing. Refile target collection makes use of that."
10595 (error "Outline path failure, more than 19 levels"))
10596 (loop for i from level upto 19 do
10597 (aset org-olpa i nil))
10599 (delq nil (append org-olpa nil))
10600 (aset org-olpa level heading)))
10601 (let (rtn case-fold-search)
10605 (while (org-up-heading-safe)
10606 (when (looking-at org-complex-heading-regexp)
10607 (push (org-match-string-no-properties 4) rtn)))
10610 (defun org-format-outline-path (path &optional width prefix)
10611 "Format the outline path PATH for display.
10612 Width is the maximum number of characters that is available.
10613 Prefix is a prefix to be included in the returned string,
10614 such as the file name."
10615 (setq width (or width 79))
10616 (if prefix (setq width (- width (length prefix))))
10619 (let* ((nsteps (length path))
10620 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10621 (maxwidth (if (<= total-width width)
10622 10000 ;; everything fits
10623 ;; we need to shorten the level headings
10624 (/ (- width nsteps) nsteps)))
10625 (org-odd-levels-only nil)
10627 (total (1+ (length prefix))))
10628 (setq maxwidth (max maxwidth 10))
10633 (if (and (= n nsteps) (< maxwidth 10000))
10634 (setq maxwidth (- total-width total)))
10635 (if (< (length h) maxwidth)
10636 (progn (setq total (+ total (length h) 1)) h)
10637 (setq h (substring h 0 (- maxwidth 2))
10638 total (+ total maxwidth 1))
10639 (if (string-match "[ \t]+\\'" h)
10640 (setq h (substring h 0 (match-beginning 0))))
10641 (setq h (concat h "..")))
10642 (org-add-props h nil 'face
10643 (nth (% (1- n) org-n-level-faces)
10648 (defun org-display-outline-path (&optional file current)
10649 "Display the current outline path in the echo area."
10651 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10652 (case-fold-search nil)
10653 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10654 (if current (setq path (append path
10656 (org-back-to-heading t)
10657 (if (looking-at org-complex-heading-regexp)
10658 (list (match-string 4)))))))
10660 (org-format-outline-path
10663 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10665 (defvar org-refile-history nil
10666 "History for refiling operations.")
10668 (defvar org-after-refile-insert-hook nil
10669 "Hook run after `org-refile' has inserted its stuff at the new location.
10670 Note that this is still *before* the stuff will be removed from
10671 the *old* location.")
10673 (defvar org-capture-last-stored-marker)
10674 (defun org-refile (&optional goto default-buffer rfloc)
10675 "Move the entry or entries at point to another heading.
10676 The list of target headings is compiled using the information in
10677 `org-refile-targets', which see.
10679 At the target location, the entry is filed as a subitem of the target
10680 heading. Depending on `org-reverse-note-order', the new subitem will
10681 either be the first or the last subitem.
10683 If there is an active region, all entries in that region will be moved.
10684 However, the region must fulfill the requirement that the first heading
10685 is the first one sets the top-level of the moved text - at most siblings
10686 below it are allowed.
10688 With prefix arg GOTO, the command will only visit the target location
10689 and not actually move anything.
10691 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10692 go to the location where the last refiling operation has put the subtree.
10693 With a prefix argument of `2', refile to the running clock.
10695 RFLOC can be a refile location obtained in a different way.
10697 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10699 If you are using target caching (see `org-refile-use-cache'),
10700 you have to clear the target cache in order to find new targets.
10701 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10702 prefix argument (`C-u C-u C-u C-c C-w')."
10705 (if (member goto '(0 (64)))
10706 (org-refile-cache-clear)
10707 (let* ((cbuf (current-buffer))
10708 (regionp (org-region-active-p))
10709 (region-start (and regionp (region-beginning)))
10710 (region-end (and regionp (region-end)))
10711 (region-length (and regionp (- region-end region-start)))
10712 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10713 pos it nbuf file re level reversed)
10714 (setq last-command nil)
10716 (goto-char region-start)
10717 (or (bolp) (goto-char (point-at-bol)))
10718 (setq region-start (point))
10719 (unless (or (org-kill-is-subtree-p
10720 (buffer-substring region-start region-end))
10721 (prog1 org-refile-active-region-within-subtree
10722 (org-toggle-heading)))
10723 (error "The region is not a (sequence of) subtree(s)")))
10724 (if (equal goto '(16))
10725 (org-refile-goto-last-stored)
10727 (and (equal goto 2)
10728 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10730 (setq it (list (or org-clock-heading "running clock")
10732 (marker-buffer org-clock-hd-marker))
10734 (marker-position org-clock-hd-marker)))
10737 (let (heading-text)
10740 (org-back-to-heading t)
10742 (nth 4 (org-heading-components))))
10743 (org-refile-get-location
10744 (cond (goto "Goto")
10745 (regionp "Refile region to")
10746 (t (concat "Refile subtree \""
10747 heading-text "\" to")))
10749 (and (not (equal '(4) goto))
10750 org-refile-allow-creating-parent-nodes)
10752 (setq file (nth 1 it)
10755 (if (and (not goto)
10757 (equal (buffer-file-name) file)
10759 (and (>= pos region-start)
10760 (<= pos region-end))
10761 (and (>= pos (point))
10762 (< pos (save-excursion
10763 (org-end-of-subtree t t))))))
10764 (error "Cannot refile to position inside the tree or region"))
10766 (setq nbuf (or (find-buffer-visiting file)
10767 (find-file-noselect file)))
10770 (org-pop-to-buffer-same-window nbuf)
10772 (org-show-context 'org-goto))
10775 (org-kill-new (buffer-substring region-start region-end))
10776 (org-save-markers-in-region region-start region-end))
10777 (org-copy-subtree 1 nil t))
10778 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10779 (find-file-noselect file)))
10780 (setq reversed (org-notes-order-reversed-p))
10787 (looking-at org-outline-regexp)
10788 (setq level (org-get-valid-level (funcall outline-level) 1))
10791 (or (outline-next-heading) (point-max))
10792 (or (save-excursion (org-get-next-sibling))
10793 (org-end-of-subtree t t)
10797 (goto-char (point-max))
10798 (goto-char (point-min))
10799 (or (outline-next-heading) (goto-char (point-max)))))
10800 (if (not (bolp)) (newline))
10801 (org-paste-subtree level)
10802 (when org-log-refile
10803 (org-add-log-setup 'refile nil nil 'findpos
10805 (unless (eq org-log-refile 'note)
10806 (save-excursion (org-add-log-note))))
10807 (and org-auto-align-tags (org-set-tags nil t))
10808 (bookmark-set "org-refile-last-stored")
10809 ;; If we are refiling for capture, make sure that the
10810 ;; last-capture pointers point here
10811 (when (org-bound-and-true-p org-refile-for-capture)
10812 (bookmark-set "org-capture-last-stored-marker")
10813 (move-marker org-capture-last-stored-marker (point)))
10814 (if (fboundp 'deactivate-mark) (deactivate-mark))
10815 (run-hooks 'org-after-refile-insert-hook))))
10817 (delete-region (point) (+ (point) region-length))
10819 (when (featurep 'org-inlinetask)
10820 (org-inlinetask-remove-END-maybe))
10821 (setq org-markers-to-move nil)
10822 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10824 (defun org-refile-goto-last-stored ()
10825 "Go to the location where the last refile was stored."
10827 (bookmark-jump "org-refile-last-stored")
10828 (message "This is the location of the last refile"))
10830 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10832 "Prompt the user for a refile location, using PROMPT.
10833 PROMPT should not be suffixed with a colon and a space, because
10834 this function appends the default value from
10835 `org-refile-history' automatically, if that is not empty.
10836 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10837 this is used for the GOTO interface."
10838 (let ((org-refile-targets org-refile-targets)
10839 (org-refile-use-outline-path org-refile-use-outline-path)
10841 (when (and (derived-mode-p 'org-mode)
10842 (not org-refile-use-cache)
10846 (setq excluded-entries
10847 (append excluded-entries (list (org-get-heading t t)))))))
10848 (setq org-refile-target-table
10849 (org-refile-get-targets default-buffer excluded-entries)))
10850 (unless org-refile-target-table
10851 (error "No refile targets"))
10852 (let* ((prompt (concat prompt
10853 (and (car org-refile-history)
10854 (concat " (default " (car org-refile-history) ")"))
10856 (cbuf (current-buffer))
10857 (partial-completion-mode nil)
10858 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10859 (cfunc (if (and org-refile-use-outline-path
10860 org-outline-path-complete-in-steps)
10861 'org-olpath-completing-read
10862 'org-icompleting-read))
10863 (extra (if org-refile-use-outline-path "/" ""))
10864 (filename (and cfn (expand-file-name cfn)))
10867 (if (and (not (member org-refile-use-outline-path
10868 '(file full-file-path)))
10869 (not (equal filename (nth 1 x))))
10870 (cons (concat (car x) extra " ("
10871 (file-name-nondirectory (nth 1 x)) ")")
10873 (cons (concat (car x) extra) (cdr x))))
10874 org-refile-target-table))
10875 (completion-ignore-case t)
10876 pa answ parent-target child parent old-hist)
10877 (setq old-hist org-refile-history)
10878 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10879 nil 'org-refile-history (car org-refile-history)))
10880 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10881 (org-refile-check-position pa)
10884 (when (or (not org-refile-history)
10885 (not (eq old-hist org-refile-history))
10886 (not (equal (car pa) (car org-refile-history))))
10887 (setq org-refile-history
10888 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10890 (cdr org-refile-history))))
10891 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10892 (pop org-refile-history)))
10894 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10896 (setq parent (match-string 1 answ)
10897 child (match-string 2 answ))
10898 (setq parent-target (or (assoc parent tbl)
10899 (assoc (concat parent "/") tbl)))
10900 (when (and parent-target
10901 (or (eq new-nodes t)
10902 (and (eq new-nodes 'confirm)
10903 (y-or-n-p (format "Create new node \"%s\"? "
10905 (org-refile-new-child parent-target child)))
10906 (error "Invalid target location")))))
10908 (declare-function org-string-nw-p "org-macs.el" (s))
10909 (defun org-refile-check-position (refile-pointer)
10910 "Check if the refile pointer matches the readline to which it points."
10911 (let* ((file (nth 1 refile-pointer))
10912 (re (nth 2 refile-pointer))
10913 (pos (nth 3 refile-pointer))
10915 (when (org-string-nw-p re)
10916 (setq buffer (if (markerp pos)
10917 (marker-buffer pos)
10918 (or (find-buffer-visiting file)
10919 (find-file-noselect file))))
10920 (with-current-buffer buffer
10925 (beginning-of-line 1)
10926 (unless (org-looking-at-p re)
10927 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10929 (defun org-refile-new-child (parent-target child)
10930 "Use refile target PARENT-TARGET to add new CHILD below it."
10931 (unless parent-target
10932 (error "Cannot find parent for new node"))
10933 (let ((file (nth 1 parent-target))
10934 (pos (nth 3 parent-target))
10936 (with-current-buffer (or (find-buffer-visiting file)
10937 (find-file-noselect file))
10943 (goto-char (point-max))
10944 (if (not (bolp)) (newline)))
10945 (when (looking-at org-outline-regexp)
10946 (setq level (funcall outline-level))
10947 (org-end-of-subtree t t))
10948 (org-back-over-empty-lines)
10949 (insert "\n" (make-string
10950 (if pos (org-get-valid-level level 1) 1) ?*)
10952 (beginning-of-line 0)
10953 (list (concat (car parent-target) "/" child) file "" (point)))))))
10955 (defun org-olpath-completing-read (prompt collection &rest args)
10956 "Read an outline path like a file name."
10957 (let ((thetable collection)
10958 (org-completion-use-ido nil) ; does not work with ido.
10959 (org-completion-use-iswitchb nil)) ; or iswitchb
10961 'org-icompleting-read prompt
10962 (lambda (string predicate &optional flag)
10963 (let (rtn r f (l (length string)))
10967 (try-completion string thetable))
10970 (setq rtn (all-completions string thetable predicate))
10973 (setq r (substring x l))
10974 (if (string-match " ([^)]*)$" x)
10975 (setq f (match-string 0 x))
10977 (if (string-match "/" r)
10978 (concat string (substring r 0 (match-end 0)) f)
10983 (assoc string thetable)))))
10986 ;;;; Dynamic blocks
10988 (defun org-find-dblock (name)
10989 "Find the first dynamic block with name NAME in the buffer.
10990 If not found, stay at current position and return nil."
10993 (goto-char (point-min))
10994 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10996 (match-beginning 0))))
10997 (if pos (goto-char pos))
11000 (defconst org-dblock-start-re
11001 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11002 "Matches the start line of a dynamic block, with parameters.")
11004 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
11005 "Matches the end of a dynamic block.")
11007 (defun org-create-dblock (plist)
11008 "Create a dynamic block section, with parameters taken from PLIST.
11009 PLIST must contain a :name entry which is used as name of the block."
11010 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11013 (let ((col (current-column))
11014 (name (plist-get plist :name)))
11015 (insert "#+BEGIN: " name)
11017 (if (eq (car plist) :name)
11018 (setq plist (cddr plist))
11019 (insert " " (prin1-to-string (pop plist)))))
11020 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11021 (beginning-of-line -2)))
11023 (defun org-prepare-dblock ()
11024 "Prepare dynamic block for refresh.
11025 This empties the block, puts the cursor at the insert position and returns
11026 the property list including an extra property :name with the block name."
11027 (unless (looking-at org-dblock-start-re)
11028 (error "Not at a dynamic block"))
11029 (let* ((begdel (1+ (match-end 0)))
11030 (name (org-no-properties (match-string 1)))
11031 (params (append (list :name name)
11032 (read (concat "(" (match-string 3) ")")))))
11034 (beginning-of-line 1)
11035 (skip-chars-forward " \t")
11036 (setq params (plist-put params :indentation-column (current-column))))
11037 (unless (re-search-forward org-dblock-end-re nil t)
11038 (error "Dynamic block not terminated"))
11041 (list :content (buffer-substring
11042 begdel (match-beginning 0)))))
11043 (delete-region begdel (match-beginning 0))
11048 (defun org-map-dblocks (&optional command)
11049 "Apply COMMAND to all dynamic blocks in the current buffer.
11050 If COMMAND is not given, use `org-update-dblock'."
11051 (let ((cmd (or command 'org-update-dblock)))
11053 (goto-char (point-min))
11054 (while (re-search-forward org-dblock-start-re nil t)
11055 (goto-char (match-beginning 0))
11057 (condition-case nil
11059 (error (message "Error during update of dynamic block"))))
11060 (unless (re-search-forward org-dblock-end-re nil t)
11061 (error "Dynamic block not terminated"))))))
11063 (defun org-dblock-update (&optional arg)
11064 "User command for updating dynamic blocks.
11065 Update the dynamic block at point. With prefix ARG, update all dynamic
11066 blocks in the buffer."
11069 (org-update-all-dblocks)
11070 (or (looking-at org-dblock-start-re)
11071 (org-beginning-of-dblock))
11072 (org-update-dblock)))
11074 (defun org-update-dblock ()
11075 "Update the dynamic block at point.
11076 This means to empty the block, parse for parameters and then call
11077 the correct writing function."
11079 (save-window-excursion
11080 (let* ((pos (point))
11081 (line (org-current-line))
11082 (params (org-prepare-dblock))
11083 (name (plist-get params :name))
11084 (indent (plist-get params :indentation-column))
11085 (cmd (intern (concat "org-dblock-write:" name))))
11086 (message "Updating dynamic block `%s' at line %d..." name line)
11087 (funcall cmd params)
11088 (message "Updating dynamic block `%s' at line %d...done" name line)
11090 (when (and indent (> indent 0))
11091 (setq indent (make-string indent ?\ ))
11093 (org-beginning-of-dblock)
11095 (while (not (looking-at org-dblock-end-re))
11097 (beginning-of-line 2))
11098 (when (looking-at org-dblock-end-re)
11099 (and (looking-at "[ \t]+")
11100 (replace-match ""))
11101 (insert indent)))))))
11103 (defun org-beginning-of-dblock ()
11104 "Find the beginning of the dynamic block at point.
11105 Error if there is no such block at point."
11106 (let ((pos (point))
11109 (if (and (re-search-backward org-dblock-start-re nil t)
11110 (setq beg (match-beginning 0))
11111 (re-search-forward org-dblock-end-re nil t)
11112 (> (match-end 0) pos))
11115 (error "Not in a dynamic block"))))
11118 (defun org-update-all-dblocks ()
11119 "Update all dynamic blocks in the buffer.
11120 This function can be used in a hook."
11122 (when (derived-mode-p 'org-mode)
11123 (org-map-dblocks 'org-update-dblock)))
11128 (defconst org-additional-option-like-keywords
11129 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11130 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11131 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11132 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11134 "ORGTBL" "TBLFM:" "TBLNAME:"
11135 "BEGIN_EXAMPLE" "END_EXAMPLE"
11136 "BEGIN_QUOTE" "END_QUOTE"
11137 "BEGIN_VERSE" "END_VERSE"
11138 "BEGIN_CENTER" "END_CENTER"
11139 "BEGIN_SRC" "END_SRC"
11140 "BEGIN_RESULT" "END_RESULT"
11142 "HEADER:" "HEADERS:"
11143 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11144 "CAPTION:" "LABEL:"
11150 (defcustom org-structure-template-alist
11152 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11153 "<src lang=\"?\">\n\n</src>")
11154 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11155 "<example>\n?\n</example>")
11156 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11157 "<quote>\n?\n</quote>")
11158 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11159 "<verse>\n?\n</verse>")
11160 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11161 "<center>\n?\n</center>")
11162 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11163 "<literal style=\"latex\">\n?\n</literal>")
11165 "<literal style=\"latex\">?</literal>")
11166 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11167 "<literal style=\"html\">\n?\n</literal>")
11169 "<literal style=\"html\">?</literal>")
11170 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11174 ("I" "#+INCLUDE %file ?"
11175 "<include file=%file markup=\"?\">")
11177 "Structure completion elements.
11178 This is a list of abbreviation keys and values. The value gets inserted
11179 if you type `<' followed by the key and then press the completion key,
11180 usually `M-TAB'. %file will be replaced by a file name after prompting
11181 for the file using completion. The cursor will be placed at the position
11182 of the `?` in the template.
11183 There are two templates for each key, the first uses the original Org syntax,
11184 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11185 the default when the /org-mtags.el/ module has been loaded. See also the
11186 variable `org-mtags-prefer-muse-templates'."
11187 :group 'org-completion
11189 (string :tag "Key")
11190 (string :tag "Template")
11191 (string :tag "Muse Template")))
11193 (defun org-try-structure-completion ()
11194 "Try to complete a structure template before point.
11195 This looks for strings like \"<e\" on an otherwise empty line and
11197 (let ((l (buffer-substring (point-at-bol) (point)))
11199 (when (and (looking-at "[ \t]*$")
11200 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11201 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11202 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11203 (match-beginning 1)) a)
11206 (defun org-complete-expand-structure-template (start cell)
11207 "Expand a structure template."
11208 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11209 (rpl (nth (if musep 2 1) cell))
11211 (delete-region start (point))
11212 (when (string-match "\\`#\\+" rpl)
11215 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11216 (setq ind (buffer-substring (point-at-bol) (point))))
11218 (setq start (point))
11219 (if (string-match "%file" rpl)
11220 (setq rpl (replace-match
11224 (abbreviate-file-name (read-file-name "Include file: ")))
11227 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11228 (concat "\n" ind)))
11230 (if (re-search-backward "\\?" start t) (delete-char 1))))
11232 ;;;; TODO, DEADLINE, Comments
11234 (defun org-toggle-comment ()
11235 "Change the COMMENT state of an entry."
11238 (org-back-to-heading)
11239 (let (case-fold-search)
11241 ((looking-at (format org-heading-keyword-regexp-format
11242 org-comment-string))
11243 (goto-char (match-end 1))
11244 (looking-at (concat " +" org-comment-string))
11245 (replace-match "" t t)
11246 (when (eolp) (insert " ")))
11247 ((looking-at org-outline-regexp)
11248 (goto-char (match-end 0))
11249 (insert org-comment-string " "))))))
11251 (defvar org-last-todo-state-is-todo nil
11252 "This is non-nil when the last TODO state change led to a TODO state.
11253 If the last change removed the TODO tag or switched to DONE, then
11256 (defvar org-setting-tags nil) ; dynamically skipped
11258 (defvar org-todo-setup-filter-hook nil
11259 "Hook for functions that pre-filter todo specs.
11260 Each function takes a todo spec and returns either nil or the spec
11261 transformed into canonical form." )
11263 (defvar org-todo-get-default-hook nil
11264 "Hook for functions that get a default item for todo.
11265 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11266 nil or a string to be used for the todo mark." )
11268 (defvar org-agenda-headline-snapshot-before-repeat)
11270 (defun org-current-effective-time ()
11271 "Return current time adjusted for `org-extend-today-until' variable"
11272 (let* ((ct (org-current-time))
11273 (dct (decode-time ct))
11275 (if (and org-use-effective-time
11276 (< (nth 2 dct) org-extend-today-until))
11277 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11281 (defun org-todo-yesterday (&optional arg)
11282 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11284 (if (eq major-mode 'org-agenda-mode)
11285 (apply 'org-agenda-todo-yesterday arg)
11286 (let* ((hour (third (decode-time
11287 (org-current-time))))
11288 (org-extend-today-until (1+ hour)))
11291 (defun org-todo (&optional arg)
11292 "Change the TODO state of an item.
11293 The state of an item is given by a keyword at the start of the heading,
11295 *** TODO Write paper
11298 The different keywords are specified in the variable `org-todo-keywords'.
11299 By default the available states are \"TODO\" and \"DONE\".
11300 So for this example: when the item starts with TODO, it is changed to DONE.
11301 When it starts with DONE, the DONE is removed. And when neither TODO nor
11302 DONE are present, add TODO at the beginning of the heading.
11304 With \\[universal-argument] prefix arg, use completion to determine the new \
11306 With numeric prefix arg, switch to that state.
11307 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11308 keywords (nextset).
11309 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11310 With a numeric prefix arg of 0, inhibit note taking for the change.
11312 For calling through lisp, arg is also interpreted in the following way:
11313 'none -> empty state
11314 \"\"(empty string) -> switch to empty state
11315 'done -> switch to DONE
11316 'nextset -> switch to the next set of keywords
11317 'previousset -> switch to the previous set of keywords
11318 \"WAITING\" -> switch to the specified keyword, but only if it
11319 really is a member of `org-todo-keywords'."
11321 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11322 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11323 'region-start-level 'region))
11324 org-loop-over-headlines-in-active-region)
11327 org-loop-over-headlines-in-active-region
11328 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11329 (if (equal arg '(16)) (setq arg 'nextset))
11330 (let ((org-blocker-hook org-blocker-hook)
11331 (case-fold-search nil))
11332 (when (equal arg '(64))
11333 (setq arg nil org-blocker-hook nil))
11334 (when (and org-blocker-hook
11335 (or org-inhibit-blocking
11336 (org-entry-get nil "NOBLOCKING")))
11337 (setq org-blocker-hook nil))
11340 (org-back-to-heading t)
11341 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11342 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11343 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11344 (let* ((match-data (match-data))
11345 (startpos (point-at-bol))
11346 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11347 (org-log-done org-log-done)
11348 (org-log-repeat org-log-repeat)
11349 (org-todo-log-states org-todo-log-states)
11350 (org-inhibit-logging
11352 (progn (setq arg nil) 'note) org-inhibit-logging))
11353 (this (match-string 1))
11354 (hl-pos (match-beginning 0))
11355 (head (org-get-todo-sequence-head this))
11356 (ass (assoc head org-todo-kwd-alist))
11357 (interpret (nth 1 ass))
11358 (done-word (nth 3 ass))
11359 (final-done-word (nth 4 ass))
11360 (org-last-state (or this ""))
11361 (completion-ignore-case t)
11362 (member (member this org-todo-keywords-1))
11363 (tail (cdr member))
11365 ((and org-todo-key-trigger
11366 (or (and (equal arg '(4))
11367 (eq org-use-fast-todo-selection 'prefix))
11368 (and (not arg) org-use-fast-todo-selection
11369 (not (eq org-use-fast-todo-selection
11371 ;; Use fast selection
11372 (org-fast-todo-selection))
11373 ((and (equal arg '(4))
11374 (or (not org-use-fast-todo-selection)
11375 (not org-todo-key-trigger)))
11376 ;; Read a state with completion
11377 (org-icompleting-read
11378 "State: " (mapcar (lambda(x) (list x))
11379 org-todo-keywords-1)
11383 (if tail (car tail) nil)
11384 (car org-todo-keywords-1)))
11386 (if (equal member org-todo-keywords-1)
11389 (nth (- (length org-todo-keywords-1)
11391 org-todo-keywords-1)
11392 (org-last org-todo-keywords-1))))
11393 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11394 (setq arg nil))) ; hack to fall back to cycling
11396 ;; user or caller requests a specific state
11398 ((equal arg "") nil)
11399 ((eq arg 'none) nil)
11400 ((eq arg 'done) (or done-word (car org-done-keywords)))
11402 (or (car (cdr (member head org-todo-heads)))
11403 (car org-todo-heads)))
11404 ((eq arg 'previousset)
11405 (let ((org-todo-heads (reverse org-todo-heads)))
11406 (or (car (cdr (member head org-todo-heads)))
11407 (car org-todo-heads))))
11408 ((car (member arg org-todo-keywords-1)))
11410 (error "State `%s' not valid in this file" arg))
11411 ((nth (1- (prefix-numeric-value arg))
11412 org-todo-keywords-1))))
11413 ((null member) (or head (car org-todo-keywords-1)))
11414 ((equal this final-done-word) nil) ;; -> make empty
11415 ((null tail) nil) ;; -> first entry
11416 ((memq interpret '(type priority))
11417 (if (eq this-command last-command)
11419 (if (> (length tail) 0)
11420 (or done-word (car org-done-keywords))
11425 (run-hook-with-args-until-success
11426 'org-todo-get-default-hook org-state org-last-state)
11428 (next (if org-state (concat " " org-state " ") " "))
11429 (change-plist (list :type 'todo-state-change :from this :to org-state
11430 :position startpos))
11432 (when org-blocker-hook
11433 (setq org-last-todo-state-is-todo
11434 (not (member this org-done-keywords)))
11435 (unless (save-excursion
11437 (org-with-wide-buffer
11438 (run-hook-with-args-until-failure
11439 'org-blocker-hook change-plist))))
11440 (if (org-called-interactively-p 'interactive)
11441 (error "TODO state change from %s to %s blocked" this org-state)
11443 (message "TODO state change from %s to %s blocked" this org-state)
11444 (throw 'exit nil))))
11445 (store-match-data match-data)
11446 (replace-match next t t)
11447 (unless (pos-visible-in-window-p hl-pos)
11448 (message "TODO state changed to %s" (org-trim next)))
11450 (setq head (org-get-todo-sequence-head org-state)
11451 ass (assoc head org-todo-kwd-alist)
11452 interpret (nth 1 ass)
11453 done-word (nth 3 ass)
11454 final-done-word (nth 4 ass)))
11455 (when (memq arg '(nextset previousset))
11456 (message "Keyword-Set %d/%d: %s"
11457 (- (length org-todo-sets) -1
11458 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11459 (length org-todo-sets)
11460 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11461 (setq org-last-todo-state-is-todo
11462 (not (member org-state org-done-keywords)))
11463 (setq now-done-p (and (member org-state org-done-keywords)
11464 (not (member this org-done-keywords))))
11465 (and logging (org-local-logging logging))
11466 (when (and (or org-todo-log-states org-log-done)
11467 (not (eq org-inhibit-logging t))
11468 (not (memq arg '(nextset previousset))))
11469 ;; we need to look at recording a time and note
11470 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11471 (nth 2 (assoc this org-todo-log-states))))
11472 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11473 (setq dolog 'time))
11474 (when (and org-state
11475 (member org-state org-not-done-keywords)
11476 (not (member this org-not-done-keywords)))
11477 ;; This is now a todo state and was not one before
11478 ;; If there was a CLOSED time stamp, get rid of it.
11479 (org-add-planning-info nil nil 'closed))
11480 (when (and now-done-p org-log-done)
11481 ;; It is now done, and it was not done before
11482 (org-add-planning-info 'closed (org-current-effective-time))
11483 (if (and (not dolog) (eq 'note org-log-done))
11484 (org-add-log-setup 'done org-state this 'findpos 'note)))
11485 (when (and org-state dolog)
11486 ;; This is a non-nil state, and we need to log it
11487 (org-add-log-setup 'state org-state this 'findpos dolog)))
11488 ;; Fixup tag positioning
11489 (org-todo-trigger-tag-changes org-state)
11490 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11491 (when org-provide-todo-statistics
11492 (org-update-parent-todo-statistics))
11493 (run-hooks 'org-after-todo-state-change-hook)
11494 (if (and arg (not (member org-state org-done-keywords)))
11495 (setq head (org-get-todo-sequence-head org-state)))
11496 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11497 ;; Do we need to trigger a repeat?
11499 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11500 ;; This is for the agenda, take a snapshot of the headline.
11502 (setq org-agenda-headline-snapshot-before-repeat
11503 (org-get-heading))))
11504 (org-auto-repeat-maybe org-state))
11505 ;; Fixup cursor location if close to the keyword
11506 (if (and (outline-on-heading-p)
11508 (save-excursion (beginning-of-line 1)
11509 (looking-at org-todo-line-regexp))
11510 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11512 (goto-char (or (match-end 2) (match-end 1)))
11513 (and (looking-at " ") (just-one-space))))
11514 (when org-trigger-hook
11516 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11518 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11519 "Block turning an entry into a TODO, using the hierarchy.
11520 This checks whether the current task should be blocked from state
11521 changes. Such blocking occurs when:
11523 1. The task has children which are not all in a completed state.
11525 2. A task has a parent with the property :ORDERED:, and there
11526 are siblings prior to the current task with incomplete
11529 3. The parent of the task is blocked because it has siblings that should
11530 be done first, or is child of a block grandparent TODO entry."
11532 (if (not org-enforce-todo-dependencies)
11533 t ; if locally turned off don't block
11535 ;; If this is not a todo state change, or if this entry is already DONE,
11537 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11538 (member (plist-get change-plist :from)
11539 (cons 'done org-done-keywords))
11540 (member (plist-get change-plist :to)
11541 (cons 'todo org-not-done-keywords))
11542 (not (plist-get change-plist :to)))
11543 (throw 'dont-block t))
11544 ;; If this task has children, and any are undone, it's blocked
11546 (org-back-to-heading t)
11547 (let ((this-level (funcall outline-level)))
11548 (outline-next-heading)
11549 (let ((child-level (funcall outline-level)))
11550 (while (and (not (eobp))
11551 (> child-level this-level))
11552 ;; this todo has children, check whether they are all
11554 (if (and (not (org-entry-is-done-p))
11555 (org-entry-is-todo-p))
11556 (throw 'dont-block nil))
11557 (outline-next-heading)
11558 (setq child-level (funcall outline-level))))))
11559 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11560 ;; any previous siblings are undone, it's blocked
11562 (org-back-to-heading t)
11563 (let* ((pos (point))
11564 (parent-pos (and (org-up-heading-safe) (point))))
11565 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11566 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11568 (re-search-forward org-not-done-heading-regexp pos t))
11569 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11570 ;; Search further up the hierarchy, to see if an ancestor is blocked
11572 (goto-char parent-pos)
11573 (if (not (looking-at org-not-done-heading-regexp))
11574 (throw 'dont-block t)) ; do not block, parent is not a TODO
11576 (setq parent-pos (and (org-up-heading-safe) (point)))
11577 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11578 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11580 (re-search-forward org-not-done-heading-regexp pos t))
11581 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11583 (defcustom org-track-ordered-property-with-tag nil
11584 "Should the ORDERED property also be shown as a tag?
11585 The ORDERED property decides if an entry should require subtasks to be
11586 completed in sequence. Since a property is not very visible, setting
11587 this option means that toggling the ORDERED property with the command
11588 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11589 not relevant for the behavior, but it makes things more visible.
11591 Note that toggling the tag with tags commands will not change the property
11592 and therefore not influence behavior!
11594 This can be t, meaning the tag ORDERED should be used, It can also be a
11595 string to select a different tag for this task."
11598 (const :tag "No tracking" nil)
11599 (const :tag "Track with ORDERED tag" t)
11600 (string :tag "Use other tag")))
11602 (defun org-toggle-ordered-property ()
11603 "Toggle the ORDERED property of the current entry.
11604 For better visibility, you can track the value of this property with a tag.
11605 See variable `org-track-ordered-property-with-tag'."
11607 (let* ((t1 org-track-ordered-property-with-tag)
11608 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11610 (org-back-to-heading)
11611 (if (org-entry-get nil "ORDERED")
11613 (org-delete-property "ORDERED")
11614 (and tag (org-toggle-tag tag 'off))
11615 (message "Subtasks can be completed in arbitrary order"))
11616 (org-entry-put nil "ORDERED" "t")
11617 (and tag (org-toggle-tag tag 'on))
11618 (message "Subtasks must be completed in sequence")))))
11620 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11621 (defun org-block-todo-from-checkboxes (change-plist)
11622 "Block turning an entry into a TODO, using checkboxes.
11623 This checks whether the current task should be blocked from state
11624 changes because there are unchecked boxes in this entry."
11625 (if (not org-enforce-todo-checkbox-dependencies)
11626 t ; if locally turned off don't block
11628 ;; If this is not a todo state change, or if this entry is already DONE,
11630 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11631 (member (plist-get change-plist :from)
11632 (cons 'done org-done-keywords))
11633 (member (plist-get change-plist :to)
11634 (cons 'todo org-not-done-keywords))
11635 (not (plist-get change-plist :to)))
11636 (throw 'dont-block t))
11637 ;; If this task has checkboxes that are not checked, it's blocked
11639 (org-back-to-heading t)
11640 (let ((beg (point)) end)
11641 (outline-next-heading)
11644 (if (org-list-search-forward
11645 (concat (org-item-beginning-re)
11646 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11650 (if (boundp 'org-blocked-by-checkboxes)
11651 (setq org-blocked-by-checkboxes t))
11652 (throw 'dont-block nil)))))
11653 t))) ; do not block
11655 (defun org-entry-blocked-p ()
11656 "Is the current entry blocked?"
11657 (if (org-entry-get nil "NOBLOCKING")
11658 nil ;; Never block this entry
11660 (run-hook-with-args-until-failure
11662 (list :type 'todo-state-change
11667 (defun org-update-statistics-cookies (all)
11668 "Update the statistics cookie, either from TODO or from checkboxes.
11669 This should be called with the cursor in a line with a statistics cookie."
11673 (org-update-checkbox-count 'all)
11674 (org-map-entries 'org-update-parent-todo-statistics))
11675 (if (not (org-at-heading-p))
11676 (org-update-checkbox-count)
11677 (let ((pos (move-marker (make-marker) (point)))
11679 (ignore-errors (org-back-to-heading t))
11680 (if (not (org-at-heading-p))
11681 (org-update-checkbox-count)
11682 (setq l1 (org-outline-level))
11683 (setq end (save-excursion
11684 (outline-next-heading)
11685 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11687 (if (and (save-excursion
11689 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11690 (not (save-excursion (re-search-forward
11691 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11692 (org-update-checkbox-count)
11693 (if (and l2 (> l2 l1))
11696 (org-update-parent-todo-statistics))
11698 (beginning-of-line 1)
11699 (while (re-search-forward
11700 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11702 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11704 (move-marker pos nil)))))
11706 (defvar org-entry-property-inherited-from) ;; defined below
11707 (defun org-update-parent-todo-statistics ()
11708 "Update any statistics cookie in the parent of the current headline.
11709 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11710 the entire subtree and this will travel up the hierarchy and update
11711 statistics everywhere."
11712 (let* ((prop (save-excursion (org-up-heading-safe)
11713 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11714 (recursive (or (not org-hierarchical-todo-statistics)
11715 (and prop (string-match "\\<recursive\\>" prop))))
11716 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11719 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11720 level ltoggle l1 new ndel
11721 (cnt-all 0) (cnt-done 0) is-percent kwd
11722 checkbox-beg ov ovs ove cookie-present)
11725 (beginning-of-line 1)
11726 (setq ltoggle (funcall outline-level))
11727 ;; Three situations are to consider:
11729 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11730 ;; to the top-level ancestor on the headline;
11732 ;; 2. If parent has "recursive" property, repeat up to the
11733 ;; headline setting that property, taking inheritance into
11736 ;; 3. Else, move up to direct parent and proceed only once.
11737 (while (and (setq level (org-up-heading-safe))
11738 (or recursive first)
11740 (setq first nil cookie-present nil)
11744 (downcase (or (org-entry-get nil "COOKIE_DATA")
11747 (while (re-search-forward box-re (point-at-eol) t)
11748 (setq cnt-all 0 cnt-done 0 cookie-present t)
11749 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11751 (unless (outline-next-heading) (throw 'exit nil))
11752 (while (and (looking-at org-complex-heading-regexp)
11753 (> (setq l1 (length (match-string 1))) level))
11754 (setq kwd (and (or recursive (= l1 ltoggle))
11756 (if (or (eq org-provide-todo-statistics 'all-headlines)
11757 (and (listp org-provide-todo-statistics)
11758 (or (member kwd org-provide-todo-statistics)
11759 (member kwd org-done-keywords))))
11760 (setq cnt-all (1+ cnt-all))
11761 (if (eq org-provide-todo-statistics t)
11762 (and kwd (setq cnt-all (1+ cnt-all)))))
11763 (and (member kwd org-done-keywords)
11764 (setq cnt-done (1+ cnt-done)))
11765 (outline-next-heading)))
11768 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11769 (format "[%d/%d]" cnt-done cnt-all))
11770 ndel (- (match-end 0) checkbox-beg))
11771 ;; handle overlays when updating cookie from column view
11772 (when (setq ov (car (overlays-at checkbox-beg)))
11773 (setq ovs (overlay-start ov) ove (overlay-end ov))
11774 (delete-overlay ov))
11775 (goto-char checkbox-beg)
11777 (delete-region (point) (+ (point) ndel))
11778 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11779 (when ov (move-overlay ov ovs ove)))
11780 (when cookie-present
11781 (run-hook-with-args 'org-after-todo-statistics-hook
11782 cnt-done (- cnt-all cnt-done))))))
11783 (run-hooks 'org-todo-statistics-hook)))
11785 (defvar org-after-todo-statistics-hook nil
11786 "Hook that is called after a TODO statistics cookie has been updated.
11787 Each function is called with two arguments: the number of not-done entries
11788 and the number of done entries.
11790 For example, the following function, when added to this hook, will switch
11791 an entry to DONE when all children are done, and back to TODO when new
11792 entries are set to a TODO status. Note that this hook is only called
11793 when there is a statistics cookie in the headline!
11795 (defun org-summary-todo (n-done n-not-done)
11796 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11797 (let (org-log-done org-log-states) ; turn off logging
11798 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11801 (defvar org-todo-statistics-hook nil
11802 "Hook that is run whenever Org thinks TODO statistics should be updated.
11803 This hook runs even if there is no statistics cookie present, in which case
11804 `org-after-todo-statistics-hook' would not run.")
11806 (defun org-todo-trigger-tag-changes (state)
11807 "Apply the changes defined in `org-todo-state-tags-triggers'."
11808 (let ((l org-todo-state-tags-triggers)
11810 (when (or (not state) (equal state ""))
11811 (setq changes (append changes (cdr (assoc "" l)))))
11812 (when (and (stringp state) (> (length state) 0))
11813 (setq changes (append changes (cdr (assoc state l)))))
11814 (when (member state org-not-done-keywords)
11815 (setq changes (append changes (cdr (assoc 'todo l)))))
11816 (when (member state org-done-keywords)
11817 (setq changes (append changes (cdr (assoc 'done l)))))
11818 (dolist (c changes)
11819 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11821 (defun org-local-logging (value)
11822 "Get logging settings from a property VALUE."
11824 ;; directly set the variables, they are already local.
11825 (setq org-log-done nil
11827 org-todo-log-states nil)
11828 (setq words (org-split-string value))
11829 (while (setq w (pop words))
11831 ((setq a (assoc w org-startup-options))
11832 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11833 (set (nth 1 a) (nth 2 a))))
11834 ((setq a (org-extract-log-state-settings w))
11835 (and (member (car a) org-todo-keywords-1)
11836 (push a org-todo-log-states)))))))
11838 (defun org-get-todo-sequence-head (kwd)
11839 "Return the head of the TODO sequence to which KWD belongs.
11840 If KWD is not set, check if there is a text property remembering the
11845 (or (get-text-property (point-at-bol) 'org-todo-head)
11847 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11848 nil (point-at-eol)))
11849 (get-text-property p 'org-todo-head))))
11850 ((not (member kwd org-todo-keywords-1))
11851 (car org-todo-keywords-1))
11852 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11854 (defun org-fast-todo-selection ()
11855 "Fast TODO keyword selection with single keys.
11856 Returns the new TODO keyword, or nil if no state change should occur."
11857 (let* ((fulltable org-todo-key-alist)
11858 (done-keywords org-done-keywords) ;; needed for the faces.
11859 (maxlen (apply 'max (mapcar
11861 (if (stringp (car x)) (string-width (car x)) 0))
11864 (fwidth (+ maxlen 3 1 3))
11865 (ncol (/ (- (window-width) 4) fwidth))
11869 (save-window-excursion
11871 (set-buffer (get-buffer-create " *Org todo*"))
11872 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11874 (org-set-local 'org-done-keywords done-keywords)
11875 (setq tbl fulltable cnt 0)
11876 (while (setq e (pop tbl))
11878 ((equal e '(:startgroup))
11879 (push '() groups) (setq ingroup t)
11880 (when (not (= cnt 0))
11884 ((equal e '(:endgroup))
11885 (setq ingroup nil cnt 0)
11887 ((equal e '(:newline))
11888 (when (not (= cnt 0))
11892 (while (equal (car tbl) '(:newline))
11894 (setq tbl (cdr tbl)))))
11896 (setq tg (car e) c (cdr e))
11897 (if ingroup (push tg (car groups)))
11898 (setq tg (org-add-props tg nil 'face
11899 (org-get-todo-face tg)))
11900 (if (and (= cnt 0) (not ingroup)) (insert " "))
11901 (insert "[" c "] " tg (make-string
11902 (- fwidth 4 (length tg)) ?\ ))
11903 (when (= (setq cnt (1+ cnt)) ncol)
11905 (if ingroup (insert " "))
11908 (goto-char (point-min))
11909 (if (not expert) (org-fit-window-to-buffer))
11910 (message "[a-z..]:Set [SPC]:clear")
11911 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11914 (and (= c ?q) (not (rassoc c fulltable))))
11915 (setq quit-flag t))
11917 ((setq e (rassoc c fulltable) tg (car e))
11919 (t (setq quit-flag t)))))))
11921 (defun org-entry-is-todo-p ()
11922 (member (org-get-todo-state) org-not-done-keywords))
11924 (defun org-entry-is-done-p ()
11925 (member (org-get-todo-state) org-done-keywords))
11927 (defun org-get-todo-state ()
11929 (org-back-to-heading t)
11930 (and (looking-at org-todo-line-regexp)
11932 (match-string 2))))
11934 (defun org-at-date-range-p (&optional inactive-ok)
11935 "Is the cursor inside a date range?"
11939 (let ((pos (point)))
11940 (skip-chars-backward "^[<\r\n")
11941 (skip-chars-backward "<[")
11942 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11943 (>= (match-end 0) pos)
11945 (skip-chars-backward "^<[\r\n")
11946 (skip-chars-backward "<[")
11947 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11948 (>= (match-end 0) pos)
11952 (defun org-get-repeat (&optional tagline)
11953 "Check if there is a deadline/schedule with repeater in this entry."
11956 (org-back-to-heading t)
11957 (and (re-search-forward (if tagline
11958 (concat tagline "\\s-*" org-repeat-re)
11960 (org-entry-end-position) t)
11961 (match-string-no-properties 1)))))
11963 (defvar org-last-changed-timestamp)
11964 (defvar org-last-inserted-timestamp)
11965 (defvar org-log-post-message)
11966 (defvar org-log-note-purpose)
11967 (defvar org-log-note-how)
11968 (defvar org-log-note-extra)
11969 (defun org-auto-repeat-maybe (done-word)
11970 "Check if the current headline contains a repeated deadline/schedule.
11971 If yes, set TODO state back to what it was and change the base date
11972 of repeating deadline/scheduled time stamps to new date.
11973 This function is run automatically after each state change to a DONE state."
11974 ;; last-state is dynamically scoped into this function
11975 (let* ((repeat (org-get-repeat))
11976 (aa (assoc org-last-state org-todo-kwd-alist))
11977 (interpret (nth 1 aa))
11979 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
11980 (msg "Entry repeats: ")
11982 (org-todo-log-states nil)
11983 re type n what ts time to-state)
11985 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11986 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11987 org-todo-repeat-to-state))
11988 (unless (and to-state (member to-state org-todo-keywords-1))
11989 (setq to-state (if (eq interpret 'type) org-last-state head)))
11990 (org-todo to-state)
11991 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11992 (org-entry-put nil "LAST_REPEAT" (format-time-string
11993 (org-time-stamp-format t t))))
11994 (when org-log-repeat
11995 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11996 (memq 'org-add-log-note post-command-hook))
11997 ;; OK, we are already setup for some record
11998 (if (eq org-log-repeat 'note)
11999 ;; make sure we take a note, not only a time stamp
12000 (setq org-log-note-how 'note))
12001 ;; Set up for taking a record
12002 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12004 'findpos org-log-repeat)))
12005 (org-back-to-heading t)
12006 (org-add-planning-info nil nil 'closed)
12007 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12008 org-deadline-time-regexp "\\)\\|\\("
12009 org-ts-regexp "\\)"))
12010 (while (re-search-forward
12011 re (save-excursion (outline-next-heading) (point)) t)
12012 (setq type (if (match-end 1) org-scheduled-string
12013 (if (match-end 3) org-deadline-string "Plain:"))
12014 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12015 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12016 (setq n (string-to-number (match-string 2 ts))
12017 what (match-string 3 ts))
12018 (if (equal what "w") (setq n (* n 7) what "d"))
12019 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12020 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12021 ;; Preparation, see if we need to modify the start date for the change
12022 (when (match-end 1)
12023 (setq time (save-match-data (org-time-string-to-time ts)))
12025 ((equal (match-string 1 ts) ".")
12026 ;; Shift starting date to today
12027 (org-timestamp-change
12028 (- (org-today) (time-to-days time))
12030 ((equal (match-string 1 ts) "+")
12031 (let ((nshiftmax 10) (nshift 0))
12032 (while (or (= nshift 0)
12033 (<= (time-to-days time)
12034 (time-to-days (current-time))))
12035 (when (= (incf nshift) nshiftmax)
12036 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12038 (org-timestamp-change n (cdr (assoc what whata)))
12039 (org-at-timestamp-p t)
12040 (setq ts (match-string 1))
12041 (setq time (save-match-data (org-time-string-to-time ts)))))
12042 (org-timestamp-change (- n) (cdr (assoc what whata)))
12043 ;; rematch, so that we have everything in place for the real shift
12044 (org-at-timestamp-p t)
12045 (setq ts (match-string 1))
12046 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12047 (org-timestamp-change n (cdr (assoc what whata)))
12048 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12049 (setq org-log-post-message msg)
12050 (message "%s" msg))))
12052 (defun org-show-todo-tree (arg)
12053 "Make a compact tree which shows all headlines marked with TODO.
12054 The tree will show the lines where the regexp matches, and all higher
12055 headlines above the match.
12056 With a \\[universal-argument] prefix, prompt for a regexp to match.
12057 With a numeric prefix N, construct a sparse tree for the Nth element
12058 of `org-todo-keywords-1'."
12060 (let ((case-fold-search nil)
12062 (cond ((null arg) org-not-done-regexp)
12064 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12065 (mapcar 'list org-todo-keywords-1))))
12067 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12069 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12070 (regexp-quote (nth (1- (prefix-numeric-value arg))
12071 org-todo-keywords-1)))
12072 (t (error "Invalid prefix argument: %s" arg)))))
12073 (message "%d TODO entries found"
12074 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12076 (defun org-deadline (&optional remove time)
12077 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12078 With argument REMOVE, remove any deadline from the item.
12079 With argument TIME, set the deadline at the corresponding date. TIME
12080 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12082 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12083 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12084 'region-start-level 'region))
12085 org-loop-over-headlines-in-active-region)
12087 `(org-deadline ',remove ,time)
12088 org-loop-over-headlines-in-active-region
12089 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12090 (let* ((old-date (org-entry-get nil "DEADLINE"))
12091 (repeater (and old-date
12093 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12095 (match-string 1 old-date))))
12098 (when (and old-date org-log-redeadline)
12099 (org-add-log-setup 'deldeadline nil old-date 'findpos
12100 org-log-redeadline))
12101 (org-remove-timestamp-with-keyword org-deadline-string)
12102 (message "Item no longer has a deadline."))
12103 (org-add-planning-info 'deadline time 'closed)
12104 (when (and old-date org-log-redeadline
12105 (not (equal old-date
12106 (substring org-last-inserted-timestamp 1 -1))))
12107 (org-add-log-setup 'redeadline nil old-date 'findpos
12108 org-log-redeadline))
12111 (org-back-to-heading t)
12112 (when (re-search-forward (concat org-deadline-string " "
12113 org-last-inserted-timestamp)
12115 (outline-next-heading) (point)) t)
12116 (goto-char (1- (match-end 0)))
12117 (insert " " repeater)
12118 (setq org-last-inserted-timestamp
12119 (concat (substring org-last-inserted-timestamp 0 -1)
12121 (substring org-last-inserted-timestamp -1))))))
12122 (message "Deadline on %s" org-last-inserted-timestamp)))))
12124 (defun org-schedule (&optional remove time)
12125 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12126 With argument REMOVE, remove any scheduling date from the item.
12127 With argument TIME, scheduled at the corresponding date. TIME can
12128 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12130 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12131 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12132 'region-start-level 'region))
12133 org-loop-over-headlines-in-active-region)
12135 `(org-schedule ',remove ,time)
12136 org-loop-over-headlines-in-active-region
12137 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12138 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12139 (repeater (and old-date
12141 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12143 (match-string 1 old-date))))
12146 (when (and old-date org-log-reschedule)
12147 (org-add-log-setup 'delschedule nil old-date 'findpos
12148 org-log-reschedule))
12149 (org-remove-timestamp-with-keyword org-scheduled-string)
12150 (message "Item is no longer scheduled."))
12151 (org-add-planning-info 'scheduled time 'closed)
12152 (when (and old-date org-log-reschedule
12153 (not (equal old-date
12154 (substring org-last-inserted-timestamp 1 -1))))
12155 (org-add-log-setup 'reschedule nil old-date 'findpos
12156 org-log-reschedule))
12159 (org-back-to-heading t)
12160 (when (re-search-forward (concat org-scheduled-string " "
12161 org-last-inserted-timestamp)
12163 (outline-next-heading) (point)) t)
12164 (goto-char (1- (match-end 0)))
12165 (insert " " repeater)
12166 (setq org-last-inserted-timestamp
12167 (concat (substring org-last-inserted-timestamp 0 -1)
12169 (substring org-last-inserted-timestamp -1))))))
12170 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12172 (defun org-get-scheduled-time (pom &optional inherit)
12173 "Get the scheduled time as a time tuple, of a format suitable
12174 for calling org-schedule with, or if there is no scheduling,
12176 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12178 (apply 'encode-time (org-parse-time-string time)))))
12180 (defun org-get-deadline-time (pom &optional inherit)
12181 "Get the deadline as a time tuple, of a format suitable for
12182 calling org-deadline with, or if there is no scheduling, returns
12184 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12186 (apply 'encode-time (org-parse-time-string time)))))
12188 (defun org-remove-timestamp-with-keyword (keyword)
12189 "Remove all time stamps with KEYWORD in the current entry."
12190 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12193 (org-back-to-heading t)
12195 (outline-next-heading)
12196 (while (re-search-backward re beg t)
12198 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12199 (equal (char-before) ?\ ))
12200 (backward-delete-char 1)
12201 (if (string-match "^[ \t]*$" (buffer-substring
12202 (point-at-bol) (point-at-eol)))
12203 (delete-region (point-at-bol)
12204 (min (point-max) (1+ (point-at-eol))))))))))
12206 (defun org-add-planning-info (what &optional time &rest remove)
12207 "Insert new timestamp with keyword in the line directly after the headline.
12208 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12209 If non is given, the user is prompted for a date.
12210 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12213 (let (org-time-was-given org-end-time-was-given ts
12214 end default-time default-input)
12217 (when (and (memq what '(scheduled deadline))
12219 (and (stringp time)
12220 (string-match "^[-+]+[0-9]" time))))
12221 ;; Try to get a default date/time from existing timestamp
12223 (org-back-to-heading t)
12224 (setq end (save-excursion (outline-next-heading) (point)))
12225 (when (re-search-forward (if (eq what 'scheduled)
12226 org-scheduled-time-regexp
12227 org-deadline-time-regexp)
12229 (setq ts (match-string 1)
12231 (apply 'encode-time (org-parse-time-string ts))
12232 default-input (and ts (org-get-compact-tod ts))))))
12236 ;; This is a string (relative or absolute), set proper date
12237 (apply 'encode-time
12238 (org-read-date-analyze
12239 time default-time (decode-time default-time)))
12240 ;; If necessary, get the time from the user
12241 (or time (org-read-date nil 'to-time nil nil
12242 default-time default-input)))))
12244 (when (and org-insert-labeled-timestamps-at-point
12245 (member what '(scheduled deadline)))
12247 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12248 (org-insert-time-stamp time org-time-was-given
12249 nil nil nil (list org-end-time-was-given))
12253 (let (col list elt ts buffer-invisibility-spec)
12254 (org-back-to-heading t)
12255 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12256 (goto-char (match-end 1))
12257 (setq col (current-column))
12258 (goto-char (match-end 0))
12259 (if (eobp) (insert "\n") (forward-char 1))
12260 (when (and (not what)
12263 org-keyword-time-not-clock-regexp))))
12264 ;; Nothing to add, nothing to remove...... :-)
12266 (if (and (not (looking-at org-outline-regexp))
12267 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12269 (not (equal (match-string 1) org-clock-string)))
12270 (narrow-to-region (match-beginning 0) (match-end 0))
12271 (insert-before-markers "\n")
12273 (narrow-to-region (point) (point))
12274 (and org-adapt-indentation (org-indent-to-column col)))
12275 ;; Check if we have to remove something.
12276 (setq list (cons what remove))
12278 (setq elt (pop list))
12279 (when (or (and (eq elt 'scheduled)
12280 (re-search-forward org-scheduled-time-regexp nil t))
12281 (and (eq elt 'deadline)
12282 (re-search-forward org-deadline-time-regexp nil t))
12283 (and (eq elt 'closed)
12284 (re-search-forward org-closed-time-regexp nil t)))
12286 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12287 (and (looking-at "[ \t]+") (replace-match ""))
12288 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12291 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12292 (cond ((eq what 'scheduled) org-scheduled-string)
12293 ((eq what 'deadline) org-deadline-string)
12294 ((eq what 'closed) org-closed-string))
12296 (setq ts (org-insert-time-stamp
12298 (or org-time-was-given
12299 (and (eq what 'closed) org-log-done-with-time))
12301 nil nil (list org-end-time-was-given)))
12303 (if (not (or (bolp) (eq (char-before) ?\ )
12304 (memq (char-after) '(32 10))
12307 (goto-char (point-min))
12309 (if (and (looking-at "[ \t]*\n")
12310 (equal (char-before) ?\n))
12311 (delete-region (1- (point)) (point-at-eol)))
12314 (defvar org-log-note-marker (make-marker))
12315 (defvar org-log-note-purpose nil)
12316 (defvar org-log-note-state nil)
12317 (defvar org-log-note-previous-state nil)
12318 (defvar org-log-note-how nil)
12319 (defvar org-log-note-extra nil)
12320 (defvar org-log-note-window-configuration nil)
12321 (defvar org-log-note-return-to (make-marker))
12322 (defvar org-log-note-effective-time nil
12323 "Remembered current time so that dynamically scoped
12324 `org-extend-today-until' affects tha timestamps in state change
12327 (defvar org-log-post-message nil
12328 "Message to be displayed after a log note has been stored.
12329 The auto-repeater uses this.")
12331 (defun org-add-note ()
12332 "Add a note to the current entry.
12333 This is done in the same way as adding a state change note."
12335 (org-add-log-setup 'note nil nil 'findpos nil))
12337 (defvar org-property-end-re)
12338 (defun org-add-log-setup (&optional purpose state prev-state
12340 "Set up the post command hook to take a note.
12341 If this is about to TODO state change, the new state is expected in STATE.
12342 When FINDPOS is non-nil, find the correct position for the note in
12343 the current entry. If not, assume that it can be inserted at point.
12344 HOW is an indicator what kind of note should be created.
12345 EXTRA is additional text that will be inserted into the notes buffer."
12346 (let* ((org-log-into-drawer (org-log-into-drawer))
12347 (drawer (cond ((stringp org-log-into-drawer)
12348 org-log-into-drawer)
12349 (org-log-into-drawer "LOGBOOK")
12354 (org-back-to-heading t)
12355 (narrow-to-region (point) (save-excursion
12356 (outline-next-heading) (point)))
12357 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12358 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12360 (goto-char (match-end 0))
12363 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12366 (goto-char (match-end 0))
12367 (or org-log-states-order-reversed
12368 (and (re-search-forward org-property-end-re nil t)
12369 (goto-char (1- (match-beginning 0))))))
12370 (insert "\n:" drawer ":\n:END:")
12371 (beginning-of-line 0)
12372 (org-indent-line-function)
12373 (beginning-of-line 2)
12374 (org-indent-line-function)
12376 ((and org-log-state-notes-insert-after-drawers
12378 (forward-line) (looking-at org-drawer-regexp)))
12380 (while (looking-at org-drawer-regexp)
12381 (goto-char (match-end 0))
12382 (re-search-forward org-property-end-re (point-max) t)
12384 (forward-line -1)))
12385 (unless org-log-states-order-reversed
12386 (and (= (char-after) ?\n) (forward-char 1))
12387 (org-skip-over-state-notes)
12388 (skip-chars-backward " \t\n\r")))
12389 (move-marker org-log-note-marker (point))
12390 (setq org-log-note-purpose purpose
12391 org-log-note-state state
12392 org-log-note-previous-state prev-state
12393 org-log-note-how how
12394 org-log-note-extra extra
12395 org-log-note-effective-time (org-current-effective-time))
12396 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12398 (defun org-skip-over-state-notes ()
12399 "Skip past the list of State notes in an entry."
12400 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12401 (when (ignore-errors (goto-char (org-in-item-p)))
12402 (let* ((struct (org-list-struct))
12403 (prevs (org-list-prevs-alist struct)))
12404 (while (looking-at "[ \t]*- State")
12405 (goto-char (or (org-list-get-next-item (point) struct prevs)
12406 (org-list-get-item-end (point) struct)))))))
12408 (defun org-add-log-note (&optional purpose)
12409 "Pop up a window for taking a note, and add this note later at point."
12410 (remove-hook 'post-command-hook 'org-add-log-note)
12411 (setq org-log-note-window-configuration (current-window-configuration))
12412 (delete-other-windows)
12413 (move-marker org-log-note-return-to (point))
12414 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12415 (goto-char org-log-note-marker)
12416 (org-switch-to-buffer-other-window "*Org Note*")
12418 (if (memq org-log-note-how '(time state))
12419 (let (current-prefix-arg) (org-store-log-note))
12420 (let ((org-inhibit-startup t)) (org-mode))
12421 (insert (format "# Insert note for %s.
12422 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12424 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12425 ((eq org-log-note-purpose 'done) "closed todo item")
12426 ((eq org-log-note-purpose 'state)
12427 (format "state change from \"%s\" to \"%s\""
12428 (or org-log-note-previous-state "")
12429 (or org-log-note-state "")))
12430 ((eq org-log-note-purpose 'reschedule)
12432 ((eq org-log-note-purpose 'delschedule)
12433 "no longer scheduled")
12434 ((eq org-log-note-purpose 'redeadline)
12435 "changing deadline")
12436 ((eq org-log-note-purpose 'deldeadline)
12437 "removing deadline")
12438 ((eq org-log-note-purpose 'refile)
12440 ((eq org-log-note-purpose 'note)
12442 (t (error "This should not happen")))))
12443 (if org-log-note-extra (insert org-log-note-extra))
12444 (org-set-local 'org-finish-function 'org-store-log-note)
12445 (run-hooks 'org-log-buffer-setup-hook)))
12447 (defvar org-note-abort nil) ; dynamically scoped
12448 (defun org-store-log-note ()
12449 "Finish taking a log note, and insert it to where it belongs."
12450 (let ((txt (buffer-string))
12451 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12453 (kill-buffer (current-buffer))
12454 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12455 (setq txt (replace-match "" t t txt)))
12456 (if (string-match "\\s-+\\'" txt)
12457 (setq txt (replace-match "" t t txt)))
12458 (setq lines (org-split-string txt "\n"))
12459 (when (and note (string-match "\\S-" note))
12461 (org-replace-escapes
12463 (list (cons "%u" (user-login-name))
12464 (cons "%U" user-full-name)
12465 (cons "%t" (format-time-string
12466 (org-time-stamp-format 'long 'inactive)
12467 org-log-note-effective-time))
12468 (cons "%T" (format-time-string
12469 (org-time-stamp-format 'long nil)
12470 org-log-note-effective-time))
12471 (cons "%d" (format-time-string
12472 (org-time-stamp-format nil 'inactive)
12473 org-log-note-effective-time))
12474 (cons "%D" (format-time-string
12475 (org-time-stamp-format nil nil)
12476 org-log-note-effective-time))
12477 (cons "%s" (if org-log-note-state
12478 (concat "\"" org-log-note-state "\"")
12480 (cons "%S" (if org-log-note-previous-state
12481 (concat "\"" org-log-note-previous-state "\"")
12483 (if lines (setq note (concat note " \\\\")))
12485 (when (or current-prefix-arg org-note-abort)
12486 (when org-log-into-drawer
12487 (org-remove-empty-drawer-at
12488 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12489 org-log-note-marker))
12492 (with-current-buffer (marker-buffer org-log-note-marker)
12494 (goto-char org-log-note-marker)
12495 (move-marker org-log-note-marker nil)
12497 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12498 (setq ind (save-excursion
12499 (if (ignore-errors (goto-char (org-in-item-p)))
12500 (let ((struct (org-list-struct)))
12502 (org-list-get-top-point struct) struct))
12503 (skip-chars-backward " \r\t\n")
12505 ((and (org-at-heading-p)
12506 org-adapt-indentation)
12507 (1+ (org-current-level)))
12508 ((org-at-heading-p) 0)
12509 (t (org-get-indentation))))))
12510 (setq bul (org-list-bullet-string "-"))
12511 (org-indent-line-to ind)
12512 (insert bul (pop lines))
12513 (let ((ind-body (+ (length bul) ind)))
12516 (org-indent-line-to ind-body)
12517 (insert (pop lines))))
12518 (message "Note stored")
12519 (org-back-to-heading t)
12520 (org-cycle-hide-drawers 'children)))))
12521 (set-window-configuration org-log-note-window-configuration)
12522 (with-current-buffer (marker-buffer org-log-note-return-to)
12523 (goto-char org-log-note-return-to))
12524 (move-marker org-log-note-return-to nil)
12525 (and org-log-post-message (message "%s" org-log-post-message)))
12527 (defun org-remove-empty-drawer-at (drawer pos)
12528 "Remove an empty drawer DRAWER at position POS.
12529 POS may also be a marker."
12530 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12536 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12537 (replace-match ""))))))
12539 (defun org-sparse-tree (&optional arg)
12540 "Create a sparse tree, prompt for the details.
12541 This command can create sparse trees. You first need to select the type
12542 of match used to create the tree:
12544 t Show all TODO entries.
12545 T Show entries with a specific TODO keyword.
12546 m Show entries selected by a tags/property match.
12547 p Enter a property name and its value (both with completion on existing
12548 names/values) and show entries with that property.
12549 r Show entries matching a regular expression (`/' can be used as well)
12550 d Show deadlines due within `org-deadline-warning-days'.
12551 b Show deadlines and scheduled items before a date.
12552 a Show deadlines and scheduled items after a date."
12554 (let (ans kwd value)
12555 (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")
12556 (setq ans (read-char-exclusive))
12559 (call-interactively 'org-check-deadlines))
12561 (call-interactively 'org-check-before-date))
12563 (call-interactively 'org-check-after-date))
12565 (call-interactively 'org-check-dates-range))
12567 (org-show-todo-tree nil))
12569 (org-show-todo-tree '(4)))
12570 ((member ans '(?T ?m))
12571 (call-interactively 'org-match-sparse-tree))
12572 ((member ans '(?p ?P))
12573 (setq kwd (org-icompleting-read "Property: "
12574 (mapcar 'list (org-buffer-property-keys))))
12575 (setq value (org-icompleting-read "Value: "
12576 (mapcar 'list (org-property-values kwd))))
12577 (unless (string-match "\\`{.*}\\'" value)
12578 (setq value (concat "\"" value "\"")))
12579 (org-match-sparse-tree arg (concat kwd "=" value)))
12580 ((member ans '(?r ?R ?/))
12581 (call-interactively 'org-occur))
12582 (t (error "No such sparse tree command \"%c\"" ans)))))
12584 (defvar org-occur-highlights nil
12585 "List of overlays used for occur matches.")
12586 (make-variable-buffer-local 'org-occur-highlights)
12587 (defvar org-occur-parameters nil
12588 "Parameters of the active org-occur calls.
12589 This is a list, each call to org-occur pushes as cons cell,
12590 containing the regular expression and the callback, onto the list.
12591 The list can contain several entries if `org-occur' has been called
12592 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12593 will only contain one set of parameters. When the highlights are
12594 removed (for example with `C-c C-c', or with the next edit (depending
12595 on `org-remove-highlights-with-change'), this variable is emptied
12597 (make-variable-buffer-local 'org-occur-parameters)
12599 (defun org-occur (regexp &optional keep-previous callback)
12600 "Make a compact tree which shows all matches of REGEXP.
12601 The tree will show the lines where the regexp matches, and all higher
12602 headlines above the match. It will also show the heading after the match,
12603 to make sure editing the matching entry is easy.
12604 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12605 call to `org-occur' will be kept, to allow stacking of calls to this
12607 If CALLBACK is non-nil, it is a function which is called to confirm
12608 that the match should indeed be shown."
12609 (interactive "sRegexp: \nP")
12610 (when (equal regexp "")
12611 (error "Regexp cannot be empty"))
12612 (unless keep-previous
12613 (org-remove-occur-highlights nil nil t))
12614 (push (cons regexp callback) org-occur-parameters)
12617 (goto-char (point-min))
12618 (if (or (not keep-previous) ; do not want to keep
12619 (not org-occur-highlights)) ; no previous matches
12622 (while (re-search-forward regexp nil t)
12623 (when (or (not callback)
12624 (save-match-data (funcall callback)))
12625 (setq cnt (1+ cnt))
12626 (when org-highlight-sparse-tree-matches
12627 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12628 (org-show-context 'occur-tree))))
12629 (when org-remove-highlights-with-change
12630 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12632 (unless org-sparse-tree-open-archived-trees
12633 (org-hide-archived-subtrees (point-min) (point-max)))
12634 (run-hooks 'org-occur-hook)
12635 (if (org-called-interactively-p 'interactive)
12636 (message "%d match(es) for regexp %s" cnt regexp))
12639 (defun org-occur-next-match (&optional n reset)
12640 "Function for `next-error-function' to find sparse tree matches.
12641 N is the number of matches to move, when negative move backwards.
12642 RESET is entirely ignored - this function always goes back to the
12643 starting point when no match is found."
12644 (let* ((limit (if (< n 0) (point-min) (point-max)))
12645 (search-func (if (< n 0)
12646 'previous-single-char-property-change
12647 'next-single-char-property-change))
12652 (while (setq p1 (funcall search-func (point) 'org-type))
12653 (when (equal p1 limit)
12655 (error "No more matches"))
12656 (when (equal (get-char-property p1 'org-type) 'org-occur)
12660 (throw 'exit (point))))
12663 (error "No more matches"))))
12665 (defun org-show-context (&optional key)
12666 "Make sure point and context are visible.
12667 How much context is shown depends upon the variables
12668 `org-show-hierarchy-above', `org-show-following-heading',
12669 `org-show-entry-below' and `org-show-siblings'."
12670 (let ((heading-p (org-at-heading-p t))
12671 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12672 (following-p (org-get-alist-option org-show-following-heading key))
12673 (entry-p (org-get-alist-option org-show-entry-below key))
12674 (siblings-p (org-get-alist-option org-show-siblings key)))
12676 ;; Show heading or entry text
12677 (if (and heading-p (not entry-p))
12678 (org-flag-heading nil) ; only show the heading
12679 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12680 (org-show-hidden-entry))) ; show entire entry
12682 ;; Show next sibling, or heading below text
12684 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12685 (org-flag-heading nil))))
12686 (when siblings-p (org-show-siblings))
12688 ;; show all higher headings, possibly with siblings
12690 (while (and (condition-case nil
12691 (progn (org-up-heading-all 1) t)
12694 (org-flag-heading nil)
12695 (when siblings-p (org-show-siblings))))))))
12697 (defvar org-reveal-start-hook nil
12698 "Hook run before revealing a location.")
12700 (defun org-reveal (&optional siblings)
12701 "Show current entry, hierarchy above it, and the following headline.
12702 This can be used to show a consistent set of context around locations
12703 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12704 not t for the search context.
12706 With optional argument SIBLINGS, on each level of the hierarchy all
12707 siblings are shown. This repairs the tree structure to what it would
12708 look like when opened with hierarchical calls to `org-cycle'.
12709 With double optional argument \\[universal-argument] \\[universal-argument], \
12710 go to the parent and show the
12713 (run-hooks 'org-reveal-start-hook)
12714 (let ((org-show-hierarchy-above t)
12715 (org-show-following-heading t)
12716 (org-show-siblings (if siblings t org-show-siblings)))
12717 (org-show-context nil))
12718 (when (equal siblings '(16))
12720 (when (org-up-heading-safe)
12722 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12724 (defun org-highlight-new-match (beg end)
12725 "Highlight from BEG to END and mark the highlight is an occur headline."
12726 (let ((ov (make-overlay beg end)))
12727 (overlay-put ov 'face 'secondary-selection)
12728 (overlay-put ov 'org-type 'org-occur)
12729 (push ov org-occur-highlights)))
12731 (defun org-remove-occur-highlights (&optional beg end noremove)
12732 "Remove the occur highlights from the buffer.
12733 BEG and END are ignored. If NOREMOVE is nil, remove this function
12734 from the `before-change-functions' in the current buffer."
12736 (unless org-inhibit-highlight-removal
12737 (mapc 'delete-overlay org-occur-highlights)
12738 (setq org-occur-highlights nil)
12739 (setq org-occur-parameters nil)
12741 (remove-hook 'before-change-functions
12742 'org-remove-occur-highlights 'local))))
12746 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12747 "Regular expression matching the priority indicator.")
12749 (defvar org-remove-priority-next-time nil)
12751 (defun org-priority-up ()
12752 "Increase the priority of the current item."
12754 (org-priority 'up))
12756 (defun org-priority-down ()
12757 "Decrease the priority of the current item."
12759 (org-priority 'down))
12761 (defun org-priority (&optional action)
12762 "Change the priority of an item by ARG.
12763 ACTION can be `set', `up', `down', or a character."
12765 (unless org-enable-priority-commands
12766 (error "Priority commands are disabled"))
12767 (setq action (or action 'set))
12768 (let (current new news have remove)
12770 (org-back-to-heading t)
12771 (if (looking-at org-priority-regexp)
12772 (setq current (string-to-char (match-string 2))
12775 ((eq action 'remove)
12776 (setq remove t new ?\ ))
12777 ((or (eq action 'set)
12778 (if (featurep 'xemacs) (characterp action) (integerp action)))
12779 (if (not (eq action 'set))
12781 (message "Priority %c-%c, SPC to remove: "
12782 org-highest-priority org-lowest-priority)
12784 (setq new (read-char-exclusive))))
12785 (if (and (= (upcase org-highest-priority) org-highest-priority)
12786 (= (upcase org-lowest-priority) org-lowest-priority))
12787 (setq new (upcase new)))
12788 (cond ((equal new ?\ ) (setq remove t))
12789 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12790 (error "Priority must be between `%c' and `%c'"
12791 org-highest-priority org-lowest-priority))))
12794 (1- current) ; normal cycling
12795 ;; last priority was empty
12796 (if (eq last-command this-command)
12797 org-lowest-priority ; wrap around empty to lowest
12799 (if org-priority-start-cycle-with-default
12800 org-default-priority
12801 (1- org-default-priority))))))
12804 (1+ current) ; normal cycling
12805 ;; last priority was empty
12806 (if (eq last-command this-command)
12807 org-highest-priority ; wrap around empty to highest
12809 (if org-priority-start-cycle-with-default
12810 org-default-priority
12811 (1+ org-default-priority))))))
12812 (t (error "Invalid action")))
12813 (if (or (< (upcase new) org-highest-priority)
12814 (> (upcase new) org-lowest-priority))
12815 (if (and (memq action '(up down))
12816 (not have) (not (eq last-command this-command)))
12817 ;; `new' is from default priority
12819 "The default can not be set, see `org-default-priority' why")
12820 ;; normal cycling: `new' is beyond highest/lowest priority
12821 ;; and is wrapped around to the empty priority
12823 (setq news (format "%c" new))
12826 (replace-match "" t t nil 1)
12827 (replace-match news t t nil 2))
12829 (error "No priority cookie found in line")
12830 (let ((case-fold-search nil))
12831 (looking-at org-todo-line-regexp))
12834 (goto-char (match-end 2))
12835 (insert " [#" news "]"))
12836 (goto-char (match-beginning 3))
12837 (insert "[#" news "] "))))
12838 (org-preserve-lc (org-set-tags nil 'align)))
12840 (message "Priority removed")
12841 (message "Priority of current item set to %s" news))))
12843 (defun org-get-priority (s)
12844 "Find priority cookie and return priority."
12845 (if (functionp org-get-priority-function)
12846 (funcall org-get-priority-function)
12848 (if (not (string-match org-priority-regexp s))
12849 (* 1000 (- org-lowest-priority org-default-priority))
12850 (* 1000 (- org-lowest-priority
12851 (string-to-char (match-string 2 s))))))))
12855 (defvar org-agenda-archives-mode)
12856 (defvar org-map-continue-from nil
12857 "Position from where mapping should continue.
12858 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12860 (defvar org-scanner-tags nil
12861 "The current tag list while the tags scanner is running.")
12862 (defvar org-trust-scanner-tags nil
12863 "Should `org-get-tags-at' use the tags for the scanner.
12864 This is for internal dynamical scoping only.
12865 When this is non-nil, the function `org-get-tags-at' will return the value
12866 of `org-scanner-tags' instead of building the list by itself. This
12867 can lead to large speed-ups when the tags scanner is used in a file with
12868 many entries, and when the list of tags is retrieved, for example to
12869 obtain a list of properties. Building the tags list for each entry in such
12870 a file becomes an N^2 operation - but with this variable set, it scales
12873 (defun org-scan-tags (action matcher todo-only &optional start-level)
12874 "Scan headline tags with inheritance and produce output ACTION.
12876 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12877 or `agenda' to produce an entry list for an agenda view. It can also be
12878 a Lisp form or a function that should be called at each matched headline, in
12879 this case the return value is a list of all return values from these calls.
12881 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12882 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12883 only lines with a not-done TODO keyword are included in the output.
12884 This should be the same variable that was scoped into
12885 and set by `org-make-tags-matcher' when it constructed MATCHER.
12887 START-LEVEL can be a string with asterisks, reducing the scope to
12888 headlines matching this string."
12889 (require 'org-agenda)
12890 (let* ((re (concat "^"
12892 ;; Get the correct level to match
12893 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12894 org-outline-regexp)
12896 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12898 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12899 (props (list 'face 'default
12900 'done-face 'org-agenda-done
12901 'undone-face 'default
12902 'mouse-face 'highlight
12903 'org-not-done-regexp org-not-done-regexp
12904 'org-todo-regexp org-todo-regexp
12905 'org-complex-heading-regexp org-complex-heading-regexp
12907 (format "mouse-2 or RET jump to org file %s"
12908 (abbreviate-file-name
12909 (or (buffer-file-name (buffer-base-buffer))
12910 (buffer-name (buffer-base-buffer)))))))
12911 (case-fold-search nil)
12912 (org-map-continue-from nil)
12913 lspos tags tags-list
12914 (tags-alist (list (cons 0 org-file-tags)))
12915 (llast 0) rtn rtn1 level category i txt
12916 todo marker entry priority)
12917 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12918 (setq action (list 'lambda nil action)))
12920 (goto-char (point-min))
12921 (when (eq action 'sparse-tree)
12923 (org-remove-occur-highlights))
12924 (while (re-search-forward re nil t)
12925 (setq org-map-continue-from nil)
12927 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12928 tags (if (match-end 4) (org-match-string-no-properties 4)))
12929 (goto-char (setq lspos (match-beginning 0)))
12930 (setq level (org-reduced-level (funcall outline-level))
12931 category (org-get-category))
12932 (setq i llast llast level)
12933 ;; remove tag lists from same and sublevels
12934 (while (>= i level)
12935 (when (setq entry (assoc i tags-alist))
12936 (setq tags-alist (delete entry tags-alist)))
12938 ;; add the next tags
12940 (setq tags (org-split-string tags ":")
12942 (cons (cons level tags) tags-alist)))
12943 ;; compile tags for current headline
12945 (if org-use-tag-inheritance
12946 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12948 org-scanner-tags tags-list)
12949 (when org-use-tag-inheritance
12950 (setcdr (car tags-alist)
12951 (mapcar (lambda (x)
12952 (setq x (copy-sequence x))
12953 (org-add-prop-inherited x))
12954 (cdar tags-alist))))
12955 (when (and tags org-use-tag-inheritance
12956 (or (not (eq t org-use-tag-inheritance))
12957 org-tags-exclude-from-inheritance))
12958 ;; selective inheritance, remove uninherited ones
12959 (setcdr (car tags-alist)
12960 (org-remove-uninherited-tags (cdar tags-alist))))
12963 ;; eval matcher only when the todo condition is OK
12964 (and (or (not todo-only) (member todo org-not-done-keywords))
12965 (let ((case-fold-search t) (org-trust-scanner-tags t))
12968 ;; Call the skipper, but return t if it does not skip,
12969 ;; so that the `and' form continues evaluating
12971 (unless (eq action 'sparse-tree) (org-agenda-skip))
12974 ;; Check if timestamps are deselecting this entry
12975 (or (not todo-only)
12976 (and (member todo org-not-done-keywords)
12977 (or (not org-agenda-tags-todo-honor-ignore-options)
12978 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12980 ;; Extra check for the archive tag
12981 ;; FIXME: Does the skipper already do this????
12983 (not (member org-archive-tag tags-list))
12984 ;; we have an archive tag, should we use this anyway?
12985 (or (not org-agenda-skip-archived-trees)
12986 (and (eq action 'agenda) org-agenda-archives-mode))))
12988 ;; select this headline
12991 ((eq action 'sparse-tree)
12992 (and org-highlight-sparse-tree-matches
12993 (org-get-heading) (match-end 0)
12994 (org-highlight-new-match
12995 (match-beginning 1) (match-end 1)))
12996 (org-show-context 'tags-tree))
12997 ((eq action 'agenda)
12998 (setq txt (org-agenda-format-item
13001 (if (eq org-tags-match-list-sublevels 'indented)
13002 (make-string (1- level) ?.) "")
13006 priority (org-get-priority txt))
13008 (setq marker (org-agenda-new-marker))
13009 (org-add-props txt props
13010 'org-marker marker 'org-hd-marker marker 'org-category category
13012 'priority priority 'type "tagsmatch")
13014 ((functionp action)
13015 (setq org-map-continue-from nil)
13017 (setq rtn1 (funcall action))
13019 (t (error "Invalid action")))
13021 ;; if we are to skip sublevels, jump to end of subtree
13022 (unless org-tags-match-list-sublevels
13023 (org-end-of-subtree t)
13024 (backward-char 1))))
13025 ;; Get the correct position from where to continue
13026 (if org-map-continue-from
13027 (goto-char org-map-continue-from)
13028 (and (= (point) lspos) (end-of-line 1)))))
13029 (when (and (eq action 'sparse-tree)
13030 (not org-sparse-tree-open-archived-trees))
13031 (org-hide-archived-subtrees (point-min) (point-max)))
13034 (defun org-remove-uninherited-tags (tags)
13035 "Remove all tags that are not inherited from the list TAGS."
13037 ((eq org-use-tag-inheritance t)
13038 (if org-tags-exclude-from-inheritance
13039 (org-delete-all org-tags-exclude-from-inheritance tags)
13041 ((not org-use-tag-inheritance) nil)
13042 ((stringp org-use-tag-inheritance)
13045 (if (and (string-match org-use-tag-inheritance x)
13046 (not (member x org-tags-exclude-from-inheritance)))
13049 ((listp org-use-tag-inheritance)
13052 (if (member x org-use-tag-inheritance) x nil))
13055 (defun org-match-sparse-tree (&optional todo-only match)
13056 "Create a sparse tree according to tags string MATCH.
13057 MATCH can contain positive and negative selection of tags, like
13058 \"+WORK+URGENT-WITHBOSS\".
13059 If optional argument TODO-ONLY is non-nil, only select lines that are
13062 (org-prepare-agenda-buffers (list (current-buffer)))
13063 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13065 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13067 (defvar org-cached-props nil)
13068 (defun org-cached-entry-get (pom property)
13069 (if (or (eq t org-use-property-inheritance)
13070 (and (stringp org-use-property-inheritance)
13071 (string-match org-use-property-inheritance property))
13072 (and (listp org-use-property-inheritance)
13073 (member property org-use-property-inheritance)))
13074 ;; Caching is not possible, check it directly
13075 (org-entry-get pom property 'inherit)
13076 ;; Get all properties, so that we can do complicated checks easily
13077 (cdr (assoc property (or org-cached-props
13078 (setq org-cached-props
13079 (org-entry-properties pom)))))))
13081 (defun org-global-tags-completion-table (&optional files)
13082 "Return the list of all tags in all agenda buffer/files.
13083 Optional FILES argument is a list of files to which can be used
13084 instead of the agenda files."
13091 (set-buffer (find-file-noselect file))
13092 (append (org-get-buffer-tags)
13093 (mapcar (lambda (x) (if (stringp (car-safe x))
13094 (list (car-safe x)) nil))
13096 (if (and files (car files))
13098 (org-agenda-files))))))))
13100 (defun org-make-tags-matcher (match)
13101 "Create the TAGS/TODO matcher form for the selection string MATCH.
13103 The variable `todo-only' is scoped dynamically into this function; it will be
13104 set to t if the matcher restricts matching to TODO entries,
13105 otherwise will not be touched.
13107 Returns a cons of the selection string MATCH and the constructed
13108 lisp form implementing the matcher. The matcher is to be
13109 evaluated at an Org entry, with point on the headline,
13110 and returns t if the entry matches the
13111 selection string MATCH. The returned lisp form references
13112 two variables with information about the entry, which must be
13113 bound around the form's evaluation: todo, the TODO keyword at the
13114 entry (or nil of none); and tags-list, the list of all tags at the
13115 entry including inherited ones. Additionally, the category
13116 of the entry (if any) must be specified as the text property
13117 'org-category on the headline.
13119 See also `org-scan-tags'.
13121 (declare (special todo-only))
13122 (unless (boundp 'todo-only)
13123 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13125 ;; Get a new match request, with completion
13126 (let ((org-last-tags-completion-table
13127 (org-global-tags-completion-table)))
13128 (setq match (org-completing-read-no-i
13129 "Match: " 'org-tags-completion-function nil nil nil
13130 'org-tags-history))))
13132 ;; Parse the string and create a lisp form
13133 (let ((match0 match)
13134 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13136 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13137 orterms term orlist re-p str-p level-p level-op time-p
13138 prop-p pn pv po gv rest)
13139 (if (string-match "/+" match)
13140 ;; match contains also a todo-matching request
13142 (setq tagsmatch (substring match 0 (match-beginning 0))
13143 todomatch (substring match (match-end 0)))
13144 (if (string-match "^!" todomatch)
13145 (setq todo-only t todomatch (substring todomatch 1)))
13146 (if (string-match "^\\s-*$" todomatch)
13147 (setq todomatch nil)))
13148 ;; only matching tags
13149 (setq tagsmatch match todomatch nil))
13151 ;; Make the tags matcher
13152 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13153 (setq tagsmatcher t)
13154 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13155 (while (setq term (pop orterms))
13156 (while (and (equal (substring term -1) "\\") orterms)
13157 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13158 (while (string-match re term)
13159 (setq rest (substring term (match-end 0))
13160 minus (and (match-end 1)
13161 (equal (match-string 1 term) "-"))
13162 tag (save-match-data (replace-regexp-in-string
13164 (match-string 2 term)))
13165 re-p (equal (string-to-char tag) ?{)
13166 level-p (match-end 4)
13167 prop-p (match-end 5)
13169 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13171 (setq level-op (org-op-to-function (match-string 3 term)))
13172 `(,level-op level ,(string-to-number
13173 (match-string 4 term))))
13175 (setq pn (match-string 5 term)
13176 po (match-string 6 term)
13177 pv (match-string 7 term)
13178 re-p (equal (string-to-char pv) ?{)
13179 str-p (equal (string-to-char pv) ?\")
13180 time-p (save-match-data
13181 (string-match "^\"[[<].*[]>]\"$" pv))
13182 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13183 (if time-p (setq pv (org-matcher-time pv)))
13184 (setq po (org-op-to-function po (if time-p 'time str-p)))
13186 ((equal pn "CATEGORY")
13187 (setq gv '(get-text-property (point) 'org-category)))
13191 (setq gv `(org-cached-entry-get nil ,pn))))
13194 `(not (string-match ,pv (or ,gv "")))
13195 `(string-match ,pv (or ,gv "")))
13197 `(,po (or ,gv "") ,pv)
13198 `(,po (string-to-number (or ,gv ""))
13199 ,(string-to-number pv) ))))
13200 (t `(member ,tag tags-list)))
13201 mm (if minus (list 'not mm) mm)
13203 (push mm tagsmatcher))
13204 (push (if (> (length tagsmatcher) 1)
13205 (cons 'and tagsmatcher)
13208 (setq tagsmatcher nil))
13209 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13211 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13212 ;; Make the todo matcher
13213 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13214 (setq todomatcher t)
13215 (setq orterms (org-split-string todomatch "|") orlist nil)
13216 (while (setq term (pop orterms))
13217 (while (string-match re term)
13218 (setq minus (and (match-end 1)
13219 (equal (match-string 1 term) "-"))
13220 kwd (match-string 2 term)
13221 re-p (equal (string-to-char kwd) ?{)
13222 term (substring term (match-end 0))
13224 `(string-match ,(substring kwd 1 -1) todo)
13225 (list 'equal 'todo kwd))
13226 mm (if minus (list 'not mm) mm))
13227 (push mm todomatcher))
13228 (push (if (> (length todomatcher) 1)
13229 (cons 'and todomatcher)
13232 (setq todomatcher nil))
13233 (setq todomatcher (if (> (length orlist) 1)
13234 (cons 'or orlist) (car orlist))))
13236 ;; Return the string and lisp forms of the matcher
13237 (setq matcher (if todomatcher
13238 (list 'and tagsmatcher todomatcher)
13241 (setq matcher (list 'and '(member todo org-not-done-keywords)
13243 (cons match0 matcher)))
13245 (defun org-op-to-function (op &optional stringp)
13246 "Turn an operator into the appropriate function."
13249 ((equal op "<" ) '(< string< org-time<))
13250 ((equal op ">" ) '(> org-string> org-time>))
13251 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13252 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13253 ((member op '("=" "==")) '(= string= org-time=))
13254 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13255 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13257 (defun org<> (a b) (not (= a b)))
13258 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13259 (defun org-string>= (a b) (not (string< a b)))
13260 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13261 (defun org-string<> (a b) (not (string= a b)))
13262 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13263 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13264 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13265 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13266 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13267 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13269 "Convert S to a floating point time.
13270 If S is already a number, just return it. If it is a string, parse
13271 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13275 (condition-case nil
13276 (float-time (apply 'encode-time (org-parse-time-string s)))
13280 (defun org-time-today ()
13281 "Time in seconds today at 0:00.
13282 Returns the float number of seconds since the beginning of the
13283 epoch to the beginning of today (00:00)."
13284 (float-time (apply 'encode-time
13285 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13287 (defun org-matcher-time (s)
13288 "Interpret a time comparison value."
13291 ((string= s "<now>") (float-time))
13292 ((string= s "<today>") (org-time-today))
13293 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13294 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13295 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13296 (+ (org-time-today)
13297 (* (string-to-number (match-string 1 s))
13298 (cdr (assoc (match-string 2 s)
13299 '(("d" . 86400.0) ("w" . 604800.0)
13300 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13303 (defun org-match-any-p (re list)
13304 "Does re match any element of list?"
13305 (setq list (mapcar (lambda (x) (string-match re x)) list))
13308 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13309 (defvar org-tags-overlay (make-overlay 1 1))
13310 (org-detach-overlay org-tags-overlay)
13312 (defun org-get-local-tags-at (&optional pos)
13313 "Get a list of tags defined in the current headline."
13314 (org-get-tags-at pos 'local))
13316 (defun org-get-local-tags ()
13317 "Get a list of tags defined in the current headline."
13318 (org-get-tags-at nil 'local))
13320 (defun org-get-tags-at (&optional pos local)
13321 "Get a list of all headline tags applicable at POS.
13322 POS defaults to point. If tags are inherited, the list contains
13323 the targets in the same sequence as the headlines appear, i.e.
13324 the tags of the current headline come last.
13325 When LOCAL is non-nil, only return tags from the current headline,
13326 ignore inherited ones."
13328 (if (and org-trust-scanner-tags
13329 (or (not pos) (equal pos (point)))
13332 (let (tags ltags lastpos parent)
13336 (goto-char (or pos (point)))
13339 (condition-case nil
13341 (org-back-to-heading t)
13342 (while (not (equal lastpos (point)))
13343 (setq lastpos (point))
13345 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13346 (setq ltags (org-split-string
13347 (org-match-string-no-properties 1) ":"))
13349 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13352 (org-remove-uninherited-tags ltags)
13355 (or org-use-tag-inheritance (throw 'done t))
13356 (if local (throw 'done t))
13357 (or (org-up-heading-safe) (error nil))
13362 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13364 (defun org-add-prop-inherited (s)
13365 (add-text-properties 0 (length s) '(inherited t) s)
13368 (defun org-toggle-tag (tag &optional onoff)
13369 "Toggle the tag TAG for the current line.
13370 If ONOFF is `on' or `off', don't toggle but set to this state."
13373 (org-back-to-heading t)
13374 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13377 (setq current (match-string 1))
13378 (replace-match ""))
13380 (setq current (nreverse (org-split-string current ":")))
13384 (or (member tag current) (push tag current)))
13386 (or (not (member tag current)) (setq current (delete tag current))))
13387 (t (if (member tag current)
13388 (setq current (delete tag current))
13390 (push tag current))))
13394 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13395 (org-set-tags nil t))
13396 (delete-horizontal-space))
13397 (run-hooks 'org-after-tags-change-hook))
13400 (defun org-align-tags-here (to-col)
13401 ;; Assumes that this is a headline
13402 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13403 (beginning-of-line 1)
13404 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13405 (< pos (match-beginning 2)))
13407 (setq tags-l (- (match-end 2) (match-beginning 2)))
13408 (goto-char (match-beginning 1))
13410 (delete-region (point) (1+ (match-beginning 2)))
13411 (setq ncol (max (current-column)
13415 (- (abs to-col) tags-l))))
13417 (insert (make-string (- ncol (current-column)) ?\ ))
13418 (setq ncol (current-column))
13419 (when indent-tabs-mode (tabify p (point-at-eol)))
13420 (org-move-to-column (min ncol col) t))
13423 (defun org-set-tags-command (&optional arg just-align)
13424 "Call the set-tags command for the current entry."
13426 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13427 (org-set-tags arg just-align)
13429 (org-back-to-heading t)
13430 (org-set-tags arg just-align))))
13432 (defun org-set-tags-to (data)
13433 "Set the tags of the current entry to DATA, replacing the current tags.
13434 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13435 If DATA is nil or the empty string, any tags will be removed."
13436 (interactive "sTags: ")
13440 ((equal data "") "")
13442 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13445 (concat ":" (mapconcat 'identity data ":") ":"))
13449 (org-back-to-heading t)
13450 (when (looking-at org-complex-heading-regexp)
13453 (goto-char (match-beginning 5))
13455 (delete-region (point) (point-at-eol))
13456 (org-set-tags nil 'align))
13457 (goto-char (point-at-eol))
13459 (org-set-tags nil 'align)))
13460 (beginning-of-line 1)
13461 (if (looking-at ".*?\\([ \t]+\\)$")
13462 (delete-region (match-beginning 1) (match-end 1))))))
13464 (defun org-align-all-tags ()
13465 "Align the tags i all headings."
13468 (or (ignore-errors (org-back-to-heading t))
13469 (outline-next-heading))
13470 (if (org-at-heading-p)
13472 (message "No headings"))))
13474 (defvar org-indent-indentation-per-level)
13475 (defun org-set-tags (&optional arg just-align)
13476 "Set the tags for the current headline.
13477 With prefix ARG, realign all tags in headings in the current buffer."
13479 (let* ((re org-outline-regexp-bol)
13480 (current (unless arg (org-get-tags-string)))
13481 (col (current-column))
13482 (org-setting-tags t)
13483 table current-tags inherited-tags ; computed below when needed
13484 tags p0 c0 c1 rpl di tc level)
13487 (goto-char (point-min))
13488 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13489 (while (re-search-forward re nil t)
13490 (org-set-tags nil t)
13492 (message "All tags realigned to column %d" org-tags-column))
13494 (setq tags current)
13495 ;; Get a new set of tags from the user
13497 (setq table (append org-tag-persistent-alist
13498 (or org-tag-alist (org-get-buffer-tags))
13500 org-complete-tags-always-offer-all-agenda-tags
13501 (org-global-tags-completion-table
13502 (org-agenda-files))))
13503 org-last-tags-completion-table table
13504 current-tags (org-split-string current ":")
13505 inherited-tags (nreverse
13506 (nthcdr (length current-tags)
13507 (nreverse (org-get-tags-at))))
13509 (if (or (eq t org-use-fast-tag-selection)
13510 (and org-use-fast-tag-selection
13511 (delq nil (mapcar 'cdr table))))
13512 (org-fast-tag-selection
13513 current-tags inherited-tags table
13514 (if org-fast-tag-selection-include-todo
13515 org-todo-key-alist))
13516 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13518 (org-icompleting-read "Tags: "
13519 'org-tags-completion-function
13520 nil nil current 'org-tags-history))))))
13521 (while (string-match "[-+&]+" tags)
13522 ;; No boolean logic, just a list
13523 (setq tags (replace-match ":" t t tags))))
13525 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13527 (if org-tags-sort-function
13528 (setq tags (mapconcat 'identity
13529 (sort (org-split-string
13530 tags (org-re "[^[:alnum:]_@#%]+"))
13531 org-tags-sort-function) ":")))
13533 (if (string-match "\\`[\t ]*\\'" tags)
13535 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13536 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13538 ;; Insert new tags at the correct column
13539 (beginning-of-line 1)
13540 (setq level (or (and (looking-at org-outline-regexp)
13541 (- (match-end 0) (point) 1))
13544 ((and (equal current "") (equal tags "")))
13545 ((re-search-forward
13546 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13548 (if (equal tags "")
13550 (goto-char (match-beginning 0))
13551 (setq c0 (current-column)
13552 ;; compute offset for the case of org-indent-mode active
13553 di (if org-indent-mode
13554 (* (1- org-indent-indentation-per-level) (1- level))
13556 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13557 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13558 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13559 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13560 (replace-match rpl t t)
13561 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13563 (t (error "Tags alignment failed")))
13564 (org-move-to-column col)
13566 (run-hooks 'org-after-tags-change-hook)))))
13568 (defun org-change-tag-in-region (beg end tag off)
13569 "Add or remove TAG for each entry in the region.
13570 This works in the agenda, and also in an org-mode buffer."
13572 (list (region-beginning) (region-end)
13573 (let ((org-last-tags-completion-table
13574 (if (derived-mode-p 'org-mode)
13575 (org-get-buffer-tags)
13576 (org-global-tags-completion-table))))
13577 (org-icompleting-read
13578 "Tag: " 'org-tags-completion-function nil nil nil
13579 'org-tags-history))
13581 (message "[s]et or
[r]emove? ")
13582 (equal (read-char-exclusive) ?r))))
13583 (if (fboundp 'deactivate-mark) (deactivate-mark))
13584 (let ((agendap (equal major-mode 'org-agenda-mode))
13585 l1 l2 m buf pos newhead (cnt 0))
13587 (setq l2 (1- (org-current-line)))
13589 (setq l1 (org-current-line))
13590 (loop for l from l1 to l2 do
13592 (setq m (get-text-property (point) 'org-hd-marker))
13593 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13595 (setq buf (if agendap (marker-buffer m) (current-buffer))
13596 pos (if agendap m (point)))
13597 (with-current-buffer buf
13601 (setq cnt (1+ cnt))
13602 (org-toggle-tag tag (if off 'off 'on))
13603 (setq newhead (org-get-heading)))))
13604 (and agendap (org-agenda-change-all-lines newhead m))))
13605 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13607 (defun org-tags-completion-function (string predicate &optional flag)
13608 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13609 (confirm (lambda (x) (stringp (car x)))))
13610 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13611 (setq s1 (match-string 1 string)
13612 s2 (match-string 2 string))
13613 (setq s1 "" s2 string))
13617 (setq rtn (try-completion s2 ctable confirm))
13620 (concat s1 s2 (substring rtn (length s2))
13621 (if (and org-add-colon-after-tag-completion
13622 (assoc rtn ctable))
13627 (all-completions s2 ctable confirm)
13631 (assoc s2 ctable)))
13634 (defun org-fast-tag-insert (kwd tags face &optional end)
13635 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13636 (insert (format "%-12s" (concat kwd ":"))
13637 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13640 (defun org-fast-tag-show-exit (flag)
13643 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13644 (replace-match ""))
13647 (org-move-to-column (- (window-width) 19) t)
13648 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13650 (defun org-set-current-tags-overlay (current prefix)
13651 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13652 (if (featurep 'xemacs)
13653 (org-overlay-display org-tags-overlay (concat prefix s)
13654 'secondary-selection)
13655 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13656 (org-overlay-display org-tags-overlay (concat prefix s)))))
13658 (defvar org-last-tag-selection-key nil)
13659 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13660 "Fast tag selection with single keys.
13661 CURRENT is the current list of tags in the headline, INHERITED is the
13662 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13663 possibly with grouping information. TODO-TABLE is a similar table with
13664 TODO keywords, should these have keys assigned to them.
13665 If the keys are nil, a-z are automatically assigned.
13666 Returns the new tags string, or nil to not change the current settings."
13667 (let* ((fulltable (append table todo-table))
13668 (maxlen (apply 'max (mapcar
13670 (if (stringp (car x)) (string-width (car x)) 0))
13672 (buf (current-buffer))
13673 (expert (eq org-fast-tag-selection-single-key 'expert))
13675 (fwidth (+ maxlen 3 1 3))
13676 (ncol (/ (- (window-width) 4) fwidth))
13679 tg cnt e c char c1 c2 ntable tbl rtn
13680 ov-start ov-end ov-prefix
13681 (exit-after-next org-fast-tag-selection-single-key)
13682 (done-keywords org-done-keywords)
13685 (beginning-of-line 1)
13687 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13688 (setq ov-start (match-beginning 1)
13689 ov-end (match-end 1)
13691 (setq ov-start (1- (point-at-eol))
13692 ov-end (1+ ov-start))
13693 (skip-chars-forward "^\n\r")
13696 (buffer-substring (1- (point)) (point))
13697 (if (> (current-column) org-tags-column)
13699 (make-string (- org-tags-column (current-column)) ?\ ))))))
13700 (move-overlay org-tags-overlay ov-start ov-end)
13701 (save-window-excursion
13703 (set-buffer (get-buffer-create " *Org tags*"))
13704 (delete-other-windows)
13705 (split-window-vertically)
13706 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13708 (org-set-local 'org-done-keywords done-keywords)
13709 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13710 (org-fast-tag-insert "Current" current c-face "\n\n")
13711 (org-fast-tag-show-exit exit-after-next)
13712 (org-set-current-tags-overlay current ov-prefix)
13713 (setq tbl fulltable char ?a cnt 0)
13714 (while (setq e (pop tbl))
13716 ((equal (car e) :startgroup)
13717 (push '() groups) (setq ingroup t)
13718 (when (not (= cnt 0))
13721 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13722 ((equal (car e) :endgroup)
13723 (setq ingroup nil cnt 0)
13724 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13725 ((equal e '(:newline))
13726 (when (not (= cnt 0))
13730 (while (equal (car tbl) '(:newline))
13732 (setq tbl (cdr tbl)))))
13734 (setq tg (copy-sequence (car e)) c2 nil)
13737 ;; automatically assign a character.
13738 (setq c1 (string-to-char
13739 (downcase (substring
13740 tg (if (= (string-to-char tg) ?@) 1 0)))))
13741 (if (or (rassoc c1 ntable) (rassoc c1 table))
13742 (while (or (rassoc char ntable) (rassoc char table))
13743 (setq char (1+ char)))
13745 (setq c (or c2 char)))
13746 (if ingroup (push tg (car groups)))
13747 (setq tg (org-add-props tg nil 'face
13749 ((not (assoc tg table))
13750 (org-get-todo-face tg))
13751 ((member tg current) c-face)
13752 ((member tg inherited) i-face)
13754 (if (and (= cnt 0) (not ingroup)) (insert " "))
13755 (insert "[" c "] " tg (make-string
13756 (- fwidth 4 (length tg)) ?\ ))
13757 (push (cons tg c) ntable)
13758 (when (= (setq cnt (1+ cnt)) ncol)
13760 (if ingroup (insert " "))
13762 (setq ntable (nreverse ntable))
13764 (goto-char (point-min))
13765 (if (not expert) (org-fit-window-to-buffer))
13769 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13770 (if (not groups) "no " "")
13771 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13772 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13773 (setq org-last-tag-selection-key c)
13775 ((= c ?\r) (throw 'exit t))
13777 (setq groups (not groups))
13778 (goto-char (point-min))
13779 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13782 (org-fast-tag-show-exit
13783 (setq exit-after-next (not exit-after-next)))
13785 (delete-other-windows)
13786 (set-window-buffer (split-window-vertically) " *Org tags*")
13787 (org-switch-to-buffer-other-window " *Org tags*")
13788 (org-fit-window-to-buffer)))
13790 (and (= c ?q) (not (rassoc c ntable))))
13791 (org-detach-overlay org-tags-overlay)
13792 (setq quit-flag t))
13795 (if exit-after-next (setq exit-after-next 'now)))
13797 (condition-case nil
13798 (setq tg (org-icompleting-read
13801 (with-current-buffer buf
13802 (org-get-buffer-tags)))))
13803 (quit (setq tg "")))
13804 (when (string-match "\\S-" tg)
13805 (add-to-list 'buffer-tags (list tg))
13806 (if (member tg current)
13807 (setq current (delete tg current))
13808 (push tg current)))
13809 (if exit-after-next (setq exit-after-next 'now)))
13810 ((setq e (rassoc c todo-table) tg (car e))
13811 (with-current-buffer buf
13812 (save-excursion (org-todo tg)))
13813 (if exit-after-next (setq exit-after-next 'now)))
13814 ((setq e (rassoc c ntable) tg (car e))
13815 (if (member tg current)
13816 (setq current (delete tg current))
13817 (loop for g in groups do
13820 (setq current (delete x current)))
13823 (if exit-after-next (setq exit-after-next 'now))))
13825 ;; Create a sorted list
13829 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13830 (if (eq exit-after-next 'now) (throw 'exit t))
13831 (goto-char (point-min))
13832 (beginning-of-line 2)
13833 (delete-region (point) (point-at-eol))
13834 (org-fast-tag-insert "Current" current c-face)
13835 (org-set-current-tags-overlay current ov-prefix)
13836 (while (re-search-forward
13837 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13838 (setq tg (match-string 1))
13839 (add-text-properties
13840 (match-beginning 1) (match-end 1)
13843 ((member tg current) c-face)
13844 ((member tg inherited) i-face)
13845 (t (get-text-property (match-beginning 1) 'face))))))
13846 (goto-char (point-min)))))
13847 (org-detach-overlay org-tags-overlay)
13849 (mapconcat 'identity current ":")
13852 (defun org-get-tags-string ()
13853 "Get the TAGS string in the current headline."
13854 (unless (org-at-heading-p t)
13855 (error "Not on a heading"))
13857 (beginning-of-line 1)
13858 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13859 (org-match-string-no-properties 1)
13862 (defun org-get-tags ()
13863 "Get the list of tags specified in the current headline."
13864 (org-split-string (org-get-tags-string) ":"))
13866 (defun org-get-buffer-tags ()
13867 "Get a table of all tags used in the buffer, for completion."
13870 (goto-char (point-min))
13871 (while (re-search-forward
13872 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13873 (when (equal (char-after (point-at-bol 0)) ?*)
13874 (mapc (lambda (x) (add-to-list 'tags x))
13875 (org-split-string (org-match-string-no-properties 1) ":")))))
13876 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13877 (mapcar 'list tags)))
13879 ;;;; The mapping API
13882 (defun org-map-entries (func &optional match scope &rest skip)
13883 "Call FUNC at each headline selected by MATCH in SCOPE.
13885 FUNC is a function or a lisp form. The function will be called without
13886 arguments, with the cursor positioned at the beginning of the headline.
13887 The return values of all calls to the function will be collected and
13888 returned as a list.
13890 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13891 does not need to preserve point. After evaluation, the cursor will be
13892 moved to the end of the line (presumably of the headline of the
13893 processed entry) and search continues from there. Under some
13894 circumstances, this may not produce the wanted results. For example,
13895 if you have removed (e.g. archived) the current (sub)tree it could
13896 mean that the next entry will be skipped entirely. In such cases, you
13897 can specify the position from where search should continue by making
13898 FUNC set the variable `org-map-continue-from' to the desired buffer
13901 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13902 Only headlines that are matched by this query will be considered during
13903 the iteration. When MATCH is nil or t, all headlines will be
13904 visited by the iteration.
13906 SCOPE determines the scope of this command. It can be any of:
13908 nil The current buffer, respecting the restriction if any
13909 tree The subtree started with the entry at point
13910 region The entries within the active region, if any
13912 The entries within the active region, but only those at
13913 the same level than the first one.
13914 file The current buffer, without restriction
13916 The current buffer, and any archives associated with it
13917 agenda All agenda files
13918 agenda-with-archives
13919 All agenda files with any archive files associated with them
13921 If this is a list, all files in the list will be scanned
13923 The remaining args are treated as settings for the skipping facilities of
13924 the scanner. The following items can be given here:
13926 archive skip trees with the archive tag.
13927 comment skip trees with the COMMENT keyword
13928 function or Emacs Lisp form:
13929 will be used as value for `org-agenda-skip-function', so whenever
13930 the function returns t, FUNC will not be called for that
13931 entry and search will continue from the point where the
13932 function leaves it.
13934 If your function needs to retrieve the tags including inherited tags
13935 at the *current* entry, you can use the value of the variable
13936 `org-scanner-tags' which will be much faster than getting the value
13937 with `org-get-tags-at'. If your function gets properties with
13938 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13939 to t around the call to `org-entry-properties' to get the same speedup.
13940 Note that if your function moves around to retrieve tags and properties at
13941 a *different* entry, you cannot use these techniques."
13942 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13943 (not (org-region-active-p)))
13944 (let* ((org-agenda-archives-mode nil) ; just to make sure
13945 (org-agenda-skip-archived-trees (memq 'archive skip))
13946 (org-agenda-skip-comment-trees (memq 'comment skip))
13947 (org-agenda-skip-function
13948 (car (org-delete-all '(comment archive) skip)))
13949 (org-tags-match-list-sublevels t)
13950 (start-level (eq scope 'region-start-level))
13952 org-todo-keywords-for-agenda
13953 org-done-keywords-for-agenda
13954 org-todo-keyword-alist-for-agenda
13955 org-drawers-for-agenda
13956 org-tag-alist-for-agenda
13960 ((eq match t) (setq matcher t))
13961 ((eq match nil) (setq matcher t))
13962 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13966 (cond ((eq scope 'tree)
13967 (org-back-to-heading t)
13968 (org-narrow-to-subtree)
13970 ((and (or (eq scope 'region) (eq scope 'region-start-level))
13971 (org-region-active-p))
13972 ;; If needed, set start-level to a string like "2"
13975 (goto-char (region-beginning))
13976 (unless (org-at-heading-p) (outline-next-heading))
13977 (setq start-level (org-current-level))))
13978 (narrow-to-region (region-beginning)
13980 (goto-char (region-end))
13981 (unless (and (bolp) (org-at-heading-p))
13982 (outline-next-heading))
13988 (org-prepare-agenda-buffers
13989 (list (buffer-file-name (current-buffer))))
13990 (setq res (org-scan-tags func matcher todo-only start-level)))
13991 ;; Get the right scope
13993 ((and scope (listp scope) (symbolp (car scope)))
13994 (setq scope (eval scope)))
13995 ((eq scope 'agenda)
13996 (setq scope (org-agenda-files t)))
13997 ((eq scope 'agenda-with-archives)
13998 (setq scope (org-agenda-files t))
13999 (setq scope (org-add-archive-files scope)))
14001 (setq scope (list (buffer-file-name))))
14002 ((eq scope 'file-with-archives)
14003 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14004 (org-prepare-agenda-buffers scope)
14005 (while (setq file (pop scope))
14006 (with-current-buffer (org-find-base-buffer-visiting file)
14010 (goto-char (point-min))
14011 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14016 ;;; Setting and retrieving properties
14018 (defconst org-special-properties
14019 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14020 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
14021 "The special properties valid in Org-mode.
14023 These are properties that are not defined in the property drawer,
14024 but in some other way.")
14026 (defconst org-default-properties
14027 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14028 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14029 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14030 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14031 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14032 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14033 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14034 "Some properties that are used by Org-mode for various purposes.
14035 Being in this list makes sure that they are offered for completion.")
14037 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14038 "Regular expression matching the first line of a property drawer.")
14040 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14041 "Regular expression matching the last line of a property drawer.")
14043 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14044 "Regular expression matching the first line of a property drawer.")
14046 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14047 "Regular expression matching the first line of a property drawer.")
14049 (defconst org-property-drawer-re
14050 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14051 org-property-end-re "\\)\n?")
14052 "Matches an entire property drawer.")
14054 (defconst org-clock-drawer-re
14055 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14056 org-property-end-re "\\)\n?")
14057 "Matches an entire clock drawer.")
14059 (defsubst org-re-property (property)
14060 "Return a regexp matching PROPERTY.
14061 Match group 1 will be set to the value "
14062 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14064 (defun org-property-action ()
14065 "Do an action on properties."
14068 (org-at-property-p)
14069 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14070 (setq c (read-char-exclusive))
14073 (call-interactively 'org-set-property))
14075 (call-interactively 'org-delete-property))
14077 (call-interactively 'org-delete-property-globally))
14079 (call-interactively 'org-compute-property-at-point))
14080 (t (error "No such property action %c" c)))))
14082 (defun org-set-effort (&optional value)
14083 "Set the effort property of the current entry.
14084 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
14087 (if (equal value 0) (setq value 10))
14088 (let* ((completion-ignore-case t)
14089 (prop org-effort-property)
14090 (cur (org-entry-get nil prop))
14091 (allowed (org-property-get-allowed-values nil prop 'table))
14092 (existing (mapcar 'list (org-property-values prop)))
14095 ((stringp value) value)
14096 ((and allowed (integerp value))
14097 (or (car (nth (1- value) allowed))
14098 (car (org-last allowed))))
14100 (message "Select 1-9,0, [RET%s]: %s"
14101 (if cur (concat "=" cur) "")
14102 (mapconcat 'car allowed " "))
14103 (setq rpl (read-char-exclusive))
14104 (if (equal rpl ?\r)
14106 (setq rpl (- rpl ?0))
14107 (if (equal rpl 0) (setq rpl 10))
14108 (if (and (> rpl 0) (<= rpl (length allowed)))
14109 (car (nth (1- rpl) allowed))
14110 (org-completing-read "Effort: " allowed nil))))
14112 (let (org-completion-use-ido org-completion-use-iswitchb)
14113 (org-completing-read
14114 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14115 (concat "[" cur "]") "")
14117 existing nil nil "" nil cur))))))
14118 (unless (equal (org-entry-get nil prop) val)
14119 (org-entry-put nil prop val))
14120 (message "%s is now %s" prop val)))
14122 (defun org-at-property-p ()
14123 "Is cursor inside a property drawer?"
14125 (beginning-of-line 1)
14126 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14127 (save-match-data ;; Used by calling procedures
14129 (range (unless (org-before-first-heading-p)
14130 (org-get-property-block))))
14131 (and range (<= (car range) p) (< p (cdr range))))))))
14133 (defun org-get-property-block (&optional beg end force)
14134 "Return the (beg . end) range of the body of the property drawer.
14135 BEG and END can be beginning and end of subtree, if not given
14136 they will be found.
14137 If the drawer does not exist and FORCE is non-nil, create the drawer."
14140 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14141 (end (or end (progn (outline-next-heading) (point)))))
14143 (if (re-search-forward org-property-start-re end t)
14144 (setq beg (1+ (match-end 0)))
14147 (org-insert-property-drawer)
14148 (setq end (progn (outline-next-heading) (point))))
14151 (if (re-search-forward org-property-start-re end t)
14152 (setq beg (1+ (match-end 0)))))
14153 (if (re-search-forward org-property-end-re end t)
14154 (setq end (match-beginning 0))
14155 (or force (throw 'exit nil))
14158 (org-indent-line-function)
14159 (insert ":END:\n"))
14162 (defun org-entry-properties (&optional pom which specific)
14163 "Get all properties of the entry at point-or-marker POM.
14164 This includes the TODO keyword, the tags, time strings for deadline,
14165 scheduled, and clocking, and any additional properties defined in the
14166 entry. The return value is an alist, keys may occur multiple times
14167 if the property key was used several times.
14168 POM may also be nil, in which case the current entry is used.
14169 If WHICH is nil or `all', get all properties. If WHICH is
14170 `special' or `standard', only get that subclass. If WHICH
14171 is a string only get exactly this property. SPECIFIC can be a string, the
14172 specific property we are interested in. Specifying it can speed
14173 things up because then unnecessary parsing is avoided."
14174 (setq which (or which 'all))
14175 (org-with-point-at pom
14176 (let ((clockstr (substring org-clock-string 0 -1))
14177 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14178 (case-fold-search nil)
14179 beg end range props sum-props key key1 value string clocksum)
14181 (when (condition-case nil
14182 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14185 (setq sum-props (get-text-property (point) 'org-summaries))
14186 (setq clocksum (get-text-property (point) :org-clock-minutes))
14187 (outline-next-heading)
14189 (when (memq which '(all special))
14190 ;; Get the special properties, like TODO and tags
14192 (when (and (or (not specific) (string= specific "TODO"))
14193 (looking-at org-todo-line-regexp) (match-end 2))
14194 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14195 (when (and (or (not specific) (string= specific "PRIORITY"))
14196 (looking-at org-priority-regexp))
14197 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14198 (when (or (not specific) (string= specific "FILE"))
14199 (push (cons "FILE" buffer-file-name) props))
14200 (when (and (or (not specific) (string= specific "TAGS"))
14201 (setq value (org-get-tags-string))
14202 (string-match "\\S-" value))
14203 (push (cons "TAGS" value) props))
14204 (when (and (or (not specific) (string= specific "ALLTAGS"))
14205 (setq value (org-get-tags-at)))
14206 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14209 (when (or (not specific) (string= specific "BLOCKED"))
14210 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14211 (when (or (not specific)
14213 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14214 "TIMESTAMP" "TIMESTAMP_IA")))
14216 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14217 (setq key (if (match-end 1)
14218 (substring (org-match-string-no-properties 1)
14220 string (if (equal key clockstr)
14224 (match-beginning 3) (goto-char
14226 (substring (org-match-string-no-properties 3)
14228 ;; Get the correct property name from the key. This is
14229 ;; necessary if the user has configured time keywords.
14230 (setq key1 (concat key ":"))
14234 (if (= (char-after (match-beginning 3)) ?\[)
14235 "TIMESTAMP_IA" "TIMESTAMP")))
14236 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14237 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14238 ((equal key1 org-closed-string) (setq key "CLOSED"))
14239 ((equal key1 org-clock-string) (setq key "CLOCK")))
14240 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14242 (push (cons key string) props)
14243 ;; no need to search further if match is found
14245 (when (or (equal key "CLOCK") (not (assoc key props)))
14246 (push (cons key string) props))))))
14249 (when (memq which '(all standard))
14250 ;; Get the standard properties, like :PROP: ...
14251 (setq range (org-get-property-block beg end))
14253 (goto-char (car range))
14254 (while (re-search-forward
14255 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14257 (setq key (org-match-string-no-properties 1)
14258 value (org-trim (or (org-match-string-no-properties 2) "")))
14259 (unless (member key excluded)
14260 (push (cons key (or value "")) props)))))
14262 (push (cons "CLOCKSUM"
14263 (org-columns-number-to-string (/ (float clocksum) 60.)
14266 (unless (assoc "CATEGORY" props)
14267 (push (cons "CATEGORY" (org-get-category)) props))
14268 (append sum-props (nreverse props)))))))
14270 (defun org-entry-get (pom property &optional inherit literal-nil)
14271 "Get value of PROPERTY for entry at point-or-marker POM.
14272 If INHERIT is non-nil and the entry does not have the property,
14273 then also check higher levels of the hierarchy.
14274 If INHERIT is the symbol `selective', use inheritance only if the setting
14275 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14276 If the property is present but empty, the return value is the empty string.
14277 If the property is not present at all, nil is returned.
14279 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14280 do not interpret it as the list atom nil. This is used for inheritance
14281 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14282 (org-with-point-at pom
14283 (if (and inherit (if (eq inherit 'selective)
14284 (org-property-inherit-p property)
14286 (org-entry-get-with-inheritance property literal-nil)
14287 (if (member property org-special-properties)
14288 ;; We need a special property. Use `org-entry-properties' to
14289 ;; retrieve it, but specify the wanted property
14290 (cdr (assoc property (org-entry-properties nil 'special property)))
14291 (let ((range (unless (org-before-first-heading-p)
14292 (org-get-property-block)))
14293 (props (list (or (assoc property org-file-properties)
14294 (assoc property org-global-properties)
14295 (assoc property org-global-properties-fixed))))
14298 (when (re-search-forward
14299 (org-re-property key) (cdr range) t)
14301 (org-update-property-plist
14304 (org-match-string-no-properties 1) "")
14306 (when (and range (goto-char (car range)))
14308 (goto-char (car range))
14309 (while (ap (concat property "+")))
14310 (setq val (cdr (assoc property props)))
14311 (when val (if literal-nil val (org-not-nil val))))))))))
14313 (defun org-property-or-variable-value (var &optional inherit)
14314 "Check if there is a property fixing the value of VAR.
14315 If yes, return this value. If not, return the current value of the variable."
14316 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14317 (if (and prop (stringp prop) (string-match "\\S-" prop))
14319 (symbol-value var))))
14321 (defun org-entry-delete (pom property)
14322 "Delete the property PROPERTY from entry at point-or-marker POM."
14323 (org-with-point-at pom
14324 (if (member property org-special-properties)
14325 nil ; cannot delete these properties.
14326 (let ((range (org-get-property-block)))
14328 (goto-char (car range))
14330 (org-re-property property)
14333 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14337 ;; Multi-values properties are properties that contain multiple values
14338 ;; These values are assumed to be single words, separated by whitespace.
14339 (defun org-entry-add-to-multivalued-property (pom property value)
14340 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14341 (let* ((old (org-entry-get pom property))
14342 (values (and old (org-split-string old "[ \t]"))))
14343 (setq value (org-entry-protect-space value))
14344 (unless (member value values)
14345 (setq values (cons value values))
14346 (org-entry-put pom property
14347 (mapconcat 'identity values " ")))))
14349 (defun org-entry-remove-from-multivalued-property (pom property value)
14350 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14351 (let* ((old (org-entry-get pom property))
14352 (values (and old (org-split-string old "[ \t]"))))
14353 (setq value (org-entry-protect-space value))
14354 (when (member value values)
14355 (setq values (delete value values))
14356 (org-entry-put pom property
14357 (mapconcat 'identity values " ")))))
14359 (defun org-entry-member-in-multivalued-property (pom property value)
14360 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14361 (let* ((old (org-entry-get pom property))
14362 (values (and old (org-split-string old "[ \t]"))))
14363 (setq value (org-entry-protect-space value))
14364 (member value values)))
14366 (defun org-entry-get-multivalued-property (pom property)
14367 "Return a list of values in a multivalued property."
14368 (let* ((value (org-entry-get pom property))
14369 (values (and value (org-split-string value "[ \t]"))))
14370 (mapcar 'org-entry-restore-space values)))
14372 (defun org-entry-put-multivalued-property (pom property &rest values)
14373 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14374 VALUES should be a list of strings. Spaces will be protected."
14375 (org-entry-put pom property
14376 (mapconcat 'org-entry-protect-space values " "))
14377 (let* ((value (org-entry-get pom property))
14378 (values (and value (org-split-string value "[ \t]"))))
14379 (mapcar 'org-entry-restore-space values)))
14381 (defun org-entry-protect-space (s)
14382 "Protect spaces and newline in string S."
14383 (while (string-match " " s)
14384 (setq s (replace-match "%20" t t s)))
14385 (while (string-match "\n" s)
14386 (setq s (replace-match "%0A" t t s)))
14389 (defun org-entry-restore-space (s)
14390 "Restore spaces and newline in string S."
14391 (while (string-match "%20" s)
14392 (setq s (replace-match " " t t s)))
14393 (while (string-match "%0A" s)
14394 (setq s (replace-match "\n" t t s)))
14397 (defvar org-entry-property-inherited-from (make-marker)
14398 "Marker pointing to the entry from where a property was inherited.
14399 Each call to `org-entry-get-with-inheritance' will set this marker to the
14400 location of the entry where the inheritance search matched. If there was
14401 no match, the marker will point nowhere.
14402 Note that also `org-entry-get' calls this function, if the INHERIT flag
14405 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14406 "Get entry property, and search higher levels if not present.
14407 The search will stop at the first ancestor which has the property defined.
14408 If the value found is \"nil\", return nil to show that the property
14409 should be considered as undefined (this is the meaning of nil here).
14410 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14411 (move-marker org-entry-property-inherited-from nil)
14413 (unless (org-before-first-heading-p)
14419 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14420 (org-back-to-heading t)
14421 (move-marker org-entry-property-inherited-from (point))
14423 (or (org-up-heading-safe) (throw 'ex nil)))))))
14425 (cdr (assoc property org-file-properties))
14426 (cdr (assoc property org-global-properties))
14427 (cdr (assoc property org-global-properties-fixed))))
14428 (if literal-nil tmp (org-not-nil tmp))))
14430 (defvar org-property-changed-functions nil
14431 "Hook called when the value of a property has changed.
14432 Each hook function should accept two arguments, the name of the property
14433 and the new value.")
14435 (defun org-entry-put (pom property value)
14436 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14437 (org-with-point-at pom
14438 (org-back-to-heading t)
14439 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14442 ((equal property "TODO")
14443 (when (and (stringp value) (string-match "\\S-" value)
14444 (not (member value org-todo-keywords-1)))
14445 (error "\"%s\" is not a valid TODO state" value))
14446 (if (or (not value)
14447 (not (string-match "\\S-" value)))
14448 (setq value 'none))
14450 (org-set-tags nil 'align))
14451 ((equal property "PRIORITY")
14452 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14453 (string-to-char value) ?\ ))
14454 (org-set-tags nil 'align))
14455 ((equal property "SCHEDULED")
14456 (if (re-search-forward org-scheduled-time-regexp end t)
14458 ((eq value 'earlier) (org-timestamp-change -1 'day))
14459 ((eq value 'later) (org-timestamp-change 1 'day))
14460 (t (call-interactively 'org-schedule)))
14461 (call-interactively 'org-schedule)))
14462 ((equal property "DEADLINE")
14463 (if (re-search-forward org-deadline-time-regexp end t)
14465 ((eq value 'earlier) (org-timestamp-change -1 'day))
14466 ((eq value 'later) (org-timestamp-change 1 'day))
14467 (t (call-interactively 'org-deadline)))
14468 (call-interactively 'org-deadline)))
14469 ((member property org-special-properties)
14470 (error "The %s property can not yet be set with `org-entry-put'"
14472 (t ; a non-special property
14473 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14474 (setq range (org-get-property-block beg end 'force))
14475 (goto-char (car range))
14476 (if (re-search-forward
14477 (org-re-property property) (cdr range) t)
14479 (delete-region (match-beginning 0) (match-end 0))
14480 (goto-char (match-beginning 0)))
14481 (goto-char (cdr range))
14484 (org-indent-line-function))
14485 (insert ":" property ":")
14486 (and value (insert " " value))
14487 (org-indent-line-function)))))
14488 (run-hook-with-args 'org-property-changed-functions property value)))
14490 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14491 "Get all property keys in the current buffer.
14492 With INCLUDE-SPECIALS, also list the special properties that reflect things
14493 like tags and TODO state.
14494 With INCLUDE-DEFAULTS, also include properties that has special meaning
14495 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14497 With INCLUDE-COLUMNS, also include property names given in COLUMN
14498 formats in the current buffer."
14499 (let (rtn range cfmt s p)
14503 (goto-char (point-min))
14504 (while (re-search-forward org-property-start-re nil t)
14505 (setq range (org-get-property-block))
14506 (goto-char (car range))
14507 (while (re-search-forward
14508 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14510 (add-to-list 'rtn (org-match-string-no-properties 1)))
14511 (outline-next-heading))))
14513 (when include-specials
14514 (setq rtn (append org-special-properties rtn)))
14516 (when include-defaults
14517 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14518 (add-to-list 'rtn org-effort-property))
14520 (when include-columns
14524 (goto-char (point-min))
14525 (while (re-search-forward
14526 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14528 (setq cfmt (match-string 2) s 0)
14529 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14531 (setq s (match-end 0)
14532 p (match-string 1 cfmt))
14533 (unless (or (equal p "ITEM")
14534 (member p org-special-properties))
14535 (add-to-list 'rtn (match-string 1 cfmt))))))))
14537 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14539 (defun org-property-values (key)
14540 "Return a list of all values of property KEY in the current buffer."
14544 (goto-char (point-min))
14545 (let ((re (org-re-property key))
14547 (while (re-search-forward re nil t)
14548 (add-to-list 'values (org-trim (match-string 1))))
14549 (delete "" values)))))
14551 (defun org-insert-property-drawer ()
14552 "Insert a property drawer into the current entry."
14553 (org-back-to-heading t)
14554 (looking-at org-outline-regexp)
14555 (let ((indent (if org-adapt-indentation
14556 (- (match-end 0) (match-beginning 0))
14559 (re (concat "^[ \t]*" org-keyword-time-regexp))
14561 (outline-next-heading)
14564 (while (re-search-forward re end t))
14565 (setq hiddenp (outline-invisible-p))
14567 (and (equal (char-after) ?\n) (forward-char 1))
14568 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14569 (if (member (match-string 1) '("CLOCK:" ":END:"))
14570 ;; just skip this line
14571 (beginning-of-line 2)
14572 ;; Drawer start, find the end
14573 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14574 (beginning-of-line 1)))
14575 (org-skip-over-state-notes)
14576 (skip-chars-backward " \t\n\r")
14577 (if (eq (char-before) ?*) (forward-char 1))
14578 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14579 (beginning-of-line 0)
14580 (org-indent-to-column indent)
14581 (beginning-of-line 2)
14582 (org-indent-to-column indent)
14583 (beginning-of-line 0)
14586 (org-back-to-heading t)
14588 (org-flag-drawer t))))
14590 (defun org-insert-drawer (&optional arg drawer)
14591 "Insert a drawer at point.
14593 Optional argument DRAWER, when non-nil, is a string representing
14594 drawer's name. Otherwise, the user is prompted for a name.
14596 If a region is active, insert the drawer around that region
14599 Point is left between drawer's boundaries."
14601 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14603 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14604 ;; internally by Org. They are meant to be inserted
14606 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14607 ;; Remove system drawers from list. Note: For some reason,
14608 ;; `org-completing-read' ignores the predicate while
14609 ;; `completing-read' handles it fine.
14610 (drawer (if arg "PROPERTIES"
14613 "Drawer: " org-drawers
14614 (lambda (d) (not (member d system-drawers))))))))
14616 ;; With C-u, fall back on `org-insert-property-drawer'
14617 (arg (org-insert-property-drawer))
14618 ;; With an active region, insert a drawer at point.
14619 ((not (org-region-active-p))
14621 (unless (bolp) (insert "\n"))
14622 (insert (format ":%s:\n\n:END:\n" drawer))
14623 (forward-line -2)))
14624 ;; Otherwise, insert the drawer at point
14626 (let ((rbeg (region-beginning))
14627 (rend (copy-marker (region-end))))
14631 (beginning-of-line)
14632 (when (save-excursion
14633 (re-search-forward org-outline-regexp-bol rend t))
14634 (error "Drawers cannot contain headlines"))
14635 ;; Position point at the beginning of the first
14636 ;; non-blank line in region. Insert drawer's opening
14637 ;; there, then indent it.
14638 (org-skip-whitespace)
14639 (beginning-of-line)
14640 (insert ":" drawer ":\n")
14642 (indent-for-tab-command)
14643 ;; Move point to the beginning of the first blank line
14644 ;; after the last non-blank line in region. Insert
14645 ;; drawer's closing, then indent it.
14647 (skip-chars-backward " \r\t\n")
14649 (indent-for-tab-command)
14650 (unless (eolp) (insert "\n")))
14651 ;; Clear marker, whatever the outcome of insertion is.
14652 (set-marker rend nil)))))))
14654 (defvar org-property-set-functions-alist nil
14655 "Property set function alist.
14656 Each entry should have the following format:
14658 (PROPERTY . READ-FUNCTION)
14660 The read function will be called with the same argument as
14661 `org-completing-read'.")
14663 (defun org-set-property-function (property)
14664 "Get the function that should be used to set PROPERTY.
14665 This is computed according to `org-property-set-functions-alist'."
14666 (or (cdr (assoc property org-property-set-functions-alist))
14667 'org-completing-read))
14669 (defun org-read-property-value (property)
14670 "Read PROPERTY value from user."
14671 (let* ((completion-ignore-case t)
14672 (allowed (org-property-get-allowed-values nil property 'table))
14673 (cur (org-entry-get nil property))
14674 (prompt (concat property " value"
14675 (if (and cur (string-match "\\S-" cur))
14676 (concat " [" cur "]") "") ": "))
14677 (set-function (org-set-property-function property))
14679 (funcall set-function prompt allowed nil
14680 (not (get-text-property 0 'org-unrestricted
14682 (let (org-completion-use-ido org-completion-use-iswitchb)
14683 (funcall set-function prompt
14684 (mapcar 'list (org-property-values property))
14685 nil nil "" nil cur)))))
14690 (defvar org-last-set-property nil)
14691 (defun org-read-property-name ()
14692 "Read a property name."
14693 (let* ((completion-ignore-case t)
14694 (keys (org-buffer-property-keys nil t t))
14695 (default-prop (or (save-excursion
14697 (beginning-of-line)
14698 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14699 (null (string= (match-string 1) "END"))
14700 (match-string 1))))
14701 org-last-set-property))
14702 (property (org-icompleting-read
14704 (if default-prop (concat " [" default-prop "]") "")
14706 (mapcar 'list keys)
14710 (if (member property keys)
14712 (or (cdr (assoc (downcase property)
14713 (mapcar (lambda (x) (cons (downcase x) x))
14717 (defun org-set-property (property value)
14718 "In the current entry, set PROPERTY to VALUE.
14719 When called interactively, this will prompt for a property name, offering
14720 completion on existing and default properties. And then it will prompt
14721 for a value, offering completion either on allowed values (via an inherited
14722 xxx_ALL property) or on existing values in other instances of this property
14723 in the current file."
14724 (interactive (list nil nil))
14725 (let* ((property (or property (org-read-property-name)))
14726 (value (or value (org-read-property-value property)))
14727 (fn (cdr (assoc property org-properties-postprocess-alist))))
14728 (setq org-last-set-property property)
14729 ;; Possibly postprocess the inserted value:
14730 (when fn (setq value (funcall fn value)))
14731 (unless (equal (org-entry-get nil property) value)
14732 (org-entry-put nil property value))))
14734 (defun org-delete-property (property)
14735 "In the current entry, delete PROPERTY."
14737 (let* ((completion-ignore-case t)
14738 (prop (org-icompleting-read "Property: "
14739 (org-entry-properties nil 'standard))))
14741 (message "Property %s %s" property
14742 (if (org-entry-delete nil property)
14744 "was not present in the entry")))
14746 (defun org-delete-property-globally (property)
14747 "Remove PROPERTY globally, from all entries."
14749 (let* ((completion-ignore-case t)
14750 (prop (org-icompleting-read
14751 "Globally remove property: "
14752 (mapcar 'list (org-buffer-property-keys)))))
14757 (goto-char (point-min))
14759 (while (re-search-forward
14760 (org-re-property property)
14762 (setq cnt (1+ cnt))
14763 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14764 (message "Property \"%s\" removed from %d entries" property cnt)))))
14766 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14768 (defun org-compute-property-at-point ()
14769 "Compute the property at point.
14770 This looks for an enclosing column format, extracts the operator and
14771 then applies it to the property in the column format's scope."
14773 (unless (org-at-property-p)
14774 (error "Not at a property"))
14775 (let ((prop (org-match-string-no-properties 2)))
14776 (org-columns-get-format-and-top-level)
14777 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14778 (error "No operator defined for property %s" prop))
14779 (org-columns-compute prop)))
14781 (defvar org-property-allowed-value-functions nil
14782 "Hook for functions supplying allowed values for a specific property.
14783 The functions must take a single argument, the name of the property, and
14784 return a flat list of allowed values. If \":ETC\" is one of
14785 the values, this means that these values are intended as defaults for
14786 completion, but that other values should be allowed too.
14787 The functions must return nil if they are not responsible for this
14790 (defun org-property-get-allowed-values (pom property &optional table)
14791 "Get allowed values for the property PROPERTY.
14792 When TABLE is non-nil, return an alist that can directly be used for
14796 ((equal property "TODO")
14797 (setq vals (org-with-point-at pom
14798 (append org-todo-keywords-1 '("")))))
14799 ((equal property "PRIORITY")
14800 (let ((n org-lowest-priority))
14801 (while (>= n org-highest-priority)
14802 (push (char-to-string n) vals)
14804 ((member property org-special-properties))
14805 ((setq vals (run-hook-with-args-until-success
14806 'org-property-allowed-value-functions property)))
14808 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14809 (when (and vals (string-match "\\S-" vals))
14810 (setq vals (car (read-from-string (concat "(" vals ")"))))
14811 (setq vals (mapcar (lambda (x)
14812 (cond ((stringp x) x)
14813 ((numberp x) (number-to-string x))
14814 ((symbolp x) (symbol-name x))
14817 (when (member ":ETC" vals)
14818 (setq vals (remove ":ETC" vals))
14819 (org-add-props (car vals) '(org-unrestricted t)))
14820 (if table (mapcar 'list vals) vals)))
14822 (defun org-property-previous-allowed-value (&optional previous)
14823 "Switch to the next allowed value for this property."
14825 (org-property-next-allowed-value t))
14827 (defun org-property-next-allowed-value (&optional previous)
14828 "Switch to the next allowed value for this property."
14830 (unless (org-at-property-p)
14831 (error "Not at a property"))
14832 (let* ((key (match-string 2))
14833 (value (match-string 3))
14834 (allowed (or (org-property-get-allowed-values (point) key)
14835 (and (member value '("[ ]" "[-]" "[X]"))
14839 (error "Allowed values for this property have not been defined"))
14840 (if previous (setq allowed (reverse allowed)))
14841 (if (member value allowed)
14842 (setq nval (car (cdr (member value allowed)))))
14843 (setq nval (or nval (car allowed)))
14844 (if (equal nval value)
14845 (error "Only one allowed value for this property"))
14846 (org-at-property-p)
14847 (replace-match (concat " :" key ": " nval) t t)
14848 (org-indent-line-function)
14849 (beginning-of-line 1)
14850 (skip-chars-forward " \t")
14851 (run-hook-with-args 'org-property-changed-functions key nval)))
14853 (defun org-find-olp (path &optional this-buffer)
14854 "Return a marker pointing to the entry at outline path OLP.
14855 If anything goes wrong, throw an error.
14856 You can wrap this call to catch the error like this:
14858 (condition-case msg
14859 (org-mobile-locate-entry (match-string 4))
14860 (error (nth 1 msg)))
14862 The return value will then be either a string with the error message,
14863 or a marker if everything is OK.
14865 If THIS-BUFFER is set, the outline path does not contain a file,
14867 (let* ((file (if this-buffer buffer-file-name (pop path)))
14868 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14872 limit re end found pos heading cnt flevel)
14873 (unless buffer (error "File not found :%s" file))
14874 (with-current-buffer buffer
14878 (setq limit (point-max))
14879 (goto-char (point-min))
14880 (while (setq heading (pop path))
14881 (setq re (format org-complex-heading-regexp-format
14882 (regexp-quote heading)))
14883 (setq cnt 0 pos (point))
14884 (while (re-search-forward re end t)
14885 (setq level (- (match-end 1) (match-beginning 1)))
14886 (if (and (>= level lmin) (<= level lmax))
14887 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14888 (when (= cnt 0) (error "Heading not found on level %d: %s"
14890 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14893 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14894 (setq end (save-excursion (org-end-of-subtree t t))))
14895 (when (org-at-heading-p)
14896 (move-marker (make-marker) (point))))))))
14898 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14899 "Find node HEADING in BUFFER.
14900 Return a marker to the heading if it was found, or nil if not.
14901 If POS-ONLY is set, return just the position instead of a marker.
14903 The heading text must match exact, but it may have a TODO keyword,
14904 a priority cookie and tags in the standard locations."
14905 (with-current-buffer (or buffer (current-buffer))
14909 (goto-char (point-min))
14910 (let (case-fold-search)
14911 (if (re-search-forward
14912 (format org-complex-heading-regexp-format
14913 (regexp-quote heading)) nil t)
14915 (match-beginning 0)
14916 (move-marker (make-marker) (match-beginning 0)))))))))
14918 (defun org-find-exact-heading-in-directory (heading &optional dir)
14919 "Find Org node headline HEADING in all .org files in directory DIR.
14920 When the target headline is found, return a marker to this location."
14921 (let ((files (directory-files (or dir default-directory)
14922 nil "\\`[^.#].*\\.org\\'"))
14923 file visiting m buffer)
14925 (while (setq file (pop files))
14926 (message "trying %s" file)
14927 (setq visiting (org-find-base-buffer-visiting file))
14928 (setq buffer (or visiting (find-file-noselect file)))
14929 (setq m (org-find-exact-headline-in-buffer
14931 (when (and (not m) (not visiting)) (kill-buffer buffer))
14932 (and m (throw 'found m))))))
14934 (defun org-find-entry-with-id (ident)
14935 "Locate the entry that contains the ID property with exact value IDENT.
14936 IDENT can be a string, a symbol or a number, this function will search for
14937 the string representation of it.
14938 Return the position where this entry starts, or nil if there is no such entry."
14939 (interactive "sID: ")
14941 ((stringp ident) ident)
14942 ((symbol-name ident) (symbol-name ident))
14943 ((numberp ident) (number-to-string ident))
14944 (t (error "IDENT %s must be a string, symbol or number" ident))))
14945 (case-fold-search nil))
14949 (goto-char (point-min))
14950 (when (re-search-forward
14951 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14953 (org-back-to-heading t)
14958 (defvar org-last-changed-timestamp nil)
14959 (defvar org-last-inserted-timestamp nil
14960 "The last time stamp inserted with `org-insert-time-stamp'.")
14961 (defvar org-time-was-given) ; dynamically scoped parameter
14962 (defvar org-end-time-was-given) ; dynamically scoped parameter
14963 (defvar org-ts-what) ; dynamically scoped parameter
14965 (defun org-time-stamp (arg &optional inactive)
14966 "Prompt for a date/time and insert a time stamp.
14967 If the user specifies a time like HH:MM, or if this command is called
14968 with a prefix argument, the time stamp will contain date and time.
14969 Otherwise, only the date will be included. All parts of a date not
14970 specified by the user will be filled in from the current date/time.
14971 So if you press just return without typing anything, the time stamp
14972 will represent the current date/time. If there is already a timestamp
14973 at the cursor, it will be modified."
14977 ;; Default time is either today, or, when entering a range,
14978 ;; the range start.
14979 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14981 (re-search-backward
14982 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14983 (- (point) 20) t)))
14984 (apply 'encode-time (org-parse-time-string (match-string 1)))
14986 (default-input (and ts (org-get-compact-tod ts)))
14987 (repeater (save-excursion
14989 (beginning-of-line)
14990 (when (re-search-forward
14991 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
14992 (save-excursion (progn (end-of-line) (point))) t)
14993 (match-string 0)))))
14994 org-time-was-given org-end-time-was-given time)
14996 ((and (org-at-timestamp-p t)
14997 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14998 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15000 (setq time (let ((this-command this-command))
15001 (org-read-date arg 'totime nil nil
15002 default-time default-input inactive)))
15003 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15004 ((org-at-timestamp-p t)
15005 (setq time (let ((this-command this-command))
15006 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15007 (when (org-at-timestamp-p t) ; just to get the match data
15008 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15010 (setq org-last-changed-timestamp
15011 (org-insert-time-stamp
15012 time (or org-time-was-given arg)
15013 inactive nil nil (list org-end-time-was-given)))
15014 (when repeater (goto-char (1- (point))) (insert " " repeater)
15015 (setq org-last-changed-timestamp
15016 (concat (substring org-last-inserted-timestamp 0 -1)
15017 " " repeater ">"))))
15018 (message "Timestamp updated"))
15020 (setq time (let ((this-command this-command))
15021 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15022 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15023 nil nil (list org-end-time-was-given))))))
15025 ;; FIXME: can we use this for something else, like computing time differences?
15026 (defun org-get-compact-tod (s)
15027 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15028 (let* ((t1 (match-string 1 s))
15029 (h1 (string-to-number (match-string 2 s)))
15030 (m1 (string-to-number (match-string 3 s)))
15031 (t2 (and (match-end 4) (match-string 5 s)))
15032 (h2 (and t2 (string-to-number (match-string 6 s))))
15033 (m2 (and t2 (string-to-number (match-string 7 s))))
15037 (setq dh (- h2 h1) dm (- m2 m1))
15038 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15039 (concat t1 "+" (number-to-string dh)
15040 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15042 (defun org-time-stamp-inactive (&optional arg)
15043 "Insert an inactive time stamp.
15044 An inactive time stamp is enclosed in square brackets instead of angle
15045 brackets. It is inactive in the sense that it does not trigger agenda entries,
15046 does not link to the calendar and cannot be changed with the S-cursor keys.
15047 So these are more for recording a certain time/date."
15049 (org-time-stamp arg 'inactive))
15051 (defvar org-date-ovl (make-overlay 1 1))
15052 (overlay-put org-date-ovl 'face 'org-date-selected)
15053 (org-detach-overlay org-date-ovl)
15055 (defvar org-ans1) ; dynamically scoped parameter
15056 (defvar org-ans2) ; dynamically scoped parameter
15058 (defvar org-plain-time-of-day-regexp) ; defined below
15060 (defvar org-overriding-default-time nil) ; dynamically scoped
15061 (defvar org-read-date-overlay nil)
15062 (defvar org-dcst nil) ; dynamically scoped
15063 (defvar org-read-date-history nil)
15064 (defvar org-read-date-final-answer nil)
15065 (defvar org-read-date-analyze-futurep nil)
15066 (defvar org-read-date-analyze-forced-year nil)
15067 (defvar org-read-date-inactive)
15069 (defun org-read-date (&optional org-with-time to-time from-string prompt
15070 default-time default-input inactive)
15071 "Read a date, possibly a time, and make things smooth for the user.
15072 The prompt will suggest to enter an ISO date, but you can also enter anything
15073 which will at least partially be understood by `parse-time-string'.
15074 Unrecognized parts of the date will default to the current day, month, year,
15075 hour and minute. If this command is called to replace a timestamp at point,
15076 or to enter the second timestamp of a range, the default time is taken
15077 from the existing stamp. Furthermore, the command prefers the future,
15078 so if you are giving a date where the year is not given, and the day-month
15079 combination is already past in the current year, it will assume you
15080 mean next year. For details, see the manual. A few examples:
15082 3-2-5 --> 2003-02-05
15083 feb 15 --> currentyear-02-15
15084 2/15 --> currentyear-02-15
15085 sep 12 9 --> 2009-09-12
15086 12:45 --> today 12:45
15087 22 sept 0:34 --> currentyear-09-22 0:34
15088 12 --> currentyear-currentmonth-12
15089 Fri --> nearest Friday (today or later)
15092 Furthermore you can specify a relative date by giving, as the *first* thing
15093 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15094 change in days weeks, months, years.
15095 With a single plus or minus, the date is relative to today. With a double
15096 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15097 +4d --> four days from today
15098 +4 --> same as above
15099 +2w --> two weeks from today
15100 ++5 --> five days from default date
15102 The function understands only English month and weekday abbreviations.
15104 While prompting, a calendar is popped up - you can also select the
15105 date with the mouse (button 1). The calendar shows a period of three
15106 months. To scroll it to other months, use the keys `>' and `<'.
15107 If you don't like the calendar, turn it off with
15108 \(setq org-read-date-popup-calendar nil)
15110 With optional argument TO-TIME, the date will immediately be converted
15111 to an internal time.
15112 With an optional argument WITH-TIME, the prompt will suggest to also
15113 insert a time. Note that when WITH-TIME is not set, you can still
15114 enter a time, and this function will inform the calling routine about
15115 this change. The calling routine may then choose to change the format
15116 used to insert the time stamp into the buffer to include the time.
15117 With optional argument FROM-STRING, read from this string instead from
15118 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15119 the time/date that is used for everything that is not specified by the
15121 (require 'parse-time)
15122 (let* ((org-time-stamp-rounding-minutes
15123 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15124 (org-dcst org-display-custom-times)
15125 (ct (org-current-time))
15126 (org-def (or org-overriding-default-time default-time ct))
15127 (org-defdecode (decode-time org-def))
15129 (when (< (nth 2 org-defdecode) org-extend-today-until)
15130 (setcar (nthcdr 2 org-defdecode) -1)
15131 (setcar (nthcdr 1 org-defdecode) 59)
15132 (setq org-def (apply 'encode-time org-defdecode)
15133 org-defdecode (decode-time org-def)))))
15134 (calendar-frame-setup nil)
15135 (calendar-setup nil)
15136 (calendar-move-hook nil)
15137 (calendar-view-diary-initially-flag nil)
15138 (calendar-view-holidays-initially-flag nil)
15139 (timestr (format-time-string
15140 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15141 (prompt (concat (if prompt (concat prompt " ") "")
15142 (format "Date+time [%s]: " timestr)))
15143 ans (org-ans0 "") org-ans1 org-ans2 final)
15146 (from-string (setq ans from-string))
15147 (org-read-date-popup-calendar
15149 (save-window-excursion
15151 (org-eval-in-calendar '(setq cursor-type nil) t)
15154 (calendar-forward-day (- (time-to-days org-def)
15155 (calendar-absolute-from-gregorian
15156 (calendar-current-date))))
15157 (org-eval-in-calendar nil t)
15158 (let* ((old-map (current-local-map))
15159 (map (copy-keymap calendar-mode-map))
15160 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15161 (org-defkey map (kbd "RET") 'org-calendar-select)
15162 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15163 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15164 (org-defkey minibuffer-local-map [(meta shift left)]
15165 (lambda () (interactive)
15166 (org-eval-in-calendar '(calendar-backward-month 1))))
15167 (org-defkey minibuffer-local-map [(meta shift right)]
15168 (lambda () (interactive)
15169 (org-eval-in-calendar '(calendar-forward-month 1))))
15170 (org-defkey minibuffer-local-map [(meta shift up)]
15171 (lambda () (interactive)
15172 (org-eval-in-calendar '(calendar-backward-year 1))))
15173 (org-defkey minibuffer-local-map [(meta shift down)]
15174 (lambda () (interactive)
15175 (org-eval-in-calendar '(calendar-forward-year 1))))
15176 (org-defkey minibuffer-local-map [?\e (shift left)]
15177 (lambda () (interactive)
15178 (org-eval-in-calendar '(calendar-backward-month 1))))
15179 (org-defkey minibuffer-local-map [?\e (shift right)]
15180 (lambda () (interactive)
15181 (org-eval-in-calendar '(calendar-forward-month 1))))
15182 (org-defkey minibuffer-local-map [?\e (shift up)]
15183 (lambda () (interactive)
15184 (org-eval-in-calendar '(calendar-backward-year 1))))
15185 (org-defkey minibuffer-local-map [?\e (shift down)]
15186 (lambda () (interactive)
15187 (org-eval-in-calendar '(calendar-forward-year 1))))
15188 (org-defkey minibuffer-local-map [(shift up)]
15189 (lambda () (interactive)
15190 (org-eval-in-calendar '(calendar-backward-week 1))))
15191 (org-defkey minibuffer-local-map [(shift down)]
15192 (lambda () (interactive)
15193 (org-eval-in-calendar '(calendar-forward-week 1))))
15194 (org-defkey minibuffer-local-map [(shift left)]
15195 (lambda () (interactive)
15196 (org-eval-in-calendar '(calendar-backward-day 1))))
15197 (org-defkey minibuffer-local-map [(shift right)]
15198 (lambda () (interactive)
15199 (org-eval-in-calendar '(calendar-forward-day 1))))
15200 (org-defkey minibuffer-local-map ">"
15201 (lambda () (interactive)
15202 (org-eval-in-calendar '(scroll-calendar-left 1))))
15203 (org-defkey minibuffer-local-map "<"
15204 (lambda () (interactive)
15205 (org-eval-in-calendar '(scroll-calendar-right 1))))
15206 (org-defkey minibuffer-local-map "\C-v"
15207 (lambda () (interactive)
15208 (org-eval-in-calendar
15209 '(calendar-scroll-left-three-months 1))))
15210 (org-defkey minibuffer-local-map "\M-v"
15211 (lambda () (interactive)
15212 (org-eval-in-calendar
15213 '(calendar-scroll-right-three-months 1))))
15214 (run-hooks 'org-read-date-minibuffer-setup-hook)
15217 (use-local-map map)
15218 (setq org-read-date-inactive inactive)
15219 (add-hook 'post-command-hook 'org-read-date-display)
15220 (setq org-ans0 (read-string prompt default-input
15221 'org-read-date-history nil))
15222 ;; org-ans0: from prompt
15223 ;; org-ans1: from mouse click
15224 ;; org-ans2: from calendar motion
15225 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15226 (remove-hook 'post-command-hook 'org-read-date-display)
15227 (use-local-map old-map)
15228 (when org-read-date-overlay
15229 (delete-overlay org-read-date-overlay)
15230 (setq org-read-date-overlay nil)))))
15231 (bury-buffer "*Calendar*")))))
15233 (t ; Naked prompt only
15235 (setq ans (read-string prompt default-input
15236 'org-read-date-history timestr))
15237 (when org-read-date-overlay
15238 (delete-overlay org-read-date-overlay)
15239 (setq org-read-date-overlay nil)))))
15241 (setq final (org-read-date-analyze ans org-def org-defdecode))
15243 (when org-read-date-analyze-forced-year
15244 (message "Year was forced into %s"
15245 (if org-read-date-force-compatible-dates
15246 "compatible range (1970-2037)"
15247 "range representable on this machine"))
15250 ;; One round trip to get rid of 34th of August and stuff like that....
15251 (setq final (decode-time (apply 'encode-time final)))
15253 (setq org-read-date-final-answer ans)
15256 (apply 'encode-time final)
15257 (if (and (boundp 'org-time-was-given) org-time-was-given)
15258 (format "%04d-%02d-%02d %02d:%02d"
15259 (nth 5 final) (nth 4 final) (nth 3 final)
15260 (nth 2 final) (nth 1 final))
15261 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15264 (defvar org-defdecode)
15265 (defvar org-with-time)
15266 (defun org-read-date-display ()
15267 "Display the current date prompt interpretation in the minibuffer."
15268 (when org-read-date-display-live
15269 (when org-read-date-overlay
15270 (delete-overlay org-read-date-overlay))
15271 (when (minibufferp (current-buffer))
15274 (while (not (equal (buffer-substring
15275 (max (point-min) (- (point) 4)) (point))
15278 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15279 " " (or org-ans1 org-ans2)))
15280 (org-end-time-was-given nil)
15281 (f (org-read-date-analyze ans org-def org-defdecode))
15283 org-time-stamp-custom-formats
15284 org-time-stamp-formats))
15285 (fmt (if (or org-with-time
15286 (and (boundp 'org-time-was-given) org-time-was-given))
15289 (txt (format-time-string fmt (apply 'encode-time f)))
15290 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15291 (txt (concat "=> " txt)))
15292 (when (and org-end-time-was-given
15293 (string-match org-plain-time-of-day-regexp txt))
15294 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15295 org-end-time-was-given
15296 (substring txt (match-end 0)))))
15297 (when org-read-date-analyze-futurep
15298 (setq txt (concat txt " (=>F)")))
15299 (setq org-read-date-overlay
15300 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15301 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15303 (defun org-read-date-analyze (ans org-def org-defdecode)
15304 "Analyze the combined answer of the date prompt."
15305 ;; FIXME: cleanup and comment
15306 (let ((nowdecode (decode-time (current-time)))
15307 delta deltan deltaw deltadef year month day
15308 hour minute second wday pm h2 m2 tl wday1
15309 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15310 (setq org-read-date-analyze-futurep nil
15311 org-read-date-analyze-forced-year nil)
15312 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15315 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15316 (setq ans (replace-match "" t t ans)
15318 deltaw (nth 1 delta)
15319 deltadef (nth 2 delta)))
15321 ;; Check if there is an iso week date in there
15322 ;; If yes, store the info and postpone interpreting it until the rest
15323 ;; of the parsing is done
15324 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15325 (setq iso-year (if (match-end 1)
15326 (org-small-year-to-year
15327 (string-to-number (match-string 1 ans))))
15328 iso-weekday (if (match-end 3)
15329 (string-to-number (match-string 3 ans)))
15330 iso-week (string-to-number (match-string 2 ans)))
15331 (setq ans (replace-match "" t t ans)))
15333 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15334 (when (string-match
15335 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15336 (setq year (if (match-end 2)
15337 (string-to-number (match-string 2 ans))
15338 (progn (setq kill-year t)
15339 (string-to-number (format-time-string "%Y"))))
15340 month (string-to-number (match-string 3 ans))
15341 day (string-to-number (match-string 4 ans)))
15342 (if (< year 100) (setq year (+ 2000 year)))
15343 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15346 ;; Help matching dotted european dates
15347 (when (string-match
15348 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15349 (setq year (if (match-end 3)
15350 (string-to-number (match-string 3 ans))
15351 (progn (setq kill-year t)
15352 (string-to-number (format-time-string "%Y"))))
15353 day (string-to-number (match-string 1 ans))
15354 month (string-to-number (match-string 2 ans))
15355 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15358 ;; Help matching american dates, like 5/30 or 5/30/7
15359 (when (string-match
15360 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15361 (setq year (if (match-end 4)
15362 (string-to-number (match-string 4 ans))
15363 (progn (setq kill-year t)
15364 (string-to-number (format-time-string "%Y"))))
15365 month (string-to-number (match-string 1 ans))
15366 day (string-to-number (match-string 2 ans)))
15367 (if (< year 100) (setq year (+ 2000 year)))
15368 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15370 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15371 ;; If there is a time with am/pm, and *no* time without it, we convert
15372 ;; so that matching will be successful.
15373 (loop for i from 1 to 2 do ; twice, for end time as well
15374 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15375 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15376 (setq hour (string-to-number (match-string 1 ans))
15377 minute (if (match-end 3)
15378 (string-to-number (match-string 3 ans))
15381 (string-to-char (downcase (match-string 4 ans)))))
15382 (if (and (= hour 12) (not pm))
15384 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15385 (setq ans (replace-match (format "%02d:%02d" hour minute)
15388 ;; Check if a time range is given as a duration
15389 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15390 (setq hour (string-to-number (match-string 1 ans))
15391 h2 (+ hour (string-to-number (match-string 3 ans)))
15392 minute (string-to-number (match-string 2 ans))
15393 m2 (+ minute (if (match-end 5) (string-to-number
15394 (match-string 5 ans))0)))
15395 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15396 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15399 ;; Check if there is a time range
15400 (when (boundp 'org-end-time-was-given)
15401 (setq org-time-was-given nil)
15402 (when (and (string-match org-plain-time-of-day-regexp ans)
15404 (setq org-end-time-was-given (match-string 8 ans))
15405 (setq ans (concat (substring ans 0 (match-beginning 7))
15406 (substring ans (match-end 7))))))
15408 (setq tl (parse-time-string ans)
15409 day (or (nth 3 tl) (nth 3 org-defdecode))
15410 month (or (nth 4 tl)
15411 (if (and org-read-date-prefer-future
15412 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15413 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15414 (nth 4 org-defdecode)))
15415 year (or (and (not kill-year) (nth 5 tl))
15416 (if (and org-read-date-prefer-future
15417 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15418 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15419 (nth 5 org-defdecode)))
15420 hour (or (nth 2 tl) (nth 2 org-defdecode))
15421 minute (or (nth 1 tl) (nth 1 org-defdecode))
15422 second (or (nth 0 tl) 0)
15425 (when (and (eq org-read-date-prefer-future 'time)
15426 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15427 (equal day (nth 3 nowdecode))
15428 (equal month (nth 4 nowdecode))
15429 (equal year (nth 5 nowdecode))
15431 (or (< (nth 2 tl) (nth 2 nowdecode))
15432 (and (= (nth 2 tl) (nth 2 nowdecode))
15434 (< (nth 1 tl) (nth 1 nowdecode)))))
15438 ;; Special date definitions below
15441 ;; There was an iso week
15444 (setq year (or iso-year year)
15445 day (or iso-weekday wday 1)
15446 wday nil ; to make sure that the trigger below does not match
15447 iso-date (calendar-gregorian-from-absolute
15448 (calendar-absolute-from-iso
15449 (list iso-week day year))))
15450 ; FIXME: Should we also push ISO weeks into the future?
15451 ; (when (and org-read-date-prefer-future
15453 ; (< (calendar-absolute-from-gregorian iso-date)
15454 ; (time-to-days (current-time))))
15455 ; (setq year (1+ year)
15456 ; iso-date (calendar-gregorian-from-absolute
15457 ; (calendar-absolute-from-iso
15458 ; (list iso-week day year)))))
15459 (setq month (car iso-date)
15460 year (nth 2 iso-date)
15461 day (nth 1 iso-date)))
15465 (let ((now (decode-time (current-time))))
15466 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15467 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15468 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15469 ((equal deltaw "m") (setq month (+ month deltan)))
15470 ((equal deltaw "y") (setq year (+ year deltan)))))
15471 ((and wday (not (nth 3 tl)))
15473 ;; Weekday was given, but no day, so pick that day in the week
15474 ;; on or after the derived date.
15475 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15476 (unless (equal wday wday1)
15477 (setq day (+ day (% (- wday wday1 -7) 7))))))
15478 (if (and (boundp 'org-time-was-given)
15480 (setq org-time-was-given t))
15481 (if (< year 100) (setq year (+ 2000 year)))
15482 ;; Check of the date is representable
15483 (if org-read-date-force-compatible-dates
15486 (setq year 1970 org-read-date-analyze-forced-year t))
15488 (setq year 2037 org-read-date-analyze-forced-year t)))
15489 (condition-case nil
15490 (ignore (encode-time second minute hour day month year))
15492 (setq year (nth 5 org-defdecode))
15493 (setq org-read-date-analyze-forced-year t))))
15494 (setq org-read-date-analyze-futurep futurep)
15495 (list second minute hour day month year)))
15497 (defvar parse-time-weekdays)
15498 (defun org-read-date-get-relative (s today default)
15499 "Check string S for special relative date string.
15500 TODAY and DEFAULT are internal times, for today and for a default.
15501 Return shift list (N what def-flag)
15502 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15503 N is the number of WHATs to shift.
15504 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15505 the DEFAULT date rather than TODAY."
15506 (require 'parse-time)
15510 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15512 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15513 "\\([ \t]\\|$\\)") s)
15514 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15515 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15516 (string-to-char (substring (match-string 1 s) -1))
15518 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15519 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15520 (what (if (match-end 3) (match-string 3 s) "d"))
15521 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15522 (date (if rel default today))
15523 (wday (nth 6 (decode-time date)))
15527 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15528 (if (= dir ?-) (setq delta (- delta 7)))
15529 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15530 (list delta "d" rel))
15531 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15533 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15534 "Turn a user-specified date into the internal representation.
15535 The internal representation needed by the calendar is (month day year).
15536 This is a wrapper to handle the brain-dead convention in calendar that
15537 user function argument order change dependent on argument order."
15538 (if (boundp 'calendar-date-style)
15540 ((eq calendar-date-style 'american)
15541 (list arg1 arg2 arg3))
15542 ((eq calendar-date-style 'european)
15543 (list arg2 arg1 arg3))
15544 ((eq calendar-date-style 'iso)
15545 (list arg2 arg3 arg1)))
15546 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15547 (if (org-bound-and-true-p european-calendar-style)
15548 (list arg2 arg1 arg3)
15549 (list arg1 arg2 arg3)))))
15551 (defun org-eval-in-calendar (form &optional keepdate)
15552 "Eval FORM in the calendar window and return to current window.
15553 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15554 otherwise stick to the current value of `org-ans2'."
15555 (let ((sf (selected-frame))
15556 (sw (selected-window)))
15557 (select-window (get-buffer-window "*Calendar*" t))
15559 (when (and (not keepdate) (calendar-cursor-to-date))
15560 (let* ((date (calendar-cursor-to-date))
15561 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15562 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15563 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15565 (org-select-frame-set-input-focus sf)))
15567 (defun org-calendar-select ()
15568 "Return to `org-read-date' with the date currently selected.
15569 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15571 (when (calendar-cursor-to-date)
15572 (let* ((date (calendar-cursor-to-date))
15573 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15574 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15575 (if (active-minibuffer-window) (exit-minibuffer))))
15577 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15578 "Insert a date stamp for the date given by the internal TIME.
15579 WITH-HM means use the stamp format that includes the time of the day.
15580 INACTIVE means use square brackets instead of angular ones, so that the
15581 stamp will not contribute to the agenda.
15582 PRE and POST are optional strings to be inserted before and after the
15584 The command returns the inserted time stamp."
15585 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15587 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15588 (insert-before-markers (or pre ""))
15589 (when (listp extra)
15590 (setq extra (car extra))
15591 (if (and (stringp extra)
15592 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15593 (setq extra (format "-%02d:%02d"
15594 (string-to-number (match-string 1 extra))
15595 (string-to-number (match-string 2 extra))))
15598 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15599 (insert-before-markers (setq stamp (format-time-string fmt time)))
15600 (insert-before-markers (or post ""))
15601 (setq org-last-inserted-timestamp stamp)))
15603 (defun org-toggle-time-stamp-overlays ()
15604 "Toggle the use of custom time stamp formats."
15606 (setq org-display-custom-times (not org-display-custom-times))
15607 (unless org-display-custom-times
15608 (let ((p (point-min)) (bmp (buffer-modified-p)))
15609 (while (setq p (next-single-property-change p 'display))
15610 (if (and (get-text-property p 'display)
15611 (eq (get-text-property p 'face) 'org-date))
15612 (remove-text-properties
15613 p (setq p (next-single-property-change p 'display))
15615 (set-buffer-modified-p bmp)))
15616 (if (featurep 'xemacs)
15617 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15618 (org-restart-font-lock)
15619 (setq org-table-may-need-update t)
15620 (if org-display-custom-times
15621 (message "Time stamps are overlaid with custom format")
15622 (message "Time stamp overlays removed")))
15624 (defun org-display-custom-time (beg end)
15625 "Overlay modified time stamp format over timestamp between BEG and END."
15626 (let* ((ts (buffer-substring beg end))
15627 t1 w1 with-hm tf time str w2 (off 0))
15629 (setq t1 (org-parse-time-string ts t))
15630 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15631 (setq off (- (match-end 0) (match-beginning 0)))))
15632 (setq end (- end off))
15633 (setq w1 (- end beg)
15634 with-hm (and (nth 1 t1) (nth 2 t1))
15635 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15636 time (org-fix-decoded-time t1)
15638 (format-time-string
15639 (substring tf 1 -1) (apply 'encode-time time))
15640 nil 'mouse-face 'highlight)
15642 (if (not (= w2 w1))
15643 (add-text-properties (1+ beg) (+ 2 beg)
15644 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15645 (if (featurep 'xemacs)
15647 (put-text-property beg end 'invisible t)
15648 (put-text-property beg end 'end-glyph (make-glyph str)))
15649 (put-text-property beg end 'display str))))
15651 (defun org-translate-time (string)
15652 "Translate all timestamps in STRING to custom format.
15653 But do this only if the variable `org-display-custom-times' is set."
15654 (when org-display-custom-times
15657 (re org-ts-regexp-both)
15658 t1 with-hm inactive tf time str beg end)
15659 (while (setq start (string-match re string start))
15660 (setq beg (match-beginning 0)
15662 t1 (save-match-data
15663 (org-parse-time-string (substring string beg end) t))
15664 with-hm (and (nth 1 t1) (nth 2 t1))
15665 inactive (equal (substring string beg (1+ beg)) "[")
15666 tf (funcall (if with-hm 'cdr 'car)
15667 org-time-stamp-custom-formats)
15668 time (org-fix-decoded-time t1)
15669 str (format-time-string
15671 (if inactive "[" "<") (substring tf 1 -1)
15672 (if inactive "]" ">"))
15673 (apply 'encode-time time))
15674 string (replace-match str t t string)
15675 start (+ start (length str)))))))
15678 (defun org-fix-decoded-time (time)
15679 "Set 0 instead of nil for the first 6 elements of time.
15680 Don't touch the rest."
15682 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15684 (defun org-days-to-time (timestamp-string)
15685 "Difference between TIMESTAMP-STRING and now in days."
15686 (- (time-to-days (org-time-string-to-time timestamp-string))
15687 (time-to-days (current-time))))
15689 (defun org-deadline-close (timestamp-string &optional ndays)
15690 "Is the time in TIMESTAMP-STRING close to the current date?"
15691 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15692 (and (< (org-days-to-time timestamp-string) ndays)
15693 (not (org-entry-is-done-p))))
15695 (defun org-get-wdays (ts)
15696 "Get the deadline lead time appropriate for timestring TS."
15698 ((<= org-deadline-warning-days 0)
15699 ;; 0 or negative, enforce this value no matter what
15700 (- org-deadline-warning-days))
15701 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15702 ;; lead time is specified.
15703 (floor (* (string-to-number (match-string 1 ts))
15704 (cdr (assoc (match-string 2 ts)
15705 '(("d" . 1) ("w" . 7)
15706 ("m" . 30.4) ("y" . 365.25)))))))
15707 ;; go for the default.
15708 (t org-deadline-warning-days)))
15710 (defun org-calendar-select-mouse (ev)
15711 "Return to `org-read-date' with the date currently selected.
15712 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15714 (mouse-set-point ev)
15715 (when (calendar-cursor-to-date)
15716 (let* ((date (calendar-cursor-to-date))
15717 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15718 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15719 (if (active-minibuffer-window) (exit-minibuffer))))
15721 (defun org-check-deadlines (ndays)
15722 "Check if there are any deadlines due or past due.
15723 A deadline is considered due if it happens within `org-deadline-warning-days'
15724 days from today's date. If the deadline appears in an entry marked DONE,
15725 it is not shown. The prefix arg NDAYS can be used to test that many
15726 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15728 (let* ((org-warn-days
15730 ((equal ndays '(4)) 100000)
15731 (ndays (prefix-numeric-value ndays))
15732 (t (abs org-deadline-warning-days))))
15733 (case-fold-search nil)
15734 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15736 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15738 (message "%d deadlines past-due or due within %d days"
15739 (org-occur regexp nil callback)
15742 (defun org-check-before-date (date)
15743 "Check if there are deadlines or scheduled entries before DATE."
15744 (interactive (list (org-read-date)))
15745 (let ((case-fold-search nil)
15746 (regexp (concat "\\<\\(" org-deadline-string
15747 "\\|" org-scheduled-string
15748 "\\) *<\\([^>]+\\)>"))
15750 (lambda () (time-less-p
15751 (org-time-string-to-time (match-string 2))
15752 (org-time-string-to-time date)))))
15753 (message "%d entries before %s"
15754 (org-occur regexp nil callback) date)))
15756 (defun org-check-after-date (date)
15757 "Check if there are deadlines or scheduled entries after DATE."
15758 (interactive (list (org-read-date)))
15759 (let ((case-fold-search nil)
15760 (regexp (concat "\\<\\(" org-deadline-string
15761 "\\|" org-scheduled-string
15762 "\\) *<\\([^>]+\\)>"))
15766 (org-time-string-to-time (match-string 2))
15767 (org-time-string-to-time date))))))
15768 (message "%d entries after %s"
15769 (org-occur regexp nil callback) date)))
15771 (defun org-check-dates-range (start-date end-date)
15772 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15773 (interactive (list (org-read-date nil nil nil "Range starts")
15774 (org-read-date nil nil nil "Range end")))
15775 (let ((case-fold-search nil)
15776 (regexp (concat "\\<\\(" org-deadline-string
15777 "\\|" org-scheduled-string
15778 "\\) *<\\([^>]+\\)>"))
15781 (let ((match (match-string 2)))
15784 (org-time-string-to-time match)
15785 (org-time-string-to-time start-date)))
15787 (org-time-string-to-time match)
15788 (org-time-string-to-time end-date)))))))
15789 (message "%d entries between %s and %s"
15790 (org-occur regexp nil callback) start-date end-date)))
15792 (defun org-evaluate-time-range (&optional to-buffer)
15793 "Evaluate a time range by computing the difference between start and end.
15794 Normally the result is just printed in the echo area, but with prefix arg
15795 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15796 If the time range is actually in a table, the result is inserted into the
15798 For time difference computation, a year is assumed to be exactly 365
15799 days in order to avoid rounding problems."
15802 (org-clock-update-time-maybe)
15804 (unless (org-at-date-range-p t)
15805 (goto-char (point-at-bol))
15806 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15807 (if (not (org-at-date-range-p t))
15808 (error "Not at a time-stamp range, and none found in current line")))
15809 (let* ((ts1 (match-string 1))
15810 (ts2 (match-string 2))
15811 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15812 (match-end (match-end 0))
15813 (time1 (org-time-string-to-time ts1))
15814 (time2 (org-time-string-to-time ts2))
15815 (t1 (org-float-time time1))
15816 (t2 (org-float-time time2))
15817 (diff (abs (- t2 t1)))
15818 (negative (< (- t2 t1) 0))
15819 ;; (ys (floor (* 365 24 60 60)))
15822 (fy "%dy %dd %02d:%02d")
15824 (fd "%dd %02d:%02d")
15829 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15831 d (floor (/ diff ds)) diff (mod diff ds)
15832 h (floor (/ diff hs)) diff (mod diff hs)
15833 m (floor (/ diff 60)))
15834 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15836 d (floor (+ (/ diff ds) 0.5))
15838 (if (not to-buffer)
15839 (message "%s" (org-make-tdiff-string y d h m))
15840 (if (org-at-table-p)
15842 (goto-char match-end)
15844 (and (looking-at " *|") (goto-char (match-end 0))))
15845 (goto-char match-end))
15847 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15848 (replace-match ""))
15849 (if negative (insert " -"))
15850 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15851 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15852 (insert " " (format fh h m))))
15853 (if align (org-table-align))
15854 (message "Time difference inserted")))))
15856 (defun org-make-tdiff-string (y d h m)
15859 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15861 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15863 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15865 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15867 (apply 'format fmt (nreverse l))))
15869 (defun org-time-string-to-time (s &optional buffer pos)
15870 (condition-case errdata
15871 (apply 'encode-time (org-parse-time-string s))
15872 (error (error "Bad timestamp `%s'%s\nError was: %s"
15873 s (if (not (and buffer pos))
15875 (format " at %d in buffer `%s'" pos buffer))
15878 (defun org-time-string-to-seconds (s)
15879 (org-float-time (org-time-string-to-time s)))
15881 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15882 "Convert a time stamp to an absolute day number.
15883 If there is a specifier for a cyclic time stamp, get the closest date to
15885 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15886 The variable date is bound by the calendar when this is called."
15888 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15889 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15892 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
15893 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15894 (time-to-days (current-time))) (match-string 0 s)
15897 (condition-case errdata
15898 (apply 'encode-time (org-parse-time-string s))
15899 (error (error "Bad timestamp `%s'%s\nError was: %s"
15900 s (if (not (and buffer pos))
15902 (format " at %d in buffer `%s'" pos buffer))
15903 (cdr errdata))))))))
15905 (defun org-days-to-iso-week (days)
15906 "Return the iso week number."
15908 (car (calendar-iso-from-absolute days)))
15910 (defun org-small-year-to-year (year)
15911 "Convert 2-digit years into 4-digit years.
15912 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15913 The year 2000 cannot be abbreviated. Any year larger than 99
15914 is returned unchanged."
15916 (setq year (+ 2000 year))
15918 (setq year (+ 1900 year))))
15921 (defun org-time-from-absolute (d)
15922 "Return the time corresponding to date D.
15923 D may be an absolute day number, or a calendar-type list (month day year)."
15924 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15925 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15927 (defun org-calendar-holiday ()
15928 "List of holidays, for Diary display in Org-mode."
15929 (require 'holidays)
15931 (if (fboundp 'calendar-check-holidays)
15932 'calendar-check-holidays 'check-calendar-holidays) date)))
15933 (if hl (mapconcat 'identity hl "; "))))
15935 (defun org-diary-sexp-entry (sexp entry date)
15936 "Process a SEXP diary ENTRY for DATE."
15937 (require 'diary-lib)
15938 (let ((result (if calendar-debug-sexp
15939 (let ((stack-trace-on-error t))
15940 (eval (car (read-from-string sexp))))
15941 (condition-case nil
15942 (eval (car (read-from-string sexp)))
15945 (message "Bad sexp at line %d in %s: %s"
15947 (buffer-file-name) sexp)
15949 (cond ((stringp result) (split-string result "; "))
15950 ((and (consp result)
15951 (not (consp (cdr result)))
15952 (stringp (cdr result))) (cdr result))
15953 ((and (consp result)
15954 (stringp (car result))) result)
15958 (defun org-diary-to-ical-string (frombuf)
15959 "Get iCalendar entries from diary entries in buffer FROMBUF.
15960 This uses the icalendar.el library."
15961 (let* ((tmpdir (if (featurep 'xemacs)
15963 temporary-file-directory))
15964 (tmpfile (make-temp-name
15965 (expand-file-name "orgics" tmpdir)))
15967 (with-current-buffer frombuf
15968 (icalendar-export-region (point-min) (point-max) tmpfile)
15969 (setq buf (find-buffer-visiting tmpfile))
15971 (goto-char (point-min))
15972 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15973 (setq b (match-beginning 0)))
15974 (goto-char (point-max))
15975 (if (re-search-backward "^END:VEVENT" nil t)
15976 (setq e (match-end 0)))
15977 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15979 (delete-file tmpfile)
15982 (defun org-closest-date (start current change prefer show-all)
15983 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15984 When PREFER is `past', return a date that is either CURRENT or past.
15985 When PREFER is `future', return a date that is either CURRENT or future.
15986 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15987 ;; Make the proper lists from the dates
15989 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15990 dn dw sday cday n1 n2 n0
15991 d m y y1 y2 date1 date2 nmonths nm ny m2)
15993 (setq start (org-date-to-gregorian start)
15994 current (org-date-to-gregorian
15997 (time-to-days (current-time))))
15998 sday (calendar-absolute-from-gregorian start)
15999 cday (calendar-absolute-from-gregorian current))
16001 (if (<= cday sday) (throw 'exit sday))
16003 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16004 (setq dn (string-to-number (match-string 1 change))
16005 dw (cdr (assoc (match-string 2 change) a1)))
16006 (error "Invalid change specifier: %s" change))
16007 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16010 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16013 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16014 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16015 (setq date1 (list m d y1)
16016 n1 (calendar-absolute-from-gregorian date1)
16017 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16018 n2 (calendar-absolute-from-gregorian date2)))
16020 ;; approx number of month between the two dates
16021 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16022 ;; How often does dn fit in there?
16023 (setq d (nth 1 start) m (car start) y (nth 2 start)
16024 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16026 ny (floor (/ m 12))
16029 (while (> m 12) (setq m (- m 12) y (1+ y)))
16030 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16031 (setq m2 (+ m dn) y2 y)
16032 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16033 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16034 (while (<= n2 cday)
16035 (setq n1 n2 m m2 y y2)
16036 (setq m2 (+ m dn) y2 y)
16037 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16038 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16039 ;; Make sure n1 is the earlier date
16040 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16043 ((eq prefer 'past) (if (= cday n2) n2 n1))
16044 ((eq prefer 'future) (if (= cday n1) n1 n2))
16045 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16047 ((eq prefer 'past) (if (= cday n2) n2 n1))
16048 ((eq prefer 'future) (if (= cday n1) n1 n2))
16049 (t (if (= cday n1) n1 n2)))))))
16051 (defun org-date-to-gregorian (date)
16052 "Turn any specification of DATE into a Gregorian date for the calendar."
16053 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16054 ((and (listp date) (= (length date) 3)) date)
16056 (setq date (org-parse-time-string date))
16057 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16059 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16061 (defun org-parse-time-string (s &optional nodefault)
16062 "Parse the standard Org-mode time string.
16063 This should be a lot faster than the normal `parse-time-string'.
16064 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16065 hour and minute fields will be nil if not given."
16066 (if (string-match org-ts-regexp0 s)
16068 (if (or (match-beginning 8) (not nodefault))
16069 (string-to-number (or (match-string 8 s) "0")))
16070 (if (or (match-beginning 7) (not nodefault))
16071 (string-to-number (or (match-string 7 s) "0")))
16072 (string-to-number (match-string 4 s))
16073 (string-to-number (match-string 3 s))
16074 (string-to-number (match-string 2 s))
16076 (error "Not a standard Org-mode time string: %s" s)))
16078 (defun org-timestamp-up (&optional arg)
16079 "Increase the date item at the cursor by one.
16080 If the cursor is on the year, change the year. If it is on the month,
16081 the day or the time, change that.
16082 With prefix ARG, change by that many units."
16084 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16086 (defun org-timestamp-down (&optional arg)
16087 "Decrease the date item at the cursor by one.
16088 If the cursor is on the year, change the year. If it is on the month,
16089 the day or the time, change that.
16090 With prefix ARG, change by that many units."
16092 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16094 (defun org-timestamp-up-day (&optional arg)
16095 "Increase the date in the time stamp by one day.
16096 With prefix ARG, change that many days."
16098 (if (and (not (org-at-timestamp-p t))
16099 (org-at-heading-p))
16101 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16103 (defun org-timestamp-down-day (&optional arg)
16104 "Decrease the date in the time stamp by one day.
16105 With prefix ARG, change that many days."
16107 (if (and (not (org-at-timestamp-p t))
16108 (org-at-heading-p))
16110 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16112 (defun org-at-timestamp-p (&optional inactive-ok)
16113 "Determine if the cursor is in or at a timestamp."
16115 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16117 (ans (or (looking-at tsr)
16119 (skip-chars-backward "^[<\n\r\t")
16120 (if (> (point) (point-min)) (backward-char 1))
16121 (and (looking-at tsr)
16122 (> (- (match-end 0) pos) -1))))))
16124 (boundp 'org-ts-what)
16127 ((= pos (match-beginning 0)) 'bracket)
16128 ;; Point is considered to be "on the bracket" whether
16129 ;; it's really on it or right after it.
16130 ((or (= pos (1- (match-end 0)))
16131 (= pos (match-end 0))) 'bracket)
16132 ((org-pos-in-match-range pos 2) 'year)
16133 ((org-pos-in-match-range pos 3) 'month)
16134 ((org-pos-in-match-range pos 7) 'hour)
16135 ((org-pos-in-match-range pos 8) 'minute)
16136 ((or (org-pos-in-match-range pos 4)
16137 (org-pos-in-match-range pos 5)) 'day)
16138 ((and (> pos (or (match-end 8) (match-end 5)))
16139 (< pos (match-end 0)))
16140 (- pos (or (match-end 8) (match-end 5))))
16144 (defun org-toggle-timestamp-type ()
16145 "Toggle the type (<active> or [inactive]) of a time stamp."
16147 (when (org-at-timestamp-p t)
16148 (let ((beg (match-beginning 0)) (end (match-end 0))
16149 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16152 (while (re-search-forward "[][<>]" end t)
16153 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16155 (message "Timestamp is now %sactive"
16156 (if (equal (char-after beg) ?<) "" "in")))))
16158 (defun org-timestamp-change (n &optional what updown)
16159 "Change the date in the time stamp at point.
16160 The date will be changed by N times WHAT. WHAT can be `day', `month',
16161 `year', `minute', `second'. If WHAT is not given, the cursor position
16162 in the timestamp determines what will be changed."
16163 (let ((origin (point)) origin-cat
16165 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16169 (if (not (org-at-timestamp-p t))
16170 (error "Not at a timestamp"))
16171 (if (and (not what) (eq org-ts-what 'bracket))
16172 (org-toggle-timestamp-type)
16173 ;; Point isn't on brackets. Remember the part of the time-stamp
16174 ;; the point was in. Indeed, size of time-stamps may change,
16175 ;; but point must be kept in the same category nonetheless.
16176 (setq origin-cat org-ts-what)
16177 (if (and (not what) (not (eq org-ts-what 'day))
16178 org-display-custom-times
16179 (get-text-property (point) 'display)
16180 (not (get-text-property (1- (point)) 'display)))
16181 (setq org-ts-what 'day))
16182 (setq org-ts-what (or what org-ts-what)
16183 inactive (= (char-after (match-beginning 0)) ?\[)
16184 ts (match-string 0))
16187 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16189 (setq extra (match-string 1 ts)))
16190 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16192 (setq time0 (org-parse-time-string ts))
16194 (eq org-ts-what 'minute)
16195 (not current-prefix-arg))
16196 ;; This looks like s-up and s-down. Change by one rounding step.
16197 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16198 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16199 (setcar (cdr time0) (+ (nth 1 time0)
16200 (if (> n 0) (- rem) (- dm rem))))))
16202 (encode-time (or (car time0) 0)
16203 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16204 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16205 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16206 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16207 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16209 (when (and (member org-ts-what '(hour minute))
16211 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16212 (setq extra (org-modify-ts-extra
16214 (if (eq org-ts-what 'hour) 2 5)
16216 (when (integerp org-ts-what)
16217 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16218 (if (eq what 'calendar)
16219 (let ((cal-date (org-get-date-from-calendar)))
16220 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16221 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16222 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16223 (setcar time0 (or (car time0) 0))
16224 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16225 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16226 (setq time (apply 'encode-time time0))))
16227 ;; Insert the new time-stamp, and ensure point stays in the same
16228 ;; category as before (i.e. not after the last position in that
16230 (let ((pos (point)))
16231 ;; Stay before inserted string. `save-excursion' is of no use.
16232 (setq org-last-changed-timestamp
16233 (org-insert-time-stamp time with-hm inactive nil nil extra))
16236 (looking-at org-ts-regexp3)
16238 ;; `day' category ends before `hour' if any, or at
16239 ;; the end of the day name.
16240 ((eq origin-cat 'day)
16241 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16242 ((eq origin-cat 'hour) (min (match-end 7) origin))
16243 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16244 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16245 ;; `year' and `month' have both fixed size: point
16246 ;; couldn't have moved into another part.
16248 ;; Update clock if on a CLOCK line.
16249 (org-clock-update-time-maybe)
16250 ;; Try to recenter the calendar window, if any.
16251 (if (and org-calendar-follow-timestamp-change
16252 (get-buffer-window "*Calendar*" t)
16253 (memq org-ts-what '(day month year)))
16254 (org-recenter-calendar (time-to-days time))))))
16256 (defun org-modify-ts-extra (s pos n dm)
16257 "Change the different parts of the lead-time and repeat fields in timestamp."
16258 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16260 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16262 ((or (org-pos-in-match-range pos 2)
16263 (org-pos-in-match-range pos 3))
16264 (setq m (string-to-number (match-string 3 s))
16265 h (string-to-number (match-string 2 s)))
16266 (if (org-pos-in-match-range pos 2)
16268 (setq n (* dm (org-no-warnings (signum n))))
16269 (when (not (= 0 (setq rem (% m dm))))
16270 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16272 (if (< m 0) (setq m (+ m 60) h (1- h)))
16273 (if (> m 59) (setq m (- m 60) h (1+ h)))
16274 (setq h (min 24 (max 0 h)))
16275 (setq ng 1 new (format "-%02d:%02d" h m)))
16276 ((org-pos-in-match-range pos 6)
16277 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16278 ((org-pos-in-match-range pos 5)
16279 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16281 ((org-pos-in-match-range pos 9)
16282 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16283 ((org-pos-in-match-range pos 8)
16284 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16288 (substring s 0 (match-beginning ng))
16290 (substring s (match-end ng))))))
16293 (defun org-recenter-calendar (date)
16294 "If the calendar is visible, recenter it to DATE."
16295 (let ((cwin (get-buffer-window "*Calendar*" t)))
16297 (let ((calendar-move-hook nil))
16298 (with-selected-window cwin
16299 (calendar-goto-date (if (listp date) date
16300 (calendar-gregorian-from-absolute date))))))))
16302 (defun org-goto-calendar (&optional arg)
16303 "Go to the Emacs calendar at the current date.
16304 If there is a time stamp in the current line, go to that date.
16305 A prefix ARG can be used to force the current date."
16307 (let ((tsr org-ts-regexp) diff
16308 (calendar-move-hook nil)
16309 (calendar-view-holidays-initially-flag nil)
16310 (calendar-view-diary-initially-flag nil))
16311 (if (or (org-at-timestamp-p)
16313 (beginning-of-line 1)
16314 (looking-at (concat ".*" tsr))))
16315 (let ((d1 (time-to-days (current-time)))
16317 (org-time-string-to-time (match-string 1)))))
16318 (setq diff (- d2 d1))))
16320 (calendar-goto-today)
16321 (if (and diff (not arg)) (calendar-forward-day diff))))
16323 (defun org-get-date-from-calendar ()
16324 "Return a list (month day year) of date at point in calendar."
16325 (with-current-buffer "*Calendar*"
16327 (calendar-cursor-to-date))))
16329 (defun org-date-from-calendar ()
16330 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16331 If there is already a time stamp at the cursor position, update it."
16333 (if (org-at-timestamp-p t)
16334 (org-timestamp-change 0 'calendar)
16335 (let ((cal-date (org-get-date-from-calendar)))
16336 (org-insert-time-stamp
16337 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16339 (defun org-minutes-to-hh:mm-string (m)
16340 "Compute H:MM from a number of minutes."
16341 (let ((h (/ m 60)))
16342 (setq m (- m (* 60 h)))
16343 (format org-time-clocksum-format h m)))
16345 (defun org-hh:mm-string-to-minutes (s)
16346 "Convert a string H:MM to a number of minutes.
16347 If the string is just a number, interpret it as minutes.
16348 In fact, the first hh:mm or number in the string will be taken,
16349 there can be extra stuff in the string.
16350 If no number is found, the return value is 0."
16353 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16354 (+ (* (string-to-number (match-string 1 s)) 60)
16355 (string-to-number (match-string 2 s))))
16356 ((string-match "\\([0-9]+\\)" s)
16357 (string-to-number (match-string 1 s)))
16360 (defcustom org-effort-durations
16363 ("w" . ,(* 60 8 5))
16364 ("m" . ,(* 60 8 5 4))
16365 ("y" . ,(* 60 8 5 40)))
16366 "Conversion factor to minutes for an effort modifier.
16368 Each entry has the form (MODIFIER . MINUTES).
16370 In an effort string, a number followed by MODIFIER is multiplied
16371 by the specified number of MINUTES to obtain an effort in
16374 For example, if the value of this variable is ((\"hours\" . 60)), then an
16375 effort string \"2hours\" is equivalent to 120 minutes."
16378 :type '(alist :key-type (string :tag "Modifier")
16379 :value-type (number :tag "Minutes")))
16381 (defun org-duration-string-to-minutes (s &optional output-to-string)
16382 "Convert a duration string S to minutes.
16384 A bare number is interpreted as minutes, modifiers can be set by
16385 customizing `org-effort-durations' (which see).
16387 Entries containing a colon are interpreted as H:MM by
16388 `org-hh:mm-string-to-minutes'."
16390 (re (concat "\\([0-9.]+\\) *\\("
16391 (regexp-opt (mapcar 'car org-effort-durations))
16393 (while (string-match re s)
16394 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16395 (string-to-number (match-string 1 s))))
16396 (setq s (replace-match "" nil t s)))
16397 (setq result (floor result))
16398 (incf result (org-hh:mm-string-to-minutes s))
16399 (if output-to-string (number-to-string result) result)))
16403 (defun org-save-all-org-buffers ()
16404 "Save all Org-mode buffers without user confirmation."
16406 (message "Saving all Org-mode buffers...")
16407 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16408 (when (featurep 'org-id) (org-id-locations-save))
16409 (message "Saving all Org-mode buffers... done"))
16411 (defun org-revert-all-org-buffers ()
16412 "Revert all Org-mode buffers.
16413 Prompt for confirmation when there are unsaved changes.
16414 Be sure you know what you are doing before letting this function
16415 overwrite your changes.
16417 This function is useful in a setup where one tracks org files
16418 with a version control system, to revert on one machine after pulling
16419 changes from another. I believe the procedure must be like this:
16421 1. M-x org-save-all-org-buffers
16422 2. Pull changes from the other machine, resolve conflicts
16423 3. M-x org-revert-all-org-buffers"
16425 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16428 (save-window-excursion
16431 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16432 (with-current-buffer b buffer-file-name))
16433 (org-pop-to-buffer-same-window b)
16434 (revert-buffer t 'no-confirm)))
16436 (when (and (featurep 'org-id) org-id-track-globally)
16437 (org-id-locations-load)))))
16442 (defun org-switchb (&optional arg)
16443 "Switch between Org buffers.
16444 With one prefix argument, restrict available buffers to files.
16445 With two prefix arguments, restrict available buffers to agenda files.
16447 Defaults to `iswitchb' for buffer name completion.
16448 Set `org-completion-use-ido' to make it use ido instead."
16450 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16451 ((equal arg '(16)) (org-buffer-list 'agenda))
16452 (t (org-buffer-list))))
16453 (org-completion-use-iswitchb org-completion-use-iswitchb)
16454 (org-completion-use-ido org-completion-use-ido))
16455 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16456 (setq org-completion-use-iswitchb t))
16457 (org-pop-to-buffer-same-window
16458 (org-icompleting-read "Org buffer: "
16459 (mapcar 'list (mapcar 'buffer-name blist))
16462 ;;; Define some older names previously used for this functionality
16464 (defalias 'org-ido-switchb 'org-switchb)
16466 (defalias 'org-iswitchb 'org-switchb)
16468 (defun org-buffer-list (&optional predicate exclude-tmp)
16469 "Return a list of Org buffers.
16470 PREDICATE can be `export', `files' or `agenda'.
16472 export restrict the list to Export buffers.
16473 files restrict the list to buffers visiting Org files.
16474 agenda restrict the list to buffers visiting agenda files.
16476 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16478 (agenda-files (and (eq predicate 'agenda)
16479 (mapcar 'file-truename (org-agenda-files t))))
16482 ((eq predicate 'files)
16483 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16484 ((eq predicate 'export)
16485 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16486 ((eq predicate 'agenda)
16488 (with-current-buffer b
16489 (and (derived-mode-p 'org-mode)
16490 (setq bfn (buffer-file-name b))
16491 (member (file-truename bfn) agenda-files)))))
16492 (t (lambda (b) (with-current-buffer b
16493 (or (derived-mode-p 'org-mode)
16494 (string-match "\*Org .*Export"
16495 (buffer-name b)))))))))
16499 (if (and (funcall filter b)
16500 (or (not exclude-tmp)
16501 (not (string-match "tmp" (buffer-name b)))))
16506 (defun org-agenda-files (&optional unrestricted archives)
16507 "Get the list of agenda files.
16508 Optional UNRESTRICTED means return the full list even if a restriction
16509 is currently in place.
16510 When ARCHIVES is t, include all archive files that are really being
16511 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16512 `org-agenda-archives-mode' is t."
16515 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16516 ((stringp org-agenda-files) (org-read-agenda-file-list))
16517 ((listp org-agenda-files) org-agenda-files)
16518 (t (error "Invalid value of `org-agenda-files'")))))
16519 (setq files (apply 'append
16520 (mapcar (lambda (f)
16521 (if (file-directory-p f)
16523 f t org-agenda-file-regexp)
16526 (when org-agenda-skip-unavailable-files
16527 (setq files (delq nil
16530 (and (file-readable-p file) file)))
16532 (when (or (eq archives t)
16533 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16534 (setq files (org-add-archive-files files)))
16537 (defun org-agenda-file-p (&optional file)
16538 "Return non-nil, if FILE is an agenda file.
16539 If FILE is omitted, use the file associated with the current
16541 (member (or file (buffer-file-name))
16542 (org-agenda-files t)))
16544 (defun org-edit-agenda-file-list ()
16545 "Edit the list of agenda files.
16546 Depending on setup, this either uses customize to edit the variable
16547 `org-agenda-files', or it visits the file that is holding the list. In the
16548 latter case, the buffer is set up in a way that saving it automatically kills
16549 the buffer and restores the previous window configuration."
16551 (if (stringp org-agenda-files)
16552 (let ((cw (current-window-configuration)))
16553 (find-file org-agenda-files)
16554 (org-set-local 'org-window-configuration cw)
16555 (org-add-hook 'after-save-hook
16557 (set-window-configuration
16558 (prog1 org-window-configuration
16559 (kill-buffer (current-buffer))))
16560 (org-install-agenda-files-menu)
16561 (message "New agenda file list installed"))
16563 (message "%s" (substitute-command-keys
16564 "Edit list and finish with \\[save-buffer]")))
16565 (customize-variable 'org-agenda-files)))
16567 (defun org-store-new-agenda-file-list (list)
16568 "Set new value for the agenda file list and save it correctly."
16569 (if (stringp org-agenda-files)
16570 (let ((fe (org-read-agenda-file-list t)) b u)
16571 (while (setq b (find-buffer-visiting org-agenda-files))
16573 (with-temp-file org-agenda-files
16576 (lambda (f) ;; Keep un-expanded entries.
16577 (if (setq u (assoc f fe))
16582 (let ((org-mode-hook nil) (org-inhibit-startup t)
16583 (org-insert-mode-line-in-empty-file nil))
16584 (setq org-agenda-files list)
16585 (customize-save-variable 'org-agenda-files org-agenda-files))))
16587 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16588 "Read the list of agenda files from a file.
16589 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16590 filenames, used by `org-store-new-agenda-file-list' to write back
16591 un-expanded file names."
16592 (when (file-directory-p org-agenda-files)
16593 (error "`org-agenda-files' cannot be a single directory"))
16594 (when (stringp org-agenda-files)
16596 (insert-file-contents org-agenda-files)
16599 (let ((e (expand-file-name (substitute-in-file-name f)
16601 (if pair-with-expansion
16604 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16607 (defun org-cycle-agenda-files ()
16608 "Cycle through the files in `org-agenda-files'.
16609 If the current buffer visits an agenda file, find the next one in the list.
16610 If the current buffer does not, find the first agenda file."
16612 (let* ((fs (org-agenda-files t))
16613 (files (append fs (list (car fs))))
16614 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16616 (unless files (error "No agenda files"))
16618 (while (setq file (pop files))
16619 (if (equal (file-truename file) tcf)
16621 (find-file (car files))
16623 (find-file (car fs)))
16624 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16626 (defun org-agenda-file-to-front (&optional to-end)
16627 "Move/add the current file to the top of the agenda file list.
16628 If the file is not present in the list, it is added to the front. If it is
16629 present, it is moved there. With optional argument TO-END, add/move to the
16632 (let ((org-agenda-skip-unavailable-files nil)
16633 (file-alist (mapcar (lambda (x)
16634 (cons (file-truename x) x))
16635 (org-agenda-files t)))
16636 (ctf (file-truename buffer-file-name))
16638 (setq x (assoc ctf file-alist) had x)
16640 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16642 (setq file-alist (append (delq x file-alist) (list x)))
16643 (setq file-alist (cons x (delq x file-alist))))
16644 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16645 (org-install-agenda-files-menu)
16646 (message "File %s to %s of agenda file list"
16647 (if had "moved" "added") (if to-end "end" "front"))))
16649 (defun org-remove-file (&optional file)
16650 "Remove current file from the list of files in variable `org-agenda-files'.
16651 These are the files which are being checked for agenda entries.
16652 Optional argument FILE means use this file instead of the current."
16654 (let* ((org-agenda-skip-unavailable-files nil)
16655 (file (or file buffer-file-name))
16656 (true-file (file-truename file))
16657 (afile (abbreviate-file-name file))
16658 (files (delq nil (mapcar
16660 (if (equal true-file
16663 (org-agenda-files t)))))
16664 (if (not (= (length files) (length (org-agenda-files t))))
16666 (org-store-new-agenda-file-list files)
16667 (org-install-agenda-files-menu)
16668 (message "Removed file: %s" afile))
16669 (message "File was not in list: %s (not removed)" afile))))
16671 (defun org-file-menu-entry (file)
16672 (vector file (list 'find-file file) t))
16674 (defun org-check-agenda-file (file)
16675 "Make sure FILE exists. If not, ask user what to do."
16676 (when (not (file-exists-p file))
16677 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16678 (abbreviate-file-name file))
16679 (let ((r (downcase (read-char-exclusive))))
16682 (org-remove-file file)
16683 (throw 'nextfile t))
16684 (t (error "Abort"))))))
16686 (defun org-get-agenda-file-buffer (file)
16687 "Get a buffer visiting FILE. If the buffer needs to be created, add
16688 it to the list of buffers which might be released later."
16689 (let ((buf (org-find-base-buffer-visiting file)))
16691 buf ; just return it
16692 ;; Make a new buffer and remember it
16693 (setq buf (find-file-noselect file))
16694 (if buf (push buf org-agenda-new-buffers))
16697 (defun org-release-buffers (blist)
16698 "Release all buffers in list, asking the user for confirmation when needed.
16699 When a buffer is unmodified, it is just killed. When modified, it is saved
16700 \(if the user agrees) and then killed."
16702 (while (setq buf (pop blist))
16703 (setq file (buffer-file-name buf))
16704 (when (and (buffer-modified-p buf)
16706 (y-or-n-p (format "Save file %s? " file)))
16707 (with-current-buffer buf (save-buffer)))
16708 (kill-buffer buf))))
16710 (defun org-prepare-agenda-buffers (files)
16711 "Create buffers for all agenda files, protect archived trees and comments."
16713 (let ((pa '(:org-archived t))
16714 (pc '(:org-comment t))
16715 (pall '(:org-archived t :org-comment t))
16716 (inhibit-read-only t)
16717 (rea (concat ":" org-archive-tag ":"))
16721 (while (setq file (pop files))
16725 (org-check-agenda-file file)
16726 (set-buffer (org-get-agenda-file-buffer file)))
16728 (setq bmp (buffer-modified-p))
16729 (org-refresh-category-properties)
16730 (setq org-todo-keywords-for-agenda
16731 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16732 (setq org-done-keywords-for-agenda
16733 (append org-done-keywords-for-agenda org-done-keywords))
16734 (setq org-todo-keyword-alist-for-agenda
16735 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16736 (setq org-drawers-for-agenda
16737 (append org-drawers-for-agenda org-drawers))
16738 (setq org-tag-alist-for-agenda
16739 (append org-tag-alist-for-agenda org-tag-alist))
16742 (remove-text-properties (point-min) (point-max) pall)
16743 (when org-agenda-skip-archived-trees
16744 (goto-char (point-min))
16745 (while (re-search-forward rea nil t)
16746 (if (org-at-heading-p t)
16747 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16748 (goto-char (point-min))
16749 (setq re (format org-heading-keyword-regexp-format
16750 org-comment-string))
16751 (while (re-search-forward re nil t)
16752 (add-text-properties
16753 (match-beginning 0) (org-end-of-subtree t) pc)))
16754 (set-buffer-modified-p bmp)))))
16755 (setq org-todo-keywords-for-agenda
16756 (org-uniquify org-todo-keywords-for-agenda))
16757 (setq org-todo-keyword-alist-for-agenda
16758 (org-uniquify org-todo-keyword-alist-for-agenda)
16759 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16761 ;;;; Embedded LaTeX
16763 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16764 "Keymap for the minor `org-cdlatex-mode'.")
16766 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16767 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16768 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16769 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16770 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16772 (defvar org-cdlatex-texmathp-advice-is-done nil
16773 "Flag remembering if we have applied the advice to texmathp already.")
16775 (define-minor-mode org-cdlatex-mode
16776 "Toggle the minor `org-cdlatex-mode'.
16777 This mode supports entering LaTeX environment and math in LaTeX fragments
16779 \\{org-cdlatex-mode-map}"
16781 (when org-cdlatex-mode
16783 (run-hooks 'cdlatex-mode-hook)
16784 (cdlatex-compute-tables))
16785 (unless org-cdlatex-texmathp-advice-is-done
16786 (setq org-cdlatex-texmathp-advice-is-done t)
16787 (defadvice texmathp (around org-math-always-on activate)
16788 "Always return t in org-mode buffers.
16789 This is because we want to insert math symbols without dollars even outside
16790 the LaTeX math segments. If Orgmode thinks that point is actually inside
16791 an embedded LaTeX fragment, let texmathp do its job.
16792 \\[org-cdlatex-mode-map]"
16796 ((not (derived-mode-p 'org-mode)) ad-do-it)
16797 ((eq this-command 'cdlatex-math-symbol)
16798 (setq ad-return-value t
16799 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16801 (let ((p (org-inside-LaTeX-fragment-p)))
16802 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16803 (setq ad-return-value t
16804 texmathp-why '("Org-mode embedded math" . 0))
16805 (if p ad-do-it)))))))))
16807 (defun turn-on-org-cdlatex ()
16808 "Unconditionally turn on `org-cdlatex-mode'."
16809 (org-cdlatex-mode 1))
16811 (defun org-inside-LaTeX-fragment-p ()
16812 "Test if point is inside a LaTeX fragment.
16813 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16814 sequence appearing also before point.
16815 Even though the matchers for math are configurable, this function assumes
16816 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16817 delimiters are skipped when they have been removed by customization.
16818 The return value is nil, or a cons cell with the delimiter and the
16819 position of this delimiter.
16821 This function does a reasonably good job, but can locally be fooled by
16822 for example currency specifications. For example it will assume being in
16823 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16824 fragments that are properly closed, but during editing, we have to live
16825 with the uncertainty caused by missing closing delimiters. This function
16826 looks only before point, not after."
16828 (let ((pos (point))
16829 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16831 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16833 dd-on str (start 0) m re)
16836 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16837 re (nth 1 (assoc "$" org-latex-regexps)))
16838 (while (string-match re str start)
16840 ((= (match-end 0) (length str))
16841 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16842 ((= (match-end 0) (- (length str) 5))
16844 (t (setq start (match-end 0))))))
16845 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16847 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16848 (and (match-beginning 2) (throw 'exit nil))
16850 (while (re-search-backward "\\$\\$" lim t)
16851 (setq dd-on (not dd-on)))
16853 (if dd-on (cons "$$" m))))))
16855 (defun org-inside-latex-macro-p ()
16856 "Is point inside a LaTeX macro or its arguments?"
16859 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16861 (defun org-try-cdlatex-tab ()
16862 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16863 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16864 - inside a LaTeX fragment, or
16865 - after the first word in a line, where an abbreviation expansion could
16866 insert a LaTeX environment."
16867 (when org-cdlatex-mode
16869 ;; Before any word on the line: No expansion possible.
16870 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16871 ;; Just after first word on the line: Expand it. Make sure it
16872 ;; cannot happen on headlines, though.
16874 (skip-chars-backward "a-zA-Z0-9*")
16875 (skip-chars-backward " \t")
16876 (and (bolp) (not (org-at-heading-p))))
16878 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16880 (defun org-cdlatex-underscore-caret (&optional arg)
16881 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16882 Revert to the normal definition outside of these fragments."
16884 (if (org-inside-LaTeX-fragment-p)
16885 (call-interactively 'cdlatex-sub-superscript)
16886 (let (org-cdlatex-mode)
16887 (call-interactively (key-binding (vector last-input-event))))))
16889 (defun org-cdlatex-math-modify (&optional arg)
16890 "Execute `cdlatex-math-modify' in LaTeX fragments.
16891 Revert to the normal definition outside of these fragments."
16893 (if (org-inside-LaTeX-fragment-p)
16894 (call-interactively 'cdlatex-math-modify)
16895 (let (org-cdlatex-mode)
16896 (call-interactively (key-binding (vector last-input-event))))))
16898 (defvar org-latex-fragment-image-overlays nil
16899 "List of overlays carrying the images of latex fragments.")
16900 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16902 (defun org-remove-latex-fragment-image-overlays ()
16903 "Remove all overlays with LaTeX fragment images in current buffer."
16904 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16905 (setq org-latex-fragment-image-overlays nil))
16907 (defun org-preview-latex-fragment (&optional subtree)
16908 "Preview the LaTeX fragment at point, or all locally or globally.
16909 If the cursor is in a LaTeX fragment, create the image and overlay
16910 it over the source code. If there is no fragment at point, display
16911 all fragments in the current text, from one headline to the next. With
16912 prefix SUBTREE, display all fragments in the current subtree. With a
16913 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16914 the cursor is before the first headline,
16915 display all fragments in the buffer.
16916 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16918 (unless buffer-file-name
16919 (error "Can't preview LaTeX fragment in a non-file buffer"))
16920 (org-remove-latex-fragment-image-overlays)
16923 (let (beg end at msg)
16925 ((or (equal subtree '(16))
16926 (not (save-excursion
16927 (re-search-backward org-outline-regexp-bol nil t))))
16928 (setq beg (point-min) end (point-max)
16929 msg "Creating images for buffer...%s"))
16930 ((equal subtree '(4))
16931 (org-back-to-heading)
16932 (setq beg (point) end (org-end-of-subtree t)
16933 msg "Creating images for subtree...%s"))
16935 (if (setq at (org-inside-LaTeX-fragment-p))
16936 (goto-char (max (point-min) (- (cdr at) 2)))
16937 (org-back-to-heading))
16938 (setq beg (point) end (progn (outline-next-heading) (point))
16939 msg (if at "Creating image...%s"
16940 "Creating images for entry...%s"))))
16942 (narrow-to-region beg end)
16945 (concat "ltxpng/" (file-name-sans-extension
16946 (file-name-nondirectory
16947 buffer-file-name)))
16948 default-directory 'overlays msg at 'forbuffer
16949 org-latex-create-formula-image-program)
16950 (message msg "done. Use `C-c C-c' to remove images.")))))
16952 (defvar org-latex-regexps
16953 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16954 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16955 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16956 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16957 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16958 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16959 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16960 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16961 "Regular expressions for matching embedded LaTeX.")
16963 (defvar org-export-have-math nil) ;; dynamic scoping
16964 (defun org-format-latex (prefix &optional dir overlays msg at
16965 forbuffer processing-type)
16966 "Replace LaTeX fragments with links to an image, and produce images.
16967 Some of the options can be changed using the variable
16968 `org-format-latex-options'."
16969 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16970 (let* ((prefixnodir (file-name-nondirectory prefix))
16971 (absprefix (expand-file-name prefix dir))
16972 (todir (file-name-directory absprefix))
16973 (opt org-format-latex-options)
16974 (matchers (plist-get opt :matchers))
16975 (re-list org-latex-regexps)
16976 (org-format-latex-header-extra
16977 (plist-get (org-infile-export-plist) :latex-header-extra))
16978 (cnt 0) txt hash link beg end re e checkdir
16979 executables-checked string
16980 m n block-type block linkfile movefile ov)
16981 ;; Check the different regular expressions
16982 (while (setq e (pop re-list))
16983 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16984 block (if block-type "\n\n" ""))
16985 (when (member m matchers)
16986 (goto-char (point-min))
16987 (while (re-search-forward re nil t)
16988 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16989 (not (get-text-property (match-beginning n)
16992 (not (eq (get-char-property (match-beginning n)
16994 'org-latex-overlay))))
16995 (setq org-export-have-math t)
16997 ((eq processing-type 'verbatim)
16998 ;; Leave the text verbatim, just protect it
16999 (add-text-properties (match-beginning n) (match-end n)
17000 '(org-protected t)))
17001 ((eq processing-type 'mathjax)
17002 ;; Prepare for MathJax processing
17003 (setq string (match-string n))
17004 (if (member m '("$" "$1"))
17006 (delete-region (match-beginning n) (match-end n))
17007 (goto-char (match-beginning n))
17008 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17010 '(org-protected t))))
17011 (add-text-properties (match-beginning n) (match-end n)
17012 '(org-protected t))))
17013 ((or (eq processing-type 'dvipng)
17014 (eq processing-type 'imagemagick))
17015 ;; Process to an image
17016 (setq txt (match-string n)
17017 beg (match-beginning n) end (match-end n)
17019 (let (print-length print-level) ; make sure full list is printed
17020 (setq hash (sha1 (prin1-to-string
17021 (list org-format-latex-header
17022 org-format-latex-header-extra
17023 org-export-latex-default-packages-alist
17024 org-export-latex-packages-alist
17025 org-format-latex-options
17027 linkfile (format "%s_%s.png" prefix hash)
17028 movefile (format "%s_%s.png" absprefix hash)))
17029 (setq link (concat block "[[file:" linkfile "]]" block))
17030 (if msg (message msg cnt))
17032 (unless checkdir ; make sure the directory exists
17034 (or (file-directory-p todir) (make-directory todir t)))
17036 ((eq processing-type 'dvipng)
17037 (unless executables-checked
17038 (org-check-external-command
17039 "latex" "needed to convert LaTeX fragments to images")
17040 (org-check-external-command
17041 "dvipng" "needed to convert LaTeX fragments to images")
17042 (setq executables-checked t))
17043 (unless (file-exists-p movefile)
17044 (org-create-formula-image-with-dvipng
17045 txt movefile opt forbuffer)))
17046 ((eq processing-type 'imagemagick)
17047 (unless executables-checked
17048 (org-check-external-command
17049 "convert" "you need to install imagemagick")
17050 (setq executables-checked t))
17051 (unless (file-exists-p movefile)
17052 (org-create-formula-image-with-imagemagick
17053 txt movefile opt forbuffer))))
17057 (if (eq (overlay-get o 'org-overlay-type)
17058 'org-latex-overlay)
17059 (delete-overlay o)))
17060 (overlays-in beg end))
17061 (setq ov (make-overlay beg end))
17062 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17063 (if (featurep 'xemacs)
17065 (overlay-put ov 'invisible t)
17068 (make-glyph (vector 'png :file movefile))))
17071 (list 'image :type 'png :file movefile :ascent 'center)))
17072 (push ov org-latex-fragment-image-overlays)
17074 (delete-region beg end)
17075 (insert (org-add-props link
17076 (list 'org-latex-src
17077 (replace-regexp-in-string
17079 'org-latex-src-embed-type
17080 (if block-type 'paragraph 'character))))))
17081 ((eq processing-type 'mathml)
17082 ;; Process to MathML
17083 (unless executables-checked
17084 (unless (save-match-data (org-format-latex-mathml-available-p))
17085 (error "LaTeX to MathML converter not configured"))
17086 (setq executables-checked t))
17087 (setq txt (match-string n)
17088 beg (match-beginning n) end (match-end n)
17090 (if msg (message msg cnt))
17092 (delete-region beg end)
17093 (insert (org-format-latex-as-mathml
17094 txt block-type prefix dir)))
17096 (error "Unknown conversion type %s for latex fragments"
17097 processing-type)))))))))
17099 (defun org-create-math-formula (latex-frag &optional mathml-file)
17100 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17101 Use `org-latex-to-mathml-convert-command'. If the conversion is
17102 sucessful, return the portion between \"<math...> </math>\"
17103 elements otherwise return nil. When MATHML-FILE is specified,
17104 write the results in to that file. When invoked as an
17105 interactive command, prompt for LATEX-FRAG, with initial value
17106 set to the current active region and echo the results for user
17108 (interactive (list (let ((frag (when (region-active-p)
17109 (buffer-substring-no-properties
17110 (region-beginning) (region-end)))))
17111 (read-string "LaTeX Fragment: " frag nil frag))))
17112 (unless latex-frag (error "Invalid latex-frag"))
17113 (let* ((tmp-in-file (file-relative-name
17114 (make-temp-name (expand-file-name "ltxmathml-in"))))
17115 (ignore (write-region latex-frag nil tmp-in-file))
17116 (tmp-out-file (file-relative-name
17117 (make-temp-name (expand-file-name "ltxmathml-out"))))
17119 org-latex-to-mathml-convert-command
17120 `((?j . ,(shell-quote-argument
17121 (expand-file-name org-latex-to-mathml-jar-file)))
17122 (?I . ,(shell-quote-argument tmp-in-file))
17123 (?o . ,(shell-quote-argument tmp-out-file)))))
17124 mathml shell-command-output)
17125 (when (org-called-interactively-p 'any)
17126 (unless (org-format-latex-mathml-available-p)
17127 (error "LaTeX to MathML converter not configured")))
17128 (message "Running %s" cmd)
17129 (setq shell-command-output (shell-command-to-string cmd))
17131 (when (file-readable-p tmp-out-file)
17132 (with-current-buffer (find-file-noselect tmp-out-file t)
17133 (goto-char (point-min))
17134 (when (re-search-forward
17137 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17139 (regexp-quote "</math>")) nil t)
17140 (prog1 (match-string 0) (kill-buffer))))))
17144 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17146 (write-region mathml nil mathml-file))
17147 (when (org-called-interactively-p 'any)
17149 ((message "LaTeX to MathML conversion failed")
17150 (message shell-command-output)))
17151 (delete-file tmp-in-file)
17152 (when (file-exists-p tmp-out-file)
17153 (delete-file tmp-out-file))
17156 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17157 prefix &optional dir)
17158 "Use `org-create-math-formula' but check local cache first."
17159 (let* ((absprefix (expand-file-name prefix dir))
17160 (print-length nil) (print-level nil)
17161 (formula-id (concat
17166 org-latex-to-mathml-convert-command)))))
17167 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17168 (formula-cache-dir (file-name-directory formula-cache)))
17170 (unless (file-directory-p formula-cache-dir)
17171 (make-directory formula-cache-dir t))
17173 (unless (file-exists-p formula-cache)
17174 (org-create-math-formula latex-frag formula-cache))
17176 (if (file-exists-p formula-cache)
17177 ;; Successful conversion. Return the link to MathML file.
17179 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17180 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17181 'org-latex-src-embed-type (if latex-frag-type
17182 'paragraph 'character)))
17183 ;; Failed conversion. Return the LaTeX fragment verbatim
17184 (add-text-properties
17185 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17188 ;; This function borrows from Ganesh Swami's latex2png.el
17189 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17190 "This calls dvipng."
17191 (require 'org-latex)
17192 (let* ((tmpdir (if (featurep 'xemacs)
17194 temporary-file-directory))
17195 (texfilebase (make-temp-name
17196 (expand-file-name "orgtex" tmpdir)))
17197 (texfile (concat texfilebase ".tex"))
17198 (dvifile (concat texfilebase ".dvi"))
17199 (pngfile (concat texfilebase ".png"))
17200 (fnh (if (featurep 'xemacs)
17201 (font-height (face-font 'default))
17202 (face-attribute 'default :height nil)))
17203 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17204 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17205 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17207 (bg (or (plist-get options (if buffer :background :html-background))
17209 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17210 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17211 (with-temp-file texfile
17212 (insert (org-splice-latex-header
17213 org-format-latex-header
17214 org-export-latex-default-packages-alist
17215 org-export-latex-packages-alist t
17216 org-format-latex-header-extra))
17217 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17218 (require 'org-latex)
17219 (org-export-latex-fix-inputenc))
17220 (let ((dir default-directory))
17221 (condition-case nil
17224 (call-process "latex" nil nil nil texfile))
17227 (if (not (file-exists-p dvifile))
17228 (progn (message "Failed to create dvi file from %s" texfile) nil)
17229 (condition-case nil
17230 (if (featurep 'xemacs)
17231 (call-process "dvipng" nil nil nil
17236 (call-process "dvipng" nil nil nil
17239 ;;"-x" scale "-y" scale
17244 (if (not (file-exists-p pngfile))
17245 (if org-format-latex-signal-error
17246 (error "Failed to create png file from %s" texfile)
17247 (message "Failed to create png file from %s" texfile)
17249 ;; Use the requested file name and clean up
17250 (copy-file pngfile tofile 'replace)
17251 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17252 (delete-file (concat texfilebase e)))
17255 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17256 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17257 "This calls convert, which is included into imagemagick."
17258 (require 'org-latex)
17259 (let* ((tmpdir (if (featurep 'xemacs)
17261 temporary-file-directory))
17262 (texfilebase (make-temp-name
17263 (expand-file-name "orgtex" tmpdir)))
17264 (texfile (concat texfilebase ".tex"))
17265 (pdffile (concat texfilebase ".pdf"))
17266 (pngfile (concat texfilebase ".png"))
17267 (fnh (if (featurep 'xemacs)
17268 (font-height (face-font 'default))
17269 (face-attribute 'default :height nil)))
17270 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17271 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17272 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17274 (bg (or (plist-get options (if buffer :background :html-background))
17276 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17277 (setq fg (org-latex-color-format fg)))
17278 (if (eq bg 'default) (setq bg (org-latex-color :background))
17279 (setq bg (org-latex-color-format
17280 (if (string= bg "Transparent")(setq bg "white")))))
17281 (with-temp-file texfile
17282 (insert (org-splice-latex-header
17283 org-format-latex-header
17284 org-export-latex-default-packages-alist
17285 org-export-latex-packages-alist t
17286 org-format-latex-header-extra))
17287 (insert "\n\\begin{document}\n"
17288 "\\definecolor{fg}{rgb}{" fg "}\n"
17289 "\\definecolor{bg}{rgb}{" bg "}\n"
17290 "\n\\pagecolor{bg}\n"
17294 "\n\\end{document}\n" )
17295 (require 'org-latex)
17296 (org-export-latex-fix-inputenc))
17297 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17298 (condition-case nil
17301 (setq cmds org-latex-to-pdf-process)
17303 (setq latex-frags-cmds (pop cmds))
17304 (if (listp latex-frags-cmds)
17306 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17307 (while latex-frags-cmds
17308 (setq cmd (pop latex-frags-cmds))
17309 (while (string-match "%b" cmd)
17310 (setq cmd (replace-match
17312 (shell-quote-argument texfile))
17314 (while (string-match "%f" cmd)
17315 (setq cmd (replace-match
17317 (shell-quote-argument (file-name-nondirectory texfile)))
17319 (while (string-match "%o" cmd)
17320 (setq cmd (replace-match
17322 (shell-quote-argument (file-name-directory texfile)))
17324 (setq cmd (split-string cmd))
17325 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17328 (if (not (file-exists-p pdffile))
17329 (progn (message "Failed to create pdf file from %s" texfile) nil)
17330 (condition-case nil
17331 (if (featurep 'xemacs)
17332 (call-process "convert" nil nil nil
17338 ;; "-sharpen" "0x1.0"
17340 (call-process "convert" nil nil nil
17346 ; "-sharpen" "0x1.0"
17349 (if (not (file-exists-p pngfile))
17350 (if org-format-latex-signal-error
17351 (error "Failed to create png file from %s" texfile)
17352 (message "Failed to create png file from %s" texfile)
17354 ;; Use the requested file name and clean up
17355 (copy-file pngfile tofile 'replace)
17356 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17357 (delete-file (concat texfilebase e)))
17360 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17361 "Fill a LaTeX header template TPL.
17362 In the template, the following place holders will be recognized:
17364 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17365 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17366 [PACKAGES] \\usepackage statements for PKG
17367 [NO-PACKAGES] do not include PKG
17368 [EXTRA] the string EXTRA
17369 [NO-EXTRA] do not include EXTRA
17371 For backward compatibility, if both the positive and the negative place
17372 holder is missing, the positive one (without the \"NO-\") will be
17373 assumed to be present at the end of the template.
17374 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17376 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17377 (let (rpl (end ""))
17378 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17379 (setq rpl (if (or (match-end 1) (not def-pkg))
17380 "" (org-latex-packages-to-string def-pkg snippets-p t))
17381 tpl (replace-match rpl t t tpl))
17382 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17384 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17385 (setq rpl (if (or (match-end 1) (not pkg))
17386 "" (org-latex-packages-to-string pkg snippets-p t))
17387 tpl (replace-match rpl t t tpl))
17390 (org-latex-packages-to-string pkg snippets-p)))))
17392 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17393 (setq rpl (if (or (match-end 1) (not extra))
17394 "" (concat extra "\n"))
17395 tpl (replace-match rpl t t tpl))
17396 (if (and extra (string-match "\\S-" extra))
17397 (setq end (concat end "\n" extra))))
17399 (if (string-match "\\S-" end)
17400 (concat tpl "\n" end)
17403 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17404 "Turn an alist of packages into a string with the \\usepackage macros."
17405 (setq pkg (mapconcat (lambda(p)
17408 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17409 (format "%% Package %s omitted" (cadr p)))
17410 ((equal "" (car p))
17411 (format "\\usepackage{%s}" (cadr p)))
17413 (format "\\usepackage[%s]{%s}"
17414 (car p) (cadr p)))))
17417 (if newline (concat pkg "\n") pkg))
17419 (defun org-dvipng-color (attr)
17420 "Return a RGB color specification for dvipng."
17421 (apply 'format "rgb %s %s %s"
17422 (mapcar 'org-normalize-color
17423 (if (featurep 'xemacs)
17424 (color-rgb-components
17425 (face-property 'default
17426 (cond ((eq attr :foreground) 'foreground)
17427 ((eq attr :background) 'background))))
17428 (color-values (face-attribute 'default attr nil))))))
17430 (defun org-latex-color (attr)
17431 "Return a RGB color for the LaTeX color package."
17432 (apply 'format "%s,%s,%s"
17433 (mapcar 'org-normalize-color
17434 (if (featurep 'xemacs)
17435 (color-rgb-components
17436 (face-property 'default
17437 (cond ((eq attr :foreground) 'foreground)
17438 ((eq attr :background) 'background))))
17439 (color-values (face-attribute 'default attr nil))))))
17441 (defun org-latex-color-format (color-name)
17442 "Convert COLOR-NAME to a RGB color value."
17443 (apply 'format "%s,%s,%s"
17444 (mapcar 'org-normalize-color
17445 (color-values color-name))))
17447 (defun org-normalize-color (value)
17448 "Return string to be used as color value for an RGB component."
17449 (format "%g" (/ value 65535.0)))
17454 (defvar org-inline-image-overlays nil)
17455 (make-variable-buffer-local 'org-inline-image-overlays)
17457 (defun org-toggle-inline-images (&optional include-linked)
17458 "Toggle the display of inline images.
17459 INCLUDE-LINKED is passed to `org-display-inline-images'."
17461 (if org-inline-image-overlays
17463 (org-remove-inline-images)
17464 (message "Inline image display turned off"))
17465 (org-display-inline-images include-linked)
17466 (if org-inline-image-overlays
17467 (message "%d images displayed inline"
17468 (length org-inline-image-overlays))
17469 (message "No images to display inline"))))
17471 (defun org-display-inline-images (&optional include-linked refresh beg end)
17472 "Display inline images.
17473 Normally only links without a description part are inlined, because this
17474 is how it will work for export. When INCLUDE-LINKED is set, also links
17475 with a description part will be inlined. This can be nice for a quick
17476 look at those images, but it does not reflect what exported files will look
17478 When REFRESH is set, refresh existing images between BEG and END.
17479 This will create new image displays only if necessary.
17480 BEG and END default to the buffer boundaries."
17483 (org-remove-inline-images)
17484 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17488 (setq beg (or beg (point-min)) end (or end (point-max)))
17490 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17491 (substring (org-image-file-name-regexp) 0 -2)
17492 "\\)\\]" (if include-linked "" "\\]")))
17494 (while (re-search-forward re end t)
17495 (setq old (get-char-property-and-overlay (match-beginning 1)
17496 'org-image-overlay))
17497 (setq file (expand-file-name
17498 (concat (or (match-string 3) "") (match-string 4))))
17499 (when (file-exists-p file)
17500 (if (and (car-safe old) refresh)
17501 (image-refresh (overlay-get (cdr old) 'display))
17502 (setq img (save-match-data (create-image file)))
17504 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17505 (overlay-put ov 'display img)
17506 (overlay-put ov 'face 'default)
17507 (overlay-put ov 'org-image-overlay t)
17508 (overlay-put ov 'modification-hooks
17509 (list 'org-display-inline-modification-hook))
17510 (push ov org-inline-image-overlays)))))))))
17512 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17513 "Remove inline-display overlay if a corresponding region is modified."
17514 (let ((inhibit-modification-hooks t))
17515 (when (and ov after)
17516 (delete ov org-inline-image-overlays)
17517 (delete-overlay ov))))
17519 (defun org-remove-inline-images ()
17520 "Remove inline display of images."
17522 (mapc 'delete-overlay org-inline-image-overlays)
17523 (setq org-inline-image-overlays nil))
17527 ;; Outline functions from `outline-mode-prefix-map'
17528 ;; that can be remapped in Org:
17529 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17530 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17531 (define-key org-mode-map [remap outline-forward-same-level]
17532 'org-forward-same-level)
17533 (define-key org-mode-map [remap outline-backward-same-level]
17534 'org-backward-same-level)
17535 (define-key org-mode-map [remap show-branches]
17536 'org-kill-note-or-show-branches)
17537 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17538 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17539 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17541 ;; Outline functions from `outline-mode-prefix-map'
17542 ;; that can not be remapped in Org:
17543 ;; - the column "key binding" shows whether the Outline function is still
17544 ;; available in Org mode on the same key that it has been bound to in
17546 ;; - "overridden": key used for a different functionality in Org mode
17547 ;; - else: key still bound to the same Outline function in Org mode
17548 ;; | Outline function | key binding | Org replacement |
17549 ;; |------------------------------------+-------------+-----------------------|
17550 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17551 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17552 ;; | `show-children' | `C-c C-i' | visibility cycling |
17553 ;; | `hide-subtree' | overridden | visibility cycling |
17554 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17555 ;; | `hide-body' | overridden | no replacement |
17556 ;; | `show-all' | overridden | no replacement |
17557 ;; | `hide-entry' | overridden | visibility cycling |
17558 ;; | `show-entry' | overridden | no replacement |
17559 ;; | `hide-leaves' | overridden | no replacement |
17560 ;; | `hide-sublevels' | overridden | no replacement |
17561 ;; | `hide-other' | overridden | no replacement |
17562 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17563 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17565 ;; Make `C-c C-x' a prefix key
17566 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17568 ;; TAB key with modifiers
17569 (org-defkey org-mode-map "\C-i" 'org-cycle)
17570 (org-defkey org-mode-map [(tab)] 'org-cycle)
17571 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17572 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17573 ;; The following line is necessary under Suse GNU/Linux
17574 (unless (featurep 'xemacs)
17575 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17576 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17577 (define-key org-mode-map [backtab] 'org-shifttab)
17579 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17580 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17581 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17583 ;; Cursor keys with modifiers
17584 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17585 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17586 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17587 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17589 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17590 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17591 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17592 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17594 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17595 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17596 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17597 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17599 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17600 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17601 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17602 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17605 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17606 (mapc (lambda (pair)
17607 (define-key org-babel-map (car pair) (cdr pair)))
17608 org-babel-key-bindings)
17610 ;;; Extra keys for tty access.
17611 ;; We only set them when really needed because otherwise the
17612 ;; menus don't show the simple keys
17614 (when (or org-use-extra-keys
17615 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17616 (not window-system))
17617 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17618 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17619 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17620 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17621 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17622 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17623 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17624 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17625 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17626 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17627 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17628 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17629 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17630 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17631 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17632 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17633 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17634 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17635 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17636 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17637 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17638 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17639 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17640 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17641 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17642 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17643 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17644 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17646 ;; All the other keys
17648 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17649 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17650 (if (boundp 'narrow-map)
17651 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17652 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17653 (if (boundp 'narrow-map)
17654 (org-defkey narrow-map "b" 'org-narrow-to-block)
17655 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17656 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17657 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17658 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17659 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17660 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17661 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17662 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17663 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17664 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17665 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17666 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17667 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17668 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17669 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17670 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17671 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17672 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17673 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17674 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17675 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17676 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17677 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17678 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17679 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17680 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17681 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17682 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17683 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17684 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17685 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17686 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17687 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17688 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17689 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17690 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17691 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17692 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17693 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17694 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17695 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17696 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17697 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17698 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17699 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17700 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17701 (org-defkey org-mode-map "\C-c^" 'org-sort)
17702 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17703 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17704 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17705 (org-defkey org-mode-map "\C-m" 'org-return)
17706 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17707 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17708 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17709 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17710 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17711 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17712 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17713 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17714 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17715 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17716 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17717 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17718 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17719 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17720 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17721 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17722 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17723 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17724 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17725 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17726 (org-defkey org-mode-map "\C-c\C-@" 'org-mark-list)
17727 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17728 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17730 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17731 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17732 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17733 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17735 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17736 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17737 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17738 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17739 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17740 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17741 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17742 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17743 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17744 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17745 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17746 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17747 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17748 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17749 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17750 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17751 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17752 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17754 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17755 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17756 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17757 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17758 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17760 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17762 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17764 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17765 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17767 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17770 (when (featurep 'xemacs)
17771 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17774 (defconst org-speed-commands-default
17776 ("Outline Navigation")
17777 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17778 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17779 ("f" . (org-speed-move-safe 'org-forward-same-level))
17780 ("b" . (org-speed-move-safe 'org-backward-same-level))
17781 ("u" . (org-speed-move-safe 'outline-up-heading))
17783 ("g" . (org-refile t))
17784 ("Outline Visibility")
17786 ("C" . org-shifttab)
17787 (" " . org-display-outline-path)
17788 ("Outline Structure Editing")
17789 ("U" . org-shiftmetaup)
17790 ("D" . org-shiftmetadown)
17791 ("r" . org-metaright)
17792 ("l" . org-metaleft)
17793 ("R" . org-shiftmetaright)
17794 ("L" . org-shiftmetaleft)
17795 ("i" . (progn (forward-char 1) (call-interactively
17796 'org-insert-heading-respect-content)))
17799 ("a" . org-archive-subtree-default-with-confirmation)
17800 ("." . org-mark-subtree)
17802 ("I" . org-clock-in)
17803 ("O" . org-clock-out)
17804 ("Meta Data Editing")
17806 ("0" . (org-priority ?\ ))
17807 ("1" . (org-priority ?A))
17808 ("2" . (org-priority ?B))
17809 ("3" . (org-priority ?C))
17810 (";" . org-set-tags-command)
17811 ("e" . org-set-effort)
17812 ("Agenda Views etc")
17814 ("/" . org-sparse-tree)
17816 ("o" . org-open-at-point)
17817 ("?" . org-speed-command-help)
17818 ("<" . (org-agenda-set-restriction-lock 'subtree))
17819 (">" . (org-agenda-remove-restriction-lock))
17821 "The default speed commands.")
17823 (defun org-print-speed-command (e)
17824 (if (> (length (car e)) 1)
17829 (princ (make-string (length (car e)) ?-))
17833 (if (symbolp (cdr e))
17834 (princ (symbol-name (cdr e)))
17838 (defun org-speed-command-help ()
17839 "Show the available speed commands."
17841 (if (not org-use-speed-commands)
17842 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17843 (with-output-to-temp-buffer "*Help*"
17844 (princ "User-defined Speed commands\n===========================\n")
17845 (mapc 'org-print-speed-command org-speed-commands-user)
17847 (princ "Built-in Speed commands\n=======================\n")
17848 (mapc 'org-print-speed-command org-speed-commands-default))
17849 (with-current-buffer "*Help*"
17850 (setq truncate-lines t))))
17852 (defun org-speed-move-safe (cmd)
17853 "Execute CMD, but make sure that the cursor always ends up in a headline.
17854 If not, return to the original position and throw an error."
17856 (let ((pos (point)))
17857 (call-interactively cmd)
17858 (unless (and (bolp) (org-at-heading-p))
17860 (error "Boundary reached while executing %s" cmd))))
17862 (defvar org-self-insert-command-undo-counter 0)
17864 (defvar org-table-auto-blank-field) ; defined in org-table.el
17865 (defvar org-speed-command nil)
17867 (defun org-speed-command-default-hook (keys)
17868 "Hook for activating single-letter speed commands.
17869 `org-speed-commands-default' specifies a minimal command set.
17870 Use `org-speed-commands-user' for further customization."
17871 (when (or (and (bolp) (looking-at org-outline-regexp))
17872 (and (functionp org-use-speed-commands)
17873 (funcall org-use-speed-commands)))
17874 (cdr (assoc keys (append org-speed-commands-user
17875 org-speed-commands-default)))))
17877 (defun org-babel-speed-command-hook (keys)
17878 "Hook for activating single-letter code block commands."
17879 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17880 (cdr (assoc keys org-babel-key-bindings))))
17882 (defcustom org-speed-command-hook
17883 '(org-speed-command-default-hook org-babel-speed-command-hook)
17884 "Hook for activating speed commands at strategic locations.
17885 Hook functions are called in sequence until a valid handler is
17888 Each hook takes a single argument, a user-pressed command key
17889 which is also a `self-insert-command' from the global map.
17891 Within the hook, examine the cursor position and the command key
17892 and return nil or a valid handler as appropriate. Handler could
17893 be one of an interactive command, a function, or a form.
17895 Set `org-use-speed-commands' to non-nil value to enable this
17896 hook. The default setting is `org-speed-command-default-hook'."
17897 :group 'org-structure
17901 (defun org-self-insert-command (N)
17902 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17903 If the cursor is in a table looking at whitespace, the whitespace is
17904 overwritten, and the table is not marked as requiring realignment."
17906 (org-check-before-invisible-edit 'insert)
17908 ((and org-use-speed-commands
17909 (setq org-speed-command
17910 (run-hook-with-args-until-success
17911 'org-speed-command-hook (this-command-keys))))
17913 ((commandp org-speed-command)
17914 (setq this-command org-speed-command)
17915 (call-interactively org-speed-command))
17916 ((functionp org-speed-command)
17917 (funcall org-speed-command))
17918 ((and org-speed-command (listp org-speed-command))
17919 (eval org-speed-command))
17920 (t (let (org-use-speed-commands)
17921 (call-interactively 'org-self-insert-command)))))
17925 ;; check if we blank the field, and if that triggers align
17926 (and (featurep 'org-table) org-table-auto-blank-field
17927 (member last-command
17928 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17929 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17930 ;; got extra space, this field does not determine column width
17931 (let (org-table-may-need-update) (org-table-blank-field))
17932 ;; no extra space, this field may determine column width
17933 (org-table-blank-field)))
17936 (looking-at "[^|\n]* |"))
17937 (let (org-table-may-need-update)
17938 (goto-char (1- (match-end 0)))
17939 (backward-delete-char 1)
17940 (goto-char (match-beginning 0))
17941 (self-insert-command N)))
17943 (setq org-table-may-need-update t)
17944 (self-insert-command N)
17945 (org-fix-tags-on-the-fly)
17946 (if org-self-insert-cluster-for-undo
17947 (if (not (eq last-command 'org-self-insert-command))
17948 (setq org-self-insert-command-undo-counter 1)
17949 (if (>= org-self-insert-command-undo-counter 20)
17950 (setq org-self-insert-command-undo-counter 1)
17951 (and (> org-self-insert-command-undo-counter 0)
17952 buffer-undo-list (listp buffer-undo-list)
17953 (not (cadr buffer-undo-list)) ; remove nil entry
17954 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17955 (setq org-self-insert-command-undo-counter
17956 (1+ org-self-insert-command-undo-counter))))))))
17958 (defun org-check-before-invisible-edit (kind)
17959 "Check is editing if kind KIND would be dangerous with invisible text around.
17960 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17961 ;; First, try to get out of here as quickly as possible, to reduce overhead
17962 (if (and org-catch-invisible-edits
17963 (or (not (boundp 'visible-mode)) (not visible-mode))
17964 (or (get-char-property (point) 'invisible)
17965 (get-char-property (max (point-min) (1- (point))) 'invisible)))
17966 ;; OK, we need to take a closer look
17967 (let* ((invisible-at-point (get-char-property (point) 'invisible))
17968 (invisible-before-point (if (bobp) nil (get-char-property
17969 (1- (point)) 'invisible)))
17970 (border-and-ok-direction
17972 ;; Check if we are acting predictably before invisible text
17973 (and invisible-at-point (not invisible-before-point)
17974 (memq kind '(insert delete-backward)))
17975 ;; Check if we are acting predictably after invisible text
17976 ;; This works not well, and I have turned it off. It seems
17977 ;; better to always show and stop after invisible text.
17978 ;; (and (not invisible-at-point) invisible-before-point
17979 ;; (memq kind '(insert delete)))
17982 (when (or (memq invisible-at-point '(outline org-hide-block))
17983 (memq invisible-before-point '(outline org-hide-block)))
17984 (if (eq org-catch-invisible-edits 'error)
17985 (error "Editing in invisible areas is prohibited - make visible first"))
17986 ;; Make the area visible
17988 (if invisible-before-point
17989 (goto-char (previous-single-char-property-change
17990 (point) 'invisible)))
17993 ((eq org-catch-invisible-edits 'show)
17994 ;; That's it, we do the edit after showing
17996 "Unfolding invisible region around point before editing")
17998 ((and (eq org-catch-invisible-edits 'smart)
17999 border-and-ok-direction)
18000 (message "Unfolding invisible region around point before editing"))
18002 ;; Don't do the edit, make the user repeat it in full visibility
18003 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
18005 (defun org-fix-tags-on-the-fly ()
18006 (when (and (equal (char-after (point-at-bol)) ?*)
18007 (org-at-heading-p))
18008 (org-align-tags-here org-tags-column)))
18010 (defun org-delete-backward-char (N)
18011 "Like `delete-backward-char', insert whitespace at field end in tables.
18012 When deleting backwards, in tables this function will insert whitespace in
18013 front of the next \"|\" separator, to keep the table aligned. The table will
18014 still be marked for re-alignment if the field did fill the entire column,
18015 because, in this case the deletion might narrow the column."
18017 (org-check-before-invisible-edit 'delete-backward)
18018 (if (and (org-table-p)
18020 (string-match "|" (buffer-substring (point-at-bol) (point)))
18021 (looking-at ".*?|"))
18022 (let ((pos (point))
18023 (noalign (looking-at "[^|\n\r]* |"))
18024 (c org-table-may-need-update))
18025 (backward-delete-char N)
18026 (if (not overwrite-mode)
18028 (skip-chars-forward "^|")
18030 (goto-char (1- pos))))
18031 ;; noalign: if there were two spaces at the end, this field
18032 ;; does not determine the width of the column.
18033 (if noalign (setq org-table-may-need-update c)))
18034 (backward-delete-char N)
18035 (org-fix-tags-on-the-fly)))
18037 (defun org-delete-char (N)
18038 "Like `delete-char', but insert whitespace at field end in tables.
18039 When deleting characters, in tables this function will insert whitespace in
18040 front of the next \"|\" separator, to keep the table aligned. The table will
18041 still be marked for re-alignment if the field did fill the entire column,
18042 because, in this case the deletion might narrow the column."
18044 (org-check-before-invisible-edit 'delete)
18045 (if (and (org-table-p)
18047 (not (= (char-after) ?|))
18049 (if (looking-at ".*?|")
18050 (let ((pos (point))
18051 (noalign (looking-at "[^|\n\r]* |"))
18052 (c org-table-may-need-update))
18053 (replace-match (concat
18054 (substring (match-string 0) 1 -1)
18057 ;; noalign: if there were two spaces at the end, this field
18058 ;; does not determine the width of the column.
18059 (if noalign (setq org-table-may-need-update c)))
18062 (org-fix-tags-on-the-fly)))
18064 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18065 (put 'org-self-insert-command 'delete-selection t)
18066 (put 'orgtbl-self-insert-command 'delete-selection t)
18067 (put 'org-delete-char 'delete-selection 'supersede)
18068 (put 'org-delete-backward-char 'delete-selection 'supersede)
18069 (put 'org-yank 'delete-selection 'yank)
18071 ;; Make `flyspell-mode' delay after some commands
18072 (put 'org-self-insert-command 'flyspell-delayed t)
18073 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18074 (put 'org-delete-char 'flyspell-delayed t)
18075 (put 'org-delete-backward-char 'flyspell-delayed t)
18077 ;; Make pabbrev-mode expand after org-mode commands
18078 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18079 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18081 ;; How to do this: Measure non-white length of current string
18082 ;; If equal to column width, we should realign.
18084 (defun org-remap (map &rest commands)
18085 "In MAP, remap the functions given in COMMANDS.
18086 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18089 (setq old (pop commands) new (pop commands))
18090 (if (fboundp 'command-remapping)
18091 (org-defkey map (vector 'remap old) new)
18092 (substitute-key-definition old new map global-map)))))
18094 (when (eq org-enable-table-editor 'optimized)
18095 ;; If the user wants maximum table support, we need to hijack
18096 ;; some standard editing functions
18097 (org-remap org-mode-map
18098 'self-insert-command 'org-self-insert-command
18099 'delete-char 'org-delete-char
18100 'delete-backward-char 'org-delete-backward-char)
18101 (org-defkey org-mode-map "|" 'org-force-self-insert))
18103 (defvar org-ctrl-c-ctrl-c-hook nil
18104 "Hook for functions attaching themselves to `C-c C-c'.
18106 This can be used to add additional functionality to the C-c C-c
18107 key which executes context-dependent commands. This hook is run
18108 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18109 run after the last test.
18111 Each function will be called with no arguments. The function
18112 must check if the context is appropriate for it to act. If yes,
18113 it should do its thing and then return a non-nil value. If the
18114 context is wrong, just do nothing and return nil.")
18116 (defvar org-ctrl-c-ctrl-c-final-hook nil
18117 "Hook for functions attaching themselves to `C-c C-c'.
18119 This can be used to add additional functionality to the C-c C-c
18120 key which executes context-dependent commands. This hook is run
18121 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18122 before the first test.
18124 Each function will be called with no arguments. The function
18125 must check if the context is appropriate for it to act. If yes,
18126 it should do its thing and then return a non-nil value. If the
18127 context is wrong, just do nothing and return nil.")
18129 (defvar org-tab-first-hook nil
18130 "Hook for functions to attach themselves to TAB.
18131 See `org-ctrl-c-ctrl-c-hook' for more information.
18132 This hook runs as the first action when TAB is pressed, even before
18133 `org-cycle' messes around with the `outline-regexp' to cater for
18134 inline tasks and plain list item folding.
18135 If any function in this hook returns t, any other actions that
18136 would have been caused by TAB (such as table field motion or visibility
18137 cycling) will not occur.")
18139 (defvar org-tab-after-check-for-table-hook nil
18140 "Hook for functions to attach themselves to TAB.
18141 See `org-ctrl-c-ctrl-c-hook' for more information.
18142 This hook runs after it has been established that the cursor is not in a
18143 table, but before checking if the cursor is in a headline or if global cycling
18145 If any function in this hook returns t, not other actions like visibility
18146 cycling will be done.")
18148 (defvar org-tab-after-check-for-cycling-hook nil
18149 "Hook for functions to attach themselves to TAB.
18150 See `org-ctrl-c-ctrl-c-hook' for more information.
18151 This hook runs after it has been established that not table field motion and
18152 not visibility should be done because of current context. This is probably
18153 the place where a package like yasnippets can hook in.")
18155 (defvar org-tab-before-tab-emulation-hook nil
18156 "Hook for functions to attach themselves to TAB.
18157 See `org-ctrl-c-ctrl-c-hook' for more information.
18158 This hook runs after every other options for TAB have been exhausted, but
18159 before indentation and \t insertion takes place.")
18161 (defvar org-metaleft-hook nil
18162 "Hook for functions attaching themselves to `M-left'.
18163 See `org-ctrl-c-ctrl-c-hook' for more information.")
18164 (defvar org-metaright-hook nil
18165 "Hook for functions attaching themselves to `M-right'.
18166 See `org-ctrl-c-ctrl-c-hook' for more information.")
18167 (defvar org-metaup-hook nil
18168 "Hook for functions attaching themselves to `M-up'.
18169 See `org-ctrl-c-ctrl-c-hook' for more information.")
18170 (defvar org-metadown-hook nil
18171 "Hook for functions attaching themselves to `M-down'.
18172 See `org-ctrl-c-ctrl-c-hook' for more information.")
18173 (defvar org-shiftmetaleft-hook nil
18174 "Hook for functions attaching themselves to `M-S-left'.
18175 See `org-ctrl-c-ctrl-c-hook' for more information.")
18176 (defvar org-shiftmetaright-hook nil
18177 "Hook for functions attaching themselves to `M-S-right'.
18178 See `org-ctrl-c-ctrl-c-hook' for more information.")
18179 (defvar org-shiftmetaup-hook nil
18180 "Hook for functions attaching themselves to `M-S-up'.
18181 See `org-ctrl-c-ctrl-c-hook' for more information.")
18182 (defvar org-shiftmetadown-hook nil
18183 "Hook for functions attaching themselves to `M-S-down'.
18184 See `org-ctrl-c-ctrl-c-hook' for more information.")
18185 (defvar org-metareturn-hook nil
18186 "Hook for functions attaching themselves to `M-RET'.
18187 See `org-ctrl-c-ctrl-c-hook' for more information.")
18188 (defvar org-shiftup-hook nil
18189 "Hook for functions attaching themselves to `S-up'.
18190 See `org-ctrl-c-ctrl-c-hook' for more information.")
18191 (defvar org-shiftup-final-hook nil
18192 "Hook for functions attaching themselves to `S-up'.
18193 This one runs after all other options except shift-select have been excluded.
18194 See `org-ctrl-c-ctrl-c-hook' for more information.")
18195 (defvar org-shiftdown-hook nil
18196 "Hook for functions attaching themselves to `S-down'.
18197 See `org-ctrl-c-ctrl-c-hook' for more information.")
18198 (defvar org-shiftdown-final-hook nil
18199 "Hook for functions attaching themselves to `S-down'.
18200 This one runs after all other options except shift-select have been excluded.
18201 See `org-ctrl-c-ctrl-c-hook' for more information.")
18202 (defvar org-shiftleft-hook nil
18203 "Hook for functions attaching themselves to `S-left'.
18204 See `org-ctrl-c-ctrl-c-hook' for more information.")
18205 (defvar org-shiftleft-final-hook nil
18206 "Hook for functions attaching themselves to `S-left'.
18207 This one runs after all other options except shift-select have been excluded.
18208 See `org-ctrl-c-ctrl-c-hook' for more information.")
18209 (defvar org-shiftright-hook nil
18210 "Hook for functions attaching themselves to `S-right'.
18211 See `org-ctrl-c-ctrl-c-hook' for more information.")
18212 (defvar org-shiftright-final-hook nil
18213 "Hook for functions attaching themselves to `S-right'.
18214 This one runs after all other options except shift-select have been excluded.
18215 See `org-ctrl-c-ctrl-c-hook' for more information.")
18217 (defun org-modifier-cursor-error ()
18218 "Throw an error, a modified cursor command was applied in wrong context."
18219 (error "This command is active in special context like tables, headlines or items"))
18221 (defun org-shiftselect-error ()
18222 "Throw an error because Shift-Cursor command was applied in wrong context."
18223 (if (and (boundp 'shift-select-mode) shift-select-mode)
18224 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18225 (error "This command works only in special context like headlines or timestamps")))
18227 (defun org-call-for-shift-select (cmd)
18228 (let ((this-command-keys-shift-translated t))
18229 (call-interactively cmd)))
18231 (defun org-shifttab (&optional arg)
18232 "Global visibility cycling or move to previous table field.
18233 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18235 See the individual commands for more information."
18238 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18240 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18241 (message "Content view to level: %d" arg)
18242 (org-content (prefix-numeric-value arg2))
18243 (setq org-cycle-global-status 'overview)))
18244 (t (call-interactively 'org-global-cycle))))
18246 (defun org-shiftmetaleft ()
18247 "Promote subtree or delete table column.
18248 Calls `org-promote-subtree', `org-outdent-item-tree', or
18249 `org-table-delete-column', depending on context. See the
18250 individual commands for more information."
18253 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18254 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18255 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18256 ((if (not (org-region-active-p)) (org-at-item-p)
18257 (save-excursion (goto-char (region-beginning))
18259 (call-interactively 'org-outdent-item-tree))
18260 (t (org-modifier-cursor-error))))
18262 (defun org-shiftmetaright ()
18263 "Demote subtree or insert table column.
18264 Calls `org-demote-subtree', `org-indent-item-tree', or
18265 `org-table-insert-column', depending on context. See the
18266 individual commands for more information."
18269 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18270 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18271 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18272 ((if (not (org-region-active-p)) (org-at-item-p)
18273 (save-excursion (goto-char (region-beginning))
18275 (call-interactively 'org-indent-item-tree))
18276 (t (org-modifier-cursor-error))))
18278 (defun org-shiftmetaup (&optional arg)
18279 "Move subtree up or kill table row.
18280 Calls `org-move-subtree-up' or `org-table-kill-row' or
18281 `org-move-item-up' depending on context. See the individual commands
18282 for more information."
18285 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18286 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18287 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18288 ((org-at-item-p) (call-interactively 'org-move-item-up))
18289 (t (org-modifier-cursor-error))))
18291 (defun org-shiftmetadown (&optional arg)
18292 "Move subtree down or insert table row.
18293 Calls `org-move-subtree-down' or `org-table-insert-row' or
18294 `org-move-item-down', depending on context. See the individual
18295 commands for more information."
18298 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18299 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18300 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18301 ((org-at-item-p) (call-interactively 'org-move-item-down))
18302 (t (org-modifier-cursor-error))))
18304 (defsubst org-hidden-tree-error ()
18306 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18308 (defun org-metaleft (&optional arg)
18309 "Promote heading or move table column to left.
18310 Calls `org-do-promote' or `org-table-move-column', depending on context.
18311 With no specific context, calls the Emacs default `backward-word'.
18312 See the individual commands for more information."
18315 ((run-hook-with-args-until-success 'org-metaleft-hook))
18316 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18317 ((org-with-limited-levels
18318 (or (org-at-heading-p)
18319 (and (org-region-active-p)
18321 (goto-char (region-beginning))
18322 (org-at-heading-p)))))
18323 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18324 (call-interactively 'org-do-promote))
18325 ;; At an inline task.
18326 ((org-at-heading-p)
18327 (call-interactively 'org-inlinetask-promote))
18328 ((or (org-at-item-p)
18329 (and (org-region-active-p)
18331 (goto-char (region-beginning))
18333 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18334 (call-interactively 'org-outdent-item))
18335 (t (call-interactively 'backward-word))))
18337 (defun org-metaright (&optional arg)
18338 "Demote a subtree, a list item or move table column to right.
18339 In front of a drawer or a block keyword, indent it correctly.
18340 With no specific context, calls the Emacs default `forward-word'.
18341 See the individual commands for more information."
18344 ((run-hook-with-args-until-success 'org-metaright-hook))
18345 ((org-at-table-p) (call-interactively 'org-table-move-column))
18346 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18347 ((org-at-block-p) (call-interactively 'org-indent-block))
18348 ((org-with-limited-levels
18349 (or (org-at-heading-p)
18350 (and (org-region-active-p)
18352 (goto-char (region-beginning))
18353 (org-at-heading-p)))))
18354 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18355 (call-interactively 'org-do-demote))
18356 ;; At an inline task.
18357 ((org-at-heading-p)
18358 (call-interactively 'org-inlinetask-demote))
18359 ((or (org-at-item-p)
18360 (and (org-region-active-p)
18362 (goto-char (region-beginning))
18364 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18365 (call-interactively 'org-indent-item))
18366 (t (call-interactively 'forward-word))))
18368 (defun org-check-for-hidden (what)
18369 "Check if there are hidden headlines/items in the current visual line.
18370 WHAT can be either `headlines' or `items'. If the current line is
18371 an outline or item heading and it has a folded subtree below it,
18372 this function returns t, nil otherwise."
18374 ((eq what 'headlines) org-outline-regexp-bol)
18375 ((eq what 'items) (org-item-beginning-re))
18376 (t (error "This should not happen"))))
18380 (unless (org-region-active-p)
18381 (setq beg (point-at-bol))
18382 (beginning-of-line 2)
18383 (while (and (not (eobp)) ;; this is like `next-line'
18384 (get-char-property (1- (point)) 'invisible))
18385 (beginning-of-line 2))
18388 (goto-char (point-at-eol))
18389 (setq end (max end (point)))
18390 (while (re-search-forward re end t)
18391 (if (get-char-property (match-beginning 0) 'invisible)
18395 (defun org-metaup (&optional arg)
18396 "Move subtree up or move table row up.
18397 Calls `org-move-subtree-up' or `org-table-move-row' or
18398 `org-move-item-up', depending on context. See the individual commands
18399 for more information."
18402 ((run-hook-with-args-until-success 'org-metaup-hook))
18403 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18404 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18405 ((org-at-item-p) (call-interactively 'org-move-item-up))
18406 (t (transpose-lines 1) (beginning-of-line -1))))
18408 (defun org-metadown (&optional arg)
18409 "Move subtree down or move table row down.
18410 Calls `org-move-subtree-down' or `org-table-move-row' or
18411 `org-move-item-down', depending on context. See the individual
18412 commands for more information."
18415 ((run-hook-with-args-until-success 'org-metadown-hook))
18416 ((org-at-table-p) (call-interactively 'org-table-move-row))
18417 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18418 ((org-at-item-p) (call-interactively 'org-move-item-down))
18419 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18421 (defun org-shiftup (&optional arg)
18422 "Increase item in timestamp or increase priority of current headline.
18423 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18424 depending on context. See the individual commands for more information."
18427 ((run-hook-with-args-until-success 'org-shiftup-hook))
18428 ((and org-support-shift-select (org-region-active-p))
18429 (org-call-for-shift-select 'previous-line))
18430 ((org-at-timestamp-p t)
18431 (call-interactively (if org-edit-timestamp-down-means-later
18432 'org-timestamp-down 'org-timestamp-up)))
18433 ((and (not (eq org-support-shift-select 'always))
18434 org-enable-priority-commands
18435 (org-at-heading-p))
18436 (call-interactively 'org-priority-up))
18437 ((and (not org-support-shift-select) (org-at-item-p))
18438 (call-interactively 'org-previous-item))
18439 ((org-clocktable-try-shift 'up arg))
18440 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18441 (org-support-shift-select
18442 (org-call-for-shift-select 'previous-line))
18443 (t (org-shiftselect-error))))
18445 (defun org-shiftdown (&optional arg)
18446 "Decrease item in timestamp or decrease priority of current headline.
18447 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18448 depending on context. See the individual commands for more information."
18451 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18452 ((and org-support-shift-select (org-region-active-p))
18453 (org-call-for-shift-select 'next-line))
18454 ((org-at-timestamp-p t)
18455 (call-interactively (if org-edit-timestamp-down-means-later
18456 'org-timestamp-up 'org-timestamp-down)))
18457 ((and (not (eq org-support-shift-select 'always))
18458 org-enable-priority-commands
18459 (org-at-heading-p))
18460 (call-interactively 'org-priority-down))
18461 ((and (not org-support-shift-select) (org-at-item-p))
18462 (call-interactively 'org-next-item))
18463 ((org-clocktable-try-shift 'down arg))
18464 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18465 (org-support-shift-select
18466 (org-call-for-shift-select 'next-line))
18467 (t (org-shiftselect-error))))
18469 (defun org-shiftright (&optional arg)
18470 "Cycle the thing at point or in the current line, depending on context.
18471 Depending on context, this does one of the following:
18473 - switch a timestamp at point one day into the future
18474 - on a headline, switch to the next TODO keyword.
18475 - on an item, switch entire list to the next bullet type
18476 - on a property line, switch to the next allowed value
18477 - on a clocktable definition line, move time block into the future"
18480 ((run-hook-with-args-until-success 'org-shiftright-hook))
18481 ((and org-support-shift-select (org-region-active-p))
18482 (org-call-for-shift-select 'forward-char))
18483 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18484 ((and (not (eq org-support-shift-select 'always))
18485 (org-at-heading-p))
18486 (let ((org-inhibit-logging
18487 (not org-treat-S-cursor-todo-selection-as-state-change))
18488 (org-inhibit-blocking
18489 (not org-treat-S-cursor-todo-selection-as-state-change)))
18490 (org-call-with-arg 'org-todo 'right)))
18491 ((or (and org-support-shift-select
18492 (not (eq org-support-shift-select 'always))
18493 (org-at-item-bullet-p))
18494 (and (not org-support-shift-select) (org-at-item-p)))
18495 (org-call-with-arg 'org-cycle-list-bullet nil))
18496 ((and (not (eq org-support-shift-select 'always))
18497 (org-at-property-p))
18498 (call-interactively 'org-property-next-allowed-value))
18499 ((org-clocktable-try-shift 'right arg))
18500 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18501 (org-support-shift-select
18502 (org-call-for-shift-select 'forward-char))
18503 (t (org-shiftselect-error))))
18505 (defun org-shiftleft (&optional arg)
18506 "Cycle the thing at point or in the current line, depending on context.
18507 Depending on context, this does one of the following:
18509 - switch a timestamp at point one day into the past
18510 - on a headline, switch to the previous TODO keyword.
18511 - on an item, switch entire list to the previous bullet type
18512 - on a property line, switch to the previous allowed value
18513 - on a clocktable definition line, move time block into the past"
18516 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18517 ((and org-support-shift-select (org-region-active-p))
18518 (org-call-for-shift-select 'backward-char))
18519 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18520 ((and (not (eq org-support-shift-select 'always))
18521 (org-at-heading-p))
18522 (let ((org-inhibit-logging
18523 (not org-treat-S-cursor-todo-selection-as-state-change))
18524 (org-inhibit-blocking
18525 (not org-treat-S-cursor-todo-selection-as-state-change)))
18526 (org-call-with-arg 'org-todo 'left)))
18527 ((or (and org-support-shift-select
18528 (not (eq org-support-shift-select 'always))
18529 (org-at-item-bullet-p))
18530 (and (not org-support-shift-select) (org-at-item-p)))
18531 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18532 ((and (not (eq org-support-shift-select 'always))
18533 (org-at-property-p))
18534 (call-interactively 'org-property-previous-allowed-value))
18535 ((org-clocktable-try-shift 'left arg))
18536 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18537 (org-support-shift-select
18538 (org-call-for-shift-select 'backward-char))
18539 (t (org-shiftselect-error))))
18541 (defun org-shiftcontrolright ()
18542 "Switch to next TODO set."
18545 ((and org-support-shift-select (org-region-active-p))
18546 (org-call-for-shift-select 'forward-word))
18547 ((and (not (eq org-support-shift-select 'always))
18548 (org-at-heading-p))
18549 (org-call-with-arg 'org-todo 'nextset))
18550 (org-support-shift-select
18551 (org-call-for-shift-select 'forward-word))
18552 (t (org-shiftselect-error))))
18554 (defun org-shiftcontrolleft ()
18555 "Switch to previous TODO set."
18558 ((and org-support-shift-select (org-region-active-p))
18559 (org-call-for-shift-select 'backward-word))
18560 ((and (not (eq org-support-shift-select 'always))
18561 (org-at-heading-p))
18562 (org-call-with-arg 'org-todo 'previousset))
18563 (org-support-shift-select
18564 (org-call-for-shift-select 'backward-word))
18565 (t (org-shiftselect-error))))
18567 (defun org-shiftcontrolup ()
18568 "Change timestamps synchronously up in CLOCK log lines."
18570 (cond ((and (not org-support-shift-select)
18571 (org-at-clock-log-p)
18572 (org-at-timestamp-p t))
18573 (org-clock-timestamps-up))
18574 (t (org-shiftselect-error))))
18576 (defun org-shiftcontroldown ()
18577 "Change timestamps synchronously down in CLOCK log lines."
18579 (cond ((and (not org-support-shift-select)
18580 (org-at-clock-log-p)
18581 (org-at-timestamp-p t))
18582 (org-clock-timestamps-down))
18583 (t (org-shiftselect-error))))
18585 (defun org-ctrl-c-ret ()
18586 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18589 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18590 (t (call-interactively 'org-insert-heading))))
18592 (defun org-find-visible ()
18594 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18595 (get-char-property s 'invisible)))
18597 (defun org-find-invisible ()
18599 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18600 (not (get-char-property s 'invisible))))
18603 (defun org-copy-visible (beg end)
18604 "Copy the visible parts of the region."
18609 (narrow-to-region beg end)
18610 (setq s (goto-char (point-min)))
18611 (while (not (= (point) (point-max)))
18612 (goto-char (org-find-invisible))
18613 (push (buffer-substring s (point)) snippets)
18614 (setq s (goto-char (org-find-visible))))))
18615 (kill-new (apply 'concat (nreverse snippets)))))
18617 (defun org-copy-special ()
18618 "Copy region in table or copy current subtree.
18619 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18620 See the individual commands for more information."
18622 (call-interactively
18623 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18625 (defun org-cut-special ()
18626 "Cut region in table or cut current subtree.
18627 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18628 See the individual commands for more information."
18630 (call-interactively
18631 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18633 (defun org-paste-special (arg)
18634 "Paste rectangular region into table, or past subtree relative to level.
18635 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18636 See the individual commands for more information."
18638 (if (org-at-table-p)
18639 (org-table-paste-rectangle)
18640 (org-paste-subtree arg)))
18642 (defun org-edit-special (&optional arg)
18643 "Call a special editor for the stuff at point.
18644 When at a table, call the formula editor with `org-table-edit-formulas'.
18645 When at the first line of an src example, call `org-edit-src-code'.
18646 When in an #+include line, visit the include file. Otherwise call
18647 `ffap' to visit the file at point."
18649 ;; possibly prep session before editing source
18651 (let* ((info (org-babel-get-src-block-info))
18652 (lang (nth 0 info))
18653 (params (nth 2 info))
18654 (session (cdr (assoc :session params))))
18655 (when (and info session) ;; we are in a source-code block with a session
18657 (intern (concat "org-babel-prep-session:" lang)) session params))))
18658 (cond ;; proceed with `org-edit-special'
18660 (beginning-of-line 1)
18661 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18662 (find-file (org-trim (match-string 1))))
18663 ((org-edit-src-code))
18664 ((org-edit-fixed-width-region))
18665 ((org-at-table.el-p)
18666 (org-edit-src-code))
18667 ((or (org-at-table-p)
18669 (beginning-of-line 1)
18670 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
18671 (call-interactively 'org-table-edit-formulas))
18672 (t (call-interactively 'ffap))))
18674 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18675 (defun org-ctrl-c-ctrl-c (&optional arg)
18676 "Set tags in headline, or update according to changed information at point.
18678 This command does many different things, depending on context:
18680 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18681 this is what we do.
18683 - If the cursor is on a statistics cookie, update it.
18685 - If the cursor is in a headline, prompt for tags and insert them
18686 into the current line, aligned to `org-tags-column'. When called
18687 with prefix arg, realign all tags in the current buffer.
18689 - If the cursor is in one of the special #+KEYWORD lines, this
18690 triggers scanning the buffer for these lines and updating the
18693 - If the cursor is inside a table, realign the table. This command
18694 works even if the automatic table editor has been turned off.
18696 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18699 - If the cursor is at a footnote reference or definition, jump to
18700 the corresponding definition or references, respectively.
18702 - If the cursor is a the beginning of a dynamic block, update it.
18704 - If the current buffer is a capture buffer, close note and file it.
18706 - If the cursor is on a <<<target>>>, update radio targets and
18707 corresponding links in this buffer.
18709 - If the cursor is on a numbered item in a plain list, renumber the
18712 - If the cursor is on a checkbox, toggle it.
18714 - If the cursor is on a code block, evaluate it. The variable
18715 `org-confirm-babel-evaluate' can be used to control prompting
18716 before code block evaluation, by default every code block
18717 evaluation requires confirmation. Code block evaluation can be
18718 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18720 (let ((org-enable-table-editor t))
18722 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18723 org-occur-highlights
18724 org-latex-fragment-image-overlays)
18725 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18726 (org-remove-occur-highlights)
18727 (org-remove-latex-fragment-image-overlays)
18728 (message "Temporary highlights/overlays removed from current buffer"))
18729 ((and (local-variable-p 'org-finish-function (current-buffer))
18730 (fboundp org-finish-function))
18731 (funcall org-finish-function))
18732 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18733 ((org-in-regexp org-ts-regexp-both)
18734 (org-timestamp-change 0 'day))
18735 ((or (looking-at org-property-start-re)
18736 (org-at-property-p))
18737 (call-interactively 'org-property-action))
18738 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18739 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18740 (or (org-at-heading-p) (org-at-item-p)))
18741 (call-interactively 'org-update-statistics-cookies))
18742 ((org-at-heading-p) (call-interactively 'org-set-tags))
18743 ((org-at-table.el-p)
18744 (message "Use C-c ' to edit table.el tables"))
18746 (org-table-maybe-eval-formula)
18748 (call-interactively 'org-table-recalculate)
18749 (org-table-maybe-recalculate-line))
18750 (call-interactively 'org-table-align)
18751 (orgtbl-send-table 'maybe))
18752 ((or (org-footnote-at-reference-p)
18753 (org-footnote-at-definition-p))
18754 (call-interactively 'org-footnote-action))
18755 ((org-at-item-checkbox-p)
18756 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18757 ;; list only if at top item.
18758 (let* ((cbox (match-string 1))
18759 (struct (org-list-struct))
18760 (old-struct (copy-tree struct))
18761 (parents (org-list-parents-alist struct))
18762 (orderedp (org-entry-get nil "ORDERED"))
18763 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18765 ;; Use a light version of `org-toggle-checkbox' to avoid
18766 ;; computing list structure twice.
18767 (let ((new-box (cond
18768 ((equal arg '(16)) "[-]")
18769 ((equal arg '(4)) nil)
18770 ((equal "[X]" cbox) "[ ]")
18772 (if (and firstp arg)
18773 ;; If at first item of sub-list, remove check-box from
18774 ;; every item at the same level.
18776 (lambda (pos) (org-list-set-checkbox pos struct new-box))
18777 (org-list-get-all-items
18778 (point-at-bol) struct (org-list-prevs-alist struct)))
18779 (org-list-set-checkbox (point-at-bol) struct new-box)))
18780 ;; Replicate `org-list-write-struct', while grabbing a return
18781 ;; value from `org-list-struct-fix-box'.
18782 (org-list-struct-fix-ind struct parents 2)
18783 (org-list-struct-fix-item-end struct)
18784 (let ((prevs (org-list-prevs-alist struct)))
18785 (org-list-struct-fix-bul struct prevs)
18786 (org-list-struct-fix-ind struct parents)
18788 (org-list-struct-fix-box struct parents prevs orderedp)))
18789 (org-list-struct-apply-struct struct old-struct)
18790 (org-update-checkbox-count-maybe)
18793 "Checkboxes were removed due to unchecked box at line %d"
18794 (org-current-line block-item)))
18795 (when firstp (org-list-send-list 'maybe))))
18797 ;; Cursor at an item: repair list. Do checkbox related actions
18798 ;; only if function was called with an argument. Send list only
18800 (let* ((struct (org-list-struct))
18801 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18804 (setq old-struct (copy-tree struct))
18806 ;; If at first item of sub-list, add check-box to every
18807 ;; item at the same level.
18810 (unless (org-list-get-checkbox pos struct)
18811 (org-list-set-checkbox pos struct "[ ]")))
18812 (org-list-get-all-items
18813 (point-at-bol) struct (org-list-prevs-alist struct)))
18814 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
18815 (org-list-write-struct
18816 struct (org-list-parents-alist struct) old-struct)
18817 (when arg (org-update-checkbox-count-maybe))
18818 (when firstp (org-list-send-list 'maybe))))
18819 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18821 (beginning-of-line 1)
18822 (save-excursion (org-update-dblock)))
18824 (let ((case-fold-search t))
18825 (beginning-of-line 1)
18826 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
18828 ((or (equal (match-string 1) "TBLFM")
18829 (equal (match-string 1) "tblfm"))
18830 ;; Recalculate the table before this line
18832 (beginning-of-line 1)
18833 (skip-chars-backward " \r\n\t")
18834 (if (org-at-table-p)
18835 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18837 (let ((org-inhibit-startup-visibility-stuff t)
18838 (org-startup-align-all-tables nil))
18839 (when (boundp 'org-table-coordinate-overlays)
18840 (mapc 'delete-overlay org-table-coordinate-overlays)
18841 (setq org-table-coordinate-overlays nil))
18842 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18843 (message "Local setup has been refreshed"))))
18844 ((org-clock-update-time-maybe))
18846 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18847 (error "C-c C-c can do nothing useful at this location"))))))
18849 (defun org-mode-restart ()
18850 "Restart Org-mode, to scan again for special lines.
18851 Also updates the keyword regular expressions."
18854 (message "Org-mode restarted"))
18856 (defun org-kill-note-or-show-branches ()
18857 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18859 (if (not org-finish-function)
18862 (call-interactively 'show-branches))
18863 (let ((org-note-abort t))
18864 (funcall org-finish-function))))
18866 (defun org-return (&optional indent)
18867 "Goto next table row or insert a newline.
18868 Calls `org-table-next-row' or `newline', depending on context.
18869 See the individual commands for more information."
18872 ((or (bobp) (org-in-src-block-p))
18873 (if indent (newline-and-indent) (newline)))
18875 (org-table-justify-field-maybe)
18876 (call-interactively 'org-table-next-row))
18877 ;; when `newline-and-indent' is called within a list, make sure
18878 ;; text moved stays inside the item.
18879 ((and (org-in-item-p) indent)
18880 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18882 (save-match-data (newline))
18883 (org-indent-line-to (length (match-string 0))))
18884 (let ((ind (org-get-indentation)))
18886 (if (org-looking-back org-list-end-re)
18887 (org-indent-line-function)
18888 (org-indent-line-to ind)))))
18889 ((and org-return-follows-link
18890 (let ((tprop (get-text-property (point) 'face)))
18891 (or (eq tprop 'org-link)
18892 (and (listp tprop) (memq 'org-link tprop)))))
18893 (call-interactively 'org-open-at-point))
18894 ((and (org-at-heading-p)
18896 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18900 (t (if indent (newline-and-indent) (newline)))))
18902 (defun org-return-indent ()
18903 "Goto next table row or insert a newline and indent.
18904 Calls `org-table-next-row' or `newline-and-indent', depending on
18905 context. See the individual commands for more information."
18909 (defun org-ctrl-c-star ()
18910 "Compute table, or change heading status of lines.
18911 Calls `org-table-recalculate' or `org-toggle-heading',
18912 depending on context."
18916 (call-interactively 'org-table-recalculate))
18918 ;; Convert all lines in region to list items
18919 (call-interactively 'org-toggle-heading))))
18921 (defun org-ctrl-c-minus ()
18922 "Insert separator line in table or modify bullet status of line.
18923 Also turns a plain line or a region of lines into list items.
18924 Calls `org-table-insert-hline', `org-toggle-item', or
18925 `org-cycle-list-bullet', depending on context."
18929 (call-interactively 'org-table-insert-hline))
18930 ((org-region-active-p)
18931 (call-interactively 'org-toggle-item))
18933 (call-interactively 'org-cycle-list-bullet))
18935 (call-interactively 'org-toggle-item))))
18937 (defun org-toggle-item (arg)
18938 "Convert headings or normal lines to items, items to normal lines.
18939 If there is no active region, only the current line is considered.
18941 If the first non blank line in the region is an headline, convert
18942 all headlines to items, shifting text accordingly.
18944 If it is an item, convert all items to normal lines.
18946 If it is normal text, change region into an item. With a prefix
18947 argument ARG, change each line in region into an item."
18951 ;; Shift text in current section to IND, from point to END.
18952 ;; The function leaves point to END line.
18954 (let ((min-i 1000) (end (copy-marker end)))
18955 ;; First determine the minimum indentation (MIN-I) of
18959 (while (< (point) end)
18960 (let ((i (org-get-indentation)))
18962 ;; Skip blank lines and inline tasks.
18963 ((looking-at "^[ \t]*$"))
18964 ((looking-at org-outline-regexp-bol))
18965 ;; We can't find less than 0 indentation.
18966 ((zerop i) (throw 'exit (setq min-i 0)))
18967 ((< i min-i) (setq min-i i))))
18969 ;; Then indent each line so that a line indented to
18970 ;; MIN-I becomes indented to IND. Ignore blank lines
18971 ;; and inline tasks in the process.
18972 (let ((delta (- ind min-i)))
18973 (while (< (point) end)
18974 (unless (or (looking-at "^[ \t]*$")
18975 (looking-at org-outline-regexp-bol))
18976 (org-indent-line-to (+ (org-get-indentation) delta)))
18977 (forward-line)))))))
18980 ;; Return beginning of first non-blank line, starting from
18985 (skip-chars-forward " \r\t\n")
18988 ;; Determine boundaries of changes.
18989 (if (org-region-active-p)
18990 (setq beg (funcall skip-blanks (region-beginning))
18991 end (copy-marker (region-end)))
18992 (setq beg (funcall skip-blanks (point-at-bol))
18993 end (copy-marker (point-at-eol))))
18994 ;; Depending on the starting line, choose an action on the text
18995 ;; between BEG and END.
18996 (org-with-limited-levels
19000 ;; Case 1. Start at an item: de-itemize. Note that it only
19001 ;; happens when a region is active: `org-ctrl-c-minus'
19002 ;; would call `org-cycle-list-bullet' otherwise.
19004 (while (< (point) end)
19005 (when (org-at-item-p)
19006 (skip-chars-forward " \t")
19007 (delete-region (point) (match-end 0)))
19009 ;; Case 2. Start at an heading: convert to items.
19010 ((org-at-heading-p)
19011 (let* ((bul (org-list-bullet-string "-"))
19012 (bul-len (length bul))
19013 ;; Indentation of the first heading. It should be
19014 ;; relative to the indentation of its parent, if any.
19015 (start-ind (save-excursion
19017 ((not org-adapt-indentation) 0)
19018 ((not (outline-previous-heading)) 0)
19019 (t (length (match-string 0))))))
19020 ;; Level of first heading. Further headings will be
19021 ;; compared to it to determine hierarchy in the list.
19022 (ref-level (org-reduced-level (org-outline-level))))
19023 (while (< (point) end)
19024 (let* ((level (org-reduced-level (org-outline-level)))
19025 (delta (max 0 (- level ref-level))))
19026 ;; If current headline is less indented than the first
19027 ;; one, set it as reference, in order to preserve
19029 (when (< level ref-level) (setq ref-level level))
19030 (replace-match bul t t)
19031 (org-indent-line-to (+ start-ind (* delta bul-len)))
19032 ;; Ensure all text down to END (or SECTION-END) belongs
19033 ;; to the newly created item.
19034 (let ((section-end (save-excursion
19035 (or (outline-next-heading) (point)))))
19037 (funcall shift-text
19038 (+ start-ind (* (1+ delta) bul-len))
19039 (min end section-end)))))))
19040 ;; Case 3. Normal line with ARG: turn each non-item line into
19043 (while (< (point) end)
19044 (unless (or (org-at-heading-p) (org-at-item-p))
19045 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19047 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19049 ;; Case 4. Normal line without ARG: make the first line of
19050 ;; region an item, and shift indentation of others
19051 ;; lines to set them as item's body.
19052 (t (let* ((bul (org-list-bullet-string "-"))
19053 (bul-len (length bul))
19054 (ref-ind (org-get-indentation)))
19055 (skip-chars-forward " \t")
19058 (while (< (point) end)
19059 ;; Ensure that lines less indented than first one
19060 ;; still get included in item body.
19061 (funcall shift-text
19062 (+ ref-ind bul-len)
19063 (min end (save-excursion (or (outline-next-heading)
19065 (forward-line)))))))))
19067 (defun org-toggle-heading (&optional nstars)
19068 "Convert headings to normal text, or items or text to headings.
19069 If there is no active region, only the current line is considered.
19071 With a \\[universal-argument] prefix, convert the whole list at
19072 point into heading.
19076 - If the first non blank line is an headline, remove the stars
19077 from all headlines in the region.
19079 - If it is a normal line turn each and every normal line (i.e. not an
19080 heading or an item) in the region into a heading.
19082 - If it is a plain list item, turn all plain list items into headings.
19084 When converting a line into a heading, the number of stars is chosen
19085 such that the lines become children of the current entry. However,
19086 when a prefix argument is given, its value determines the number of
19091 ;; Return beginning of first non-blank line, starting from
19096 (skip-chars-forward " \r\t\n")
19099 ;; Determine boundaries of changes. If a universal prefix has
19100 ;; been given, put the list in a region. If region ends at a bol,
19101 ;; do not consider the last line to be in the region.
19103 (when (and current-prefix-arg (org-at-item-p))
19104 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19107 (if (org-region-active-p)
19108 (setq beg (funcall skip-blanks (region-beginning))
19109 end (copy-marker (save-excursion
19110 (goto-char (region-end))
19111 (if (bolp) (point) (point-at-eol)))))
19112 (setq beg (funcall skip-blanks (point-at-bol))
19113 end (copy-marker (point-at-eol))))
19114 ;; Ensure inline tasks don't count as headings.
19115 (org-with-limited-levels
19119 ;; Case 1. Started at an heading: de-star headings.
19120 ((org-at-heading-p)
19121 (while (< (point) end)
19122 (when (org-at-heading-p t)
19123 (looking-at org-outline-regexp) (replace-match ""))
19125 ;; Case 2. Started at an item: change items into headlines.
19126 ;; One star will be added by `org-list-to-subtree'.
19128 (let* ((stars (make-string
19130 ;; subtract the star that will be added again by
19131 ;; `org-list-to-subtree'
19132 (1- (prefix-numeric-value current-prefix-arg))
19133 (or (org-current-level) 0))
19136 (cond (nstars "") ; stars from prefix only
19137 ((equal stars "") "") ; before first heading
19138 (org-odd-levels-only "*") ; inside heading, odd
19139 (t "")))) ; inside heading, oddeven
19140 (while (< (point) end)
19141 (when (org-at-item-p)
19142 ;; Pay attention to cases when region ends before list.
19143 (let* ((struct (org-list-struct))
19144 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19146 (narrow-to-region (point) list-end)
19148 (org-list-to-subtree
19149 (org-list-parse-list t)
19150 '(:istart (concat stars add-stars (funcall get-stars depth))
19151 :icount (concat stars add-stars (funcall get-stars depth))))))))
19153 ;; Case 3. Started at normal text: make every line an heading,
19154 ;; skipping headlines and items.
19155 (t (let* ((stars (make-string
19157 (prefix-numeric-value current-prefix-arg)
19158 (or (org-current-level) 0))
19161 (cond (nstars "") ; stars from prefix only
19162 ((equal stars "") "*") ; before first heading
19163 (org-odd-levels-only "**") ; inside heading, odd
19164 (t "*"))) ; inside heading, oddeven
19165 (rpl (concat stars add-stars " ")))
19166 (while (< (point) end)
19167 (when (and (not (org-at-heading-p)) (not (org-at-item-p))
19168 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19169 (replace-match (concat rpl (match-string 2))))
19170 (forward-line)))))))))
19172 (defun org-meta-return (&optional arg)
19173 "Insert a new heading or wrap a region in a table.
19174 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19175 See the individual commands for more information."
19178 ((run-hook-with-args-until-success 'org-metareturn-hook))
19179 ((or (org-at-drawer-p) (org-at-property-p))
19180 (newline-and-indent))
19182 (call-interactively 'org-table-wrap-region))
19183 (t (call-interactively 'org-insert-heading))))
19187 ;; Define the Org-mode menus
19188 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19190 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19191 ["Next Field" org-cycle (org-at-table-p)]
19192 ["Previous Field" org-shifttab (org-at-table-p)]
19193 ["Next Row" org-return (org-at-table-p)]
19195 ["Blank Field" org-table-blank-field (org-at-table-p)]
19196 ["Edit Field" org-table-edit-field (org-at-table-p)]
19197 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19200 ["Move Column Left" org-metaleft (org-at-table-p)]
19201 ["Move Column Right" org-metaright (org-at-table-p)]
19202 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19203 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19205 ["Move Row Up" org-metaup (org-at-table-p)]
19206 ["Move Row Down" org-metadown (org-at-table-p)]
19207 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19208 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19209 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19211 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19213 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19214 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19215 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19216 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19219 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19220 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19221 ["Edit Formulas" org-edit-special (org-at-table-p)]
19223 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19224 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19225 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19227 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19229 ["Sum Column/Rectangle" org-table-sum
19230 (or (org-at-table-p) (org-region-active-p))]
19231 ["Which Column?" org-table-current-column (org-at-table-p)])
19233 org-table-toggle-formula-debugger
19234 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19235 ["Show Col/Row Numbers"
19236 org-table-toggle-coordinate-overlays
19238 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19240 ["Create" org-table-create (and (not (org-at-table-p))
19241 org-enable-table-editor)]
19242 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19243 ["Import from File" org-table-import (not (org-at-table-p))]
19244 ["Export to File" org-table-export (org-at-table-p)]
19246 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19248 (easy-menu-define org-org-menu org-mode-map "Org menu"
19251 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19252 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19253 ["Sparse Tree..." org-sparse-tree t]
19254 ["Reveal Context" org-reveal t]
19255 ["Show All" show-all t]
19257 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19259 ["New Heading" org-insert-heading t]
19260 ("Navigate Headings"
19261 ["Up" outline-up-heading t]
19262 ["Next" outline-next-visible-heading t]
19263 ["Previous" outline-previous-visible-heading t]
19264 ["Next Same Level" outline-forward-same-level t]
19265 ["Previous Same Level" outline-backward-same-level t]
19267 ["Jump" org-goto t])
19269 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19270 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19272 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19273 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19274 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19276 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19278 ["Copy visible text" org-copy-visible t]
19280 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19281 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19282 ["Demote Heading" org-metaright (not (org-at-table-p))]
19283 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19285 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19287 ["Convert to odd levels" org-convert-to-odd-levels t]
19288 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19290 ["Emphasis..." org-emphasize t]
19291 ["Edit Source Example" org-edit-special t]
19293 ["Footnote new/jump" org-footnote-action t]
19294 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19296 ["Archive (default method)" org-archive-subtree-default t]
19298 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19299 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19300 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19304 ["Store Link (Global)" org-store-link t]
19305 ["Find existing link to here" org-occur-link-in-agenda-files t]
19306 ["Insert Link" org-insert-link t]
19307 ["Follow Link" org-open-at-point t]
19309 ["Next link" org-next-link t]
19310 ["Previous link" org-previous-link t]
19312 ["Descriptive Links"
19313 org-toggle-link-display
19315 :selected org-descriptive-links
19318 org-toggle-link-display
19320 :selected (not org-descriptive-links)])
19323 ["TODO/DONE/-" org-todo t]
19325 ["Next keyword" org-shiftright (org-at-heading-p)]
19326 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19327 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19328 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19329 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19330 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19331 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19333 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19334 :selected org-enforce-todo-dependencies :style toggle :active t]
19335 "Settings for tree at point"
19336 ["Do Children sequentially" org-toggle-ordered-property :style radio
19337 :selected (org-entry-get nil "ORDERED")
19338 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19339 ["Do Children parallel" org-toggle-ordered-property :style radio
19340 :selected (not (org-entry-get nil "ORDERED"))
19341 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19343 ["Set Priority" org-priority t]
19344 ["Priority Up" org-shiftup t]
19345 ["Priority Down" org-shiftdown t]
19347 ["Get news from all feeds" org-feed-update-all t]
19348 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19349 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19350 ("TAGS and Properties"
19351 ["Set Tags" org-set-tags-command t]
19352 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19354 ["Set property" org-set-property t]
19355 ["Column view of properties" org-columns t]
19356 ["Insert Column View DBlock" org-insert-columns-dblock t])
19357 ("Dates and Scheduling"
19358 ["Timestamp" org-time-stamp t]
19359 ["Timestamp (inactive)" org-time-stamp-inactive t]
19361 ["1 Day Later" org-shiftright t]
19362 ["1 Day Earlier" org-shiftleft t]
19363 ["1 ... Later" org-shiftup t]
19364 ["1 ... Earlier" org-shiftdown t])
19365 ["Compute Time Range" org-evaluate-time-range t]
19366 ["Schedule Item" org-schedule t]
19367 ["Deadline" org-deadline t]
19369 ["Custom time format" org-toggle-time-stamp-overlays
19370 :style radio :selected org-display-custom-times]
19372 ["Goto Calendar" org-goto-calendar t]
19373 ["Date from Calendar" org-date-from-calendar t]
19375 ["Start/Restart Timer" org-timer-start t]
19376 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19377 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19378 ["Insert Timer String" org-timer t]
19379 ["Insert Timer Item" org-timer-item t])
19381 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19382 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19383 ["Clock out" org-clock-out t]
19384 ["Clock cancel" org-clock-cancel t]
19386 ["Mark as default task" org-clock-mark-default-task t]
19387 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19388 ["Goto running clock" org-clock-goto t]
19390 ["Display times" org-clock-display t]
19391 ["Create clock table" org-clock-report t]
19393 ["Record DONE time"
19394 (progn (setq org-log-done (not org-log-done))
19395 (message "Switching to %s will %s record a timestamp"
19396 (car org-done-keywords)
19397 (if org-log-done "automatically" "not")))
19398 :style toggle :selected org-log-done])
19400 ["Agenda Command..." org-agenda t]
19401 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19402 ("File List for Agenda")
19403 ("Special views current file"
19404 ["TODO Tree" org-show-todo-tree t]
19405 ["Check Deadlines" org-check-deadlines t]
19406 ["Timeline" org-timeline t]
19407 ["Tags/Property tree" org-match-sparse-tree t])
19409 ["Export/Publish..." org-export t]
19411 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19412 :selected org-cdlatex-mode]
19413 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19414 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19415 ["Modify math symbol" org-cdlatex-math-modify
19416 (org-inside-LaTeX-fragment-p)]
19417 ["Insert citation" org-reftex-citation t]
19419 ["Template for BEAMER" (progn (require 'org-beamer)
19420 (org-insert-beamer-options-template)) t])
19423 ["Push Files and Views" org-mobile-push t]
19424 ["Get Captured and Flagged" org-mobile-pull t]
19425 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19427 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19430 ["Show Version" org-version t]
19431 ["Info Documentation" org-info t])
19433 ["Browse Org Group" org-customize t]
19435 ["Expand This Menu" org-create-customize-menu
19436 (fboundp 'customize-menu-create)])
19437 ["Send bug report" org-submit-bug-report t]
19440 ["Refresh setup current buffer" org-mode-restart t]
19441 ["Reload Org (after update)" org-reload t]
19442 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19445 (defun org-info (&optional node)
19446 "Read documentation for Org-mode in the info system.
19447 With optional NODE, go directly to that node."
19449 (info (format "(org)%s" (or node ""))))
19452 (defun org-submit-bug-report ()
19453 "Submit a bug report on Org-mode via mail.
19455 Don't hesitate to report any problems or inaccurate documentation.
19457 If you don't have setup sending mail from (X)Emacs, please copy the
19458 output buffer into your mail program, as it gives us important
19459 information about your Org-mode version and configuration."
19461 (require 'reporter)
19462 (org-load-modules-maybe)
19463 (org-require-autoloaded-modules)
19464 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19465 (reporter-submit-bug-report
19466 "emacs-orgmode@gnu.org"
19469 (save-window-excursion
19470 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19471 (delete-other-windows)
19473 (insert "You are about to submit a bug report to the Org-mode mailing list.
19475 We would like to add your full Org-mode and Outline configuration to the
19476 bug report. This greatly simplifies the work of the maintainer and
19477 other experts on the mailing list.
19479 HOWEVER, some variables you have customized may contain private
19480 information. The names of customers, colleagues, or friends, might
19481 appear in the form of file names, tags, todo states, or search strings.
19482 If you answer yes to the prompt, you might want to check and remove
19483 such private information before sending the email.")
19484 (add-text-properties (point-min) (point-max) '(face org-warning))
19485 (when (yes-or-no-p "Include your Org-mode configuration ")
19489 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19490 (or (and (symbol-value v)
19491 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19493 (get v 'custom-type) (get v 'standard-value)
19494 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19496 (kill-buffer (get-buffer "*Warn about privacy*"))
19499 "Remember to cover the basics, that is, what you expected to happen and
19500 what in fact did happen. You don't know how to make a good report? See
19502 http://orgmode.org/manual/Feedback.html#Feedback
19504 Your bug report will be posted to the Org-mode mailing list.
19505 ------------------------------------------------------------------------")
19507 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19508 (replace-match "\\1Bug: \\3 [\\2]")))))
19511 (defun org-install-agenda-files-menu ()
19512 (let ((bl (buffer-list)))
19515 (set-buffer (pop bl))
19516 (if (derived-mode-p 'org-mode) (setq bl nil)))
19517 (when (derived-mode-p 'org-mode)
19519 '("Org") "File List for Agenda"
19522 ["Edit File List" (org-edit-agenda-file-list) t]
19523 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19524 ["Remove Current File from List" org-remove-file t]
19525 ["Cycle through agenda files" org-cycle-agenda-files t]
19526 ["Occur in all agenda files" org-occur-in-agenda-files t]
19528 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19533 (defun org-require-autoloaded-modules ()
19536 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19537 org-docbook org-exp org-html org-icalendar
19539 org-publish org-remember org-table
19540 org-timer org-xoxo)))
19543 (defun org-reload (&optional uncompiled)
19544 "Reload all org lisp files.
19545 With prefix arg UNCOMPILED, load the uncompiled versions."
19547 (require 'find-func)
19548 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19549 (dir-org (file-name-directory (org-find-library-name "org")))
19550 (dir-org-contrib (ignore-errors
19551 (file-name-directory
19552 (org-find-library-name "org-contribdir"))))
19554 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19555 (append (list nil "comint" "eval" "exp" "keys"
19556 "lob" "ref" "table" "tangle")
19560 (when (cdr lang) (symbol-name (car lang))))
19561 org-babel-load-languages)))))
19563 (append (directory-files dir-org t file-re)
19565 (and dir-org-contrib
19566 (directory-files dir-org-contrib t file-re))))
19567 (remove-re (concat (if (featurep 'xemacs)
19568 "org-colview" "org-colview-xemacs")
19570 (setq files (mapcar 'file-name-sans-extension files))
19571 (setq files (mapcar
19572 (lambda (x) (if (string-match remove-re x) nil x))
19574 (setq files (delq nil files))
19577 (when (featurep (intern (file-name-nondirectory f)))
19578 (if (and (not uncompiled)
19579 (file-exists-p (concat f ".elc")))
19580 (load (concat f ".elc") nil nil t)
19581 (load (concat f ".el") nil nil t))))
19586 (defun org-customize ()
19587 "Call the customize function with org as argument."
19589 (org-load-modules-maybe)
19590 (org-require-autoloaded-modules)
19591 (customize-browse 'org))
19593 (defun org-create-customize-menu ()
19594 "Create a full customization menu for Org-mode, insert it into the menu."
19596 (org-load-modules-maybe)
19597 (org-require-autoloaded-modules)
19598 (if (fboundp 'customize-menu-create)
19601 '("Org") "Customize"
19602 `(["Browse Org group" org-customize t]
19604 ,(customize-menu-create 'org)
19605 ["Set" Custom-set t]
19606 ["Save" Custom-save t]
19607 ["Reset to Current" Custom-reset-current t]
19608 ["Reset to Saved" Custom-reset-saved t]
19609 ["Reset to Standard Settings" Custom-reset-standard t]))
19610 (message "\"Org\"-menu now contains full customization menu"))
19611 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19613 ;;;; Miscellaneous stuff
19615 ;;; Generally useful functions
19617 (defun org-get-at-bol (property)
19618 "Get text property PROPERTY at beginning of line."
19619 (get-text-property (point-at-bol) property))
19621 (defun org-find-text-property-in-string (prop s)
19622 "Return the first non-nil value of property PROP in string S."
19623 (or (get-text-property 0 prop s)
19624 (get-text-property (or (next-single-property-change 0 prop s) 0)
19627 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19628 "Display the given MESSAGE as a warning."
19629 (if (fboundp 'display-warning)
19630 (display-warning 'org message
19631 (if (featurep 'xemacs) 'warning :warning))
19632 (let ((buf (get-buffer-create "*Org warnings*")))
19633 (with-current-buffer buf
19634 (goto-char (point-max))
19635 (insert "Warning (Org): " message)
19638 (display-buffer buf)
19641 (defun org-eval (form)
19642 "Eval FORM and return result."
19643 (condition-case error
19645 (error (format "%%![Error: %s]" error))))
19647 (defun org-in-clocktable-p ()
19648 "Check if the cursor is in a clocktable."
19649 (let ((pos (point)) start)
19652 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19653 (setq start (match-beginning 0))
19654 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19655 (>= (match-end 0) pos)
19658 (defun org-in-commented-line ()
19659 "Is point in a line starting with `#'?"
19660 (equal (char-after (point-at-bol)) ?#))
19662 (defun org-in-indented-comment-line ()
19663 "Is point in a line starting with `#' after some white space?"
19666 (goto-char (point-at-bol))
19667 (looking-at "[ \t]*#"))))
19669 (defun org-in-verbatim-emphasis ()
19671 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19673 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19674 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19675 (if (and marker (marker-buffer marker)
19676 (buffer-live-p (marker-buffer marker)))
19678 (org-pop-to-buffer-same-window (marker-buffer marker))
19679 (if (or (> marker (point-max)) (< marker (point-min)))
19682 (org-show-context 'org-goto))
19684 (bookmark-jump bookmark)
19685 (error "Cannot find location"))))
19687 (defun org-quote-csv-field (s)
19688 "Quote field for inclusion in CSV material."
19689 (if (string-match "[\",]" s)
19690 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19693 (defun org-force-self-insert (N)
19694 "Needed to enforce self-insert under remapping."
19696 (self-insert-command N))
19698 (defun org-string-width (s)
19699 "Compute width of string, ignoring invisible characters.
19700 This ignores character with invisibility property `org-link', and also
19701 characters with property `org-cwidth', because these will become invisible
19702 upon the next fontification round."
19704 (when (or (eq t buffer-invisibility-spec)
19705 (assq 'org-link buffer-invisibility-spec))
19706 (while (setq b (text-property-any 0 (length s)
19707 'invisible 'org-link s))
19708 (setq s (concat (substring s 0 b)
19709 (substring s (or (next-single-property-change
19710 b 'invisible s) (length s)))))))
19711 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19712 (setq s (concat (substring s 0 b)
19713 (substring s (or (next-single-property-change
19714 b 'org-cwidth s) (length s))))))
19715 (setq l (string-width s) b -1)
19716 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19717 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19720 (defun org-shorten-string (s maxlength)
19721 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19722 If the string is shorter or has length MAXLENGTH, just return the
19723 original string. If it is longer, the functions finds a space in the
19724 string, breaks this string off at that locations and adds three dots
19725 as ellipsis. Including the ellipsis, the string will not be longer
19726 than MAXLENGTH. If finding a good breaking point in the string does
19727 not work, the string is just chopped off in the middle of a word
19729 (if (<= (length s) maxlength)
19731 (let* ((n (max (- maxlength 4) 1))
19732 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19733 (if (string-match re s)
19734 (concat (match-string 1 s) "...")
19735 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19737 (defun org-get-indentation (&optional line)
19738 "Get the indentation of the current line, interpreting tabs.
19739 When LINE is given, assume it represents a line and compute its indentation."
19741 (if (string-match "^ *" (org-remove-tabs line))
19744 (beginning-of-line 1)
19745 (skip-chars-forward " \t")
19746 (current-column))))
19748 (defun org-get-string-indentation (s)
19749 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19750 (let ((n -1) (i 0) (w tab-width) c)
19752 (while (< (setq n (1+ n)) (length s))
19753 (setq c (aref s n))
19754 (cond ((= c ?\ ) (setq i (1+ i)))
19755 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19756 (t (throw 'exit t)))))
19759 (defun org-remove-tabs (s &optional width)
19760 "Replace tabulators in S with spaces.
19761 Assumes that s is a single line, starting in column 0."
19762 (setq width (or width tab-width))
19763 (while (string-match "\t" s)
19764 (setq s (replace-match
19766 (- (* width (/ (+ (match-beginning 0) width) width))
19767 (match-beginning 0)) ?\ )
19771 (defun org-fix-indentation (line ind)
19772 "Fix indentation in LINE.
19773 IND is a cons cell with target and minimum indentation.
19774 If the current indentation in LINE is smaller than the minimum,
19775 leave it alone. If it is larger than ind, set it to the target."
19776 (let* ((l (org-remove-tabs line))
19777 (i (org-get-indentation l))
19778 (i1 (car ind)) (i2 (cdr ind)))
19779 (if (>= i i2) (setq l (substring line i2)))
19781 (concat (make-string i1 ?\ ) l)
19784 (defun org-remove-indentation (code &optional n)
19785 "Remove the maximum common indentation from the lines in CODE.
19786 N may optionally be the number of spaces to remove."
19789 (org-do-remove-indentation n)
19792 (defun org-do-remove-indentation (&optional n)
19793 "Remove the maximum common indentation from the buffer."
19794 (untabify (point-min) (point-max))
19795 (let ((min 10000) re)
19798 (goto-char (point-min))
19799 (while (re-search-forward "^ *[^ \n]" nil t)
19800 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19801 (unless (or (= min 0) (= min 10000))
19802 (setq re (format "^ \\{%d\\}" min))
19803 (goto-char (point-min))
19804 (while (re-search-forward re nil t)
19809 (defun org-fill-template (template alist)
19810 "Find each %key of ALIST in TEMPLATE and replace it."
19811 (let ((case-fold-search nil)
19813 (setq alist (sort (copy-sequence alist)
19814 (lambda (a b) (< (length (car a)) (length (car b))))))
19815 (while (setq entry (pop alist))
19817 (replace-regexp-in-string
19818 (concat "%" (regexp-quote (car entry)))
19819 (cdr entry) template t t)))
19822 (defun org-base-buffer (buffer)
19823 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19826 (or (buffer-base-buffer buffer)
19829 (defun org-trim (s)
19830 "Remove whitespace at beginning and end of string."
19831 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19832 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19835 (defun org-wrap (string &optional width lines)
19836 "Wrap string to either a number of lines, or a width in characters.
19837 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19838 that costs. If there is a word longer than WIDTH, the text is actually
19839 wrapped to the length of that word.
19840 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19841 many lines, whatever width that takes.
19842 The return value is a list of lines, without newlines at the end."
19843 (let* ((words (org-split-string string "[ \t\n]+"))
19844 (maxword (apply 'max (mapcar 'org-string-width words)))
19847 (org-do-wrap words (max maxword width)))
19850 (setq ll (org-do-wrap words maxword))
19851 (if (<= (length ll) lines)
19854 (while (> (length ll) lines)
19856 (setq ll (org-do-wrap words w)))
19858 (t (error "Cannot wrap this")))))
19860 (defun org-do-wrap (words width)
19861 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19864 (setq line (pop words))
19865 (while (and words (< (+ (length line) (length (car words))) width))
19866 (setq line (concat line " " (pop words))))
19867 (setq lines (push line lines)))
19870 (defun org-split-string (string &optional separators)
19871 "Splits STRING into substrings at SEPARATORS.
19872 No empty strings are returned if there are matches at the beginning
19873 and end of string."
19874 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19878 (while (and (string-match rexp string
19880 (= start (match-beginning 0))
19881 (< start (length string)))
19883 (< (match-beginning 0) (length string)))
19885 (or (eq (match-beginning 0) 0)
19886 (and (eq (match-beginning 0) (match-end 0))
19887 (eq (match-beginning 0) start))
19889 (cons (substring string start (match-beginning 0))
19891 (setq start (match-end 0)))
19892 (or (eq start (length string))
19894 (cons (substring string start)
19898 (defun org-quote-vert (s)
19899 "Replace \"|\" with \"\\vert\"."
19900 (while (string-match "|" s)
19901 (setq s (replace-match "\\vert" t t s)))
19904 (defun org-uuidgen-p (s)
19905 "Is S an ID created by UUIDGEN?"
19906 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19908 (defun org-in-src-block-p nil
19909 "Whether point is in a code source block."
19911 (when (setq ov (overlays-at (point)))
19912 (memq 'org-block-background
19913 (overlay-properties
19916 (defun org-context ()
19917 "Return a list of contexts of the current cursor position.
19918 If several contexts apply, all are returned.
19919 Each context entry is a list with a symbol naming the context, and
19920 two positions indicating start and end of the context. Possible
19923 :headline anywhere in a headline
19924 :headline-stars on the leading stars in a headline
19925 :todo-keyword on a TODO keyword (including DONE) in a headline
19926 :tags on the TAGS in a headline
19927 :priority on the priority cookie in a headline
19928 :item on the first line of a plain list item
19929 :item-bullet on the bullet/number of a plain list item
19930 :checkbox on the checkbox in a plain list item
19931 :table in an org-mode table
19932 :table-special on a special filed in a table
19933 :table-table in a table.el table
19934 :clocktable in a clocktable
19935 :src-block in a source block
19936 :link on a hyperlink
19937 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
19938 :target on a <<target>>
19939 :radio-target on a <<<radio-target>>>
19940 :latex-fragment on a LaTeX fragment
19941 :latex-preview on a LaTeX fragment with overlaid preview image
19943 This function expects the position to be visible because it uses font-lock
19944 faces as a help to recognize the following contexts: :table-special, :link,
19946 (let* ((f (get-text-property (point) 'face))
19947 (faces (if (listp f) f (list f)))
19948 (case-fold-search t)
19949 (p (point)) clist o)
19950 ;; First the large context
19952 ((org-at-heading-p t)
19953 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19955 (beginning-of-line 1)
19956 (looking-at org-todo-line-tags-regexp))
19957 (push (org-point-in-group p 1 :headline-stars) clist)
19958 (push (org-point-in-group p 2 :todo-keyword) clist)
19959 (push (org-point-in-group p 4 :tags) clist))
19961 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19962 (if (looking-at "\\[#[A-Z0-9]\\]")
19963 (push (org-point-in-group p 0 :priority) clist)))
19966 (push (org-point-in-group p 2 :item-bullet) clist)
19967 (push (list :item (point-at-bol)
19968 (save-excursion (org-end-of-item) (point)))
19970 (and (org-at-item-checkbox-p)
19971 (push (org-point-in-group p 0 :checkbox) clist)))
19974 (push (list :table (org-table-begin) (org-table-end)) clist)
19975 (if (memq 'org-formula faces)
19976 (push (list :table-special
19977 (previous-single-property-change p 'face)
19978 (next-single-property-change p 'face)) clist)))
19979 ((org-at-table-p 'any)
19980 (push (list :table-table) clist)))
19983 ;; New the "medium" contexts: clocktables, source blocks
19984 (cond ((org-in-clocktable-p)
19985 (push (list :clocktable
19986 (and (or (looking-at "#\\+BEGIN: clocktable")
19987 (search-backward "#+BEGIN: clocktable" nil t))
19988 (match-beginning 0))
19989 (and (re-search-forward "#\\+END:?" nil t)
19990 (match-end 0))) clist))
19991 ((org-in-src-block-p)
19992 (push (list :src-block
19993 (and (or (looking-at "#\\+BEGIN_SRC")
19994 (search-backward "#+BEGIN_SRC" nil t))
19995 (match-beginning 0))
19996 (and (search-forward "#+END_SRC" nil t)
19997 (match-beginning 0))) clist)))
20000 ;; Now the small context
20002 ((org-at-timestamp-p)
20003 (push (org-point-in-group p 0 :timestamp) clist))
20004 ((memq 'org-link faces)
20006 (previous-single-property-change p 'face)
20007 (next-single-property-change p 'face)) clist))
20008 ((memq 'org-special-keyword faces)
20009 (push (list :keyword
20010 (previous-single-property-change p 'face)
20011 (next-single-property-change p 'face)) clist))
20013 (push (org-point-in-group p 0 :target) clist)
20014 (goto-char (1- (match-beginning 0)))
20015 (if (looking-at org-radio-target-regexp)
20016 (push (org-point-in-group p 0 :radio-target) clist))
20018 ((setq o (car (delq nil
20021 (if (memq x org-latex-fragment-image-overlays) x))
20022 (overlays-at (point))))))
20023 (push (list :latex-fragment
20024 (overlay-start o) (overlay-end o)) clist)
20025 (push (list :latex-preview
20026 (overlay-start o) (overlay-end o)) clist))
20027 ((org-inside-LaTeX-fragment-p)
20028 ;; FIXME: positions wrong.
20029 (push (list :latex-fragment (point) (point)) clist)))
20031 (setq clist (nreverse (delq nil clist)))
20034 ;; FIXME: Compare with at-regexp-p Do we need both?
20035 (defun org-in-regexp (re &optional nlines visually)
20036 "Check if point is inside a match of regexp.
20037 Normally only the current line is checked, but you can include NLINES extra
20038 lines both before and after point into the search.
20039 If VISUALLY is set, require that the cursor is not after the match but
20040 really on, so that the block visually is on the match."
20042 (let ((pos (point))
20043 (eol (point-at-eol (+ 1 (or nlines 0))))
20044 (inc (if visually 1 0)))
20046 (beginning-of-line (- 1 (or nlines 0)))
20047 (while (re-search-forward re eol t)
20048 (if (and (<= (match-beginning 0) pos)
20049 (>= (+ inc (match-end 0)) pos))
20050 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20052 (defun org-at-regexp-p (regexp)
20053 "Is point inside a match of REGEXP in the current line?"
20056 (let ((pos (point)) (end (point-at-eol)))
20057 (beginning-of-line 1)
20058 (while (re-search-forward regexp end t)
20059 (if (and (<= (match-beginning 0) pos)
20060 (>= (match-end 0) pos))
20064 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20065 "Non-nil when point is between matches of START-RE and END-RE.
20067 Also return a non-nil value when point is on one of the matches.
20069 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20070 buffer positions. Default values are the positions of headlines
20071 surrounding the point.
20073 The functions returns a cons cell whose car (resp. cdr) is the
20074 position before START-RE (resp. after END-RE)."
20076 (let ((pos (point))
20077 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20078 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20081 ;; Point is on a block when on START-RE or if START-RE can be
20082 ;; found before it...
20083 (and (or (org-at-regexp-p start-re)
20084 (re-search-backward start-re limit-up t))
20085 (setq beg (match-beginning 0))
20086 ;; ... and END-RE after it...
20087 (goto-char (match-end 0))
20088 (re-search-forward end-re limit-down t)
20089 (> (setq end (match-end 0)) pos)
20090 ;; ... without another START-RE in-between.
20091 (goto-char (match-beginning 0))
20092 (not (re-search-backward start-re (1+ beg) t))
20094 (cons beg end))))))
20096 (defun org-in-block-p (names)
20097 "Non-nil when point belongs to a block whose name belongs to NAMES.
20099 NAMES is a list of strings containing names of blocks.
20101 Return first block name matched, or nil. Beware that in case of
20102 nested blocks, the returned name may not belong to the closest
20106 (let ((case-fold-search t)
20107 (lim-up (save-excursion (outline-previous-heading)))
20108 (lim-down (save-excursion (outline-next-heading))))
20109 (mapc (lambda (name)
20110 (let ((n (regexp-quote name)))
20111 (when (org-between-regexps-p
20112 (concat "^[ \t]*#\\+begin_" n)
20113 (concat "^[ \t]*#\\+end_" n)
20119 (defun org-occur-in-agenda-files (regexp &optional nlines)
20120 "Call `multi-occur' with buffers for all agenda files."
20121 (interactive "sOrg-files matching: \np")
20122 (let* ((files (org-agenda-files))
20123 (tnames (mapcar 'file-truename files))
20124 (extra org-agenda-text-search-extra-files)
20126 (when (eq (car extra) 'agenda-archives)
20127 (setq extra (cdr extra))
20128 (setq files (org-add-archive-files files)))
20129 (while (setq f (pop extra))
20130 (unless (member (file-truename f) tnames)
20131 (add-to-list 'files f 'append)
20132 (add-to-list 'tnames (file-truename f) 'append)))
20134 (mapcar (lambda (x)
20135 (with-current-buffer
20136 (or (get-file-buffer x) (find-file-noselect x))
20142 (if (boundp 'occur-mode-find-occurrence-hook)
20144 (add-hook 'occur-mode-find-occurrence-hook
20146 (when (derived-mode-p 'org-mode)
20149 (defadvice occur-mode-goto-occurrence
20150 (after org-occur-reveal activate)
20151 (and (derived-mode-p 'org-mode) (org-reveal)))
20152 (defadvice occur-mode-goto-occurrence-other-window
20153 (after org-occur-reveal activate)
20154 (and (derived-mode-p 'org-mode) (org-reveal)))
20155 (defadvice occur-mode-display-occurrence
20156 (after org-occur-reveal activate)
20157 (when (derived-mode-p 'org-mode)
20158 (let ((pos (occur-mode-find-occurrence)))
20159 (with-current-buffer (marker-buffer pos)
20164 (defun org-occur-link-in-agenda-files ()
20165 "Create a link and search for it in the agendas.
20166 The link is not stored in `org-stored-links', it is just created
20167 for the search purpose."
20169 (let ((link (condition-case nil
20170 (org-store-link nil)
20171 (error "Unable to create a link to here"))))
20172 (org-occur-in-agenda-files (regexp-quote link))))
20174 (defun org-uniquify (list)
20175 "Remove duplicate elements from LIST."
20177 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20180 (defun org-delete-all (elts list)
20181 "Remove all elements in ELTS from LIST."
20183 (setq list (delete (pop elts) list)))
20186 (defun org-count (cl-item cl-seq)
20187 "Count the number of occurrences of ITEM in SEQ.
20188 Taken from `count' in cl-seq.el with all keyword arguments removed."
20189 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20190 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20191 (while (< cl-start cl-end)
20192 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20193 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20194 (setq cl-start (1+ cl-start)))
20197 (defun org-remove-if (predicate seq)
20198 "Remove everything from SEQ that fulfills PREDICATE."
20202 (if (not (funcall predicate e)) (push e res)))
20205 (defun org-remove-if-not (predicate seq)
20206 "Remove everything from SEQ that does not fulfill PREDICATE."
20210 (if (funcall predicate e) (push e res)))
20213 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20214 "Reduce two-argument FUNCTION across SEQ.
20215 Taken from `reduce' in cl-seq.el with all keyword arguments but
20216 \":initial-value\" removed."
20217 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20218 (cadr (memq :initial-value cl-keys)))
20219 (cl-seq (pop cl-seq))
20220 (t (funcall cl-func)))))
20222 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20225 (defun org-back-over-empty-lines ()
20226 "Move backwards over whitespace, to the beginning of the first empty line.
20227 Returns the number of empty lines passed."
20228 (let ((pos (point)))
20229 (if (cdr (assoc 'heading org-blank-before-new-entry))
20230 (skip-chars-backward " \t\n\r")
20232 (forward-line -1)))
20233 (beginning-of-line 2)
20234 (goto-char (min (point) pos))
20235 (count-lines (point) pos)))
20237 (defun org-skip-whitespace ()
20238 (skip-chars-forward " \t\n\r"))
20240 (defun org-point-in-group (point group &optional context)
20241 "Check if POINT is in match-group GROUP.
20242 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20243 match. If the match group does not exist or point is not inside it,
20245 (and (match-beginning group)
20246 (>= point (match-beginning group))
20247 (<= point (match-end group))
20249 (list context (match-beginning group) (match-end group))
20252 (defun org-switch-to-buffer-other-window (&rest args)
20253 "Switch to buffer in a second window on the current frame.
20254 In particular, do not allow pop-up frames.
20255 Returns the newly created buffer."
20256 (let (pop-up-frames special-display-buffer-names special-display-regexps
20257 special-display-function)
20258 (apply 'switch-to-buffer-other-window args)))
20260 (defun org-combine-plists (&rest plists)
20261 "Create a single property list from all plists in PLISTS.
20262 The process starts by copying the first list, and then setting properties
20263 from the other lists. Settings in the last list are the most significant
20264 ones and overrule settings in the other lists."
20265 (let ((rtn (copy-sequence (pop plists)))
20268 (setq ls (pop plists))
20270 (setq p (pop ls) v (pop ls))
20271 (setq rtn (plist-put rtn p v))))
20274 (defun org-move-line-down (arg)
20275 "Move the current line down. With prefix argument, move it past ARG lines."
20277 (let ((col (current-column))
20279 (beginning-of-line 1) (setq beg (point))
20280 (beginning-of-line 2) (setq end (point))
20281 (beginning-of-line (+ 1 arg))
20282 (setq pos (move-marker (make-marker) (point)))
20283 (insert (delete-and-extract-region beg end))
20285 (org-move-to-column col)))
20287 (defun org-move-line-up (arg)
20288 "Move the current line up. With prefix argument, move it past ARG lines."
20290 (let ((col (current-column))
20292 (beginning-of-line 1) (setq beg (point))
20293 (beginning-of-line 2) (setq end (point))
20294 (beginning-of-line (- arg))
20295 (setq pos (move-marker (make-marker) (point)))
20296 (insert (delete-and-extract-region beg end))
20298 (org-move-to-column col)))
20300 (defun org-replace-escapes (string table)
20301 "Replace %-escapes in STRING with values in TABLE.
20302 TABLE is an association list with keys like \"%a\" and string values.
20303 The sequences in STRING may contain normal field width and padding information,
20304 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20305 so values can contain further %-escapes if they are define later in TABLE."
20306 (let ((tbl (copy-alist table))
20307 (case-fold-search nil)
20310 (while (setq e (pop tbl))
20311 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20312 (when (and (cdr e) (string-match re (cdr e)))
20313 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20315 (add-text-properties 0 3 (list 'sref sref) safe)
20316 (setcdr e (replace-match safe t t (cdr e)))))
20317 (while (string-match re string)
20318 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20320 (setq string (replace-match rpl t t string))))
20321 (while (setq pchg (next-property-change pchg string))
20322 (let ((sref (get-text-property pchg 'sref string)))
20323 (when (and sref (string-match "SREF" string pchg))
20324 (setq string (replace-match sref t t string)))))
20327 (defun org-sublist (list start end)
20328 "Return a section of LIST, from START to END.
20329 Counting starts at 1."
20330 (let (rtn (c start))
20331 (setq list (nthcdr (1- start) list))
20332 (while (and list (<= c end))
20333 (push (pop list) rtn)
20337 (defun org-find-base-buffer-visiting (file)
20338 "Like `find-buffer-visiting' but always return the base buffer and
20339 not an indirect buffer."
20340 (let ((buf (or (get-file-buffer file)
20341 (find-buffer-visiting file))))
20343 (or (buffer-base-buffer buf) buf)
20346 (defun org-image-file-name-regexp (&optional extensions)
20347 "Return regexp matching the file names of images.
20348 If EXTENSIONS is given, only match these."
20349 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20350 (image-file-name-regexp)
20351 (let ((image-file-name-extensions
20353 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20354 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20356 (regexp-opt (nconc (mapcar 'upcase
20357 image-file-name-extensions)
20358 image-file-name-extensions)
20362 (defun org-file-image-p (file &optional extensions)
20363 "Return non-nil if FILE is an image."
20365 (string-match (org-image-file-name-regexp extensions) file)))
20367 (defun org-get-cursor-date ()
20368 "Return the date at cursor in as a time.
20369 This works in the calendar and in the agenda, anywhere else it just
20370 returns the current time."
20371 (let (date day defd)
20373 ((eq major-mode 'calendar-mode)
20374 (setq date (calendar-cursor-to-date)
20375 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20376 ((eq major-mode 'org-agenda-mode)
20377 (setq day (get-text-property (point) 'day))
20379 (setq date (calendar-gregorian-from-absolute day)
20380 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20382 (or defd (current-time))))
20384 (defvar org-agenda-action-marker (make-marker)
20385 "Marker pointing to the entry for the next agenda action.")
20387 (defun org-mark-entry-for-agenda-action ()
20388 "Mark the current entry as target of an agenda action.
20389 Agenda actions are actions executed from the agenda with the key `k',
20390 which make use of the date at the cursor."
20392 (move-marker org-agenda-action-marker
20393 (save-excursion (org-back-to-heading t) (point))
20396 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20398 (defun org-mark-subtree ()
20399 "Mark the current subtree.
20400 This puts point at the start of the current subtree, and mark at the end.
20402 If point is in an inline task, mark that task instead."
20404 (let ((inline-task-p
20405 (and (featurep 'org-inlinetask)
20406 (org-inlinetask-in-task-p)))
20408 ;; Get beginning of subtree
20410 (inline-task-p (org-inlinetask-goto-beginning))
20411 ((org-at-heading-p) (beginning-of-line))
20412 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20416 (org-inlinetask-goto-end)
20417 (org-end-of-subtree))
20419 (push-mark (point) nil t)
20422 ;;; Paragraph filling stuff.
20423 ;; We want this to be just right, so use the full arsenal.
20425 (declare-function orgstruct++-ignore-org-filling "org-macs.el" (&rest body))
20426 (defun org-indent-line-function ()
20427 "Indent line depending on context."
20429 (if orgstruct-is-++
20430 (orgstruct++-ignore-org-filling
20431 (funcall indent-line-function))
20432 (let* ((pos (point))
20433 (itemp (org-at-item-p))
20434 (case-fold-search t)
20435 (org-drawer-regexp (or org-drawer-regexp "\000"))
20436 (inline-task-p (and (featurep 'org-inlinetask)
20437 (org-inlinetask-in-task-p)))
20438 (inline-re (and inline-task-p
20439 (org-inlinetask-outline-regexp)))
20441 (beginning-of-line 1)
20444 ((looking-at "# ") (setq column 0))
20446 ((looking-at org-outline-regexp) (setq column 0))
20448 ((looking-at "#\\+include:") (setq column 0))
20449 ;; Footnote definition
20450 ((looking-at org-footnote-definition-re) (setq column 0))
20451 ;; Literal examples
20452 ((looking-at "[ \t]*:\\( \\|$\\)")
20453 (setq column (org-get-indentation))) ; do nothing
20455 ((ignore-errors (goto-char (org-in-item-p)))
20456 (setq column (if itemp
20457 (org-get-indentation)
20458 (org-list-item-body-column (point))))
20461 ((and (looking-at "[ \t]*:END:")
20462 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20464 (goto-char (1- (match-beginning 1)))
20465 (setq column (current-column))))
20467 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20469 (re-search-backward
20470 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20471 (setq column (org-get-indentation (match-string 0))))
20472 ((and (not (looking-at "[ \t]*#\\+begin_"))
20473 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20475 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20477 (cond ((equal (downcase (match-string 1)) "src")
20478 ;; src blocks: let `org-edit-src-exit' handle them
20479 (org-get-indentation))
20480 ((equal (downcase (match-string 1)) "example")
20481 (max (org-get-indentation)
20482 (org-get-indentation (match-string 0))))
20484 (org-get-indentation (match-string 0))))))
20485 ;; This line has nothing special, look at the previous relevant
20486 ;; line to compute indentation
20488 (beginning-of-line 0)
20489 (while (and (not (bobp))
20490 (not (looking-at org-drawer-regexp))
20491 ;; When point started in an inline task, do not move
20492 ;; above task starting line.
20493 (not (and inline-task-p (looking-at inline-re)))
20494 ;; Skip drawers, blocks, empty lines, verbatim,
20495 ;; comments, tables, footnotes definitions, lists,
20497 (or (and (looking-at "[ \t]*:END:")
20498 (re-search-backward org-drawer-regexp nil t))
20499 (and (looking-at "[ \t]*#\\+end_")
20500 (re-search-backward "[ \t]*#\\+begin_"nil t))
20501 (looking-at "[ \t]*[\n:#|]")
20502 (looking-at org-footnote-definition-re)
20503 (and (ignore-errors (goto-char (org-in-item-p)))
20505 (org-list-get-top-point (org-list-struct))))
20506 (and (not inline-task-p)
20507 (featurep 'org-inlinetask)
20508 (org-inlinetask-in-task-p)
20509 (or (org-inlinetask-goto-beginning) t))))
20510 (beginning-of-line 0))
20512 ;; There was an heading above.
20513 ((looking-at "\\*+[ \t]+")
20514 (if (not org-adapt-indentation)
20516 (goto-char (match-end 0))
20517 (setq column (current-column))))
20518 ;; A drawer had started and is unfinished
20519 ((looking-at org-drawer-regexp)
20520 (goto-char (1- (match-beginning 1)))
20521 (setq column (current-column)))
20522 ;; Else, nothing noticeable found: get indentation and go on.
20523 (t (setq column (org-get-indentation))))))
20524 ;; Now apply indentation and move cursor accordingly
20526 (if (<= (current-column) (current-indentation))
20527 (org-indent-line-to column)
20528 (save-excursion (org-indent-line-to column)))
20529 ;; Special polishing for properties, see `org-property-format'
20530 (setq column (current-column))
20531 (beginning-of-line 1)
20533 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20534 (replace-match (concat (match-string 1)
20535 (format org-property-format
20536 (match-string 2) (match-string 3)))
20538 (org-move-to-column column))))
20540 (defun org-indent-drawer ()
20541 "Indent the drawer at point."
20544 (e (and (save-excursion (re-search-forward ":END:" nil t))
20549 (when (overlays-at (point))
20550 (member 'invisible (overlay-properties
20551 (car (overlays-at (point)))))))))
20552 (when folded (org-cycle))
20553 (indent-for-tab-command)
20554 (while (and (move-beginning-of-line 2) (< (point) e))
20555 (indent-for-tab-command))
20557 (when folded (org-cycle)))
20558 (message "Drawer at point indented"))
20560 (defun org-indent-block ()
20561 "Indent the block at point."
20564 (case-fold-search t)
20565 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20570 (when (overlays-at (point))
20571 (member 'invisible (overlay-properties
20572 (car (overlays-at (point)))))))))
20573 (when folded (org-cycle))
20574 (indent-for-tab-command)
20575 (while (and (move-beginning-of-line 2) (< (point) e))
20576 (indent-for-tab-command))
20578 (when folded (org-cycle)))
20579 (message "Block at point indented"))
20581 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20582 "Variable to store copy of `adaptive-fill-regexp'.
20583 Since `adaptive-fill-regexp' is set to never match, we need to
20584 store a backup of its value before entering `org-mode' so that
20585 the functionality can be provided as a fall-back.")
20587 (defun org-set-autofill-regexps ()
20589 ;; In the paragraph separator we include headlines, because filling
20590 ;; text in a line directly attached to a headline would otherwise
20591 ;; fill the headline as well.
20592 (org-set-local 'comment-start-skip "^#+[ \t]*")
20593 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20594 ;; The paragraph starter includes hand-formatted lists.
20600 org-outline-regexp "\\|"
20602 (org-item-re) "\\|"
20605 "\\\\\\(begin\\|end\\|[][]\\)"))
20606 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20607 ;; But only if the user has not turned off tables or fixed-width regions
20609 'auto-fill-inhibit-regexp
20610 (concat org-outline-regexp
20612 "\\|[ \t]*" org-keyword-time-regexp
20613 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20616 (if org-enable-table-editor "|" "")
20617 (if org-enable-fixed-width-editor ":" "")
20619 ;; We use our own fill-paragraph function, to make sure that tables
20620 ;; and fixed-width regions are not wrapped. That function will pass
20621 ;; through to `fill-paragraph' when appropriate.
20622 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20623 ;; Prevent auto-fill from inserting unwanted new items.
20624 (if (boundp 'fill-nobreak-predicate)
20626 'fill-nobreak-predicate
20628 (append fill-nobreak-predicate
20629 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20630 ;; Adaptive filling: To get full control, first make sure that
20631 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20632 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20633 (org-set-local 'org-adaptive-fill-regexp-backup
20634 adaptive-fill-regexp))
20635 (org-set-local 'adaptive-fill-regexp "\000")
20636 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20637 (org-set-local 'adaptive-fill-function
20638 'org-adaptive-fill-function)
20640 'align-mode-rules-list
20641 '((org-in-buffer-settings
20642 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20643 (modes . '(org-mode))))))
20645 (defun org-fill-item-nobreak-p ()
20646 "Non-nil when a line break at point would insert a new item."
20647 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20649 (defun org-fill-line-break-nobreak-p ()
20650 "Non-nil when a line break at point would create an Org line break."
20652 (skip-chars-backward "[ \t]")
20653 (skip-chars-backward "\\\\")
20654 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20656 (defun org-fill-paragraph (&optional justify)
20657 "Re-align a table, pass through to fill-paragraph if no table."
20658 (let ((table-p (org-at-table-p))
20659 (table.el-p (org-at-table.el-p))
20660 (itemp (org-in-item-p)))
20661 (cond ((and (equal (char-after (point-at-bol)) ?*)
20662 (save-excursion (goto-char (point-at-bol))
20663 (looking-at org-outline-regexp)))
20664 t) ; skip headlines
20665 (table.el-p t) ; skip table.el tables
20666 (table-p (org-table-align) t) ; align Org tables
20667 (itemp ; align text in items
20668 (let* ((struct (save-excursion (goto-char itemp)
20669 (org-list-struct)))
20670 (parents (org-list-parents-alist struct))
20671 (children (org-list-get-children itemp struct parents))
20672 beg end prev next prefix)
20673 ;; Determine in which part of item point is: before
20674 ;; first child, after last child, between two
20675 ;; sub-lists, or simply in item if there's no child.
20678 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20680 end (org-list-get-item-end itemp struct)))
20681 ((< (point) (setq next (car children)))
20682 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20685 ((> (point) (setq prev (car (last children))))
20686 (setq beg (org-list-get-item-end prev struct)
20687 end (org-list-get-item-end itemp struct)
20688 prefix (save-excursion
20690 (skip-chars-forward " \t")
20691 (make-string (current-column) ?\ ))))
20693 (while (setq next (pop children))
20694 (if (> (point) next)
20696 (setq beg (org-list-get-item-end prev struct)
20698 prefix (save-excursion
20700 (skip-chars-forward " \t")
20701 (make-string (current-column) ?\ )))
20702 (throw 'exit nil))))))
20703 ;; Use `fill-paragraph' with buffer narrowed to item
20704 ;; without any child, and with our computed PREFIX.
20705 (flet ((fill-context-prefix (from to &optional flr) prefix))
20707 (narrow-to-region beg end)
20708 (save-excursion (fill-paragraph justify)))) t))
20709 ;; Special case where point is not in a list but is on
20710 ;; a paragraph adjacent to a list: make sure this paragraph
20711 ;; doesn't get merged with the end of the list by narrowing
20713 ((and (derived-mode-p 'org-mode)
20714 (save-excursion (forward-paragraph -1)
20715 (setq itemp (org-in-item-p))))
20716 (let ((struct (save-excursion (goto-char itemp)
20717 (org-list-struct))))
20719 (narrow-to-region (org-list-get-bottom-point struct)
20720 (save-excursion (forward-paragraph 1)
20722 (fill-paragraph justify) t)))
20723 ;; Don't fill schedule/deadline line before a paragraph
20724 ;; This only makes sense in real org-mode buffers
20725 ((and (eq major-mode 'org-mode)
20726 (save-excursion (forward-paragraph -1)
20727 (or (looking-at (concat "^[^\n]*" org-scheduled-regexp ".*$"))
20728 (looking-at (concat "^[^\n]*" org-deadline-regexp ".*$")))))
20730 (narrow-to-region (1+ (match-end 0))
20731 (save-excursion (forward-paragraph 1) (point)))
20732 (fill-paragraph justify) t))
20733 ;; Else falls back on `org-fill-paragraph-fallback-function'
20735 (orgstruct++-ignore-org-filling
20737 ;; (org-fill-paragraph-fallback-function
20738 ;; (funcall org-fill-paragraph-fallback-function justify))
20739 ;; Else simply call `fill-paragraph'.
20742 ;; For reference, this is the default value of adaptive-fill-regexp
20743 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20745 (defun org-adaptive-fill-function ()
20746 "Return a fill prefix for org-mode files."
20751 ((looking-at "#[ \t]+")
20752 (match-string-no-properties 0))
20755 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20756 ;; Point is in a list after `backward-paragraph': original
20757 ;; point wasn't in the list, or filling would have been taken
20758 ;; care of by `org-auto-fill-function', but the list and the
20759 ;; real paragraph are not separated by a blank line. Thus, move
20760 ;; point after the list to go back to real paragraph and
20761 ;; determine fill-prefix.
20762 ((setq itemp (org-in-item-p))
20764 (let* ((struct (org-list-struct))
20765 (bottom (org-list-get-bottom-point struct)))
20767 (make-string (org-get-indentation) ?\ )))
20769 ((looking-at org-adaptive-fill-regexp-backup)
20770 (match-string-no-properties 0))))))
20772 (defun org-auto-fill-function ()
20773 "Auto-fill function."
20774 (unless (and org-src-prevent-auto-filling (org-in-src-block-p))
20775 (let (itemp prefix)
20776 ;; When in a list, compute an appropriate fill-prefix and make
20777 ;; sure it will be used by `do-auto-fill'.
20778 (cond ((setq itemp (org-in-item-p))
20780 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20781 (flet ((fill-context-prefix (from to &optional flr) prefix))
20784 (orgstruct++-ignore-org-filling
20786 (t (do-auto-fill))))))
20790 (defun org-toggle-fixed-width-section (arg)
20791 "Toggle the fixed-width export.
20792 If there is no active region, the QUOTE keyword at the current headline is
20793 inserted or removed. When present, it causes the text between this headline
20794 and the next to be exported as fixed-width text, and unmodified.
20795 If there is an active region, this command adds or removes a colon as the
20796 first character of this line. If the first character of a line is a colon,
20797 this line is also exported in fixed-width font."
20800 (regionp (org-region-active-p))
20801 (beg (if regionp (region-beginning) (point)))
20802 (end (if regionp (region-end)))
20803 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20804 (case-fold-search nil)
20805 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20810 (setq cc (current-column))
20811 (beginning-of-line 1)
20812 (setq off (looking-at re))
20813 (while (> nlines 0)
20814 (setq nlines (1- nlines))
20815 (beginning-of-line 1)
20818 (org-move-to-column cc t)
20821 ((and off (looking-at re))
20822 (replace-match "" t t nil 1))
20823 ((not off) (org-move-to-column cc t) (insert ": ")))
20826 (org-back-to-heading)
20828 ((looking-at (format org-heading-keyword-regexp-format
20830 (goto-char (match-end 1))
20831 (looking-at (concat " +" org-quote-string))
20832 (replace-match "" t t)
20833 (when (eolp) (insert " ")))
20834 ((looking-at org-outline-regexp)
20835 (goto-char (match-end 0))
20836 (insert org-quote-string " ")))))))
20838 (defun org-reftex-citation ()
20839 "Use reftex-citation to insert a citation into the buffer.
20840 This looks for a line like
20842 #+BIBLIOGRAPHY: foo plain option:-d
20844 and derives from it that foo.bib is the bibliography file relevant
20845 for this document. It then installs the necessary environment for RefTeX
20846 to work in this buffer and calls `reftex-citation' to insert a citation
20849 Export of such citations to both LaTeX and HTML is handled by the contributed
20850 package org-exp-bibtex by Taru Karttunen."
20852 (let ((reftex-docstruct-symbol 'rds)
20853 (reftex-cite-format "\\cite{%l}")
20858 (let ((case-fold-search t)
20859 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20860 (if (not (save-excursion
20861 (or (re-search-forward re nil t)
20862 (re-search-backward re nil t))))
20863 (error "No bibliography defined in file")
20864 (setq bib (concat (match-string 1) ".bib")
20865 rds (list (list 'bib bib)))))))
20866 (call-interactively 'reftex-citation)))
20868 ;;;; Functions extending outline functionality
20870 (defun org-beginning-of-line (&optional arg)
20871 "Go to the beginning of the current line. If that is invisible, continue
20872 to a visible line beginning. This makes the function of C-a more intuitive.
20873 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20874 first attempt, and only move to after the tags when the cursor is already
20875 beyond the end of the headline."
20877 (let ((pos (point))
20878 (special (if (consp org-special-ctrl-a/e)
20879 (car org-special-ctrl-a/e)
20880 org-special-ctrl-a/e))
20882 (if (org-bound-and-true-p line-move-visual)
20883 (beginning-of-visual-line 1)
20884 (beginning-of-line 1))
20885 (if (and arg (fboundp 'move-beginning-of-line))
20886 (call-interactively 'move-beginning-of-line)
20890 (if (org-truely-invisible-p)
20891 (while (and (not (bobp)) (org-truely-invisible-p))
20893 (beginning-of-line 1))
20894 (forward-char 1))))
20897 ((and (looking-at org-complex-heading-regexp)
20898 (= (char-after (match-end 1)) ?\ ))
20899 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20903 (cond ((> pos refpos) refpos)
20904 ((= pos (point)) refpos)
20906 (cond ((> pos (point)) (point))
20907 ((not (eq last-command this-command)) (point))
20910 ;; Being at an item and not looking at an the item means point
20911 ;; was previously moved to beginning of a visual line, which
20912 ;; doesn't contain the item. Therefore, do nothing special,
20914 (when (looking-at org-list-full-item-re)
20915 ;; Set special position at first white space character after
20916 ;; bullet, and check-box, if any.
20917 (let ((after-bullet
20918 (let ((box (match-end 3)))
20919 (if (not box) (match-end 1)
20920 (let ((after (char-after box)))
20921 (if (and after (= after ? )) (1+ box) box))))))
20922 ;; Special case: Move point to special position when
20923 ;; currently after it or at beginning of line.
20925 (when (or (> pos after-bullet) (= (point) pos))
20926 (goto-char after-bullet))
20927 ;; Reversed case: Move point to special position when
20928 ;; point was already at beginning of line and command is
20930 (when (and (= (point) pos) (eq last-command this-command))
20931 (goto-char after-bullet))))))))
20933 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20935 (defun org-end-of-line (&optional arg)
20936 "Go to the end of the line.
20937 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20938 first attempt, and only move to after the tags when the cursor is already
20939 beyond the end of the headline."
20941 (let ((special (if (consp org-special-ctrl-a/e)
20942 (cdr org-special-ctrl-a/e)
20943 org-special-ctrl-a/e)))
20945 ((or (not special) arg
20946 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
20947 (call-interactively
20948 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20949 ((fboundp 'move-end-of-line) 'move-end-of-line)
20950 (t 'end-of-line))))
20951 ((org-at-heading-p)
20952 (let ((pos (point)))
20953 (beginning-of-line 1)
20954 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20956 (if (or (< pos (match-beginning 1))
20957 (= pos (match-end 0)))
20958 (goto-char (match-beginning 1))
20959 (goto-char (match-end 0)))
20960 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20961 (goto-char (match-end 0))
20962 (goto-char (match-beginning 1))))
20963 (call-interactively (if (fboundp 'move-end-of-line)
20967 (move-end-of-line 1)
20968 (when (overlays-at (1- (point))) (backward-char 1)))
20969 ;; At an item: Move before any hidden text.
20970 (t (call-interactively
20971 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20972 ((fboundp 'move-end-of-line) 'move-end-of-line)
20973 (t 'end-of-line)))))
20975 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20977 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20978 (define-key org-mode-map "\C-e" 'org-end-of-line)
20980 (defun org-backward-sentence (&optional arg)
20981 "Go to beginning of sentence, or beginning of table field.
20982 This will call `backward-sentence' or `org-table-beginning-of-field',
20983 depending on context."
20986 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20987 (t (call-interactively 'backward-sentence))))
20989 (defun org-forward-sentence (&optional arg)
20990 "Go to end of sentence, or end of table field.
20991 This will call `forward-sentence' or `org-table-end-of-field',
20992 depending on context."
20995 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20996 (t (call-interactively 'forward-sentence))))
20998 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20999 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21001 (defun org-kill-line (&optional arg)
21002 "Kill line, to tags or end of line."
21005 ((or (not org-special-ctrl-k)
21007 (not (org-at-heading-p)))
21008 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21009 org-ctrl-k-protect-subtree)
21010 (if (or (eq org-ctrl-k-protect-subtree 'error)
21011 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21012 (error "C-k aborted - would kill hidden subtree")))
21013 (call-interactively
21014 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21015 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21016 (kill-region (point) (match-beginning 1))
21017 (org-set-tags nil t))
21018 (t (kill-region (point) (point-at-eol)))))
21020 (define-key org-mode-map "\C-k" 'org-kill-line)
21022 (defun org-yank (&optional arg)
21023 "Yank. If the kill is a subtree, treat it specially.
21024 This command will look at the current kill and check if is a single
21025 subtree, or a series of subtrees[1]. If it passes the test, and if the
21026 cursor is at the beginning of a line or after the stars of a currently
21027 empty headline, then the yank is handled specially. How exactly depends
21028 on the value of the following variables, both set by default.
21030 org-yank-folded-subtrees
21031 When set, the subtree(s) will be folded after insertion, but only
21032 if doing so would now swallow text after the yanked text.
21034 org-yank-adjusted-subtrees
21035 When set, the subtree will be promoted or demoted in order to
21036 fit into the local outline tree structure, which means that the level
21037 will be adjusted so that it becomes the smaller one of the two
21038 *visible* surrounding headings.
21040 Any prefix to this command will cause `yank' to be called directly with
21041 no special treatment. In particular, a simple \\[universal-argument] prefix \
21043 plainly yank the text as it is.
21045 \[1] The test checks if the first non-white line is a heading
21046 and if there are no other headings with fewer stars."
21048 (org-yank-generic 'yank arg))
21050 (defun org-yank-generic (command arg)
21051 "Perform some yank-like command.
21053 This function implements the behavior described in the `org-yank'
21054 documentation. However, it has been generalized to work for any
21055 interactive command with similar behavior."
21057 ;; pretend to be command COMMAND
21058 (setq this-command command)
21061 (call-interactively command)
21063 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21064 (and (org-kill-is-subtree-p)
21066 (and (looking-at "[ \t]*$")
21069 (buffer-substring (point-at-bol) (point)))))))
21072 ((and subtreep org-yank-folded-subtrees)
21073 (let ((beg (point))
21075 (if (and subtreep org-yank-adjusted-subtrees)
21076 (org-paste-subtree nil nil 'for-yank)
21077 (call-interactively command))
21081 (when (and (bolp) subtreep
21082 (not (setq swallowp
21083 (org-yank-folding-would-swallow-text beg end))))
21084 (org-with-limited-levels
21085 (or (looking-at org-outline-regexp)
21086 (re-search-forward org-outline-regexp-bol end t))
21087 (while (and (< (point) end) (looking-at org-outline-regexp))
21089 (org-cycle-show-empty-lines 'folded)
21090 (condition-case nil
21091 (outline-forward-same-level 1)
21092 (error (goto-char end))))))
21095 "Inserted text not folded because that would swallow text"))
21098 (skip-chars-forward " \t\n\r")
21099 (beginning-of-line 1)
21100 (push-mark beg 'nomsg)))
21101 ((and subtreep org-yank-adjusted-subtrees)
21102 (let ((beg (point-at-bol)))
21103 (org-paste-subtree nil nil 'for-yank)
21104 (push-mark beg 'nomsg)))
21106 (call-interactively command))))))
21108 (defun org-yank-folding-would-swallow-text (beg end)
21109 "Would hide-subtree at BEG swallow any text after END?"
21111 (org-with-limited-levels
21114 (when (or (looking-at org-outline-regexp)
21115 (re-search-forward org-outline-regexp-bol end t))
21116 (setq level (org-outline-level)))
21118 (skip-chars-forward " \t\r\n\v\f")
21120 (and (bolp) (looking-at org-outline-regexp)
21121 (<= (org-outline-level) level)))
21122 nil ; Nothing would be swallowed
21123 t))))) ; something would swallow
21125 (define-key org-mode-map "\C-y" 'org-yank)
21127 (defun org-truely-invisible-p ()
21128 "Check if point is at a character currently not visible.
21129 This version does not only check the character property, but also
21131 ;; Early versions of noutline don't have `outline-invisible-p'.
21132 (if (org-bound-and-true-p visible-mode)
21134 (outline-invisible-p)))
21136 (defun org-invisible-p2 ()
21137 "Check if point is at a character currently not visible."
21139 (if (and (eolp) (not (bobp))) (backward-char 1))
21140 ;; Early versions of noutline don't have `outline-invisible-p'.
21141 (outline-invisible-p)))
21143 (defun org-back-to-heading (&optional invisible-ok)
21144 "Call `outline-back-to-heading', but provide a better error message."
21145 (condition-case nil
21146 (outline-back-to-heading invisible-ok)
21147 (error (error "Before first headline at position %d in buffer %s"
21148 (point) (current-buffer)))))
21150 (defun org-beginning-of-defun ()
21151 "Go to the beginning of the subtree, i.e. back to the heading."
21152 (org-back-to-heading))
21153 (defun org-end-of-defun ()
21154 "Go to the end of the subtree."
21155 (org-end-of-subtree nil t))
21157 (defun org-before-first-heading-p ()
21158 "Before first heading?"
21161 (null (re-search-backward org-outline-regexp-bol nil t))))
21163 (defun org-at-heading-p (&optional ignored)
21164 (outline-on-heading-p t))
21165 ;; Compatibility alias with Org versions < 7.8.03
21166 (defalias 'org-on-heading-p 'org-at-heading-p)
21168 (defun org-at-drawer-p nil
21169 "Is cursor at a drawer keyword?"
21171 (move-beginning-of-line 1)
21172 (looking-at org-drawer-regexp)))
21174 (defun org-at-block-p nil
21175 "Is cursor at a block keyword?"
21177 (move-beginning-of-line 1)
21178 (looking-at org-block-regexp)))
21180 (defun org-point-at-end-of-empty-headline ()
21181 "If point is at the end of an empty headline, return t, else nil.
21182 If the heading only contains a TODO keyword, it is still still considered
21184 (and (looking-at "[ \t]*$")
21185 (when org-todo-line-regexp
21187 (beginning-of-line 1)
21188 (let ((case-fold-search nil))
21189 (looking-at org-todo-line-regexp)
21190 (string= (match-string 3) ""))))))
21192 (defun org-at-heading-or-item-p ()
21193 (or (org-at-heading-p) (org-at-item-p)))
21195 (defun org-at-target-p ()
21196 (or (org-in-regexp org-radio-target-regexp)
21197 (org-in-regexp org-target-regexp)))
21198 ;; Compatibility alias with Org versions < 7.8.03
21199 (defalias 'org-on-target-p 'org-at-target-p)
21201 (defun org-up-heading-all (arg)
21202 "Move to the heading line of which the present line is a subheading.
21203 This function considers both visible and invisible heading lines.
21204 With argument, move up ARG levels."
21205 (if (fboundp 'outline-up-heading-all)
21206 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21207 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21209 (defun org-up-heading-safe ()
21210 "Move to the heading line of which the present line is a subheading.
21211 This version will not throw an error. It will return the level of the
21212 headline found, or nil if no higher level is found.
21214 Also, this function will be a lot faster than `outline-up-heading',
21215 because it relies on stars being the outline starters. This can really
21216 make a significant difference in outlines with very many siblings."
21217 (let (start-level re)
21218 (org-back-to-heading t)
21219 (setq start-level (funcall outline-level))
21220 (if (equal start-level 1)
21222 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21223 (if (re-search-backward re nil t)
21224 (funcall outline-level)))))
21226 (defun org-first-sibling-p ()
21227 "Is this heading the first child of its parents?"
21229 (let ((re org-outline-regexp-bol)
21231 (unless (org-at-heading-p t)
21232 (error "Not at a heading"))
21233 (setq level (funcall outline-level))
21235 (if (not (re-search-backward re nil t))
21237 (setq l (funcall outline-level))
21240 (defun org-goto-sibling (&optional previous)
21241 "Goto the next sibling, even if it is invisible.
21242 When PREVIOUS is set, go to the previous sibling instead. Returns t
21243 when a sibling was found. When none is found, return nil and don't
21245 (let ((fun (if previous 're-search-backward 're-search-forward))
21247 (re org-outline-regexp-bol)
21249 (when (condition-case nil (org-back-to-heading t) (error nil))
21250 (setq level (funcall outline-level))
21252 (or previous (forward-char 1))
21253 (while (funcall fun re nil t)
21254 (setq l (funcall outline-level))
21255 (when (< l level) (goto-char pos) (throw 'exit nil))
21256 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21260 (defun org-show-siblings ()
21261 "Show all siblings of the current headline."
21263 (while (org-goto-sibling) (org-flag-heading nil)))
21265 (while (org-goto-sibling 'previous)
21266 (org-flag-heading nil))))
21268 (defun org-goto-first-child ()
21269 "Goto the first child, even if it is invisible.
21270 Return t when a child was found. Otherwise don't move point and
21272 (let (level (pos (point)) (re org-outline-regexp-bol))
21273 (when (condition-case nil (org-back-to-heading t) (error nil))
21274 (setq level (outline-level))
21276 (if (and (re-search-forward re nil t) (> (outline-level) level))
21277 (progn (goto-char (match-beginning 0)) t)
21278 (goto-char pos) nil))))
21280 (defun org-show-hidden-entry ()
21281 "Show an entry where even the heading is hidden."
21285 (defun org-flag-heading (flag &optional entry)
21286 "Flag the current heading. FLAG non-nil means make invisible.
21287 When ENTRY is non-nil, show the entire entry."
21289 (org-back-to-heading t)
21290 ;; Check if we should show the entire entry
21295 (and (outline-next-heading)
21296 (org-flag-heading nil))))
21297 (outline-flag-region (max (point-min) (1- (point)))
21298 (save-excursion (outline-end-of-heading) (point))
21301 (defun org-get-next-sibling ()
21302 "Move to next heading of the same level, and return point.
21303 If there is no such heading, return nil.
21304 This is like outline-next-sibling, but invisible headings are ok."
21305 (let ((level (funcall outline-level)))
21306 (outline-next-heading)
21307 (while (and (not (eobp)) (> (funcall outline-level) level))
21308 (outline-next-heading))
21309 (if (or (eobp) (< (funcall outline-level) level))
21313 (defun org-get-last-sibling ()
21314 "Move to previous heading of the same level, and return point.
21315 If there is no such heading, return nil."
21316 (let ((opoint (point))
21317 (level (funcall outline-level)))
21318 (outline-previous-heading)
21319 (when (and (/= (point) opoint) (outline-on-heading-p t))
21320 (while (and (> (funcall outline-level) level)
21322 (outline-previous-heading))
21323 (if (< (funcall outline-level) level)
21327 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21328 ;; This contains an exact copy of the original function, but it uses
21329 ;; `org-back-to-heading', to make it work also in invisible
21330 ;; trees. And is uses an invisible-OK argument.
21331 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21332 ;; Furthermore, when used inside Org, finding the end of a large subtree
21333 ;; with many children and grandchildren etc, this can be much faster
21334 ;; than the outline version.
21335 (org-back-to-heading invisible-OK)
21337 (level (funcall outline-level)))
21338 (if (and (derived-mode-p 'org-mode) (< level 1000))
21339 ;; A true heading (not a plain list item), in Org-mode
21340 ;; This means we can easily find the end by looking
21341 ;; only for the right number of stars. Using a regexp to do
21342 ;; this is so much faster than using a Lisp loop.
21343 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21345 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21346 ;; something else, do it the slow way
21347 (while (and (not (eobp))
21348 (or first (> (funcall outline-level) level)))
21350 (outline-next-heading)))
21352 (if (memq (preceding-char) '(?\n ?\^M))
21354 ;; Go to end of line before heading
21356 (if (memq (preceding-char) '(?\n ?\^M))
21357 ;; leave blank line before heading
21358 (forward-char -1))))))
21361 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21362 "Use Org version in org-mode, for dramatic speed-up."
21363 (if (derived-mode-p 'org-mode)
21365 (org-end-of-subtree nil t)
21366 (unless (eobp) (backward-char 1)))
21369 (defun org-end-of-meta-data-and-drawers ()
21370 "Jump to the first text after meta data and drawers in the current entry.
21371 This will move over empty lines, lines with planning time stamps,
21372 clocking lines, and drawers."
21373 (org-back-to-heading t)
21374 (let ((end (save-excursion (outline-next-heading) (point)))
21375 (re (concat "\\(" org-drawer-regexp "\\)"
21376 "\\|" "[ \t]*" org-keyword-time-regexp)))
21378 (while (re-search-forward re end t)
21379 (if (not (match-end 1))
21380 ;; empty or planning line
21382 ;; a drawer, find the end
21383 (re-search-forward "^[ \t]*:END:" end 'move)
21385 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21388 (defun org-forward-same-level (arg &optional invisible-ok)
21389 "Move forward to the arg'th subheading at same level as this one.
21390 Stop at the first and last subheadings of a superior heading.
21391 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
21392 it wil also look at invisible ones."
21394 (org-back-to-heading invisible-ok)
21396 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21397 (re (format "^\\*\\{1,%d\\} " level))
21401 (while (and (re-search-forward re nil 'move)
21402 (setq l (- (match-end 0) (match-beginning 0) 1))
21405 (progn (backward-char 1) (outline-invisible-p)))
21406 (if (< l level) (setq arg 1)))
21407 (setq arg (1- arg)))
21408 (beginning-of-line 1)))
21410 (defun org-backward-same-level (arg &optional invisible-ok)
21411 "Move backward to the arg'th subheading at same level as this one.
21412 Stop at the first and last subheadings of a superior heading."
21414 (org-back-to-heading)
21416 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21417 (re (format "^\\*\\{1,%d\\} " level))
21420 (while (and (re-search-backward re nil 'move)
21421 (setq l (- (match-end 0) (match-beginning 0) 1))
21424 (outline-invisible-p))
21425 (if (< l level) (setq arg 1)))
21426 (setq arg (1- arg)))))
21428 (defun org-show-subtree ()
21429 "Show everything after this heading at deeper levels."
21431 (outline-flag-region
21434 (org-end-of-subtree t t))
21437 (defun org-show-entry ()
21438 "Show the body directly following this heading.
21439 Show the heading too, if it is currently invisible."
21442 (condition-case nil
21444 (org-back-to-heading t)
21445 (outline-flag-region
21446 (max (point-min) (1- (point)))
21448 (if (re-search-forward
21449 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21450 (match-beginning 1)
21453 (org-cycle-hide-drawers 'children))
21456 (defun org-make-options-regexp (kwds &optional extra)
21457 "Make a regular expression for keyword lines."
21461 (mapconcat 'regexp-quote kwds "\\|")
21462 (if extra (concat "\\|" extra))
21466 ;; Make isearch reveal the necessary context
21467 (defun org-isearch-end ()
21468 "Reveal context after isearch exits."
21469 (when isearch-success ; only if search was successful
21470 (if (featurep 'xemacs)
21471 ;; Under XEmacs, the hook is run in the correct place,
21472 ;; we directly show the context.
21473 (org-show-context 'isearch)
21474 ;; In Emacs the hook runs *before* restoring the overlays.
21475 ;; So we have to use a one-time post-command-hook to do this.
21476 ;; (Emacs 22 has a special variable, see function `org-mode')
21477 (unless (and (boundp 'isearch-mode-end-hook-quit)
21478 isearch-mode-end-hook-quit)
21479 ;; Only when the isearch was not quitted.
21480 (org-add-hook 'post-command-hook 'org-isearch-post-command
21481 'append 'local)))))
21483 (defun org-isearch-post-command ()
21484 "Remove self from hook, and show context."
21485 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21486 (org-show-context 'isearch))
21489 ;;;; Integration with and fixes for other packages
21493 (defvar org-imenu-markers nil
21494 "All markers currently used by Imenu.")
21495 (make-variable-buffer-local 'org-imenu-markers)
21497 (defun org-imenu-new-marker (&optional pos)
21498 "Return a new marker for use by Imenu, and remember the marker."
21499 (let ((m (make-marker)))
21500 (move-marker m (or pos (point)))
21501 (push m org-imenu-markers)
21504 (defun org-imenu-get-tree ()
21505 "Produce the index for Imenu."
21506 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21507 (setq org-imenu-markers nil)
21508 (let* ((n org-imenu-depth)
21509 (re (concat "^" (org-get-limited-outline-regexp)))
21510 (subs (make-vector (1+ n) nil))
21516 (goto-char (point-max))
21517 (while (re-search-backward re nil t)
21518 (setq level (org-reduced-level (funcall outline-level)))
21519 (when (and (<= level n)
21520 (looking-at org-complex-heading-regexp))
21521 (setq head (org-link-display-format
21522 (org-match-string-no-properties 4))
21523 m (org-imenu-new-marker))
21524 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21525 (if (>= level last-level)
21526 (push (cons head m) (aref subs level))
21527 (push (cons head (aref subs (1+ level))) (aref subs level))
21528 (loop for i from (1+ level) to n do (aset subs i nil)))
21529 (setq last-level level)))))
21532 (eval-after-load "imenu"
21534 (add-hook 'imenu-after-jump-hook
21536 (if (derived-mode-p 'org-mode)
21537 (org-show-context 'org-goto))))))
21539 (defun org-link-display-format (link)
21540 "Replace a link with either the description, or the link target
21541 if no description is present"
21543 (if (string-match org-bracket-link-analytic-regexp link)
21544 (replace-match (if (match-end 5)
21545 (match-string 5 link)
21546 (concat (match-string 1 link)
21547 (match-string 3 link)))
21551 (defun org-toggle-link-display ()
21552 "Toggle the literal or descriptive display of links."
21554 (if org-descriptive-links
21555 (progn (org-remove-from-invisibility-spec '(org-link))
21556 (org-restart-font-lock)
21557 (setq org-descriptive-links nil))
21558 (progn (add-to-invisibility-spec '(org-link))
21559 (org-restart-font-lock)
21560 (setq org-descriptive-links t))))
21562 ;; Speedbar support
21564 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21565 "Overlay marking the agenda restriction line in speedbar.")
21566 (overlay-put org-speedbar-restriction-lock-overlay
21567 'face 'org-agenda-restriction-lock)
21568 (overlay-put org-speedbar-restriction-lock-overlay
21569 'help-echo "Agendas are currently limited to this item.")
21570 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21572 (defun org-speedbar-set-agenda-restriction ()
21573 "Restrict future agenda commands to the location at point in speedbar.
21574 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21576 (require 'org-agenda)
21577 (let (p m tp np dir txt)
21579 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21581 (setq m (get-text-property p 'org-imenu-marker))
21582 (with-current-buffer (marker-buffer m)
21584 (org-agenda-set-restriction-lock 'subtree)))
21585 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21586 'speedbar-function 'speedbar-find-file))
21587 (setq tp (previous-single-property-change
21588 (1+ p) 'speedbar-function)
21589 np (next-single-property-change
21590 tp 'speedbar-function)
21591 dir (speedbar-line-directory)
21592 txt (buffer-substring-no-properties (or tp (point-min))
21593 (or np (point-max))))
21594 (with-current-buffer (find-file-noselect
21595 (let ((default-directory dir))
21596 (expand-file-name txt)))
21597 (unless (derived-mode-p 'org-mode)
21598 (error "Cannot restrict to non-Org-mode file"))
21599 (org-agenda-set-restriction-lock 'file)))
21600 (t (error "Don't know how to restrict Org-mode's agenda")))
21601 (move-overlay org-speedbar-restriction-lock-overlay
21602 (point-at-bol) (point-at-eol))
21603 (setq current-prefix-arg nil)
21604 (org-agenda-maybe-redo)))
21606 (eval-after-load "speedbar"
21608 (speedbar-add-supported-extension ".org")
21609 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21610 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21611 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21612 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21613 (add-hook 'speedbar-visiting-tag-hook
21614 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
21616 ;;; Fixes and Hacks for problems with other packages
21618 ;; Make flyspell not check words in links, to not mess up our keymap
21619 (defun org-mode-flyspell-verify ()
21620 "Don't let flyspell put overlays at active buttons, or on
21621 {todo,all-time,additional-option-like}-keywords."
21622 (let ((pos (max (1- (point)) (point-min)))
21623 (word (thing-at-point 'word)))
21624 (and (not (get-text-property pos 'keymap))
21625 (not (get-text-property pos 'org-no-flyspell))
21626 (not (member word org-todo-keywords-1))
21627 (not (member word org-all-time-keywords))
21628 (not (member word org-additional-option-like-keywords)))))
21630 (defun org-remove-flyspell-overlays-in (beg end)
21631 "Remove flyspell overlays in region."
21632 (and (org-bound-and-true-p flyspell-mode)
21633 (fboundp 'flyspell-delete-region-overlays)
21634 (flyspell-delete-region-overlays beg end))
21635 (add-text-properties beg end '(org-no-flyspell t)))
21637 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21638 (eval-after-load "bookmark"
21639 '(if (boundp 'bookmark-after-jump-hook)
21640 ;; We can use the hook
21641 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21642 ;; Hook not available, use advice
21643 (defadvice bookmark-jump (after org-make-visible activate)
21644 "Make the position visible."
21645 (org-bookmark-jump-unhide))))
21647 ;; Make sure saveplace shows the location if it was hidden
21648 (eval-after-load "saveplace"
21649 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21650 "Make the position visible."
21651 (org-bookmark-jump-unhide)))
21653 ;; Make sure ecb shows the location if it was hidden
21654 (eval-after-load "ecb"
21655 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21656 "Make hierarchy visible when jumping into location from ECB tree buffer."
21657 (if (derived-mode-p 'org-mode)
21658 (org-show-context))))
21660 (defun org-bookmark-jump-unhide ()
21661 "Unhide the current position, to show the bookmark location."
21662 (and (derived-mode-p 'org-mode)
21663 (or (outline-invisible-p)
21664 (save-excursion (goto-char (max (point-min) (1- (point))))
21665 (outline-invisible-p)))
21666 (org-show-context 'bookmark-jump)))
21668 ;; Make session.el ignore our circular variable
21669 (eval-after-load "session"
21670 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21672 ;;;; Experimental code
21674 (defun org-closed-in-range ()
21675 "Sparse tree of items closed in a certain time range.
21676 Still experimental, may disappear in the future."
21678 ;; Get the time interval from the user.
21679 (let* ((time1 (org-float-time
21680 (org-read-date nil 'to-time nil "Starting date: ")))
21681 (time2 (org-float-time
21682 (org-read-date nil 'to-time nil "End date:")))
21683 ;; callback function
21684 (callback (lambda ()
21687 (apply 'encode-time
21688 (org-parse-time-string
21689 (match-string 1))))))
21690 ;; check if time in interval
21691 (and (>= time time1) (<= time time2))))))
21692 ;; make tree, check each match with the callback
21693 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21699 (run-hooks 'org-load-hook)
21701 ;;; org.el ends here