1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010
4 ;; Free Software Foundation, Inc.
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; 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
78 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
79 (when (fboundp 'defvaralias
)
80 (unless (boundp 'calendar-view-holidays-initially-flag
)
81 (defvaralias 'calendar-view-holidays-initially-flag
82 'view-calendar-holidays-initially
))
83 (unless (boundp 'calendar-view-diary-initially-flag
)
84 (defvaralias 'calendar-view-diary-initially-flag
85 'view-diary-entries-initially
))
86 (unless (boundp 'diary-fancy-buffer
)
87 (defvaralias 'diary-fancy-buffer
'fancy-diary-buffer
)))
89 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
90 ;; the file noutline.el being loaded.
91 (if (featurep 'xemacs
) (condition-case nil
(require 'noutline
)))
92 ;; We require noutline, which might be provided in outline.el
93 (require 'outline
) (require 'noutline
)
94 ;; Other stuff we need.
96 (unless (fboundp 'time-subtract
) (defalias 'time-subtract
'subtract-time
))
101 (require 'org-entities
)
102 (require 'org-compat
)
106 (require 'org-footnote
)
117 ;; load languages based on value of `org-babel-load-languages'
118 (defvar org-babel-load-languages
)
120 (defun org-babel-do-load-languages (sym value
)
121 "Load the languages defined in `org-babel-load-languages'."
122 (set-default sym value
)
124 (let ((active (cdr pair
)) (lang (symbol-name (car pair
))))
127 (require (intern (concat "ob-" lang
))))
129 (funcall 'fmakunbound
130 (intern (concat "org-babel-execute:" lang
)))
131 (funcall 'fmakunbound
132 (intern (concat "org-babel-expand-body:" lang
)))))))
133 org-babel-load-languages
))
135 (defcustom org-babel-load-languages
'((emacs-lisp . t
))
136 "Languages which can be evaluated in Org-mode buffers.
137 This list can be used to load support for any of the languages
138 below, note that each language will depend on a different set of
139 system executables and/or Emacs modes. When a language is
140 \"loaded\", then code blocks in that language can be evaluated
141 with `org-babel-execute-src-block' bound by default to C-c
142 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
143 be set to remove code block evaluation from the C-c C-c
144 keybinding. By default only Emacs Lisp (which has no
145 requirements) is loaded."
147 :set
'org-babel-do-load-languages
148 :type
'(alist :tag
"Babel Languages"
153 (const :tag
"Asymptote" asymptote
)
154 (const :tag
"Clojure" clojure
)
155 (const :tag
"CSS" css
)
156 (const :tag
"Ditaa" ditaa
)
157 (const :tag
"Dot" dot
)
158 (const :tag
"Emacs Lisp" emacs-lisp
)
159 (const :tag
"Gnuplot" gnuplot
)
160 (const :tag
"Haskell" haskell
)
161 (const :tag
"Latex" latex
)
162 (const :tag
"Ledger" ledger
)
163 (const :tag
"Matlab" matlab
)
164 (const :tag
"Mscgen" mscgen
)
165 (const :tag
"Ocaml" ocaml
)
166 (const :tag
"Octave" octave
)
167 (const :tag
"Perl" perl
)
168 (const :tag
"Python" python
)
169 (const :tag
"Ruby" ruby
)
170 (const :tag
"Sass" sass
)
171 (const :tag
"Screen" screen
)
172 (const :tag
"Shell Script" sh
)
173 (const :tag
"Sql" sql
)
174 (const :tag
"Sqlite" sqlite
))
175 :value-type
(boolean :tag
"Activate" :value t
)))
177 ;;;; Customization variables
178 (defcustom org-clone-delete-id nil
179 "Remove ID property of clones of a subtree.
180 When non-nil, clones of a subtree don't inherit the ID property.
181 Otherwise they inherit the ID property with a new unique
188 (defconst org-version
"7.01trans"
189 "The version number of the file org.el.")
191 (defun org-version (&optional here
)
192 "Show the org-mode version in the echo area.
193 With prefix arg HERE, insert it at point."
195 (let* ((origin default-directory
)
196 (version org-version
)
198 (dir (concat (file-name-directory (locate-library "org")) "../" )))
199 (when (and (file-exists-p (expand-file-name ".git" dir
))
200 (executable-find "git"))
204 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
205 (with-current-buffer "*Shell Command Output*"
206 (goto-char (point-min))
207 (setq git-version
(buffer-substring (point) (point-at-eol))))
208 (subst-char-in-string ?- ?. git-version t
)
209 (when (string-match "\\S-"
210 (shell-command-to-string
211 "git diff-index --name-only HEAD --"))
212 (setq git-version
(concat git-version
".dirty")))
213 (setq version
(concat version
" (" git-version
")"))))
215 (setq version
(format "Org-mode version %s" version
))
216 (if here
(insert version
))
219 ;;; Compatibility constants
221 ;;; The custom variables
224 "Outline-based notes management and organizer."
229 (defcustom org-mode-hook nil
230 "Mode hook for Org-mode, run after the mode was turned on."
234 (defcustom org-load-hook nil
235 "Hook that is run after org.el has been loaded."
239 (defvar org-modules
) ; defined below
240 (defvar org-modules-loaded nil
241 "Have the modules been loaded already?")
243 (defun org-load-modules-maybe (&optional force
)
244 "Load all extensions listed in `org-modules'."
245 (when (or force
(not org-modules-loaded
))
247 (condition-case nil
(require ext
)
248 (error (message "Problems while trying to load feature `%s'" ext
))))
250 (setq org-modules-loaded t
)))
252 (defun org-set-modules (var value
)
253 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
255 (when (featurep 'org
)
256 (org-load-modules-maybe 'force
)))
258 (when (org-bound-and-true-p org-modules
)
259 (let ((a (member 'org-infojs org-modules
)))
260 (and a
(setcar a
'org-jsinfo
))))
262 (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
)
263 "Modules that should always be loaded together with org.el.
264 If a description starts with <C>, the file is not part of Emacs
265 and loading it will require that you have downloaded and properly installed
266 the org-mode distribution.
268 You can also use this system to load external packages (i.e. neither Org
269 core modules, nor modules from the CONTRIB directory). Just add symbols
270 to the end of the list. If the package is called org-xyz.el, then you need
271 to add the symbol `xyz', and the package must have a call to
275 :set
'org-set-modules
278 (const :tag
" bbdb: Links to BBDB entries" org-bbdb
)
279 (const :tag
" bibtex: Links to BibTeX entries" org-bibtex
)
280 (const :tag
" crypt: Encryption of subtrees" org-crypt
)
281 (const :tag
" ctags: Access to Emacs tags with links" org-ctags
)
282 (const :tag
" docview: Links to doc-view buffers" org-docview
)
283 (const :tag
" gnus: Links to GNUS folders/messages" org-gnus
)
284 (const :tag
" id: Global IDs for identifying entries" org-id
)
285 (const :tag
" info: Links to Info nodes" org-info
)
286 (const :tag
" jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo
)
287 (const :tag
" habit: Track your consistency with habits" org-habit
)
288 (const :tag
" inlinetask: Tasks independent of outline hierarchy" org-inlinetask
)
289 (const :tag
" irc: Links to IRC/ERC chat sessions" org-irc
)
290 (const :tag
" mac-message: Links to messages in Apple Mail" org-mac-message
)
291 (const :tag
" mew Links to Mew folders/messages" org-mew
)
292 (const :tag
" mhe: Links to MHE folders/messages" org-mhe
)
293 (const :tag
" protocol: Intercept calls from emacsclient" org-protocol
)
294 (const :tag
" rmail: Links to RMAIL folders/messages" org-rmail
)
295 (const :tag
" vm: Links to VM folders/messages" org-vm
)
296 (const :tag
" wl: Links to Wanderlust folders/messages" org-wl
)
297 (const :tag
" w3m: Special cut/paste from w3m to Org-mode." org-w3m
)
298 (const :tag
" mouse: Additional mouse support" org-mouse
)
299 (const :tag
" TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler
)
301 (const :tag
"C annotate-file: Annotate a file with org syntax" org-annotate-file
)
302 (const :tag
"C bookmark: Org-mode links to bookmarks" org-bookmark
)
303 (const :tag
"C checklist: Extra functions for checklists in repeated tasks" org-checklist
)
304 (const :tag
"C choose: Use TODO keywords to mark decisions states" org-choose
)
305 (const :tag
"C collector: Collect properties into tables" org-collector
)
306 (const :tag
"C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend
)
307 (const :tag
"C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol
)
308 (const :tag
"C eval: Include command output as text" org-eval
)
309 (const :tag
"C eval-light: Evaluate inbuffer-code on demand" org-eval-light
)
310 (const :tag
"C expiry: Expiry mechanism for Org-mode entries" org-expiry
)
311 (const :tag
"C exp-bibtex: Export citations using BibTeX" org-exp-bibtex
)
312 (const :tag
"C git-link: Provide org links to specific file version" org-git-link
)
313 (const :tag
"C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query
)
315 (const :tag
"C invoice: Help manage client invoices in Org-mode" org-invoice
)
317 (const :tag
"C jira: Add a jira:ticket protocol to Org-mode" org-jira
)
318 (const :tag
"C learn: SuperMemo's incremental learning algorithm" org-learn
)
319 (const :tag
"C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix
)
320 (const :tag
"C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal
)
321 (const :tag
"C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber
)
322 (const :tag
"C man: Support for links to manpages in Org-mode" org-man
)
323 (const :tag
"C mtags: Support for muse-like tags" org-mtags
)
324 (const :tag
"C panel: Simple routines for us with bad memory" org-panel
)
325 (const :tag
"C registry: A registry for Org-mode links" org-registry
)
326 (const :tag
"C org2rem: Convert org appointments into reminders" org2rem
)
327 (const :tag
"C screen: Visit screen sessions through Org-mode links" org-screen
)
328 (const :tag
"C secretary: Team management with org-mode" org-secretary
)
329 (const :tag
"C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks
)
330 (const :tag
"C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert
)
331 (const :tag
"C toc: Table of contents for Org-mode buffer" org-toc
)
332 (const :tag
"C track: Keep up with Org-mode development" org-track
)
333 (const :tag
"C velocity Something like Notational Velocity for Org" org-velocity
)
334 (const :tag
"C wikinodes: CamelCase wiki-like links" org-wikinodes
)
335 (repeat :tag
"External packages" :inline t
(symbol :tag
"Package"))))
337 (defcustom org-support-shift-select nil
338 "Non-nil means make shift-cursor commands select text when possible.
340 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
341 selecting a region, or enlarge regions started in this way.
342 In Org-mode, in special contexts, these same keys are used for other
343 purposes, important enough to compete with shift selection. Org tries
344 to balance these needs by supporting `shift-select-mode' outside these
345 special contexts, under control of this variable.
347 The default of this variable is nil, to avoid confusing behavior. Shifted
348 cursor keys will then execute Org commands in the following contexts:
349 - on a headline, changing TODO state (left/right) and priority (up/down)
350 - on a time stamp, changing the time
351 - in a plain list item, changing the bullet type
352 - in a property definition line, switching between allowed values
353 - in the BEGIN line of a clock table (changing the time block).
354 Outside these contexts, the commands will throw an error.
356 When this variable is t and the cursor is not in a special context,
357 Org-mode will support shift-selection for making and enlarging regions.
358 To make this more effective, the bullet cycling will no longer happen
359 anywhere in an item line, but only if the cursor is exactly on the bullet.
361 If you set this variable to the symbol `always', then the keys
362 will not be special in headlines, property lines, and item lines, to make
363 shift selection work there as well. If this is what you want, you can
364 use the following alternative commands: `C-c C-t' and `C-c ,' to
365 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
366 TODO sets, `C-c -' to cycle item bullet types, and properties can be
367 edited by hand or in column view.
369 However, when the cursor is on a timestamp, shift-cursor commands
370 will still edit the time stamp - this is just too good to give up.
372 XEmacs user should have this variable set to nil, because shift-select-mode
376 (const :tag
"Never" nil
)
377 (const :tag
"When outside special context" t
)
378 (const :tag
"Everywhere except timestamps" always
)))
380 (defgroup org-startup nil
381 "Options concerning startup of Org-mode."
385 (defcustom org-startup-folded t
386 "Non-nil means entering Org-mode will switch to OVERVIEW.
387 This can also be configured on a per-file basis by adding one of
388 the following lines anywhere in the buffer:
390 #+STARTUP: fold (or `overview', this is equivalent)
391 #+STARTUP: nofold (or `showall', this is equivalent)
393 #+STARTUP: showeverything"
396 (const :tag
"nofold: show all" nil
)
397 (const :tag
"fold: overview" t
)
398 (const :tag
"content: all headlines" content
)
399 (const :tag
"show everything, even drawers" showeverything
)))
401 (defcustom org-startup-truncated t
402 "Non-nil means entering Org-mode will set `truncate-lines'.
403 This is useful since some lines containing links can be very long and
404 uninteresting. Also tables look terrible when wrapped."
408 (defcustom org-startup-indented nil
409 "Non-nil means turn on `org-indent-mode' on startup.
410 This can also be configured on a per-file basis by adding one of
411 the following lines anywhere in the buffer:
415 :group
'org-structure
417 (const :tag
"Not" nil
)
418 (const :tag
"Globally (slow on startup in large files)" t
)))
420 (defcustom org-use-sub-superscripts t
421 "Non-nil means interpret \"_\" and \"^\" for export.
422 When this option is turned on, you can use TeX-like syntax for sub- and
423 superscripts. Several characters after \"_\" or \"^\" will be
424 considered as a single item - so grouping with {} is normally not
425 needed. For example, the following things will be parsed as single
426 sub- or superscripts.
428 10^24 or 10^tau several digits will be considered 1 item.
429 10^-12 or 10^-tau a leading sign with digits or a word
430 x^2-y^3 will be read as x^2 - y^3, because items are
431 terminated by almost any nonword/nondigit char.
432 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
434 Still, ambiguity is possible - so when in doubt use {} to enclose the
435 sub/superscript. If you set this variable to the symbol `{}',
436 the braces are *required* in order to trigger interpretations as
437 sub/superscript. This can be helpful in documents that need \"_\"
438 frequently in plain text.
440 Not all export backends support this, but HTML does.
442 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
444 :group
'org-export-translation
446 (const :tag
"Always interpret" t
)
447 (const :tag
"Only with braces" {})
448 (const :tag
"Never interpret" nil
)))
450 (if (fboundp 'defvaralias
)
451 (defvaralias 'org-export-with-sub-superscripts
'org-use-sub-superscripts
))
454 (defcustom org-startup-with-beamer-mode nil
455 "Non-nil means turn on `org-beamer-mode' on startup.
456 This can also be configured on a per-file basis by adding one of
457 the following lines anywhere in the buffer:
463 (defcustom org-startup-align-all-tables nil
464 "Non-nil means align all tables when visiting a file.
465 This is useful when the column width in tables is forced with <N> cookies
466 in table fields. Such tables will look correct only after the first re-align.
467 This can also be configured on a per-file basis by adding one of
468 the following lines anywhere in the buffer:
474 (defcustom org-insert-mode-line-in-empty-file nil
475 "Non-nil means insert the first line setting Org-mode in empty files.
476 When the function `org-mode' is called interactively in an empty file, this
477 normally means that the file name does not automatically trigger Org-mode.
478 To ensure that the file will always be in Org-mode in the future, a
479 line enforcing Org-mode will be inserted into the buffer, if this option
484 (defcustom org-replace-disputed-keys nil
485 "Non-nil means use alternative key bindings for some keys.
486 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
487 These keys are also used by other packages like shift-selection-mode'
488 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
489 If you want to use Org-mode together with one of these other modes,
490 or more generally if you would like to move some Org-mode commands to
491 other keys, set this variable and configure the keys with the variable
494 This option is only relevant at load-time of Org-mode, and must be set
495 *before* org.el is loaded. Changing it requires a restart of Emacs to
500 (defcustom org-use-extra-keys nil
501 "Non-nil means use extra key sequence definitions for certain commands.
502 This happens automatically if you run XEmacs or if `window-system'
503 is nil. This variable lets you do the same manually. You must
504 set it before loading org.
506 Example: on Carbon Emacs 22 running graphically, with an external
507 keyboard on a Powerbook, the default way of setting M-left might
508 not work for either Alt or ESC. Setting this variable will make
513 (if (fboundp 'defvaralias
)
514 (defvaralias 'org-CUA-compatible
'org-replace-disputed-keys
))
516 (defcustom org-disputed-keys
517 '(([(shift up
)] .
[(meta p
)])
518 ([(shift down
)] .
[(meta n
)])
519 ([(shift left
)] .
[(meta -
)])
520 ([(shift right
)] .
[(meta +)])
521 ([(control shift right
)] .
[(meta shift
+)])
522 ([(control shift left
)] .
[(meta shift -
)]))
523 "Keys for which Org-mode and other modes compete.
524 This is an alist, cars are the default keys, second element specifies
525 the alternative to use when `org-replace-disputed-keys' is t.
527 Keys can be specified in any syntax supported by `define-key'.
528 The value of this option takes effect only at Org-mode's startup,
529 therefore you'll have to restart Emacs to apply it after changing."
534 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
535 Or return the original if not disputed.
536 Also apply the translations defined in `org-xemacs-key-equivalents'."
537 (when org-replace-disputed-keys
538 (let* ((nkey (key-description key
))
539 (x (org-find-if (lambda (x)
540 (equal (key-description (car x
)) nkey
))
542 (setq key
(if x
(cdr x
) key
))))
543 (when (featurep 'xemacs
)
544 (setq key
(or (cdr (assoc key org-xemacs-key-equivalents
)) key
)))
547 (defun org-find-if (predicate seq
)
550 (if (funcall predicate
(car seq
))
551 (throw 'exit
(car seq
))
554 (defun org-defkey (keymap key def
)
555 "Define a key, possibly translated, as returned by `org-key'."
556 (define-key keymap
(org-key key
) def
))
558 (defcustom org-ellipsis nil
559 "The ellipsis to use in the Org-mode outline.
560 When nil, just use the standard three dots. When a string, use that instead,
561 When a face, use the standard 3 dots, but with the specified face.
562 The change affects only Org-mode (which will then use its own display table).
563 Changing this requires executing `M-x org-mode' in a buffer to become
566 :type
'(choice (const :tag
"Default" nil
)
567 (face :tag
"Face" :value org-warning
)
568 (string :tag
"String" :value
"...#")))
570 (defvar org-display-table nil
571 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
573 (defgroup org-keywords nil
574 "Keywords in Org-mode."
578 (defcustom org-deadline-string
"DEADLINE:"
579 "String to mark deadline entries.
580 A deadline is this string, followed by a time stamp. Should be a word,
581 terminated by a colon. You can insert a schedule keyword and
582 a timestamp with \\[org-deadline].
583 Changes become only effective after restarting Emacs."
587 (defcustom org-scheduled-string
"SCHEDULED:"
588 "String to mark scheduled TODO entries.
589 A schedule is this string, followed by a time stamp. Should be a word,
590 terminated by a colon. You can insert a schedule keyword and
591 a timestamp with \\[org-schedule].
592 Changes become only effective after restarting Emacs."
596 (defcustom org-closed-string
"CLOSED:"
597 "String used as the prefix for timestamps logging closing a TODO entry."
601 (defcustom org-clock-string
"CLOCK:"
602 "String used as prefix for timestamps clocking work hours on an item."
606 (defcustom org-comment-string
"COMMENT"
607 "Entries starting with this keyword will never be exported.
608 An entry can be toggled between COMMENT and normal with
609 \\[org-toggle-comment].
610 Changes become only effective after restarting Emacs."
614 (defcustom org-quote-string
"QUOTE"
615 "Entries starting with this keyword will be exported in fixed-width font.
616 Quoting applies only to the text in the entry following the headline, and does
617 not extend beyond the next headline, even if that is lower level.
618 An entry can be toggled between QUOTE and normal with
619 \\[org-toggle-fixed-width-section]."
623 (defconst org-repeat-re
624 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
625 "Regular expression for specifying repeated events.
626 After a match, group 1 contains the repeat expression.")
628 (defgroup org-structure nil
629 "Options concerning the general structure of Org-mode files."
633 (defgroup org-reveal-location nil
634 "Options about how to make context of a location visible."
635 :tag
"Org Reveal Location"
636 :group
'org-structure
)
638 (defconst org-context-choice
640 (const :tag
"Always" t
)
641 (const :tag
"Never" nil
)
642 (repeat :greedy t
:tag
"Individual contexts"
644 (choice :tag
"Context"
651 (const bookmark-jump
)
655 "Contexts for the reveal options.")
657 (defcustom org-show-hierarchy-above
'((default . t
))
658 "Non-nil means show full hierarchy when revealing a location.
659 Org-mode often shows locations in an org-mode file which might have
660 been invisible before. When this is set, the hierarchy of headings
661 above the exposed location is shown.
662 Turning this off for example for sparse trees makes them very compact.
663 Instead of t, this can also be an alist specifying this option for different
664 contexts. Valid contexts are
665 agenda when exposing an entry from the agenda
666 org-goto when using the command `org-goto' on key C-c C-j
667 occur-tree when using the command `org-occur' on key C-c /
668 tags-tree when constructing a sparse tree based on tags matches
669 link-search when exposing search matches associated with a link
670 mark-goto when exposing the jump goal of a mark
671 bookmark-jump when exposing a bookmark location
672 isearch when exiting from an incremental search
673 default default for all contexts not set explicitly"
674 :group
'org-reveal-location
675 :type org-context-choice
)
677 (defcustom org-show-following-heading
'((default . nil
))
678 "Non-nil means show following heading when revealing a location.
679 Org-mode often shows locations in an org-mode file which might have
680 been invisible before. When this is set, the heading following the
682 Turning this off for example for sparse trees makes them very compact,
683 but makes it harder to edit the location of the match. In such a case,
684 use the command \\[org-reveal] to show more context.
685 Instead of t, this can also be an alist specifying this option for different
686 contexts. See `org-show-hierarchy-above' for valid contexts."
687 :group
'org-reveal-location
688 :type org-context-choice
)
690 (defcustom org-show-siblings
'((default . nil
) (isearch t
))
691 "Non-nil means show all sibling heading when revealing a location.
692 Org-mode often shows locations in an org-mode file which might have
693 been invisible before. When this is set, the sibling of the current entry
694 heading are all made visible. If `org-show-hierarchy-above' is t,
695 the same happens on each level of the hierarchy above the current entry.
697 By default this is on for the isearch context, off for all other contexts.
698 Turning this off for example for sparse trees makes them very compact,
699 but makes it harder to edit the location of the match. In such a case,
700 use the command \\[org-reveal] to show more context.
701 Instead of t, this can also be an alist specifying this option for different
702 contexts. See `org-show-hierarchy-above' for valid contexts."
703 :group
'org-reveal-location
704 :type org-context-choice
)
706 (defcustom org-show-entry-below
'((default . nil
))
707 "Non-nil means show the entry below a headline when revealing a location.
708 Org-mode often shows locations in an org-mode file which might have
709 been invisible before. When this is set, the text below the headline that is
710 exposed is also shown.
712 By default this is off for all contexts.
713 Instead of t, this can also be an alist specifying this option for different
714 contexts. See `org-show-hierarchy-above' for valid contexts."
715 :group
'org-reveal-location
716 :type org-context-choice
)
718 (defcustom org-indirect-buffer-display
'other-window
719 "How should indirect tree buffers be displayed?
720 This applies to indirect buffers created with the commands
721 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
723 current-window Display in the current window
724 other-window Just display in another window.
725 dedicated-frame Create one new frame, and re-use it each time.
726 new-frame Make a new frame each time. Note that in this case
727 previously-made indirect buffers are kept, and you need to
728 kill these buffers yourself."
729 :group
'org-structure
730 :group
'org-agenda-windows
732 (const :tag
"In current window" current-window
)
733 (const :tag
"In current frame, other window" other-window
)
734 (const :tag
"Each time a new frame" new-frame
)
735 (const :tag
"One dedicated frame" dedicated-frame
)))
737 (defcustom org-use-speed-commands nil
738 "Non-nil means activate single letter commands at beginning of a headline.
739 This may also be a function to test for appropriate locations where speed
740 commands should be active."
741 :group
'org-structure
743 (const :tag
"Never" nil
)
744 (const :tag
"At beginning of headline stars" t
)
747 (defcustom org-speed-commands-user nil
748 "Alist of additional speed commands.
749 This list will be checked before `org-speed-commands-default'
750 when the variable `org-use-speed-commands' is non-nil
751 and when the cursor is at the beginning of a headline.
752 The car if each entry is a string with a single letter, which must
753 be assigned to `self-insert-command' in the global map.
754 The cdr is either a command to be called interactively, a function
755 to be called, or a form to be evaluated.
756 An entry that is just a list with a single string will be interpreted
757 as a descriptive headline that will be added when listing the speed
758 commands in the Help buffer using the `?' speed command."
759 :group
'org-structure
760 :type
'(repeat :value
("k" . ignore
)
761 (choice :value
("k" . ignore
)
762 (list :tag
"Descriptive Headline" (string :tag
"Headline"))
763 (cons :tag
"Letter and Command"
764 (string :tag
"Command letter")
769 (defgroup org-cycle nil
770 "Options concerning visibility cycling in Org-mode."
772 :group
'org-structure
)
774 (defcustom org-cycle-skip-children-state-if-no-children t
775 "Non-nil means skip CHILDREN state in entries that don't have any."
779 (defcustom org-cycle-max-level nil
780 "Maximum level which should still be subject to visibility cycling.
781 Levels higher than this will, for cycling, be treated as text, not a headline.
782 When `org-odd-levels-only' is set, a value of N in this variable actually
783 means 2N-1 stars as the limiting headline.
784 When nil, cycle all levels.
785 Note that the limiting level of cycling is also influenced by
786 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
787 `org-inlinetask-min-level' is, cycling will be limited to levels one less
791 (const :tag
"No limit" nil
)
792 (integer :tag
"Maximum level")))
794 (defcustom org-drawers
'("PROPERTIES" "CLOCK" "LOGBOOK")
795 "Names of drawers. Drawers are not opened by cycling on the headline above.
796 Drawers only open with a TAB on the drawer line itself. A drawer looks like
801 The drawer \"PROPERTIES\" is special for capturing properties through
804 Drawers can be defined on the per-file basis with a line like:
806 #+DRAWERS: HIDDEN STATE PROPERTIES"
807 :group
'org-structure
809 :type
'(repeat (string :tag
"Drawer Name")))
811 (defcustom org-hide-block-startup nil
812 "Non-nil means entering Org-mode will fold all blocks.
813 This can also be set in on a per-file basis with
815 #+STARTUP: hideblocks
816 #+STARTUP: showblocks"
821 (defcustom org-cycle-global-at-bob nil
822 "Cycle globally if cursor is at beginning of buffer and not at a headline.
823 This makes it possible to do global cycling without having to use S-TAB or
824 \\[universal-argument] TAB. For this special case to work, the first line \
826 must not be a headline - it may be empty or some other text. When used in
827 this way, `org-cycle-hook' is disables temporarily, to make sure the
828 cursor stays at the beginning of the buffer.
829 When this option is nil, don't do anything special at the beginning
834 (defcustom org-cycle-level-after-item
/entry-creation t
835 "Non-nil means cycle entry level or item indentation in new empty entries.
837 When the cursor is at the end of an empty headline, i.e with only stars
838 and maybe a TODO keyword, TAB will then switch the entry to become a child,
839 and then all possible ancestor states, before returning to the original state.
840 This makes data entry extremely fast: M-RET to create a new headline,
841 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
843 When the cursor is at the end of an empty plain list item, one TAB will
844 make it a subitem, two or more tabs will back up to make this an item
845 higher up in the item hierarchy."
849 (defcustom org-cycle-emulate-tab t
850 "Where should `org-cycle' emulate TAB.
852 white Only in completely white lines
853 whitestart Only at the beginning of lines, before the first non-white char
854 t Everywhere except in headlines
855 exc-hl-bol Everywhere except at the start of a headline
856 If TAB is used in a place where it does not emulate TAB, the current subtree
857 visibility is cycled."
859 :type
'(choice (const :tag
"Never" nil
)
860 (const :tag
"Only in completely white lines" white
)
861 (const :tag
"Before first char in a line" whitestart
)
862 (const :tag
"Everywhere except in headlines" t
)
863 (const :tag
"Everywhere except at bol in headlines" exc-hl-bol
)
866 (defcustom org-cycle-separator-lines
2
867 "Number of empty lines needed to keep an empty line between collapsed trees.
868 If you leave an empty line between the end of a subtree and the following
869 headline, this empty line is hidden when the subtree is folded.
870 Org-mode will leave (exactly) one empty line visible if the number of
871 empty lines is equal or larger to the number given in this variable.
872 So the default 2 means at least 2 empty lines after the end of a subtree
873 are needed to produce free space between a collapsed subtree and the
876 If the number is negative, and the number of empty lines is at least -N,
877 all empty lines are shown.
879 Special case: when 0, never leave empty lines in collapsed view."
882 (put 'org-cycle-separator-lines
'safe-local-variable
'integerp
)
884 (defcustom org-pre-cycle-hook nil
885 "Hook that is run before visibility cycling is happening.
886 The function(s) in this hook must accept a single argument which indicates
887 the new state that will be set right after running this hook. The
888 argument is a symbol. Before a global state change, it can have the values
889 `overview', `content', or `all'. Before a local state change, it can have
890 the values `folded', `children', or `subtree'."
894 (defcustom org-cycle-hook
'(org-cycle-hide-archived-subtrees
895 org-cycle-hide-drawers
896 org-cycle-show-empty-lines
897 org-optimize-window-after-visibility-change
)
898 "Hook that is run after `org-cycle' has changed the buffer visibility.
899 The function(s) in this hook must accept a single argument which indicates
900 the new state that was set by the most recent `org-cycle' command. The
901 argument is a symbol. After a global state change, it can have the values
902 `overview', `content', or `all'. After a local state change, it can have
903 the values `folded', `children', or `subtree'."
907 (defgroup org-edit-structure nil
908 "Options concerning structure editing in Org-mode."
909 :tag
"Org Edit Structure"
910 :group
'org-structure
)
912 (defcustom org-odd-levels-only nil
913 "Non-nil means skip even levels and only use odd levels for the outline.
914 This has the effect that two stars are being added/taken away in
915 promotion/demotion commands. It also influences how levels are
916 handled by the exporters.
917 Changing it requires restart of `font-lock-mode' to become effective
918 for fontification also in regions already fontified.
919 You may also set this on a per-file basis by adding one of the following
924 :group
'org-edit-structure
925 :group
'org-appearance
928 (defcustom org-adapt-indentation t
929 "Non-nil means adapt indentation to outline node level.
931 When this variable is set, Org assumes that you write outlines by
932 indenting text in each node to align with the headline (after the stars).
933 The following issues are influenced by this variable:
935 - When this is set and the *entire* text in an entry is indented, the
936 indentation is increased by one space in a demotion command, and
937 decreased by one in a promotion command. If any line in the entry
938 body starts with text at column 0, indentation is not changed at all.
940 - Property drawers and planning information is inserted indented when
941 this variable s set. When nil, they will not be indented.
943 - TAB indents a line relative to context. The lines below a headline
944 will be indented when this variable is set.
946 Note that this is all about true indentation, by adding and removing
947 space characters. See also `org-indent.el' which does level-dependent
948 indentation in a virtual way, i.e. at display time in Emacs."
949 :group
'org-edit-structure
952 (defcustom org-special-ctrl-a
/e nil
953 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
955 When t, `C-a' will bring back the cursor to the beginning of the
956 headline text, i.e. after the stars and after a possible TODO keyword.
957 In an item, this will be the position after the bullet.
958 When the cursor is already at that position, another `C-a' will bring
959 it to the beginning of the line.
961 `C-e' will jump to the end of the headline, ignoring the presence of tags
962 in the headline. A second `C-e' will then jump to the true end of the
963 line, after any tags. This also means that, when this variable is
964 non-nil, `C-e' also will never jump beyond the end of the heading of a
965 folded section, i.e. not after the ellipses.
967 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
968 going to the true line boundary first. Only a directly following, identical
969 keypress will bring the cursor to the special positions.
971 This may also be a cons cell where the behavior for `C-a' and `C-e' is
973 :group
'org-edit-structure
975 (const :tag
"off" nil
)
976 (const :tag
"on: after stars/bullet and before tags first" t
)
977 (const :tag
"reversed: true line boundary first" reversed
)
978 (cons :tag
"Set C-a and C-e separately"
979 (choice :tag
"Special C-a"
980 (const :tag
"off" nil
)
981 (const :tag
"on: after stars/bullet first" t
)
982 (const :tag
"reversed: before stars/bullet first" reversed
))
983 (choice :tag
"Special C-e"
984 (const :tag
"off" nil
)
985 (const :tag
"on: before tags first" t
)
986 (const :tag
"reversed: after tags first" reversed
)))))
987 (if (fboundp 'defvaralias
)
988 (defvaralias 'org-special-ctrl-a
'org-special-ctrl-a
/e
))
990 (defcustom org-special-ctrl-k nil
991 "Non-nil means `C-k' will behave specially in headlines.
992 When nil, `C-k' will call the default `kill-line' command.
993 When t, the following will happen while the cursor is in the headline:
995 - When the cursor is at the beginning of a headline, kill the entire
996 line and possible the folded subtree below the line.
997 - When in the middle of the headline text, kill the headline up to the tags.
998 - When after the headline text, kill the tags."
999 :group
'org-edit-structure
1002 (defcustom org-ctrl-k-protect-subtree nil
1003 "Non-nil means, do not delete a hidden subtree with C-k.
1004 When set to the symbol `error', simply throw an error when C-k is
1005 used to kill (part-of) a headline that has hidden text behind it.
1006 Any other non-nil value will result in a query to the user, if it is
1007 OK to kill that hidden subtree. When nil, kill without remorse."
1008 :group
'org-edit-structure
1010 (const :tag
"Do not protect hidden subtrees" nil
)
1011 (const :tag
"Protect hidden subtrees with a security query" t
)
1012 (const :tag
"Never kill a hidden subtree with C-k" error
)))
1014 (defcustom org-yank-folded-subtrees t
1015 "Non-nil means when yanking subtrees, fold them.
1016 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1017 it starts with a heading and all other headings in it are either children
1018 or siblings, then fold all the subtrees. However, do this only if no
1019 text after the yank would be swallowed into a folded tree by this action."
1020 :group
'org-edit-structure
1023 (defcustom org-yank-adjusted-subtrees nil
1024 "Non-nil means when yanking subtrees, adjust the level.
1025 With this setting, `org-paste-subtree' is used to insert the subtree, see
1026 this function for details."
1027 :group
'org-edit-structure
1030 (defcustom org-M-RET-may-split-line
'((default . t
))
1031 "Non-nil means M-RET will split the line at the cursor position.
1032 When nil, it will go to the end of the line before making a
1034 You may also set this option in a different way for different
1035 contexts. Valid contexts are:
1037 headline when creating a new headline
1038 item when creating a new item
1039 table in a table field
1040 default the value to be used for all contexts not explicitly
1042 :group
'org-structure
1045 (const :tag
"Always" t
)
1046 (const :tag
"Never" nil
)
1047 (repeat :greedy t
:tag
"Individual contexts"
1049 (choice :tag
"Context"
1057 (defcustom org-insert-heading-respect-content nil
1058 "Non-nil means insert new headings after the current subtree.
1059 When nil, the new heading is created directly after the current line.
1060 The commands \\[org-insert-heading-respect-content] and
1061 \\[org-insert-todo-heading-respect-content] turn this variable on
1062 for the duration of the command."
1063 :group
'org-structure
1066 (defcustom org-blank-before-new-entry
'((heading . auto
)
1067 (plain-list-item . auto
))
1068 "Should `org-insert-heading' leave a blank line before new heading/item?
1069 The value is an alist, with `heading' and `plain-list-item' as car,
1070 and a boolean flag as cdr. For plain lists, if the variable
1071 `org-empty-line-terminates-plain-lists' is set, the setting here
1072 is ignored and no empty line is inserted, to keep the list in tact."
1073 :group
'org-edit-structure
1075 (cons (const heading
)
1076 (choice (const :tag
"Never" nil
)
1077 (const :tag
"Always" t
)
1078 (const :tag
"Auto" auto
)))
1079 (cons (const plain-list-item
)
1080 (choice (const :tag
"Never" nil
)
1081 (const :tag
"Always" t
)
1082 (const :tag
"Auto" auto
)))))
1084 (defcustom org-insert-heading-hook nil
1085 "Hook being run after inserting a new heading."
1086 :group
'org-edit-structure
1089 (defcustom org-enable-fixed-width-editor t
1090 "Non-nil means lines starting with \":\" are treated as fixed-width.
1091 This currently only means they are never auto-wrapped.
1092 When nil, such lines will be treated like ordinary lines.
1093 See also the QUOTE keyword."
1094 :group
'org-edit-structure
1097 (defcustom org-goto-auto-isearch t
1098 "Non-nil means typing characters in `org-goto' starts incremental search."
1099 :group
'org-edit-structure
1102 (defgroup org-sparse-trees nil
1103 "Options concerning sparse trees in Org-mode."
1104 :tag
"Org Sparse Trees"
1105 :group
'org-structure
)
1107 (defcustom org-highlight-sparse-tree-matches t
1108 "Non-nil means highlight all matches that define a sparse tree.
1109 The highlights will automatically disappear the next time the buffer is
1110 changed by an edit command."
1111 :group
'org-sparse-trees
1114 (defcustom org-remove-highlights-with-change t
1115 "Non-nil means any change to the buffer will remove temporary highlights.
1116 Such highlights are created by `org-occur' and `org-clock-display'.
1117 When nil, `C-c C-c needs to be used to get rid of the highlights.
1118 The highlights created by `org-preview-latex-fragment' always need
1119 `C-c C-c' to be removed."
1120 :group
'org-sparse-trees
1125 (defcustom org-occur-hook
'(org-first-headline-recenter)
1126 "Hook that is run after `org-occur' has constructed a sparse tree.
1127 This can be used to recenter the window to show as much of the structure
1129 :group
'org-sparse-trees
1132 (defgroup org-imenu-and-speedbar nil
1133 "Options concerning imenu and speedbar in Org-mode."
1134 :tag
"Org Imenu and Speedbar"
1135 :group
'org-structure
)
1137 (defcustom org-imenu-depth
2
1138 "The maximum level for Imenu access to Org-mode headlines.
1139 This also applied for speedbar access."
1140 :group
'org-imenu-and-speedbar
1143 (defgroup org-table nil
1144 "Options concerning tables in Org-mode."
1148 (defcustom org-enable-table-editor
'optimized
1149 "Non-nil means lines starting with \"|\" are handled by the table editor.
1150 When nil, such lines will be treated like ordinary lines.
1152 When equal to the symbol `optimized', the table editor will be optimized to
1154 - Automatic overwrite mode in front of whitespace in table fields.
1155 This makes the structure of the table stay in tact as long as the edited
1156 field does not exceed the column width.
1157 - Minimize the number of realigns. Normally, the table is aligned each time
1158 TAB or RET are pressed to move to another field. With optimization this
1159 happens only if changes to a field might have changed the column width.
1160 Optimization requires replacing the functions `self-insert-command',
1161 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1162 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1163 very good at guessing when a re-align will be necessary, but you can always
1164 force one with \\[org-ctrl-c-ctrl-c].
1166 If you would like to use the optimized version in Org-mode, but the
1167 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1169 This variable can be used to turn on and off the table editor during a session,
1170 but in order to toggle optimization, a restart is required.
1172 See also the variable `org-table-auto-blank-field'."
1175 (const :tag
"off" nil
)
1177 (const :tag
"on, optimized" optimized
)))
1179 (defcustom org-self-insert-cluster-for-undo t
1180 "Non-nil means cluster self-insert commands for undo when possible.
1181 If this is set, then, like in the Emacs command loop, 20 consecutive
1182 characters will be undone together.
1183 This is configurable, because there is some impact on typing performance."
1187 (defcustom org-table-tab-recognizes-table.el t
1188 "Non-nil means TAB will automatically notice a table.el table.
1189 When it sees such a table, it moves point into it and - if necessary -
1190 calls `table-recognize-table'."
1191 :group
'org-table-editing
1194 (defgroup org-link nil
1195 "Options concerning links in Org-mode."
1199 (defvar org-link-abbrev-alist-local nil
1200 "Buffer-local version of `org-link-abbrev-alist', which see.
1201 The value of this is taken from the #+LINK lines.")
1202 (make-variable-buffer-local 'org-link-abbrev-alist-local
)
1204 (defcustom org-link-abbrev-alist nil
1205 "Alist of link abbreviations.
1206 The car of each element is a string, to be replaced at the start of a link.
1207 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1208 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1210 [[linkkey:tag][description]]
1212 The 'linkkey' must be a word word, starting with a letter, followed
1213 by letters, numbers, '-' or '_'.
1215 If REPLACE is a string, the tag will simply be appended to create the link.
1216 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1217 the placeholder \"%h\" will cause a url-encoded version of the tag to
1218 be inserted at that point (see the function `url-hexify-string').
1220 REPLACE may also be a function that will be called with the tag as the
1221 only argument to create the link, which should be returned as a string.
1223 See the manual for examples."
1227 (string :tag
"Protocol")
1229 (string :tag
"Format")
1232 (defcustom org-descriptive-links t
1233 "Non-nil means hide link part and only show description of bracket links.
1234 Bracket links are like [[link][description]]. This variable sets the initial
1235 state in new org-mode buffers. The setting can then be toggled on a
1236 per-buffer basis from the Org->Hyperlinks menu."
1240 (defcustom org-link-file-path-type
'adaptive
1241 "How the path name in file links should be stored.
1244 relative Relative to the current directory, i.e. the directory of the file
1245 into which the link is being inserted.
1246 absolute Absolute path, if possible with ~ for home directory.
1247 noabbrev Absolute path, no abbreviation of home directory.
1248 adaptive Use relative path for files in the current directory and sub-
1249 directories of it. For other files, use an absolute path."
1257 (defcustom org-activate-links
'(bracket angle plain radio tag date footnote
)
1258 "Types of links that should be activated in Org-mode files.
1259 This is a list of symbols, each leading to the activation of a certain link
1260 type. In principle, it does not hurt to turn on most link types - there may
1261 be a small gain when turning off unused link types. The types are:
1263 bracket The recommended [[link][description]] or [[link]] links with hiding.
1264 angular Links in angular brackets that may contain whitespace like
1265 <bbdb:Carsten Dominik>.
1266 plain Plain links in normal text, no whitespace, like http://google.com.
1267 radio Text that is matched by a radio target, see manual for details.
1268 tag Tag settings in a headline (link to tag search).
1269 date Time stamps (link to calendar).
1270 footnote Footnote labels.
1272 Changing this variable requires a restart of Emacs to become effective."
1274 :type
'(set :greedy t
1275 (const :tag
"Double bracket links (new style)" bracket
)
1276 (const :tag
"Angular bracket links (old style)" angular
)
1277 (const :tag
"Plain text links" plain
)
1278 (const :tag
"Radio target matches" radio
)
1279 (const :tag
"Tags" tag
)
1280 (const :tag
"Timestamps" date
)
1281 (const :tag
"Footnotes" footnote
)))
1283 (defcustom org-make-link-description-function nil
1284 "Function to use to generate link descriptions from links.
1285 If nil the link location will be used. This function must take
1286 two parameters; the first is the link and the second the
1287 description `org-insert-link' has generated, and should return the
1288 description to use."
1292 (defgroup org-link-store nil
1293 "Options concerning storing links in Org-mode."
1294 :tag
"Org Store Link"
1297 (defcustom org-email-link-description-format
"Email %c: %.30s"
1298 "Format of the description part of a link to an email or usenet message.
1299 The following %-escapes will be replaced by corresponding information:
1301 %F full \"From\" field
1302 %f name, taken from \"From\" field, address if no name
1303 %T full \"To\" field
1304 %t first name in \"To\" field, address if no name
1305 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1306 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1310 You may use normal field width specification between the % and the letter.
1311 This is for example useful to limit the length of the subject.
1313 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1314 :group
'org-link-store
1317 (defcustom org-from-is-user-regexp
1319 (when (and user-mail-address
(not (string= user-mail-address
"")))
1320 (setq r1
(concat "\\<" (regexp-quote user-mail-address
) "\\>")))
1321 (when (and user-full-name
(not (string= user-full-name
"")))
1322 (setq r2
(concat "\\<" (regexp-quote user-full-name
) "\\>")))
1323 (if (and r1 r2
) (concat r1
"\\|" r2
) (or r1 r2
)))
1324 "Regexp matched against the \"From:\" header of an email or usenet message.
1325 It should match if the message is from the user him/herself."
1326 :group
'org-link-store
1329 (defcustom org-link-to-org-use-id
'create-if-interactive-and-no-custom-id
1330 "Non-nil means storing a link to an Org file will use entry IDs.
1332 Note that before this variable is even considered, org-id must be loaded,
1333 so please customize `org-modules' and turn it on.
1335 The variable can have the following values:
1337 t Create an ID if needed to make a link to the current entry.
1339 create-if-interactive
1340 If `org-store-link' is called directly (interactively, as a user
1341 command), do create an ID to support the link. But when doing the
1342 job for remember, only use the ID if it already exists. The
1343 purpose of this setting is to avoid proliferation of unwanted
1344 IDs, just because you happen to be in an Org file when you
1345 call `org-remember' that automatically and preemptively
1346 creates a link. If you do want to get an ID link in a remember
1347 template to an entry not having an ID, create it first by
1348 explicitly creating a link to it, using `C-c C-l' first.
1350 create-if-interactive-and-no-custom-id
1351 Like create-if-interactive, but do not create an ID if there is
1352 a CUSTOM_ID property defined in the entry. This is the default.
1355 Use existing ID, do not create one.
1357 nil Never use an ID to make a link, instead link using a text search for
1359 :group
'org-link-store
1361 (const :tag
"Create ID to make link" t
)
1362 (const :tag
"Create if storing link interactively"
1363 create-if-interactive
)
1364 (const :tag
"Create if storing link interactively and no CUSTOM_ID is present"
1365 create-if-interactive-and-no-custom-id
)
1366 (const :tag
"Only use existing" use-existing
)
1367 (const :tag
"Do not use ID to create link" nil
)))
1369 (defcustom org-context-in-file-links t
1370 "Non-nil means file links from `org-store-link' contain context.
1371 A search string will be added to the file name with :: as separator and
1372 used to find the context when the link is activated by the command
1373 `org-open-at-point'.
1374 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1375 negates this setting for the duration of the command."
1376 :group
'org-link-store
1379 (defcustom org-keep-stored-link-after-insertion nil
1380 "Non-nil means keep link in list for entire session.
1382 The command `org-store-link' adds a link pointing to the current
1383 location to an internal list. These links accumulate during a session.
1384 The command `org-insert-link' can be used to insert links into any
1385 Org-mode file (offering completion for all stored links). When this
1386 option is nil, every link which has been inserted once using \\[org-insert-link]
1387 will be removed from the list, to make completing the unused links
1389 :group
'org-link-store
1392 (defgroup org-link-follow nil
1393 "Options concerning following links in Org-mode."
1394 :tag
"Org Follow Link"
1397 (defcustom org-link-translation-function nil
1398 "Function to translate links with different syntax to Org syntax.
1399 This can be used to translate links created for example by the Planner
1400 or emacs-wiki packages to Org syntax.
1401 The function must accept two parameters, a TYPE containing the link
1402 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1403 which is everything after the link protocol. It should return a cons
1404 with possibly modified values of type and path.
1405 Org contains a function for this, so if you set this variable to
1406 `org-translate-link-from-planner', you should be able follow many
1407 links created by planner."
1408 :group
'org-link-follow
1411 (defcustom org-follow-link-hook nil
1412 "Hook that is run after a link has been followed."
1413 :group
'org-link-follow
1416 (defcustom org-tab-follows-link nil
1417 "Non-nil means on links TAB will follow the link.
1418 Needs to be set before org.el is loaded.
1419 This really should not be used, it does not make sense, and the
1420 implementation is bad."
1421 :group
'org-link-follow
1424 (defcustom org-return-follows-link nil
1425 "Non-nil means on links RET will follow the link."
1426 :group
'org-link-follow
1429 (defcustom org-mouse-1-follows-link
1430 (if (boundp 'mouse-1-click-follows-link
) mouse-1-click-follows-link t
)
1431 "Non-nil means mouse-1 on a link will follow the link.
1432 A longer mouse click will still set point. Does not work on XEmacs.
1433 Needs to be set before org.el is loaded."
1434 :group
'org-link-follow
1437 (defcustom org-mark-ring-length
4
1438 "Number of different positions to be recorded in the ring.
1439 Changing this requires a restart of Emacs to work correctly."
1440 :group
'org-link-follow
1443 (defcustom org-link-search-must-match-exact-headline
'query-to-create
1444 "Non-nil means internal links in Org files must exactly match a headline.
1445 When nil, the link search tries to match a phrase will all words
1446 in the search text."
1447 :group
'org-link-follow
1449 (const :tag
"Use fuzy text search" nil
)
1450 (const :tag
"Match only exact headline" t
)
1451 (const :tag
"Match extact headline or query to create it"
1454 (defcustom org-link-frame-setup
1455 '((vm . vm-visit-folder-other-frame
)
1456 (gnus . org-gnus-no-new-news
)
1457 (file . find-file-other-window
)
1458 (wl . wl-other-frame
))
1459 "Setup the frame configuration for following links.
1460 When following a link with Emacs, it may often be useful to display
1461 this link in another window or frame. This variable can be used to
1462 set this up for the different types of links.
1465 `vm-visit-folder-other-frame'
1466 For Gnus, use any of
1469 `org-gnus-no-new-news'
1470 For FILE, use any of
1472 `find-file-other-window'
1473 `find-file-other-frame'
1474 For Wanderlust use any of
1477 For the calendar, use the variable `calendar-setup'.
1478 For BBDB, it is currently only possible to display the matches in
1480 :group
'org-link-follow
1484 (const vm-visit-folder
)
1485 (const vm-visit-folder-other-window
)
1486 (const vm-visit-folder-other-frame
)))
1490 (const gnus-other-frame
)
1491 (const org-gnus-no-new-news
)))
1495 (const find-file-other-window
)
1496 (const find-file-other-frame
)))
1500 (const wl-other-frame
)))))
1502 (defcustom org-display-internal-link-with-indirect-buffer nil
1503 "Non-nil means use indirect buffer to display infile links.
1504 Activating internal links (from one location in a file to another location
1505 in the same file) normally just jumps to the location. When the link is
1506 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1508 another window. When this option is set, the other window actually displays
1509 an indirect buffer clone of the current buffer, to avoid any visibility
1510 changes to the current buffer."
1511 :group
'org-link-follow
1514 (defcustom org-open-non-existing-files nil
1515 "Non-nil means `org-open-file' will open non-existing files.
1516 When nil, an error will be generated.
1517 This variable applies only to external applications because they
1518 might choke on non-existing files. If the link is to a file that
1519 will be opened in Emacs, the variable is ignored."
1520 :group
'org-link-follow
1523 (defcustom org-open-directory-means-index-dot-org nil
1524 "Non-nil means a link to a directory really means to index.org.
1525 When nil, following a directory link will run dired or open a finder/explorer
1526 window on that directory."
1527 :group
'org-link-follow
1530 (defcustom org-link-mailto-program
'(browse-url "mailto:%a?subject=%s")
1531 "Function and arguments to call for following mailto links.
1532 This is a list with the first element being a Lisp function, and the
1533 remaining elements being arguments to the function. In string arguments,
1534 %a will be replaced by the address, and %s will be replaced by the subject
1535 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1536 :group
'org-link-follow
1538 (const :tag
"browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1539 (const :tag
"compose-mail" (compose-mail "%a" "%s"))
1540 (const :tag
"message-mail" (message-mail "%a" "%s"))
1541 (cons :tag
"other" (function) (repeat :tag
"argument" sexp
))))
1543 (defcustom org-confirm-shell-link-function
'yes-or-no-p
1544 "Non-nil means ask for confirmation before executing shell links.
1545 Shell links can be dangerous: just think about a link
1547 [[shell:rm -rf ~/*][Google Search]]
1549 This link would show up in your Org-mode document as \"Google Search\",
1550 but really it would remove your entire home directory.
1551 Therefore we advise against setting this variable to nil.
1552 Just change it to `y-or-n-p' if you want to confirm with a
1553 single keystroke rather than having to type \"yes\"."
1554 :group
'org-link-follow
1556 (const :tag
"with yes-or-no (safer)" yes-or-no-p
)
1557 (const :tag
"with y-or-n (faster)" y-or-n-p
)
1558 (const :tag
"no confirmation (dangerous)" nil
)))
1559 (put 'org-confirm-shell-link-function
1560 'safe-local-variable
1561 '(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
1563 (defcustom org-confirm-elisp-link-function
'yes-or-no-p
1564 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1565 Elisp links can be dangerous: just think about a link
1567 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1569 This link would show up in your Org-mode document as \"Google Search\",
1570 but really it would remove your entire home directory.
1571 Therefore we advise against setting this variable to nil.
1572 Just change it to `y-or-n-p' if you want to confirm with a
1573 single keystroke rather than having to type \"yes\"."
1574 :group
'org-link-follow
1576 (const :tag
"with yes-or-no (safer)" yes-or-no-p
)
1577 (const :tag
"with y-or-n (faster)" y-or-n-p
)
1578 (const :tag
"no confirmation (dangerous)" nil
)))
1579 (put 'org-confirm-shell-link-function
1580 'safe-local-variable
1581 '(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
1583 (defconst org-file-apps-defaults-gnu
1587 "Default file applications on a UNIX or GNU/Linux system.
1588 See `org-file-apps'.")
1590 (defconst org-file-apps-defaults-macosx
1593 (system .
"open %s")
1595 ("eps.gz" .
"gv %s")
1597 ("fig" .
"xfig %s"))
1598 "Default file applications on a MacOS X system.
1599 The system \"open\" is known as a default, but we use X11 applications
1600 for some files for which the OS does not have a good default.
1601 See `org-file-apps'.")
1603 (defconst org-file-apps-defaults-windowsnt
1607 (list (if (featurep 'xemacs
)
1608 'mswindows-shell-execute
1612 (list (if (featurep 'xemacs
)
1613 'mswindows-shell-execute
1616 "Default file applications on a Windows NT system.
1617 The system \"open\" is used for most files.
1618 See `org-file-apps'.")
1620 (defcustom org-file-apps
1623 ("\\.mm\\'" . default
)
1624 ("\\.x?html?\\'" . default
)
1625 ("\\.pdf\\'" . default
)
1627 "External applications for opening `file:path' items in a document.
1628 Org-mode uses system defaults for different file types, but
1629 you can use this variable to set the application for a given file
1630 extension. The entries in this list are cons cells where the car identifies
1631 files and the cdr the corresponding command. Possible values for the
1633 \"string\" A string as a file identifier can be interpreted in different
1634 ways, depending on its contents:
1636 - Alphanumeric characters only:
1637 Match links with this file extension.
1638 Example: (\"pdf\" . \"evince %s\")
1639 to open PDFs with evince.
1641 - Regular expression: Match links where the
1642 filename matches the regexp. If you want to
1643 use groups here, use shy groups.
1645 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1646 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1647 to open *.html and *.xhtml with firefox.
1649 - Regular expression which contains (non-shy) groups:
1650 Match links where the whole link, including \"::\", and
1651 anything after that, matches the regexp.
1652 In a custom command string, %1, %2, etc. are replaced with
1653 the parts of the link that were matched by the groups.
1654 For backwards compatibility, if a command string is given
1655 that does not use any of the group matches, this case is
1656 handled identically to the second one (i.e. match against
1658 In a custom lisp form, you can access the group matches with
1659 (match-string n link).
1661 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1662 to open [[file:document.pdf::5]] with evince at page 5.
1664 `directory' Matches a directory
1665 `remote' Matches a remote file, accessible through tramp or efs.
1666 Remote files most likely should be visited through Emacs
1667 because external applications cannot handle such paths.
1668 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1669 so all files Emacs knows how to handle. Using this with
1670 command `emacs' will open most files in Emacs. Beware that this
1671 will also open html files inside Emacs, unless you add
1672 (\"html\" . default) to the list as well.
1673 t Default for files not matched by any of the other options.
1674 `system' The system command to open files, like `open' on Windows
1675 and Mac OS X, and mailcap under GNU/Linux. This is the command
1676 that will be selected if you call `C-c C-o' with a double
1677 \\[universal-argument] \\[universal-argument] prefix.
1679 Possible values for the command are:
1680 `emacs' The file will be visited by the current Emacs process.
1681 `default' Use the default application for this file type, which is the
1682 association for t in the list, most likely in the system-specific
1684 This can be used to overrule an unwanted setting in the
1685 system-specific variable.
1686 `system' Use the system command for opening files, like \"open\".
1687 This command is specified by the entry whose car is `system'.
1688 Most likely, the system-specific version of this variable
1689 does define this command, but you can overrule/replace it
1691 string A command to be executed by a shell; %s will be replaced
1692 by the path to the file.
1693 sexp A Lisp form which will be evaluated. The file path will
1694 be available in the Lisp variable `file'.
1695 For more examples, see the system specific constants
1696 `org-file-apps-defaults-macosx'
1697 `org-file-apps-defaults-windowsnt'
1698 `org-file-apps-defaults-gnu'."
1699 :group
'org-link-follow
1701 (cons (choice :value
""
1702 (string :tag
"Extension")
1703 (const :tag
"System command to open files" system
)
1704 (const :tag
"Default for unrecognized files" t
)
1705 (const :tag
"Remote file" remote
)
1706 (const :tag
"Links to a directory" directory
)
1707 (const :tag
"Any files that have Emacs modes"
1710 (const :tag
"Visit with Emacs" emacs
)
1711 (const :tag
"Use default" default
)
1712 (const :tag
"Use the system command" system
)
1713 (string :tag
"Command")
1714 (sexp :tag
"Lisp form")))))
1718 (defgroup org-refile nil
1719 "Options concerning refiling entries in Org-mode."
1723 (defcustom org-directory
"~/org"
1724 "Directory with org files.
1725 This is just a default location to look for Org files. There is no need
1726 at all to put your files into this directory. It is only used in the
1727 following situations:
1729 1. When a remember template specifies a target file that is not an
1730 absolute path. The path will then be interpreted relative to
1732 2. When a remember note is filed away in an interactive way (when exiting the
1733 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1734 with `org-directory' as the default path."
1736 :group
'org-remember
1739 (defcustom org-default-notes-file
(convert-standard-filename "~/.notes")
1740 "Default target for storing notes.
1741 Used as a fall back file for org-remember.el and org-capture.el, for
1742 templates that do not specify a target file."
1744 :group
'org-remember
1746 (const :tag
"Default from remember-data-file" nil
)
1749 (defcustom org-goto-interface
'outline
1750 "The default interface to be used for `org-goto'.
1752 outline The interface shows an outline of the relevant file
1753 and the correct heading is found by moving through
1754 the outline or by searching with incremental search.
1755 outline-path-completion Headlines in the current buffer are offered via
1756 completion. This is the interface also used by
1757 the refile command."
1760 (const :tag
"Outline" outline
)
1761 (const :tag
"Outline-path-completion" outline-path-completion
)))
1763 (defcustom org-goto-max-level
5
1764 "Maximum target level when running `org-goto' with refile interface."
1768 (defcustom org-reverse-note-order nil
1769 "Non-nil means store new notes at the beginning of a file or entry.
1770 When nil, new notes will be filed to the end of a file or entry.
1771 This can also be a list with cons cells of regular expressions that
1772 are matched against file names, and values."
1773 :group
'org-remember
1776 (const :tag
"Reverse always" t
)
1777 (const :tag
"Reverse never" nil
)
1778 (repeat :tag
"By file name regexp"
1779 (cons regexp boolean
))))
1781 (defcustom org-log-refile nil
1782 "Information to record when a task is refiled.
1784 Possible values are:
1786 nil Don't add anything
1787 time Add a time stamp to the task
1788 note Prompt for a note and add it with template `org-log-note-headings'
1790 This option can also be set with on a per-file-basis with
1792 #+STARTUP: nologrefile
1793 #+STARTUP: logrefile
1794 #+STARTUP: lognoterefile
1796 You can have local logging settings for a subtree by setting the LOGGING
1797 property to one or more of these keywords.
1799 When bulk-refiling from the agenda, the value `note' is forbidden and
1800 will temporarily be changed to `time'."
1802 :group
'org-progress
1804 (const :tag
"No logging" nil
)
1805 (const :tag
"Record timestamp" time
)
1806 (const :tag
"Record timestamp with note." note
)))
1808 (defcustom org-refile-targets nil
1809 "Targets for refiling entries with \\[org-refile].
1810 This is list of cons cells. Each cell contains:
1811 - a specification of the files to be considered, either a list of files,
1812 or a symbol whose function or variable value will be used to retrieve
1813 a file name or a list of file names. If you use `org-agenda-files' for
1814 that, all agenda files will be scanned for targets. Nil means consider
1815 headings in the current buffer.
1816 - A specification of how to find candidate refile targets. This may be
1818 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1819 This tag has to be present in all target headlines, inheritance will
1821 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1823 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1824 headlines that are refiling targets.
1825 - a cons cell (:level . N). Any headline of level N is considered a target.
1826 Note that, when `org-odd-levels-only' is set, level corresponds to
1827 order in hierarchy, not to the number of stars.
1828 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1829 Note that, when `org-odd-levels-only' is set, level corresponds to
1830 order in hierarchy, not to the number of stars.
1832 You can set the variable `org-refile-target-verify-function' to a function
1833 to verify each headline found by the simple criteria above.
1835 When this variable is nil, all top-level headlines in the current buffer
1836 are used, equivalent to the value `((nil . (:level . 1))'."
1840 (choice :value org-agenda-files
1841 (const :tag
"All agenda files" org-agenda-files
)
1842 (const :tag
"Current buffer" nil
)
1843 (function) (variable) (file))
1844 (choice :tag
"Identify target headline by"
1845 (cons :tag
"Specific tag" (const :value
:tag
) (string))
1846 (cons :tag
"TODO keyword" (const :value
:todo
) (string))
1847 (cons :tag
"Regular expression" (const :value
:regexp
) (regexp))
1848 (cons :tag
"Level number" (const :value
:level
) (integer))
1849 (cons :tag
"Max Level number" (const :value
:maxlevel
) (integer))))))
1851 (defcustom org-refile-target-verify-function nil
1852 "Function to verify if the headline at point should be a refile target.
1853 The function will be called without arguments, with point at the
1854 beginning of the headline. It should return t and leave point
1855 where it is if the headline is a valid target for refiling.
1857 If the target should not be selected, the function must return nil.
1858 In addition to this, it may move point to a place from where the search
1859 should be continued. For example, the function may decide that the entire
1860 subtree of the current entry should be excluded and move point to the end
1865 (defcustom org-refile-use-cache nil
1866 "Non-nil means cache refile targets to speed up the process.
1867 The cache for a particular file will be updated automatically when
1868 the buffer has been killed, or when any of the marker used for flagging
1869 refile targets no longer points at a live buffer.
1870 If you have added new entries to a buffer that might themselves be targets,
1871 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1872 find that easier, `C-u C-u C-u C-c C-w'."
1876 (defcustom org-refile-use-outline-path nil
1877 "Non-nil means provide refile targets as paths.
1878 So a level 3 headline will be available as level1/level2/level3.
1880 When the value is `file', also include the file name (without directory)
1881 into the path. In this case, you can also stop the completion after
1882 the file name, to get entries inserted as top level in the file.
1884 When `full-file-path', include the full file path."
1887 (const :tag
"Not" nil
)
1888 (const :tag
"Yes" t
)
1889 (const :tag
"Start with file name" file
)
1890 (const :tag
"Start with full file path" full-file-path
)))
1892 (defcustom org-outline-path-complete-in-steps t
1893 "Non-nil means complete the outline path in hierarchical steps.
1894 When Org-mode uses the refile interface to select an outline path
1895 \(see variable `org-refile-use-outline-path'), the completion of
1896 the path can be done is a single go, or if can be done in steps down
1897 the headline hierarchy. Going in steps is probably the best if you
1898 do not use a special completion package like `ido' or `icicles'.
1899 However, when using these packages, going in one step can be very
1900 fast, while still showing the whole path to the entry."
1904 (defcustom org-refile-allow-creating-parent-nodes nil
1905 "Non-nil means allow to create new nodes as refile targets.
1906 New nodes are then created by adding \"/new node name\" to the completion
1907 of an existing node. When the value of this variable is `confirm',
1908 new node creation must be confirmed by the user (recommended)
1909 When nil, the completion must match an existing entry.
1911 Note that, if the new heading is not seen by the criteria
1912 listed in `org-refile-targets', multiple instances of the same
1913 heading would be created by trying again to file under the new
1917 (const :tag
"Never" nil
)
1918 (const :tag
"Always" t
)
1919 (const :tag
"Prompt for confirmation" confirm
)))
1921 (defgroup org-todo nil
1922 "Options concerning TODO items in Org-mode."
1926 (defgroup org-progress nil
1927 "Options concerning Progress logging in Org-mode."
1931 (defvar org-todo-interpretation-widgets
1933 (:tag
"Sequence (cycling hits every state)" sequence
)
1934 (:tag
"Type (cycling directly to DONE)" type
))
1935 "The available interpretation symbols for customizing `org-todo-keywords'.
1936 Interested libraries should add to this list.")
1938 (defcustom org-todo-keywords
'((sequence "TODO" "DONE"))
1939 "List of TODO entry keyword sequences and their interpretation.
1940 \\<org-mode-map>This is a list of sequences.
1942 Each sequence starts with a symbol, either `sequence' or `type',
1943 indicating if the keywords should be interpreted as a sequence of
1944 action steps, or as different types of TODO items. The first
1945 keywords are states requiring action - these states will select a headline
1946 for inclusion into the global TODO list Org-mode produces. If one of
1947 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1948 signify that no further action is necessary. If \"|\" is not found,
1949 the last keyword is treated as the only DONE state of the sequence.
1951 The command \\[org-todo] cycles an entry through these states, and one
1952 additional state where no keyword is present. For details about this
1953 cycling, see the manual.
1955 TODO keywords and interpretation can also be set on a per-file basis with
1956 the special #+SEQ_TODO and #+TYP_TODO lines.
1958 Each keyword can optionally specify a character for fast state selection
1959 \(in combination with the variable `org-use-fast-todo-selection')
1960 and specifiers for state change logging, using the same syntax
1961 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1962 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1963 indicates to record a time stamp each time this state is selected.
1965 Each keyword may also specify if a timestamp or a note should be
1966 recorded when entering or leaving the state, by adding additional
1967 characters in the parenthesis after the keyword. This looks like this:
1968 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1969 record only the time of the state change. With X and Y being either
1970 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1971 Y when leaving the state if and only if the *target* state does not
1972 define X. You may omit any of the fast-selection key or X or /Y,
1973 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1975 For backward compatibility, this variable may also be just a list
1976 of keywords - in this case the interpretation (sequence or type) will be
1977 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1979 :group
'org-keywords
1981 (repeat :tag
"Old syntax, just keywords"
1982 (string :tag
"Keyword"))
1983 (repeat :tag
"New syntax"
1986 :tag
"Interpretation"
1987 ;;Quick and dirty way to see
1988 ;;`org-todo-interpretations'. This takes the
1989 ;;place of item arguments
1997 org-todo-interpretation-widgets
))
2000 (string :tag
"Keyword"))))))
2002 (defvar org-todo-keywords-1 nil
2003 "All TODO and DONE keywords active in a buffer.")
2004 (make-variable-buffer-local 'org-todo-keywords-1
)
2005 (defvar org-todo-keywords-for-agenda nil
)
2006 (defvar org-done-keywords-for-agenda nil
)
2007 (defvar org-drawers-for-agenda nil
)
2008 (defvar org-todo-keyword-alist-for-agenda nil
)
2009 (defvar org-tag-alist-for-agenda nil
)
2010 (defvar org-agenda-contributing-files nil
)
2011 (defvar org-not-done-keywords nil
)
2012 (make-variable-buffer-local 'org-not-done-keywords
)
2013 (defvar org-done-keywords nil
)
2014 (make-variable-buffer-local 'org-done-keywords
)
2015 (defvar org-todo-heads nil
)
2016 (make-variable-buffer-local 'org-todo-heads
)
2017 (defvar org-todo-sets nil
)
2018 (make-variable-buffer-local 'org-todo-sets
)
2019 (defvar org-todo-log-states nil
)
2020 (make-variable-buffer-local 'org-todo-log-states
)
2021 (defvar org-todo-kwd-alist nil
)
2022 (make-variable-buffer-local 'org-todo-kwd-alist
)
2023 (defvar org-todo-key-alist nil
)
2024 (make-variable-buffer-local 'org-todo-key-alist
)
2025 (defvar org-todo-key-trigger nil
)
2026 (make-variable-buffer-local 'org-todo-key-trigger
)
2028 (defcustom org-todo-interpretation
'sequence
2029 "Controls how TODO keywords are interpreted.
2030 This variable is in principle obsolete and is only used for
2031 backward compatibility, if the interpretation of todo keywords is
2032 not given already in `org-todo-keywords'. See that variable for
2035 :group
'org-keywords
2036 :type
'(choice (const sequence
)
2039 (defcustom org-use-fast-todo-selection t
2040 "Non-nil means use the fast todo selection scheme with C-c C-t.
2041 This variable describes if and under what circumstances the cycling
2042 mechanism for TODO keywords will be replaced by a single-key, direct
2045 When nil, fast selection is never used.
2047 When the symbol `prefix', it will be used when `org-todo' is called with
2048 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2049 in an agenda buffer.
2051 When t, fast selection is used by default. In this case, the prefix
2052 argument forces cycling instead.
2054 In all cases, the special interface is only used if access keys have actually
2055 been assigned by the user, i.e. if keywords in the configuration are followed
2056 by a letter in parenthesis, like TODO(t)."
2059 (const :tag
"Never" nil
)
2060 (const :tag
"By default" t
)
2061 (const :tag
"Only with C-u C-c C-t" prefix
)))
2063 (defcustom org-provide-todo-statistics t
2064 "Non-nil means update todo statistics after insert and toggle.
2065 ALL-HEADLINES means update todo statistics by including headlines
2066 with no TODO keyword as well, counting them as not done.
2067 A list of TODO keywords means the same, but skip keywords that are
2070 When this is set, todo statistics is updated in the parent of the
2071 current entry each time a todo state is changed."
2074 (const :tag
"Yes, only for TODO entries" t
)
2075 (const :tag
"Yes, including all entries" 'all-headlines
)
2076 (repeat :tag
"Yes, for TODOs in this list"
2077 (string :tag
"TODO keyword"))
2078 (other :tag
"No TODO statistics" nil
)))
2080 (defcustom org-hierarchical-todo-statistics t
2081 "Non-nil means TODO statistics covers just direct children.
2082 When nil, all entries in the subtree are considered.
2083 This has only an effect if `org-provide-todo-statistics' is set.
2084 To set this to nil for only a single subtree, use a COOKIE_DATA
2085 property and include the word \"recursive\" into the value."
2089 (defcustom org-after-todo-state-change-hook nil
2090 "Hook which is run after the state of a TODO item was changed.
2091 The new state (a string with a TODO keyword, or nil) is available in the
2092 Lisp variable `state'."
2096 (defvar org-blocker-hook nil
2097 "Hook for functions that are allowed to block a state change.
2099 Each function gets as its single argument a property list, see
2100 `org-trigger-hook' for more information about this list.
2102 If any of the functions in this hook returns nil, the state change
2105 (defvar org-trigger-hook nil
2106 "Hook for functions that are triggered by a state change.
2108 Each function gets as its single argument a property list with at least
2109 the following elements:
2111 (:type type-of-change :position pos-at-entry-start
2112 :from old-state :to new-state)
2114 Depending on the type, more properties may be present.
2116 This mechanism is currently implemented for:
2120 :type todo-state-change
2121 :from previous state (keyword as a string), or nil, or a symbol
2122 'todo' or 'done', to indicate the general type of state.
2123 :to new state, like in :from")
2125 (defcustom org-enforce-todo-dependencies nil
2126 "Non-nil means undone TODO entries will block switching the parent to DONE.
2127 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2128 be blocked if any prior sibling is not yet done.
2129 Finally, if the parent is blocked because of ordered siblings of its own,
2130 the child will also be blocked.
2131 This variable needs to be set before org.el is loaded, and you need to
2132 restart Emacs after a change to make the change effective. The only way
2133 to change is while Emacs is running is through the customize interface."
2134 :set
(lambda (var val
)
2137 (add-hook 'org-blocker-hook
2138 'org-block-todo-from-children-or-siblings-or-parent
)
2139 (remove-hook 'org-blocker-hook
2140 'org-block-todo-from-children-or-siblings-or-parent
)))
2144 (defcustom org-enforce-todo-checkbox-dependencies nil
2145 "Non-nil means unchecked boxes will block switching the parent to DONE.
2146 When this is nil, checkboxes have no influence on switching TODO states.
2147 When non-nil, you first need to check off all check boxes before the TODO
2148 entry can be switched to DONE.
2149 This variable needs to be set before org.el is loaded, and you need to
2150 restart Emacs after a change to make the change effective. The only way
2151 to change is while Emacs is running is through the customize interface."
2152 :set
(lambda (var val
)
2155 (add-hook 'org-blocker-hook
2156 'org-block-todo-from-checkboxes
)
2157 (remove-hook 'org-blocker-hook
2158 'org-block-todo-from-checkboxes
)))
2162 (defcustom org-treat-insert-todo-heading-as-state-change nil
2163 "Non-nil means inserting a TODO heading is treated as state change.
2164 So when the command \\[org-insert-todo-heading] is used, state change
2165 logging will apply if appropriate. When nil, the new TODO item will
2166 be inserted directly, and no logging will take place."
2170 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2171 "Non-nil means switching TODO states with S-cursor counts as state change.
2172 This is the default behavior. However, setting this to nil allows a
2173 convenient way to select a TODO state and bypass any logging associated
2178 (defcustom org-todo-state-tags-triggers nil
2179 "Tag changes that should be triggered by TODO state changes.
2180 This is a list. Each entry is
2182 (state-change (tag . flag) .......)
2184 State-change can be a string with a state, and empty string to indicate the
2185 state that has no TODO keyword, or it can be one of the symbols `todo'
2186 or `done', meaning any not-done or done state, respectively."
2190 (cons (choice :tag
"When changing to"
2191 (const :tag
"Not-done state" todo
)
2192 (const :tag
"Done state" done
)
2193 (string :tag
"State"))
2195 (cons :tag
"Tag action"
2197 (choice (const :tag
"Add" t
) (const :tag
"Remove" nil
)))))))
2199 (defcustom org-log-done nil
2200 "Information to record when a task moves to the DONE state.
2202 Possible values are:
2204 nil Don't add anything, just change the keyword
2205 time Add a time stamp to the task
2206 note Prompt for a note and add it with template `org-log-note-headings'
2208 This option can also be set with on a per-file-basis with
2210 #+STARTUP: nologdone
2212 #+STARTUP: lognotedone
2214 You can have local logging settings for a subtree by setting the LOGGING
2215 property to one or more of these keywords."
2217 :group
'org-progress
2219 (const :tag
"No logging" nil
)
2220 (const :tag
"Record CLOSED timestamp" time
)
2221 (const :tag
"Record CLOSED timestamp with note." note
)))
2223 ;; Normalize old uses of org-log-done.
2225 ((eq org-log-done t
) (setq org-log-done
'time
))
2226 ((and (listp org-log-done
) (memq 'done org-log-done
))
2227 (setq org-log-done
'note
)))
2229 (defcustom org-log-reschedule nil
2230 "Information to record when the scheduling date of a tasks is modified.
2232 Possible values are:
2234 nil Don't add anything, just change the date
2235 time Add a time stamp to the task
2236 note Prompt for a note and add it with template `org-log-note-headings'
2238 This option can also be set with on a per-file-basis with
2240 #+STARTUP: nologreschedule
2241 #+STARTUP: logreschedule
2242 #+STARTUP: lognotereschedule"
2244 :group
'org-progress
2246 (const :tag
"No logging" nil
)
2247 (const :tag
"Record timestamp" time
)
2248 (const :tag
"Record timestamp with note." note
)))
2250 (defcustom org-log-redeadline nil
2251 "Information to record when the deadline date of a tasks is modified.
2253 Possible values are:
2255 nil Don't add anything, just change the date
2256 time Add a time stamp to the task
2257 note Prompt for a note and add it with template `org-log-note-headings'
2259 This option can also be set with on a per-file-basis with
2261 #+STARTUP: nologredeadline
2262 #+STARTUP: logredeadline
2263 #+STARTUP: lognoteredeadline
2265 You can have local logging settings for a subtree by setting the LOGGING
2266 property to one or more of these keywords."
2268 :group
'org-progress
2270 (const :tag
"No logging" nil
)
2271 (const :tag
"Record timestamp" time
)
2272 (const :tag
"Record timestamp with note." note
)))
2274 (defcustom org-log-note-clock-out nil
2275 "Non-nil means record a note when clocking out of an item.
2276 This can also be configured on a per-file basis by adding one of
2277 the following lines anywhere in the buffer:
2279 #+STARTUP: lognoteclock-out
2280 #+STARTUP: nolognoteclock-out"
2282 :group
'org-progress
2285 (defcustom org-log-done-with-time t
2286 "Non-nil means the CLOSED time stamp will contain date and time.
2287 When nil, only the date will be recorded."
2288 :group
'org-progress
2291 (defcustom org-log-note-headings
2292 '((done .
"CLOSING NOTE %t")
2293 (state .
"State %-12s from %-12S %t")
2294 (note .
"Note taken on %t")
2295 (reschedule .
"Rescheduled from %S on %t")
2296 (delschedule .
"Not scheduled, was %S on %t")
2297 (redeadline .
"New deadline from %S on %t")
2298 (deldeadline .
"Removed deadline, was %S on %t")
2299 (refile .
"Refiled on %t")
2301 "Headings for notes added to entries.
2302 The value is an alist, with the car being a symbol indicating the note
2303 context, and the cdr is the heading to be used. The heading may also be the
2305 %t in the heading will be replaced by a time stamp.
2306 %T will be an active time stamp instead the default inactive one
2307 %s will be replaced by the new TODO state, in double quotes.
2308 %S will be replaced by the old TODO state, in double quotes.
2309 %u will be replaced by the user name.
2310 %U will be replaced by the full user name.
2312 In fact, it is not a good idea to change the `state' entry, because
2313 agenda log mode depends on the format of these entries."
2315 :group
'org-progress
2316 :type
'(list :greedy t
2317 (cons (const :tag
"Heading when closing an item" done
) string
)
2319 "Heading when changing todo state (todo sequence only)"
2321 (cons (const :tag
"Heading when just taking a note" note
) string
)
2322 (cons (const :tag
"Heading when clocking out" clock-out
) string
)
2323 (cons (const :tag
"Heading when an item is no longer scheduled" delschedule
) string
)
2324 (cons (const :tag
"Heading when rescheduling" reschedule
) string
)
2325 (cons (const :tag
"Heading when changing deadline" redeadline
) string
)
2326 (cons (const :tag
"Heading when deleting a deadline" deldeadline
) string
)
2327 (cons (const :tag
"Heading when refiling" refile
) string
)))
2329 (unless (assq 'note org-log-note-headings
)
2330 (push '(note .
"%t") org-log-note-headings
))
2332 (defcustom org-log-into-drawer nil
2333 "Non-nil means insert state change notes and time stamps into a drawer.
2334 When nil, state changes notes will be inserted after the headline and
2335 any scheduling and clock lines, but not inside a drawer.
2337 The value of this variable should be the name of the drawer to use.
2338 LOGBOOK is proposed at the default drawer for this purpose, you can
2339 also set this to a string to define the drawer of your choice.
2341 A value of t is also allowed, representing \"LOGBOOK\".
2343 If this variable is set, `org-log-state-notes-insert-after-drawers'
2346 You can set the property LOG_INTO_DRAWER to overrule this setting for
2349 :group
'org-progress
2351 (const :tag
"Not into a drawer" nil
)
2352 (const :tag
"LOGBOOK" t
)
2353 (string :tag
"Other")))
2355 (if (fboundp 'defvaralias
)
2356 (defvaralias 'org-log-state-notes-into-drawer
'org-log-into-drawer
))
2358 (defun org-log-into-drawer ()
2359 "Return the value of `org-log-into-drawer', but let properties overrule.
2360 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2361 used instead of the default value."
2362 (let ((p (ignore-errors (org-entry-get nil
"LOG_INTO_DRAWER" 'inherit
))))
2364 ((or (not p
) (equal p
"nil")) org-log-into-drawer
)
2365 ((equal p
"t") "LOGBOOK")
2368 (defcustom org-log-state-notes-insert-after-drawers nil
2369 "Non-nil means insert state change notes after any drawers in entry.
2370 Only the drawers that *immediately* follow the headline and the
2371 deadline/scheduled line are skipped.
2372 When nil, insert notes right after the heading and perhaps the line
2373 with deadline/scheduling if present.
2375 This variable will have no effect if `org-log-into-drawer' is
2378 :group
'org-progress
2381 (defcustom org-log-states-order-reversed t
2382 "Non-nil means the latest state note will be directly after heading.
2383 When nil, the state change notes will be ordered according to time."
2385 :group
'org-progress
2388 (defcustom org-todo-repeat-to-state nil
2389 "The TODO state to which a repeater should return the repeating task.
2390 By default this is the first task in a TODO sequence, or the previous state
2391 in a TODO_TYP set. But you can specify another task here.
2392 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2394 :type
'(choice (const :tag
"Head of sequence" nil
)
2395 (string :tag
"Specific state")))
2397 (defcustom org-log-repeat
'time
2398 "Non-nil means record moving through the DONE state when triggering repeat.
2399 An auto-repeating task is immediately switched back to TODO when
2400 marked DONE. If you are not logging state changes (by adding \"@\"
2401 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2402 record a closing note, there will be no record of the task moving
2403 through DONE. This variable forces taking a note anyway.
2405 nil Don't force a record
2406 time Record a time stamp
2409 This option can also be set with on a per-file-basis with
2411 #+STARTUP: logrepeat
2412 #+STARTUP: lognoterepeat
2413 #+STARTUP: nologrepeat
2415 You can have local logging settings for a subtree by setting the LOGGING
2416 property to one or more of these keywords."
2418 :group
'org-progress
2420 (const :tag
"Don't force a record" nil
)
2421 (const :tag
"Force recording the DONE state" time
)
2422 (const :tag
"Force recording a note with the DONE state" note
)))
2425 (defgroup org-priorities nil
2426 "Priorities in Org-mode."
2427 :tag
"Org Priorities"
2430 (defcustom org-enable-priority-commands t
2431 "Non-nil means priority commands are active.
2432 When nil, these commands will be disabled, so that you never accidentally
2434 :group
'org-priorities
2437 (defcustom org-highest-priority ?A
2438 "The highest priority of TODO items. A character like ?A, ?B etc.
2439 Must have a smaller ASCII number than `org-lowest-priority'."
2440 :group
'org-priorities
2443 (defcustom org-lowest-priority ?C
2444 "The lowest priority of TODO items. A character like ?A, ?B etc.
2445 Must have a larger ASCII number than `org-highest-priority'."
2446 :group
'org-priorities
2449 (defcustom org-default-priority ?B
2450 "The default priority of TODO items.
2451 This is the priority an item get if no explicit priority is given."
2452 :group
'org-priorities
2455 (defcustom org-priority-start-cycle-with-default t
2456 "Non-nil means start with default priority when starting to cycle.
2457 When this is nil, the first step in the cycle will be (depending on the
2458 command used) one higher or lower that the default priority."
2459 :group
'org-priorities
2462 (defgroup org-time nil
2463 "Options concerning time stamps and deadlines in Org-mode."
2467 (defcustom org-insert-labeled-timestamps-at-point nil
2468 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2469 When nil, these labeled time stamps are forces into the second line of an
2470 entry, just after the headline. When scheduling from the global TODO list,
2471 the time stamp will always be forced into the second line."
2475 (defconst org-time-stamp-formats
'("<%Y-%m-%d %a>" .
"<%Y-%m-%d %a %H:%M>")
2476 "Formats for `format-time-string' which are used for time stamps.
2477 It is not recommended to change this constant.")
2479 (defcustom org-time-stamp-rounding-minutes
'(0 5)
2480 "Number of minutes to round time stamps to.
2481 These are two values, the first applies when first creating a time stamp.
2482 The second applies when changing it with the commands `S-up' and `S-down'.
2483 When changing the time stamp, this means that it will change in steps
2484 of N minutes, as given by the second value.
2486 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2487 numbers should be factors of 60, so for example 5, 10, 15.
2489 When this is larger than 1, you can still force an exact time stamp by using
2490 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2491 and by using a prefix arg to `S-up/down' to specify the exact number
2492 of minutes to shift."
2494 :get
'(lambda (var) ; Make sure both elements are there
2495 (if (integerp (default-value var
))
2496 (list (default-value var
) 5)
2497 (default-value var
)))
2499 (integer :tag
"when inserting times")
2500 (integer :tag
"when modifying times")))
2502 ;; Normalize old customizations of this variable.
2503 (when (integerp org-time-stamp-rounding-minutes
)
2504 (setq org-time-stamp-rounding-minutes
2505 (list org-time-stamp-rounding-minutes
2506 org-time-stamp-rounding-minutes
)))
2508 (defcustom org-display-custom-times nil
2509 "Non-nil means overlay custom formats over all time stamps.
2510 The formats are defined through the variable `org-time-stamp-custom-formats'.
2511 To turn this on on a per-file basis, insert anywhere in the file:
2512 #+STARTUP: customtime"
2516 (make-variable-buffer-local 'org-display-custom-times
)
2518 (defcustom org-time-stamp-custom-formats
2519 '("<%m/%d/%y %a>" .
"<%m/%d/%y %a %H:%M>") ; american
2520 "Custom formats for time stamps. See `format-time-string' for the syntax.
2521 These are overlayed over the default ISO format if the variable
2522 `org-display-custom-times' is set. Time like %H:%M should be at the
2523 end of the second format. The custom formats are also honored by export
2524 commands, if custom time display is turned on at the time of export."
2528 (defun org-time-stamp-format (&optional long inactive
)
2529 "Get the right format for a time string."
2530 (let ((f (if long
(cdr org-time-stamp-formats
)
2531 (car org-time-stamp-formats
))))
2533 (concat "[" (substring f
1 -
1) "]")
2536 (defcustom org-time-clocksum-format
"%d:%02d"
2537 "The format string used when creating CLOCKSUM lines.
2538 This is also used when org-mode generates a time duration."
2542 (defcustom org-time-clocksum-use-fractional nil
2543 "If non-nil, \\[org-clock-display] uses fractional times.
2544 org-mode generates a time duration."
2548 (defcustom org-time-clocksum-fractional-format
"%.2f"
2549 "The format string used when creating CLOCKSUM lines, or when
2550 org-mode generates a time duration."
2554 (defcustom org-deadline-warning-days
14
2555 "No. of days before expiration during which a deadline becomes active.
2556 This variable governs the display in sparse trees and in the agenda.
2557 When 0 or negative, it means use this number (the absolute value of it)
2558 even if a deadline has a different individual lead time specified.
2560 Custom commands can set this variable in the options section."
2562 :group
'org-agenda-daily
/weekly
2565 (defcustom org-read-date-prefer-future t
2566 "Non-nil means assume future for incomplete date input from user.
2567 This affects the following situations:
2568 1. The user gives a month but not a year.
2569 For example, if it is April and you enter \"feb 2\", this will be read
2570 as Feb 2, *next* year. \"May 5\", however, will be this year.
2571 2. The user gives a day, but no month.
2572 For example, if today is the 15th, and you enter \"3\", Org-mode will
2573 read this as the third of *next* month. However, if you enter \"17\",
2574 it will be considered as *this* month.
2576 If you set this variable to the symbol `time', then also the following
2579 3. If the user gives a time, but no day. If the time is before now,
2580 to will be interpreted as tomorrow.
2582 Currently none of this works for ISO week specifications.
2584 When this option is nil, the current day, month and year will always be
2588 (const :tag
"Never" nil
)
2589 (const :tag
"Check month and day" t
)
2590 (const :tag
"Check month, day, and time" time
)))
2592 (defcustom org-read-date-display-live t
2593 "Non-nil means display current interpretation of date prompt live.
2594 This display will be in an overlay, in the minibuffer."
2598 (defcustom org-read-date-popup-calendar t
2599 "Non-nil means pop up a calendar when prompting for a date.
2600 In the calendar, the date can be selected with mouse-1. However, the
2601 minibuffer will also be active, and you can simply enter the date as well.
2602 When nil, only the minibuffer will be available."
2605 (if (fboundp 'defvaralias
)
2606 (defvaralias 'org-popup-calendar-for-date-prompt
2607 'org-read-date-popup-calendar
))
2609 (defcustom org-read-date-minibuffer-setup-hook nil
2610 "Hook to be used to set up keys for the date/time interface.
2611 Add key definitions to `minibuffer-local-map', which will be a temporary
2616 (defcustom org-extend-today-until
0
2617 "The hour when your day really ends. Must be an integer.
2618 This has influence for the following applications:
2619 - When switching the agenda to \"today\". It it is still earlier than
2620 the time given here, the day recognized as TODAY is actually yesterday.
2621 - When a date is read from the user and it is still before the time given
2622 here, the current date and time will be assumed to be yesterday, 23:59.
2623 Also, timestamps inserted in remember templates follow this rule.
2625 IMPORTANT: This is a feature whose implementation is and likely will
2626 remain incomplete. Really, it is only here because past midnight seems to
2627 be the favorite working time of John Wiegley :-)"
2631 (defcustom org-edit-timestamp-down-means-later nil
2632 "Non-nil means S-down will increase the time in a time stamp.
2633 When nil, S-up will increase."
2637 (defcustom org-calendar-follow-timestamp-change t
2638 "Non-nil means make the calendar window follow timestamp changes.
2639 When a timestamp is modified and the calendar window is visible, it will be
2640 moved to the new date."
2644 (defgroup org-tags nil
2645 "Options concerning tags in Org-mode."
2649 (defcustom org-tag-alist nil
2650 "List of tags allowed in Org-mode files.
2651 When this list is nil, Org-mode will base TAG input on what is already in the
2653 The value of this variable is an alist, the car of each entry must be a
2654 keyword as a string, the cdr may be a character that is used to select
2655 that tag through the fast-tag-selection interface.
2656 See the manual for details."
2660 (cons (string :tag
"Tag name")
2661 (character :tag
"Access char"))
2662 (list :tag
"Start radio group"
2664 (option (string :tag
"Group description")))
2665 (list :tag
"End radio group"
2667 (option (string :tag
"Group description")))
2668 (const :tag
"New line" (:newline
)))))
2670 (defcustom org-tag-persistent-alist nil
2671 "List of tags that will always appear in all Org-mode files.
2672 This is in addition to any in buffer settings or customizations
2674 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2675 The value of this variable is an alist, the car of each entry must be a
2676 keyword as a string, the cdr may be a character that is used to select
2677 that tag through the fast-tag-selection interface.
2678 See the manual for details.
2679 To disable these tags on a per-file basis, insert anywhere in the file:
2684 (cons (string :tag
"Tag name")
2685 (character :tag
"Access char"))
2686 (const :tag
"Start radio group" (:startgroup
))
2687 (const :tag
"End radio group" (:endgroup
))
2688 (const :tag
"New line" (:newline
)))))
2690 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2691 "If non-nil, always offer completion for all tags of all agenda files.
2692 Instead of customizing this variable directly, you might want to
2693 set it locally for remember buffers, because there no list of
2694 tags in that file can be created dynamically (there are none).
2696 (add-hook 'org-remember-mode-hook
2698 (set (make-local-variable
2699 'org-complete-tags-always-offer-all-agenda-tags)
2704 (defvar org-file-tags nil
2705 "List of tags that can be inherited by all entries in the file.
2706 The tags will be inherited if the variable `org-use-tag-inheritance'
2707 says they should be.
2708 This variable is populated from #+FILETAGS lines.")
2710 (defcustom org-use-fast-tag-selection
'auto
2711 "Non-nil means use fast tag selection scheme.
2712 This is a special interface to select and deselect tags with single keys.
2713 When nil, fast selection is never used.
2714 When the symbol `auto', fast selection is used if and only if selection
2715 characters for tags have been configured, either through the variable
2716 `org-tag-alist' or through a #+TAGS line in the buffer.
2717 When t, fast selection is always used and selection keys are assigned
2718 automatically if necessary."
2721 (const :tag
"Always" t
)
2722 (const :tag
"Never" nil
)
2723 (const :tag
"When selection characters are configured" 'auto
)))
2725 (defcustom org-fast-tag-selection-single-key nil
2726 "Non-nil means fast tag selection exits after first change.
2727 When nil, you have to press RET to exit it.
2728 During fast tag selection, you can toggle this flag with `C-c'.
2729 This variable can also have the value `expert'. In this case, the window
2730 displaying the tags menu is not even shown, until you press C-c again."
2733 (const :tag
"No" nil
)
2734 (const :tag
"Yes" t
)
2735 (const :tag
"Expert" expert
)))
2737 (defvar org-fast-tag-selection-include-todo nil
2738 "Non-nil means fast tags selection interface will also offer TODO states.
2739 This is an undocumented feature, you should not rely on it.")
2741 (defcustom org-tags-column
(if (featurep 'xemacs
) -
76 -
77)
2742 "The column to which tags should be indented in a headline.
2743 If this number is positive, it specifies the column. If it is negative,
2744 it means that the tags should be flushright to that column. For example,
2745 -80 works well for a normal 80 character screen."
2749 (defcustom org-auto-align-tags t
2750 "Non-nil means realign tags after pro/demotion of TODO state change.
2751 These operations change the length of a headline and therefore shift
2752 the tags around. With this options turned on, after each such operation
2753 the tags are again aligned to `org-tags-column'."
2757 (defcustom org-use-tag-inheritance t
2758 "Non-nil means tags in levels apply also for sublevels.
2759 When nil, only the tags directly given in a specific line apply there.
2760 This may also be a list of tags that should be inherited, or a regexp that
2761 matches tags that should be inherited. Additional control is possible
2762 with the variable `org-tags-exclude-from-inheritance' which gives an
2763 explicit list of tags to be excluded from inheritance., even if the value of
2764 `org-use-tag-inheritance' would select it for inheritance.
2766 If this option is t, a match early-on in a tree can lead to a large
2767 number of matches in the subtree when constructing the agenda or creating
2768 a sparse tree. If you only want to see the first match in a tree during
2769 a search, check out the variable `org-tags-match-list-sublevels'."
2772 (const :tag
"Not" nil
)
2773 (const :tag
"Always" t
)
2774 (repeat :tag
"Specific tags" (string :tag
"Tag"))
2775 (regexp :tag
"Tags matched by regexp")))
2777 (defcustom org-tags-exclude-from-inheritance nil
2778 "List of tags that should never be inherited.
2779 This is a way to exclude a few tags from inheritance. For way to do
2780 the opposite, to actively allow inheritance for selected tags,
2781 see the variable `org-use-tag-inheritance'."
2783 :type
'(repeat (string :tag
"Tag")))
2785 (defun org-tag-inherit-p (tag)
2786 "Check if TAG is one that should be inherited."
2788 ((member tag org-tags-exclude-from-inheritance
) nil
)
2789 ((eq org-use-tag-inheritance t
) t
)
2790 ((not org-use-tag-inheritance
) nil
)
2791 ((stringp org-use-tag-inheritance
)
2792 (string-match org-use-tag-inheritance tag
))
2793 ((listp org-use-tag-inheritance
)
2794 (member tag org-use-tag-inheritance
))
2795 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2797 (defcustom org-tags-match-list-sublevels t
2798 "Non-nil means list also sublevels of headlines matching a search.
2799 This variable applies to tags/property searches, and also to stuck
2800 projects because this search is based on a tags match as well.
2802 When set to the symbol `indented', sublevels are indented with
2805 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2806 the sublevels of a headline matching a tag search often also match
2807 the same search. Listing all of them can create very long lists.
2808 Setting this variable to nil causes subtrees of a match to be skipped.
2810 This variable is semi-obsolete and probably should always be true. It
2811 is better to limit inheritance to certain tags using the variables
2812 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2815 (const :tag
"No, don't list them" nil
)
2816 (const :tag
"Yes, do list them" t
)
2817 (const :tag
"List them, indented with leading dots" indented
)))
2819 (defcustom org-tags-sort-function nil
2820 "When set, tags are sorted using this function as a comparator."
2823 (const :tag
"No sorting" nil
)
2824 (const :tag
"Alphabetical" string
<)
2825 (const :tag
"Reverse alphabetical" string
>)
2826 (function :tag
"Custom function" nil
)))
2828 (defvar org-tags-history nil
2829 "History of minibuffer reads for tags.")
2830 (defvar org-last-tags-completion-table nil
2831 "The last used completion table for tags.")
2832 (defvar org-after-tags-change-hook nil
2833 "Hook that is run after the tags in a line have changed.")
2835 (defgroup org-properties nil
2836 "Options concerning properties in Org-mode."
2837 :tag
"Org Properties"
2840 (defcustom org-property-format
"%-10s %s"
2841 "How property key/value pairs should be formatted by `indent-line'.
2842 When `indent-line' hits a property definition, it will format the line
2843 according to this format, mainly to make sure that the values are
2844 lined-up with respect to each other."
2845 :group
'org-properties
2848 (defcustom org-use-property-inheritance nil
2849 "Non-nil means properties apply also for sublevels.
2851 This setting is chiefly used during property searches. Turning it on can
2852 cause significant overhead when doing a search, which is why it is not
2855 When nil, only the properties directly given in the current entry count.
2856 When t, every property is inherited. The value may also be a list of
2857 properties that should have inheritance, or a regular expression matching
2858 properties that should be inherited.
2860 However, note that some special properties use inheritance under special
2861 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2862 and the properties ending in \"_ALL\" when they are used as descriptor
2863 for valid values of a property.
2865 Note for programmers:
2866 When querying an entry with `org-entry-get', you can control if inheritance
2867 should be used. By default, `org-entry-get' looks only at the local
2868 properties. You can request inheritance by setting the inherit argument
2869 to t (to force inheritance) or to `selective' (to respect the setting
2871 :group
'org-properties
2873 (const :tag
"Not" nil
)
2874 (const :tag
"Always" t
)
2875 (repeat :tag
"Specific properties" (string :tag
"Property"))
2876 (regexp :tag
"Properties matched by regexp")))
2878 (defun org-property-inherit-p (property)
2879 "Check if PROPERTY is one that should be inherited."
2881 ((eq org-use-property-inheritance t
) t
)
2882 ((not org-use-property-inheritance
) nil
)
2883 ((stringp org-use-property-inheritance
)
2884 (string-match org-use-property-inheritance property
))
2885 ((listp org-use-property-inheritance
)
2886 (member property org-use-property-inheritance
))
2887 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2889 (defcustom org-columns-default-format
"%25ITEM %TODO %3PRIORITY %TAGS"
2890 "The default column format, if no other format has been defined.
2891 This variable can be set on the per-file basis by inserting a line
2893 #+COLUMNS: %25ITEM ....."
2894 :group
'org-properties
2897 (defcustom org-columns-ellipses
".."
2898 "The ellipses to be used when a field in column view is truncated.
2899 When this is the empty string, as many characters as possible are shown,
2900 but then there will be no visual indication that the field has been truncated.
2901 When this is a string of length N, the last N characters of a truncated
2902 field are replaced by this string. If the column is narrower than the
2903 ellipses string, only part of the ellipses string will be shown."
2904 :group
'org-properties
2907 (defcustom org-columns-modify-value-for-display-function nil
2908 "Function that modifies values for display in column view.
2909 For example, it can be used to cut out a certain part from a time stamp.
2910 The function must take 2 arguments:
2912 column-title The title of the column (*not* the property name)
2913 value The value that should be modified.
2915 The function should return the value that should be displayed,
2916 or nil if the normal value should be used."
2917 :group
'org-properties
2920 (defcustom org-effort-property
"Effort"
2921 "The property that is being used to keep track of effort estimates.
2922 Effort estimates given in this property need to have the format H:MM."
2923 :group
'org-properties
2924 :group
'org-progress
2925 :type
'(string :tag
"Property"))
2927 (defconst org-global-properties-fixed
2928 '(("VISIBILITY_ALL" .
"folded children content all")
2929 ("CLOCK_MODELINE_TOTAL_ALL" .
"current today repeat all auto"))
2930 "List of property/value pairs that can be inherited by any entry.
2932 These are fixed values, for the preset properties. The user variable
2933 that can be used to add to this list is `org-global-properties'.
2935 The entries in this list are cons cells where the car is a property
2936 name and cdr is a string with the value. If the value represents
2937 multiple items like an \"_ALL\" property, separate the items by
2940 (defcustom org-global-properties nil
2941 "List of property/value pairs that can be inherited by any entry.
2943 This list will be combined with the constant `org-global-properties-fixed'.
2945 The entries in this list are cons cells where the car is a property
2946 name and cdr is a string with the value.
2948 You can set buffer-local values for the same purpose in the variable
2949 `org-file-properties' this by adding lines like
2951 #+PROPERTY: NAME VALUE"
2952 :group
'org-properties
2954 (cons (string :tag
"Property")
2955 (string :tag
"Value"))))
2957 (defvar org-file-properties nil
2958 "List of property/value pairs that can be inherited by any entry.
2959 Valid for the current buffer.
2960 This variable is populated from #+PROPERTY lines.")
2961 (make-variable-buffer-local 'org-file-properties
)
2963 (defgroup org-agenda nil
2964 "Options concerning agenda views in Org-mode."
2968 (defvar org-category nil
2969 "Variable used by org files to set a category for agenda display.
2970 Such files should use a file variable to set it, for example
2972 # -*- mode: org; org-category: \"ELisp\"
2974 or contain a special line
2978 If the file does not specify a category, then file's base name
2980 (make-variable-buffer-local 'org-category
)
2981 (put 'org-category
'safe-local-variable
'(lambda (x) (or (symbolp x
) (stringp x
))))
2983 (defcustom org-agenda-files nil
2984 "The files to be used for agenda display.
2985 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2986 \\[org-remove-file]. You can also use customize to edit the list.
2988 If an entry is a directory, all files in that directory that are matched by
2989 `org-agenda-file-regexp' will be part of the file list.
2991 If the value of the variable is not a list but a single file name, then
2992 the list of agenda files is actually stored and maintained in that file, one
2993 agenda file per line. In this file paths can be given relative to
2994 `org-directory'. Tilde expansion and environment variable substitution
2998 (repeat :tag
"List of files and directories" file
)
2999 (file :tag
"Store list in a file\n" :value
"~/.agenda_files")))
3001 (defcustom org-agenda-file-regexp
"\\`[^.].*\\.org\\'"
3002 "Regular expression to match files for `org-agenda-files'.
3003 If any element in the list in that variable contains a directory instead
3004 of a normal file, all files in that directory that are matched by this
3005 regular expression will be included."
3009 (defcustom org-agenda-text-search-extra-files nil
3010 "List of extra files to be searched by text search commands.
3011 These files will be search in addition to the agenda files by the
3012 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3013 Note that these files will only be searched for text search commands,
3014 not for the other agenda views like todo lists, tag searches or the weekly
3015 agenda. This variable is intended to list notes and possibly archive files
3016 that should also be searched by these two commands.
3017 In fact, if the first element in the list is the symbol `agenda-archives',
3018 than all archive files of all agenda files will be added to the search
3021 :type
'(set :greedy t
3022 (const :tag
"Agenda Archives" agenda-archives
)
3023 (repeat :inline t
(file))))
3025 (if (fboundp 'defvaralias
)
3026 (defvaralias 'org-agenda-multi-occur-extra-files
3027 'org-agenda-text-search-extra-files
))
3029 (defcustom org-agenda-skip-unavailable-files nil
3030 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3031 A nil value means to remove them, after a query, from the list."
3035 (defcustom org-calendar-to-agenda-key
[?c
]
3036 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3037 The command `org-calendar-goto-agenda' will be bound to this key. The
3038 default is the character `c' because then `c' can be used to switch back and
3039 forth between agenda and calendar."
3043 (defcustom org-calendar-agenda-action-key
[?k
]
3044 "The key to be installed in `calendar-mode-map' for agenda-action.
3045 The command `org-agenda-action' will be bound to this key. The
3046 default is the character `k' because we use the same key in the agenda."
3050 (defcustom org-calendar-insert-diary-entry-key
[?i
]
3051 "The key to be installed in `calendar-mode-map' for adding diary entries.
3052 This option is irrelevant until `org-agenda-diary-file' has been configured
3053 to point to an Org-mode file. When that is the case, the command
3054 `org-agenda-diary-entry' will be bound to the key given here, by default
3055 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3056 if you want to continue doing this, you need to change this to a different
3061 (defcustom org-agenda-diary-file
'diary-file
3062 "File to which to add new entries with the `i' key in agenda and calendar.
3063 When this is the symbol `diary-file', the functionality in the Emacs
3064 calendar will be used to add entries to the `diary-file'. But when this
3065 points to a file, `org-agenda-diary-entry' will be used instead."
3068 (const :tag
"The standard Emacs diary file" diary-file
)
3069 (file :tag
"Special Org file diary entries")))
3071 (eval-after-load "calendar"
3073 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3074 'org-calendar-goto-agenda
)
3075 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3077 (add-hook 'calendar-mode-hook
3079 (unless (eq org-agenda-diary-file
'diary-file
)
3080 (define-key calendar-mode-map
3081 org-calendar-insert-diary-entry-key
3082 'org-agenda-diary-entry
))))))
3084 (defgroup org-latex nil
3085 "Options for embedding LaTeX code into Org-mode."
3089 (defcustom org-format-latex-options
3090 '(:foreground default
:background default
:scale
1.0
3091 :html-foreground
"Black" :html-background
"Transparent"
3092 :html-scale
1.0 :matchers
("begin" "$1" "$" "$$" "\\(" "\\["))
3093 "Options for creating images from LaTeX fragments.
3094 This is a property list with the following properties:
3095 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3096 `default' means use the foreground of the default face.
3097 :background the background color, or \"Transparent\".
3098 `default' means use the background of the default face.
3099 :scale a scaling factor for the size of the images, to get more pixels
3100 :html-foreground, :html-background, :html-scale
3101 the same numbers for HTML export.
3102 :matchers a list indicating which matchers should be used to
3103 find LaTeX fragments. Valid members of this list are:
3104 \"begin\" find environments
3105 \"$1\" find single characters surrounded by $.$
3106 \"$\" find math expressions surrounded by $...$
3107 \"$$\" find math expressions surrounded by $$....$$
3108 \"\\(\" find math expressions surrounded by \\(...\\)
3109 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3113 (defcustom org-format-latex-signal-error t
3114 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3115 When nil, just push out a message."
3119 (defcustom org-format-latex-header
"\\documentclass{article}
3120 \\usepackage[usenames]{color}
3121 \\usepackage{amsmath}
3122 \\usepackage[mathscr]{eucal}
3123 \\pagestyle{empty} % do not remove
3126 % The settings below are copied from fullpage.sty
3127 \\setlength{\\textwidth}{\\paperwidth}
3128 \\addtolength{\\textwidth}{-3cm}
3129 \\setlength{\\oddsidemargin}{1.5cm}
3130 \\addtolength{\\oddsidemargin}{-2.54cm}
3131 \\setlength{\\evensidemargin}{\\oddsidemargin}
3132 \\setlength{\\textheight}{\\paperheight}
3133 \\addtolength{\\textheight}{-\\headheight}
3134 \\addtolength{\\textheight}{-\\headsep}
3135 \\addtolength{\\textheight}{-\\footskip}
3136 \\addtolength{\\textheight}{-3cm}
3137 \\setlength{\\topmargin}{1.5cm}
3138 \\addtolength{\\topmargin}{-2.54cm}"
3139 "The document header used for processing LaTeX fragments.
3140 It is imperative that this header make sure that no page number
3141 appears on the page. The package defined in the variables
3142 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3143 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3148 (defvar org-format-latex-header-extra nil
)
3150 (defun org-set-packages-alist (var val
)
3151 "Set the packages alist and make sure it has 3 elements per entry."
3152 (set var
(mapcar (lambda (x)
3153 (if (and (consp x
) (= (length x
) 2))
3154 (list (car x
) (nth 1 x
) t
)
3158 (defun org-get-packages-alist (var)
3160 "Get the packages alist and make sure it has 3 elements per entry."
3162 (if (and (consp x
) (= (length x
) 2))
3163 (list (car x
) (nth 1 x
) t
)
3165 (default-value var
)))
3167 ;; The following variables are defined here because is it also used
3168 ;; when formatting latex fragments. Originally it was part of the
3169 ;; LaTeX exporter, which is why the name includes "export".
3170 (defcustom org-export-latex-default-packages-alist
3171 '(("AUTO" "inputenc" t
)
3175 ("" "longtable" nil
)
3188 "Alist of default packages to be inserted in the header.
3189 Change this only if one of the packages here causes an incompatibility
3190 with another package you are using.
3191 The packages in this list are needed by one part or another of Org-mode
3192 to function properly.
3194 - inputenc, fontenc, t1enc: for basic font and character selection
3195 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3196 for interpreting the entities in `org-entities'. You can skip some of these
3197 packages if you don't use any of the symbols in it.
3198 - graphicx: for including images
3199 - float, wrapfig: for figure placement
3200 - longtable: for long tables
3201 - hyperref: for cross references
3203 Therefore you should not modify this variable unless you know what you
3204 are doing. The one reason to change it anyway is that you might be loading
3205 some other package that conflicts with one of the default packages.
3206 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3207 If SNIPPET-FLAG is t, the package also needs to be included when
3208 compiling LaTeX snippets into images for inclusion into HTML."
3209 :group
'org-export-latex
3210 :set
'org-set-packages-alist
3211 :get
'org-get-packages-alist
3214 (list :tag
"options/package pair"
3215 (string :tag
"options")
3216 (string :tag
"package")
3217 (boolean :tag
"Snippet"))
3218 (string :tag
"A line of LaTeX"))))
3220 (defcustom org-export-latex-packages-alist nil
3221 "Alist of packages to be inserted in every LaTeX header.
3222 These will be inserted after `org-export-latex-default-packages-alist'.
3223 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3224 SNIPPET-FLAG, when t, indicates that this package is also needed when
3225 turning LaTeX snippets into images for inclusion into HTML.
3226 Make sure that you only list packages here which:
3227 - you want in every file
3228 - do not conflict with the default packages in
3229 `org-export-latex-default-packages-alist'
3230 - do not conflict with the setup in `org-format-latex-header'."
3231 :group
'org-export-latex
3232 :set
'org-set-packages-alist
3233 :get
'org-get-packages-alist
3236 (list :tag
"options/package pair"
3237 (string :tag
"options")
3238 (string :tag
"package")
3239 (boolean :tag
"Snippet"))
3240 (string :tag
"A line of LaTeX"))))
3243 (defgroup org-appearance nil
3244 "Settings for Org-mode appearance."
3245 :tag
"Org Appearance"
3248 (defcustom org-level-color-stars-only nil
3249 "Non-nil means fontify only the stars in each headline.
3250 When nil, the entire headline is fontified.
3251 Changing it requires restart of `font-lock-mode' to become effective
3252 also in regions already fontified."
3253 :group
'org-appearance
3256 (defcustom org-hide-leading-stars nil
3257 "Non-nil means hide the first N-1 stars in a headline.
3258 This works by using the face `org-hide' for these stars. This
3259 face is white for a light background, and black for a dark
3260 background. You may have to customize the face `org-hide' to
3262 Changing it requires restart of `font-lock-mode' to become effective
3263 also in regions already fontified.
3264 You may also set this on a per-file basis by adding one of the following
3265 lines to the buffer:
3267 #+STARTUP: hidestars
3268 #+STARTUP: showstars"
3269 :group
'org-appearance
3272 (defcustom org-hidden-keywords nil
3273 "List of keywords that should be hidden when typed in the org buffer.
3274 For example, add #+TITLE to this list in order to make the
3275 document title appear in the buffer without the initial #+TITLE:
3277 :group
'org-appearance
3278 :type
'(set (const :tag
"#+AUTHOR" author
)
3279 (const :tag
"#+DATE" date
)
3280 (const :tag
"#+EMAIL" email
)
3281 (const :tag
"#+TITLE" title
)))
3283 (defcustom org-fontify-done-headline nil
3284 "Non-nil means change the face of a headline if it is marked DONE.
3285 Normally, only the TODO/DONE keyword indicates the state of a headline.
3286 When this is non-nil, the headline after the keyword is set to the
3287 `org-headline-done' as an additional indication."
3288 :group
'org-appearance
3291 (defcustom org-fontify-emphasized-text t
3292 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3293 Changing this variable requires a restart of Emacs to take effect."
3294 :group
'org-appearance
3297 (defcustom org-fontify-whole-heading-line nil
3298 "Non-nil means fontify the whole line for headings.
3299 This is useful when setting a background color for the
3301 :group
'org-appearance
3304 (defcustom org-highlight-latex-fragments-and-specials nil
3305 "Non-nil means fontify what is treated specially by the exporters."
3306 :group
'org-appearance
3309 (defcustom org-hide-emphasis-markers nil
3310 "Non-nil mean font-lock should hide the emphasis marker characters."
3311 :group
'org-appearance
3314 (defcustom org-pretty-entities nil
3315 "Non-nil means show entities as UTF8 characters.
3316 When nil, the \\name form remains in the buffer."
3317 :group
'org-appearance
3320 (defcustom org-pretty-entities-include-sub-superscripts t
3321 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3322 :group
'org-appearance
3325 (defvar org-emph-re nil
3326 "Regular expression for matching emphasis.
3327 After a match, the match groups contain these elements:
3328 1 The character before the proper match, or empty at beginning of line
3329 2 The proper match, including the leading and trailing markers
3330 3 The leading marker like * or /, indicating the type of highlighting
3331 4 The text between the emphasis markers, not including the markers
3332 5 The character after the match, empty at the end of a line")
3333 (defvar org-verbatim-re nil
3334 "Regular expression for matching verbatim text.")
3335 (defvar org-emphasis-regexp-components
) ; defined just below
3336 (defvar org-emphasis-alist
) ; defined just below
3337 (defun org-set-emph-re (var val
)
3338 "Set variable and compute the emphasis regular expression."
3340 (when (and (boundp 'org-emphasis-alist
)
3341 (boundp 'org-emphasis-regexp-components
)
3342 org-emphasis-alist org-emphasis-regexp-components
)
3343 (let* ((e org-emphasis-regexp-components
)
3349 (body1 (concat body
"*?"))
3350 (markers (mapconcat 'car org-emphasis-alist
""))
3351 (vmarkers (mapconcat
3352 (lambda (x) (if (eq (nth 4 x
) 'verbatim
) (car x
) ""))
3353 org-emphasis-alist
"")))
3354 ;; make sure special characters appear at the right position in the class
3355 (if (string-match "\\^" markers
)
3356 (setq markers
(concat (replace-match "" t t markers
) "^")))
3357 (if (string-match "-" markers
)
3358 (setq markers
(concat (replace-match "" t t markers
) "-")))
3359 (if (string-match "\\^" vmarkers
)
3360 (setq vmarkers
(concat (replace-match "" t t vmarkers
) "^")))
3361 (if (string-match "-" vmarkers
)
3362 (setq vmarkers
(concat (replace-match "" t t vmarkers
) "-")))
3364 (setq body1
(concat body1
"\\(?:\n" body
"*?\\)\\{0,"
3365 (int-to-string nl
) "\\}")))
3368 (concat "\\([" pre
"]\\|^\\)"
3370 "\\([" markers
"]\\)"
3378 "\\([" post
"]\\|$\\)"))
3379 (setq org-verbatim-re
3380 (concat "\\([" pre
"]\\|^\\)"
3382 "\\([" vmarkers
"]\\)"
3390 "\\([" post
"]\\|$\\)")))))
3392 (defcustom org-emphasis-regexp-components
3393 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3394 "Components used to build the regular expression for emphasis.
3395 This is a list with 6 entries. Terminology: In an emphasis string
3396 like \" *strong word* \", we call the initial space PREMATCH, the final
3397 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3398 and \"trong wor\" is the body. The different components in this variable
3399 specify what is allowed/forbidden in each part:
3401 pre Chars allowed as prematch. Beginning of line will be allowed too.
3402 post Chars allowed as postmatch. End of line will be allowed too.
3403 border The chars *forbidden* as border characters.
3404 body-regexp A regexp like \".\" to match a body character. Don't use
3405 non-shy groups here, and don't allow newline here.
3406 newline The maximum number of newlines allowed in an emphasis exp.
3408 Use customize to modify this, or restart Emacs after changing it."
3409 :group
'org-appearance
3410 :set
'org-set-emph-re
3412 (sexp :tag
"Allowed chars in pre ")
3413 (sexp :tag
"Allowed chars in post ")
3414 (sexp :tag
"Forbidden chars in border ")
3415 (sexp :tag
"Regexp for body ")
3416 (integer :tag
"number of newlines allowed")
3417 (option (boolean :tag
"Please ignore this button"))))
3419 (defcustom org-emphasis-alist
3420 `(("*" bold
"<b>" "</b>")
3421 ("/" italic
"<i>" "</i>")
3422 ("_" underline
"<span style=\"text-decoration:underline;\">" "</span>")
3423 ("=" org-code
"<code>" "</code>" verbatim
)
3424 ("~" org-verbatim
"<code>" "</code>" verbatim
)
3425 ("+" ,(if (featurep 'xemacs
) 'org-table
'(:strike-through t
))
3428 "Special syntax for emphasized text.
3429 Text starting and ending with a special character will be emphasized, for
3430 example *bold*, _underlined_ and /italic/. This variable sets the marker
3431 characters, the face to be used by font-lock for highlighting in Org-mode
3432 Emacs buffers, and the HTML tags to be used for this.
3433 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3434 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3435 Use customize to modify this, or restart Emacs after changing it."
3436 :group
'org-appearance
3437 :set
'org-set-emph-re
3440 (string :tag
"Marker character")
3442 (face :tag
"Font-lock-face")
3443 (plist :tag
"Face property list"))
3444 (string :tag
"HTML start tag")
3445 (string :tag
"HTML end tag")
3446 (option (const verbatim
)))))
3448 (defvar org-protecting-blocks
3449 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3450 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3451 This is needed for font-lock setup.")
3453 ;;; Miscellaneous options
3455 (defgroup org-completion nil
3456 "Completion in Org-mode."
3457 :tag
"Org Completion"
3460 (defcustom org-completion-use-ido nil
3461 "Non-nil means use ido completion wherever possible.
3462 Note that `ido-mode' must be active for this variable to be relevant.
3463 If you decide to turn this variable on, you might well want to turn off
3464 `org-outline-path-complete-in-steps'.
3465 See also `org-completion-use-iswitchb'."
3466 :group
'org-completion
3469 (defcustom org-completion-use-iswitchb nil
3470 "Non-nil means use iswitchb completion wherever possible.
3471 Note that `iswitchb-mode' must be active for this variable to be relevant.
3472 If you decide to turn this variable on, you might well want to turn off
3473 `org-outline-path-complete-in-steps'.
3474 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3475 :group
'org-completion
3478 (defcustom org-completion-fallback-command
'hippie-expand
3479 "The expansion command called by \\[org-complete] in normal context.
3480 Normal means no org-mode-specific context."
3481 :group
'org-completion
3484 ;;; Functions and variables from their packages
3485 ;; Declared here to avoid compiler warnings
3488 (defvar outline-mode-menu-heading
)
3489 (defvar outline-mode-menu-show
)
3490 (defvar outline-mode-menu-hide
)
3491 (defvar zmacs-regions
) ; XEmacs regions
3494 (defvar mark-active
)
3497 (declare-function calendar-absolute-from-iso
"cal-iso" (date))
3498 (declare-function calendar-forward-day
"cal-move" (arg))
3499 (declare-function calendar-goto-date
"cal-move" (date))
3500 (declare-function calendar-goto-today
"cal-move" ())
3501 (declare-function calendar-iso-from-absolute
"cal-iso" (date))
3502 (defvar calc-embedded-close-formula
)
3503 (defvar calc-embedded-open-formula
)
3504 (declare-function cdlatex-tab
"ext:cdlatex" ())
3505 (declare-function dired-get-filename
"dired" (&optional localp no-error-if-not-filep
))
3506 (defvar font-lock-unfontify-region-function
)
3507 (declare-function iswitchb-read-buffer
"iswitchb"
3508 (prompt &optional default require-match start matches-set
))
3509 (defvar iswitchb-temp-buflist
)
3510 (declare-function org-gnus-follow-link
"org-gnus" (&optional group article
))
3511 (defvar org-agenda-tags-todo-honor-ignore-options
)
3512 (declare-function org-agenda-skip
"org-agenda" ())
3514 org-format-agenda-item
"org-agenda"
3515 (extra txt
&optional category tags dotime noprefix remove-re habitp
))
3516 (declare-function org-agenda-new-marker
"org-agenda" (&optional pos
))
3517 (declare-function org-agenda-change-all-lines
"org-agenda"
3518 (newhead hdmarker
&optional fixface just-this
))
3519 (declare-function org-agenda-set-restriction-lock
"org-agenda" (&optional type
))
3520 (declare-function org-agenda-maybe-redo
"org-agenda" ())
3521 (declare-function org-agenda-save-markers-for-cut-and-paste
"org-agenda"
3523 (declare-function org-agenda-copy-local-variable
"org-agenda" (var))
3524 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3525 "org-agenda" (&optional end
))
3526 (declare-function org-inlinetask-remove-END-maybe
"org-inlinetask" ())
3527 (declare-function org-indent-mode
"org-indent" (&optional arg
))
3528 (declare-function parse-time-string
"parse-time" (string))
3529 (declare-function org-attach-reveal
"org-attach" (&optional if-exists
))
3530 (declare-function org-export-latex-fix-inputenc
"org-latex" ())
3531 (defvar remember-data-file
)
3532 (defvar texmathp-why
)
3533 (declare-function speedbar-line-directory
"speedbar" (&optional depth
))
3534 (declare-function table--at-cell-p
"table" (position &optional object at-column
))
3536 (defvar w3m-current-url
)
3537 (defvar w3m-current-title
)
3539 (defvar org-latex-regexps
)
3541 ;;; Autoload and prepare some org modules
3543 ;; Some table stuff that needs to be defined here, because it is used
3544 ;; by the functions setting up org-mode or checking for table context.
3546 (defconst org-table-any-line-regexp
"^[ \t]*\\(|\\|\\+-[-+]\\)"
3547 "Detect an org-type or table-type table.")
3548 (defconst org-table-line-regexp
"^[ \t]*|"
3549 "Detect an org-type table line.")
3550 (defconst org-table-dataline-regexp
"^[ \t]*|[^-]"
3551 "Detect an org-type table line.")
3552 (defconst org-table-hline-regexp
"^[ \t]*|-"
3553 "Detect an org-type table hline.")
3554 (defconst org-table1-hline-regexp
"^[ \t]*\\+-[-+]"
3555 "Detect a table-type table hline.")
3556 (defconst org-table-any-border-regexp
"^[ \t]*[^|+ \t]"
3557 "Detect the first line outside a table when searching from within it.
3558 This works for both table types.")
3560 ;; Autoload the functions in org-table.el that are needed by functions here.
3563 (org-autoload "org-table"
3564 '(org-table-align org-table-begin org-table-blank-field
3565 org-table-convert org-table-convert-region org-table-copy-down
3566 org-table-copy-region org-table-create
3567 org-table-create-or-convert-from-region
3568 org-table-create-with-table.el org-table-current-dline
3569 org-table-cut-region org-table-delete-column org-table-edit-field
3570 org-table-edit-formulas org-table-end org-table-eval-formula
3571 org-table-export org-table-field-info
3572 org-table-get-stored-formulas org-table-goto-column
3573 org-table-hline-and-move org-table-import org-table-insert-column
3574 org-table-insert-hline org-table-insert-row org-table-iterate
3575 org-table-justify-field-maybe org-table-kill-row
3576 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3577 org-table-move-column org-table-move-column-left
3578 org-table-move-column-right org-table-move-row
3579 org-table-move-row-down org-table-move-row-up
3580 org-table-next-field org-table-next-row org-table-paste-rectangle
3581 org-table-previous-field org-table-recalculate
3582 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3583 org-table-toggle-coordinate-overlays
3584 org-table-toggle-formula-debugger org-table-wrap-region
3585 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3586 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3587 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo
)))
3589 (defun org-at-table-p (&optional table-type
)
3590 "Return t if the cursor is inside an org-type table.
3591 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3592 (if org-enable-table-editor
3594 (beginning-of-line 1)
3595 (looking-at (if table-type org-table-any-line-regexp
3596 org-table-line-regexp
)))
3598 (defsubst org-table-p
() (org-at-table-p))
3600 (defun org-at-table.el-p
()
3601 "Return t if and only if we are at a table.el table."
3602 (and (org-at-table-p 'any
)
3604 (goto-char (org-table-begin 'any
))
3605 (looking-at org-table1-hline-regexp
))))
3606 (defun org-table-recognize-table.el
()
3607 "If there is a table.el table nearby, recognize it and move into it."
3608 (if org-table-tab-recognizes-table.el
3609 (if (org-at-table.el-p
)
3611 (beginning-of-line 1)
3612 (if (looking-at org-table-dataline-regexp
)
3614 (if (looking-at org-table1-hline-regexp
)
3616 (beginning-of-line 2)
3617 (if (looking-at org-table-any-border-regexp
)
3618 (beginning-of-line -
1)))))
3619 (if (re-search-forward "|" (org-table-end t
) t
)
3622 (if (table--at-cell-p (point))
3624 (message "recognizing table.el table...")
3625 (table-recognize-table)
3626 (message "recognizing table.el table...done")))
3627 (error "This should not happen"))
3632 (defun org-at-table-hline-p ()
3633 "Return t if the cursor is inside a hline in a table."
3634 (if org-enable-table-editor
3636 (beginning-of-line 1)
3637 (looking-at org-table-hline-regexp
))
3640 (defvar org-table-clean-did-remove-column nil
)
3642 (defun org-table-map-tables (function &optional quietly
)
3643 "Apply FUNCTION to the start of all tables in the buffer."
3647 (goto-char (point-min))
3648 (while (re-search-forward org-table-any-line-regexp nil t
)
3650 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3651 (beginning-of-line 1)
3652 (when (looking-at org-table-line-regexp
)
3653 (save-excursion (funcall function
))
3654 (or (looking-at org-table-line-regexp
)
3656 (re-search-forward org-table-any-border-regexp nil
1))))
3657 (unless quietly
(message "Mapping tables: done")))
3659 ;; Declare and autoload functions from org-exp.el & Co
3661 (declare-function org-default-export-plist
"org-exp")
3662 (declare-function org-infile-export-plist
"org-exp")
3663 (declare-function org-get-current-options
"org-exp")
3665 (org-autoload "org-exp"
3666 '(org-export org-export-visible
3667 org-insert-export-options-template
3668 org-table-clean-before-export
))
3669 (org-autoload "org-ascii"
3670 '(org-export-as-ascii org-export-ascii-preprocess
3671 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3672 org-export-region-as-ascii
))
3673 (org-autoload "org-latex"
3674 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3675 org-replace-region-by-latex org-export-region-as-latex
3676 org-export-as-latex org-export-as-pdf
3677 org-export-as-pdf-and-open
))
3678 (org-autoload "org-html"
3679 '(org-export-as-html-and-open
3680 org-export-as-html-batch org-export-as-html-to-buffer
3681 org-replace-region-by-html org-export-region-as-html
3682 org-export-as-html
))
3683 (org-autoload "org-docbook"
3684 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3685 org-replace-region-by-docbook org-export-region-as-docbook
3686 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3687 org-export-as-docbook
))
3688 (org-autoload "org-icalendar"
3689 '(org-export-icalendar-this-file
3690 org-export-icalendar-all-agenda-files
3691 org-export-icalendar-combine-agenda-files
))
3692 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3693 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning
)))
3695 ;; Declare and autoload functions from org-agenda.el
3698 (org-autoload "org-agenda"
3699 '(org-agenda org-agenda-list org-search-view
3700 org-todo-list org-tags-view org-agenda-list-stuck-projects
3701 org-diary org-agenda-to-appt
3702 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
)))
3704 ;; Autoload org-remember
3707 (org-autoload "org-remember"
3708 '(org-remember-insinuate org-remember-annotation
3709 org-remember-apply-template org-remember org-remember-handler
)))
3712 (org-autoload "org-capture"
3713 '(org-capture org-capture-insert-template-here
3714 org-capture-import-remember-templates
)))
3716 ;; Autoload org-clock.el
3719 (declare-function org-clock-save-markers-for-cut-and-paste
"org-clock"
3721 (declare-function org-clock-update-mode-line
"org-clock" ())
3722 (declare-function org-resolve-clocks
"org-clock"
3723 (&optional also-non-dangling-p prompt last-valid
))
3724 (defvar org-clock-start-time
)
3725 (defvar org-clock-marker
(make-marker)
3726 "Marker recording the last clock-in.")
3727 (defvar org-clock-hd-marker
(make-marker)
3728 "Marker recording the last clock-in, but the headline position.")
3729 (defvar org-clock-heading
""
3730 "The heading of the current clock entry.")
3731 (defun org-clock-is-active ()
3732 "Return non-nil if clock is currently running.
3733 The return value is actually the clock marker."
3734 (marker-buffer org-clock-marker
))
3739 '(org-clock-in org-clock-out org-clock-cancel
3740 org-clock-goto org-clock-sum org-clock-display
3741 org-clock-remove-overlays org-clock-report
3742 org-clocktable-shift org-dblock-write
:clocktable
3743 org-get-clocktable org-resolve-clocks
)))
3745 (defun org-clock-update-time-maybe ()
3746 "If this is a CLOCK line, update it and return t.
3747 Otherwise, return nil."
3750 (beginning-of-line 1)
3751 (skip-chars-forward " \t")
3752 (when (looking-at org-clock-string
)
3753 (let ((re (concat "[ \t]*" org-clock-string
3754 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3755 "\\([ \t]*=>.*\\)?\\)?"))
3758 ((not (looking-at re
))
3760 ((not (match-end 2))
3761 (when (and (equal (marker-buffer org-clock-marker
) (current-buffer))
3762 (> org-clock-marker
(point))
3763 (<= org-clock-marker
(point-at-eol)))
3764 ;; The clock is running here
3765 (setq org-clock-start-time
3767 (org-parse-time-string (match-string 1))))
3768 (org-clock-update-mode-line)))
3770 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3772 (setq ts
(match-string 1)
3773 te
(match-string 3))
3774 (setq s
(- (org-float-time
3775 (apply 'encode-time
(org-parse-time-string te
)))
3777 (apply 'encode-time
(org-parse-time-string ts
))))
3780 h
(floor (/ s
3600))
3784 (insert " => " (format (if neg
"-%d:%02d" "%2d:%02d") h m
))
3787 (defun org-check-running-clock ()
3788 "Check if the current buffer contains the running clock.
3789 If yes, offer to stop it and to save the buffer with the changes."
3790 (when (and (equal (marker-buffer org-clock-marker
) (current-buffer))
3791 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3794 (when (y-or-n-p "Save changed buffer?")
3797 (defun org-clocktable-try-shift (dir n
)
3798 "Check if this line starts a clock table, if yes, shift the time block."
3799 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3800 (org-clocktable-shift dir n
)))
3802 ;; Autoload org-timer.el
3807 '(org-timer-start org-timer org-timer-item
3808 org-timer-change-times-in-region
3810 org-timer-reset-timers
3811 org-timer-show-remaining-time
)))
3813 ;; Autoload org-feed.el
3818 '(org-feed-update org-feed-update-all org-feed-goto-inbox
)))
3821 ;; Autoload org-indent.el
3823 ;; Define the variable already here, to make sure we have it.
3824 (defvar org-indent-mode nil
3825 "Non-nil if Org-Indent mode is enabled.
3826 Use the command `org-indent-mode' to change this variable.")
3831 '(org-indent-mode)))
3833 ;; Autoload org-mobile.el
3838 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda
)))
3840 ;; Autoload archiving code
3841 ;; The stuff that is needed for cycling and tags has to be defined here.
3843 (defgroup org-archive nil
3844 "Options concerning archiving in Org-mode."
3846 :group
'org-structure
)
3848 (defcustom org-archive-location
"%s_archive::"
3849 "The location where subtrees should be archived.
3851 The value of this variable is a string, consisting of two parts,
3852 separated by a double-colon. The first part is a filename and
3853 the second part is a headline.
3855 When the filename is omitted, archiving happens in the same file.
3856 %s in the filename will be replaced by the current file
3857 name (without the directory part). Archiving to a different file
3858 is useful to keep archived entries from contributing to the
3861 The archived entries will be filed as subtrees of the specified
3862 headline. When the headline is omitted, the subtrees are simply
3863 filed away at the end of the file, as top-level entries. Also in
3864 the heading you can use %s to represent the file name, this can be
3865 useful when using the same archive for a number of different files.
3867 Here are a few examples:
3869 If the current file is Projects.org, archive in file
3870 Projects.org_archive, as top-level trees. This is the default.
3872 \"::* Archived Tasks\"
3873 Archive in the current file, under the top-level headline
3874 \"* Archived Tasks\".
3876 \"~/org/archive.org::\"
3877 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3879 \"~/org/archive.org::From %s\"
3880 Archive in file ~/org/archive.org (absolute path), under headlines
3881 \"From FILENAME\" where file name is the current file name.
3883 \"basement::** Finished Tasks\"
3884 Archive in file ./basement (relative path), as level 3 trees
3885 below the level 2 heading \"** Finished Tasks\".
3887 You may set this option on a per-file basis by adding to the buffer a
3890 #+ARCHIVE: basement::** Finished Tasks
3892 You may also define it locally for a subtree by setting an ARCHIVE property
3893 in the entry. If such a property is found in an entry, or anywhere up
3894 the hierarchy, it will be used."
3898 (defcustom org-archive-tag
"ARCHIVE"
3899 "The tag that marks a subtree as archived.
3900 An archived subtree does not open during visibility cycling, and does
3901 not contribute to the agenda listings.
3902 After changing this, font-lock must be restarted in the relevant buffers to
3903 get the proper fontification."
3905 :group
'org-keywords
3908 (defcustom org-agenda-skip-archived-trees t
3909 "Non-nil means the agenda will skip any items located in archived trees.
3910 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3911 variable is no longer recommended, you should leave it at the value t.
3912 Instead, use the key `v' to cycle the archives-mode in the agenda."
3914 :group
'org-agenda-skip
3917 (defcustom org-columns-skip-archived-trees t
3918 "Non-nil means ignore archived trees when creating column view."
3920 :group
'org-properties
3923 (defcustom org-cycle-open-archived-trees nil
3924 "Non-nil means `org-cycle' will open archived trees.
3925 An archived tree is a tree marked with the tag ARCHIVE.
3926 When nil, archived trees will stay folded. You can still open them with
3927 normal outline commands like `show-all', but not with the cycling commands."
3932 (defcustom org-sparse-tree-open-archived-trees nil
3933 "Non-nil means sparse tree construction shows matches in archived trees.
3934 When nil, matches in these trees are highlighted, but the trees are kept in
3937 :group
'org-sparse-trees
3940 (defun org-cycle-hide-archived-subtrees (state)
3941 "Re-hide all archived subtrees after a visibility state change."
3942 (when (and (not org-cycle-open-archived-trees
)
3943 (not (memq state
'(overview folded
))))
3945 (let* ((globalp (memq state
'(contents all
)))
3946 (beg (if globalp
(point-min) (point)))
3947 (end (if globalp
(point-max) (org-end-of-subtree t
))))
3948 (org-hide-archived-subtrees beg end
)
3950 (if (looking-at (concat ".*:" org-archive-tag
":"))
3951 (message "%s" (substitute-command-keys
3952 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3954 (defun org-force-cycle-archived ()
3955 "Cycle subtree even if it is archived."
3957 (setq this-command
'org-cycle
)
3958 (let ((org-cycle-open-archived-trees t
))
3959 (call-interactively 'org-cycle
)))
3961 (defun org-hide-archived-subtrees (beg end
)
3962 "Re-hide all archived subtrees after a visibility state change."
3964 (let* ((re (concat ":" org-archive-tag
":")))
3966 (while (re-search-forward re end t
)
3967 (when (org-on-heading-p)
3968 (org-flag-subtree t
)
3969 (org-end-of-subtree t
))))))
3971 (defun org-flag-subtree (flag)
3973 (org-back-to-heading t
)
3974 (outline-end-of-heading)
3975 (outline-flag-region (point)
3976 (progn (org-end-of-subtree t
) (point))
3979 (defalias 'org-advertized-archive-subtree
'org-archive-subtree
)
3982 (org-autoload "org-archive"
3983 '(org-add-archive-files org-archive-subtree
3984 org-archive-to-archive-sibling org-toggle-archive-tag
3985 org-archive-subtree-default
3986 org-archive-subtree-default-with-confirmation
)))
3988 ;; Autoload Column View Code
3990 (declare-function org-columns-number-to-string
"org-colview")
3991 (declare-function org-columns-get-format-and-top-level
"org-colview")
3992 (declare-function org-columns-compute
"org-colview")
3994 (org-autoload (if (featurep 'xemacs
) "org-colview-xemacs" "org-colview")
3995 '(org-columns-number-to-string org-columns-get-format-and-top-level
3996 org-columns-compute org-agenda-columns org-columns-remove-overlays
3997 org-columns org-insert-columns-dblock org-dblock-write
:columnview
))
4001 (declare-function org-id-store-link
"org-id")
4002 (declare-function org-id-locations-load
"org-id")
4003 (declare-function org-id-locations-save
"org-id")
4004 (defvar org-id-track-globally
)
4005 (org-autoload "org-id"
4006 '(org-id-get-create org-id-new org-id-copy org-id-get
4007 org-id-get-with-outline-path-completion
4008 org-id-get-with-outline-drilling org-id-store-link
4009 org-id-goto org-id-find org-id-store-link
))
4011 ;; Autoload Plotting Code
4013 (org-autoload "org-plot"
4014 '(org-plot/gnuplot
))
4016 ;;; Variables for pre-computed regular expressions, all buffer local
4018 (defvar org-drawer-regexp nil
4019 "Matches first line of a hidden block.")
4020 (make-variable-buffer-local 'org-drawer-regexp
)
4021 (defvar org-todo-regexp nil
4022 "Matches any of the TODO state keywords.")
4023 (make-variable-buffer-local 'org-todo-regexp
)
4024 (defvar org-not-done-regexp nil
4025 "Matches any of the TODO state keywords except the last one.")
4026 (make-variable-buffer-local 'org-not-done-regexp
)
4027 (defvar org-not-done-heading-regexp nil
4028 "Matches a TODO headline that is not done.")
4029 (make-variable-buffer-local 'org-not-done-regexp
)
4030 (defvar org-todo-line-regexp nil
4031 "Matches a headline and puts TODO state into group 2 if present.")
4032 (make-variable-buffer-local 'org-todo-line-regexp
)
4033 (defvar org-complex-heading-regexp nil
4034 "Matches a headline and puts everything into groups:
4036 group 2: The todo keyword, maybe
4037 group 3: Priority cookie
4038 group 4: True headline
4040 (make-variable-buffer-local 'org-complex-heading-regexp
)
4041 (defvar org-complex-heading-regexp-format nil
)
4042 (make-variable-buffer-local 'org-complex-heading-regexp-format
)
4043 (defvar org-todo-line-tags-regexp nil
4044 "Matches a headline and puts TODO state into group 2 if present.
4045 Also put tags into group 4 if tags are present.")
4046 (make-variable-buffer-local 'org-todo-line-tags-regexp
)
4047 (defvar org-nl-done-regexp nil
4048 "Matches newline followed by a headline with the DONE keyword.")
4049 (make-variable-buffer-local 'org-nl-done-regexp
)
4050 (defvar org-looking-at-done-regexp nil
4051 "Matches the DONE keyword a point.")
4052 (make-variable-buffer-local 'org-looking-at-done-regexp
)
4053 (defvar org-ds-keyword-length
12
4054 "Maximum length of the Deadline and SCHEDULED keywords.")
4055 (make-variable-buffer-local 'org-ds-keyword-length
)
4056 (defvar org-deadline-regexp nil
4057 "Matches the DEADLINE keyword.")
4058 (make-variable-buffer-local 'org-deadline-regexp
)
4059 (defvar org-deadline-time-regexp nil
4060 "Matches the DEADLINE keyword together with a time stamp.")
4061 (make-variable-buffer-local 'org-deadline-time-regexp
)
4062 (defvar org-deadline-line-regexp nil
4063 "Matches the DEADLINE keyword and the rest of the line.")
4064 (make-variable-buffer-local 'org-deadline-line-regexp
)
4065 (defvar org-scheduled-regexp nil
4066 "Matches the SCHEDULED keyword.")
4067 (make-variable-buffer-local 'org-scheduled-regexp
)
4068 (defvar org-scheduled-time-regexp nil
4069 "Matches the SCHEDULED keyword together with a time stamp.")
4070 (make-variable-buffer-local 'org-scheduled-time-regexp
)
4071 (defvar org-closed-time-regexp nil
4072 "Matches the CLOSED keyword together with a time stamp.")
4073 (make-variable-buffer-local 'org-closed-time-regexp
)
4075 (defvar org-keyword-time-regexp nil
4076 "Matches any of the 4 keywords, together with the time stamp.")
4077 (make-variable-buffer-local 'org-keyword-time-regexp
)
4078 (defvar org-keyword-time-not-clock-regexp nil
4079 "Matches any of the 3 keywords, together with the time stamp.")
4080 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp
)
4081 (defvar org-maybe-keyword-time-regexp nil
4082 "Matches a timestamp, possibly preceded by a keyword.")
4083 (make-variable-buffer-local 'org-maybe-keyword-time-regexp
)
4084 (defvar org-planning-or-clock-line-re nil
4085 "Matches a line with planning or clock info.")
4086 (make-variable-buffer-local 'org-planning-or-clock-line-re
)
4087 (defvar org-all-time-keywords nil
4088 "List of time keywords.")
4089 (make-variable-buffer-local 'org-all-time-keywords
)
4091 (defconst org-plain-time-of-day-regexp
4094 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4097 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4099 "Regular expression to match a plain time or time range.
4100 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4101 groups carry important information:
4103 1 the first time, range or not
4104 8 the second time, if it is a range.")
4106 (defconst org-plain-time-extension-regexp
4109 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4110 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4111 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4112 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4113 groups carry important information:
4116 9 minutes of duration")
4118 (defconst org-stamp-time-of-day-regexp
4120 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4121 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4123 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4124 "Regular expression to match a timestamp time or time range.
4125 After a match, the following groups carry important information:
4127 1 date plus weekday, for back referencing to make sure both times are on the same day
4128 2 the first time, range or not
4129 4 the second time, if it is a range.")
4131 (defconst org-startup-options
4132 '(("fold" org-startup-folded t
)
4133 ("overview" org-startup-folded t
)
4134 ("nofold" org-startup-folded nil
)
4135 ("showall" org-startup-folded nil
)
4136 ("showeverything" org-startup-folded showeverything
)
4137 ("content" org-startup-folded content
)
4138 ("indent" org-startup-indented t
)
4139 ("noindent" org-startup-indented nil
)
4140 ("hidestars" org-hide-leading-stars t
)
4141 ("showstars" org-hide-leading-stars nil
)
4142 ("odd" org-odd-levels-only t
)
4143 ("oddeven" org-odd-levels-only nil
)
4144 ("align" org-startup-align-all-tables t
)
4145 ("noalign" org-startup-align-all-tables nil
)
4146 ("customtime" org-display-custom-times t
)
4147 ("logdone" org-log-done time
)
4148 ("lognotedone" org-log-done note
)
4149 ("nologdone" org-log-done nil
)
4150 ("lognoteclock-out" org-log-note-clock-out t
)
4151 ("nolognoteclock-out" org-log-note-clock-out nil
)
4152 ("logrepeat" org-log-repeat state
)
4153 ("lognoterepeat" org-log-repeat note
)
4154 ("nologrepeat" org-log-repeat nil
)
4155 ("logreschedule" org-log-reschedule time
)
4156 ("lognotereschedule" org-log-reschedule note
)
4157 ("nologreschedule" org-log-reschedule nil
)
4158 ("logredeadline" org-log-redeadline time
)
4159 ("lognoteredeadline" org-log-redeadline note
)
4160 ("nologredeadline" org-log-redeadline nil
)
4161 ("logrefile" org-log-refile time
)
4162 ("lognoterefile" org-log-refile note
)
4163 ("nologrefile" org-log-refile nil
)
4164 ("fninline" org-footnote-define-inline t
)
4165 ("nofninline" org-footnote-define-inline nil
)
4166 ("fnlocal" org-footnote-section nil
)
4167 ("fnauto" org-footnote-auto-label t
)
4168 ("fnprompt" org-footnote-auto-label nil
)
4169 ("fnconfirm" org-footnote-auto-label confirm
)
4170 ("fnplain" org-footnote-auto-label plain
)
4171 ("fnadjust" org-footnote-auto-adjust t
)
4172 ("nofnadjust" org-footnote-auto-adjust nil
)
4173 ("constcgs" constants-unit-system cgs
)
4174 ("constSI" constants-unit-system SI
)
4175 ("noptag" org-tag-persistent-alist nil
)
4176 ("hideblocks" org-hide-block-startup t
)
4177 ("nohideblocks" org-hide-block-startup nil
)
4178 ("beamer" org-startup-with-beamer-mode t
)
4179 ("entitiespretty" org-pretty-entities t
)
4180 ("entitiesplain" org-pretty-entities nil
))
4181 "Variable associated with STARTUP options for org-mode.
4182 Each element is a list of three items: The startup options as written
4183 in the #+STARTUP line, the corresponding variable, and the value to
4184 set this variable to if the option is found. An optional forth element PUSH
4185 means to push this value onto the list in the variable.")
4187 (defun org-set-regexps-and-options ()
4188 "Precompute regular expressions for current buffer."
4190 (org-set-local 'org-todo-kwd-alist nil
)
4191 (org-set-local 'org-todo-key-alist nil
)
4192 (org-set-local 'org-todo-key-trigger nil
)
4193 (org-set-local 'org-todo-keywords-1 nil
)
4194 (org-set-local 'org-done-keywords nil
)
4195 (org-set-local 'org-todo-heads nil
)
4196 (org-set-local 'org-todo-sets nil
)
4197 (org-set-local 'org-todo-log-states nil
)
4198 (org-set-local 'org-file-properties nil
)
4199 (org-set-local 'org-file-tags nil
)
4200 (let ((re (org-make-options-regexp
4201 '("CATEGORY" "TODO" "COLUMNS"
4202 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4203 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4205 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4207 (scripts org-use-sub-superscripts
)
4208 kwds kws0 kwsa key log value cat arch tags const links hw dws
4209 tail sep kws1 prio props ftags drawers beamer-p
4210 ext-setup-or-nil setup-contents
(start 0))
4214 (goto-char (point-min))
4215 (while (or (and ext-setup-or-nil
4216 (string-match re ext-setup-or-nil start
)
4217 (setq start
(match-end 0)))
4218 (and (setq ext-setup-or-nil nil start
0)
4219 (re-search-forward re nil t
)))
4220 (setq key
(upcase (match-string 1 ext-setup-or-nil
))
4221 value
(org-match-string-no-properties 2 ext-setup-or-nil
))
4222 (if (stringp value
) (setq value
(org-trim value
)))
4224 ((equal key
"CATEGORY")
4226 ((member key
'("SEQ_TODO" "TODO"))
4227 (push (cons 'sequence
(org-split-string value splitre
)) kwds
))
4228 ((equal key
"TYP_TODO")
4229 (push (cons 'type
(org-split-string value splitre
)) kwds
))
4230 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key
)
4231 ;; general TODO-like setup
4232 (push (cons (intern (downcase (match-string 1 key
)))
4233 (org-split-string value splitre
)) kwds
))
4235 (setq tags
(append tags
(if tags
'("\\n") nil
)
4236 (org-split-string value splitre
))))
4237 ((equal key
"COLUMNS")
4238 (org-set-local 'org-columns-default-format value
))
4240 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value
)
4241 (push (cons (match-string 1 value
)
4242 (org-trim (match-string 2 value
)))
4244 ((equal key
"PRIORITIES")
4245 (setq prio
(org-split-string value
" +")))
4246 ((equal key
"PROPERTY")
4247 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value
)
4248 (push (cons (match-string 1 value
) (match-string 2 value
))
4250 ((equal key
"FILETAGS")
4251 (when (string-match "\\S-" value
)
4256 (mapcar (lambda (x) (org-split-string x
":"))
4257 (org-split-string value
)))))))
4258 ((equal key
"DRAWERS")
4259 (setq drawers
(org-split-string value splitre
)))
4260 ((equal key
"CONSTANTS")
4261 (setq const
(append const
(org-split-string value splitre
))))
4262 ((equal key
"STARTUP")
4263 (let ((opts (org-split-string value splitre
))
4265 (while (setq l
(pop opts
))
4266 (when (setq l
(assoc l org-startup-options
))
4267 (setq var
(nth 1 l
) val
(nth 2 l
))
4269 (set (make-local-variable var
) val
)
4270 (if (not (listp (symbol-value var
)))
4271 (set (make-local-variable var
) nil
))
4272 (set (make-local-variable var
) (symbol-value var
))
4273 (add-to-list var val
))))))
4274 ((equal key
"ARCHIVE")
4276 (remove-text-properties 0 (length arch
)
4277 '(face t fontified t
) arch
))
4278 ((equal key
"LATEX_CLASS")
4279 (setq beamer-p
(equal value
"beamer")))
4280 ((equal key
"OPTIONS")
4281 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value
)
4282 (setq scripts
(read (match-string 2 value
)))))
4283 ((equal key
"SETUPFILE")
4284 (setq setup-contents
(org-file-contents
4286 (org-remove-double-quotes value
))
4288 (if (not ext-setup-or-nil
)
4289 (setq ext-setup-or-nil setup-contents start
0)
4290 (setq ext-setup-or-nil
4291 (concat (substring ext-setup-or-nil
0 start
)
4292 "\n" setup-contents
"\n"
4293 (substring ext-setup-or-nil start
)))))
4295 (org-set-local 'org-use-sub-superscripts scripts
)
4297 (org-set-local 'org-category
(intern cat
))
4298 (push (cons "CATEGORY" cat
) props
))
4300 (if (< (length prio
) 3) (setq prio
'("A" "C" "B")))
4301 (setq prio
(mapcar 'string-to-char prio
))
4302 (org-set-local 'org-highest-priority
(nth 0 prio
))
4303 (org-set-local 'org-lowest-priority
(nth 1 prio
))
4304 (org-set-local 'org-default-priority
(nth 2 prio
)))
4305 (and props
(org-set-local 'org-file-properties
(nreverse props
)))
4306 (and ftags
(org-set-local 'org-file-tags
4307 (mapcar 'org-add-prop-inherited ftags
)))
4308 (and drawers
(org-set-local 'org-drawers drawers
))
4309 (and arch
(org-set-local 'org-archive-location arch
))
4310 (and links
(setq org-link-abbrev-alist-local
(nreverse links
)))
4311 ;; Process the TODO keywords
4313 ;; Use the global values as if they had been given locally.
4314 (setq kwds
(default-value 'org-todo-keywords
))
4315 (if (stringp (car kwds
))
4316 (setq kwds
(list (cons org-todo-interpretation
4317 (default-value 'org-todo-keywords
)))))
4318 (setq kwds
(reverse kwds
)))
4319 (setq kwds
(nreverse kwds
))
4321 (while (setq kws
(pop kwds
))
4323 (run-hook-with-args-until-success
4324 'org-todo-setup-filter-hook kws
)
4326 (setq inter
(pop kws
) sep
(member "|" kws
)
4327 kws0
(delete "|" (copy-sequence kws
))
4332 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x
)
4334 (setq kw
(match-string 1 x
)
4335 key
(and (match-end 2) (match-string 2 x
))
4336 log
(org-extract-log-state-settings x
))
4337 (push (cons kw
(and key
(string-to-char key
))) kwsa
)
4338 (and log
(push log org-todo-log-states
))
4340 (error "Invalid TODO keyword %s" x
)))
4342 kwsa
(if kwsa
(append '((:startgroup
))
4346 dws
(if sep
(org-remove-keyword-keys (cdr sep
)) (last kws1
))
4347 tail
(list inter hw
(car dws
) (org-last dws
))))
4348 (add-to-list 'org-todo-heads hw
'append
)
4349 (push kws1 org-todo-sets
)
4350 (setq org-done-keywords
(append org-done-keywords dws nil
))
4351 (setq org-todo-key-alist
(append org-todo-key-alist kwsa
))
4352 (mapc (lambda (x) (push (cons x tail
) org-todo-kwd-alist
)) kws1
)
4353 (setq org-todo-keywords-1
(append org-todo-keywords-1 kws1 nil
)))
4354 (setq org-todo-sets
(nreverse org-todo-sets
)
4355 org-todo-kwd-alist
(nreverse org-todo-kwd-alist
)
4356 org-todo-key-trigger
(delq nil
(mapcar 'cdr org-todo-key-alist
))
4357 org-todo-key-alist
(org-assign-fast-keys org-todo-key-alist
)))
4358 ;; Process the constants
4361 (while (setq e
(pop const
))
4362 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e
)
4363 (push (cons (match-string 1 e
) (match-string 2 e
)) cst
)))
4364 (setq org-table-formula-constants-local cst
)))
4366 ;; Process the tags.
4369 (while (setq e
(pop tags
))
4371 ((equal e
"{") (push '(:startgroup
) tgs
))
4372 ((equal e
"}") (push '(:endgroup
) tgs
))
4373 ((equal e
"\\n") (push '(:newline
) tgs
))
4374 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e
)
4375 (push (cons (match-string 1 e
)
4376 (string-to-char (match-string 2 e
)))
4378 (t (push (list e
) tgs
))))
4379 (org-set-local 'org-tag-alist nil
)
4380 (while (setq e
(pop tgs
))
4381 (or (and (stringp (car e
))
4382 (assoc (car e
) org-tag-alist
))
4383 (push e org-tag-alist
)))))
4385 ;; Compute the regular expressions and other local variables
4386 (if (not org-done-keywords
)
4387 (setq org-done-keywords
(and org-todo-keywords-1
4388 (list (org-last org-todo-keywords-1
)))))
4389 (setq org-ds-keyword-length
(+ 2 (max (length org-deadline-string
)
4390 (length org-scheduled-string
)
4391 (length org-clock-string
)
4392 (length org-closed-string
)))
4394 (concat "^[ \t]*:\\("
4395 (mapconcat 'regexp-quote org-drawers
"\\|")
4397 org-not-done-keywords
4398 (org-delete-all org-done-keywords
(copy-sequence org-todo-keywords-1
))
4400 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4404 (mapconcat 'regexp-quote org-not-done-keywords
"\\|")
4406 org-not-done-heading-regexp
4407 (concat "^\\(\\*+\\)[ \t]+\\("
4408 (mapconcat 'regexp-quote org-not-done-keywords
"\\|")
4410 org-todo-line-regexp
4411 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4412 (mapconcat 'regexp-quote org-todo-keywords-1
"\\|")
4413 "\\)\\>\\)?[ \t]*\\(.*\\)")
4414 org-complex-heading-regexp
4415 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4416 (mapconcat 'regexp-quote org-todo-keywords-1
"\\|")
4417 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4418 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4419 org-complex-heading-regexp-format
4420 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4421 (mapconcat 'regexp-quote org-todo-keywords-1
"\\|")
4423 "\\(?:[ \t]*\\(\\[#.\\]\\)\\)?"
4424 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4426 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4427 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4429 (concat "\n\\*+[ \t]+"
4430 "\\(?:" (mapconcat 'regexp-quote org-done-keywords
"\\|")
4432 org-todo-line-tags-regexp
4433 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4434 (mapconcat 'regexp-quote org-todo-keywords-1
"\\|")
4436 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4437 org-looking-at-done-regexp
4439 (mapconcat 'regexp-quote org-done-keywords
"\\|") "\\)"
4441 org-deadline-regexp
(concat "\\<" org-deadline-string
)
4442 org-deadline-time-regexp
4443 (concat "\\<" org-deadline-string
" *<\\([^>]+\\)>")
4444 org-deadline-line-regexp
4445 (concat "\\<\\(" org-deadline-string
"\\).*")
4446 org-scheduled-regexp
4447 (concat "\\<" org-scheduled-string
)
4448 org-scheduled-time-regexp
4449 (concat "\\<" org-scheduled-string
" *<\\([^>]+\\)>")
4450 org-closed-time-regexp
4451 (concat "\\<" org-closed-string
" *\\[\\([^]]+\\)\\]")
4452 org-keyword-time-regexp
4453 (concat "\\<\\(" org-scheduled-string
4454 "\\|" org-deadline-string
4455 "\\|" org-closed-string
4456 "\\|" org-clock-string
"\\)"
4457 " *[[<]\\([^]>]+\\)[]>]")
4458 org-keyword-time-not-clock-regexp
4459 (concat "\\<\\(" org-scheduled-string
4460 "\\|" org-deadline-string
4461 "\\|" org-closed-string
4463 " *[[<]\\([^]>]+\\)[]>]")
4464 org-maybe-keyword-time-regexp
4465 (concat "\\(\\<\\(" org-scheduled-string
4466 "\\|" org-deadline-string
4467 "\\|" org-closed-string
4468 "\\|" org-clock-string
"\\)\\)?"
4469 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4470 org-planning-or-clock-line-re
4471 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4472 "\\|" org-deadline-string
4473 "\\|" org-closed-string
"\\|" org-clock-string
4475 org-all-time-keywords
4476 (mapcar (lambda (w) (substring w
0 -
1))
4477 (list org-scheduled-string org-deadline-string
4478 org-clock-string org-closed-string
))
4480 (org-compute-latex-and-specials-regexp)
4481 (org-set-font-lock-defaults))))
4483 (defun org-file-contents (file &optional noerror
)
4484 "Return the contents of FILE, as a string."
4486 (not (file-readable-p file
)))
4489 (message "Cannot read file \"%s\"" file
)
4492 (error "Cannot read file \"%s\"" file
))
4494 (insert-file-contents file
)
4497 (defun org-extract-log-state-settings (x)
4498 "Extract the log state setting from a TODO keyword string.
4499 This will extract info from a string like \"WAIT(w@/!)\"."
4500 (let (kw key log1 log2
)
4501 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x
)
4502 (setq kw
(match-string 1 x
)
4503 key
(and (match-end 2) (match-string 2 x
))
4504 log1
(and (match-end 3) (match-string 3 x
))
4505 log2
(and (match-end 4) (match-string 4 x
)))
4508 (and log1
(if (equal log1
"!") 'time
'note
))
4509 (and log2
(if (equal log2
"!") 'time
'note
)))))))
4511 (defun org-remove-keyword-keys (list)
4512 "Remove a pair of parenthesis at the end of each string in LIST."
4514 (if (string-match "(.*)$" x
)
4515 (substring x
0 (match-beginning 0))
4519 (defun org-assign-fast-keys (alist)
4520 "Assign fast keys to a keyword-key alist.
4521 Respect keys that are already there."
4522 (let (new e
(alt ?
0))
4523 (while (setq e
(pop alist
))
4524 (if (or (memq (car e
) '(:newline
:endgroup
:startgroup
))
4525 (cdr e
)) ;; Key already assigned.
4527 (let ((clist (string-to-list (downcase (car e
))))
4528 (used (append new alist
)))
4529 (when (= (car clist
) ?
@)
4531 (while (and clist
(rassoc (car clist
) used
))
4534 (while (rassoc alt used
)
4536 (push (cons (car e
) (or (car clist
) alt
)) new
))))
4539 ;;; Some variables used in various places
4541 (defvar org-window-configuration nil
4542 "Used in various places to store a window configuration.")
4543 (defvar org-selected-window nil
4544 "Used in various places to store a window configuration.")
4545 (defvar org-finish-function nil
4546 "Function to be called when `C-c C-c' is used.
4547 This is for getting out of special buffers like remember.")
4550 ;; FIXME: Occasionally check by commenting these, to make sure
4551 ;; no other functions uses these, forgetting to let-bind them.
4556 ;; Defined somewhere in this file, but used before definition.
4557 (defvar org-entities
) ;; defined in org-entities.el
4558 (defvar org-struct-menu
)
4559 (defvar org-org-menu
)
4560 (defvar org-tbl-menu
)
4562 ;;;; Define the Org-mode
4564 (if (and (not (keymapp outline-mode-map
)) (featurep 'allout
))
4565 (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"))
4568 ;; We use a before-change function to check if a table might need
4570 (defvar org-table-may-need-update t
4571 "Indicates that a table might need an update.
4572 This variable is set by `org-before-change-function'.
4573 `org-table-align' sets it back to nil.")
4574 (defun org-before-change-function (beg end
)
4575 "Every change indicates that a table might need an update."
4576 (setq org-table-may-need-update t
))
4577 (defvar org-mode-map
)
4578 (defvar org-inhibit-startup nil
) ; Dynamically-scoped param.
4579 (defvar org-inhibit-startup-visibility-stuff nil
) ; Dynamically-scoped param.
4580 (defvar org-agenda-keep-modes nil
) ; Dynamically-scoped param.
4581 (defvar org-inhibit-logging nil
) ; Dynamically-scoped param.
4582 (defvar org-inhibit-blocking nil
) ; Dynamically-scoped param.
4583 (defvar org-table-buffer-is-an nil
)
4584 (defconst org-outline-regexp
"\\*+ ")
4587 (define-derived-mode org-mode outline-mode
"Org"
4588 "Outline-based notes management and organizer, alias
4589 \"Carsten's outline-mode for keeping track of everything.\"
4591 Org-mode develops organizational tasks around a NOTES file which
4592 contains information about projects as plain text. Org-mode is
4593 implemented on top of outline-mode, which is ideal to keep the content
4594 of large files well structured. It supports ToDo items, deadlines and
4595 time stamps, which magically appear in the diary listing of the Emacs
4596 calendar. Tables are easily created with a built-in table editor.
4597 Plain text URL-like links connect to websites, emails (VM), Usenet
4598 messages (Gnus), BBDB entries, and any files related to the project.
4599 For printing and sharing of notes, an Org-mode file (or a part of it)
4600 can be exported as a structured ASCII or HTML file.
4602 The following commands are available:
4606 ;; Get rid of Outline menus, they are not needed
4607 ;; Need to do this here because define-derived-mode sets up
4608 ;; the keymap so late. Still, it is a waste to call this each time
4609 ;; we switch another buffer into org-mode.
4610 (if (featurep 'xemacs
)
4611 (when (boundp 'outline-mode-menu-heading
)
4612 ;; Assume this is Greg's port, it uses easymenu
4613 (easy-menu-remove outline-mode-menu-heading
)
4614 (easy-menu-remove outline-mode-menu-show
)
4615 (easy-menu-remove outline-mode-menu-hide
))
4616 (define-key org-mode-map
[menu-bar headings
] 'undefined
)
4617 (define-key org-mode-map
[menu-bar hide
] 'undefined
)
4618 (define-key org-mode-map
[menu-bar show
] 'undefined
))
4620 (org-load-modules-maybe)
4621 (easy-menu-add org-org-menu
)
4622 (easy-menu-add org-tbl-menu
)
4623 (org-install-agenda-files-menu)
4624 (if org-descriptive-links
(add-to-invisibility-spec '(org-link)))
4625 (add-to-invisibility-spec '(org-cwidth))
4626 (add-to-invisibility-spec '(org-hide-block . t
))
4627 (when (featurep 'xemacs
)
4628 (org-set-local 'line-move-ignore-invisible t
))
4629 (org-set-local 'outline-regexp org-outline-regexp
)
4630 (org-set-local 'outline-level
'org-outline-level
)
4631 (when (and org-ellipsis
4632 (fboundp 'set-display-table-slot
) (boundp 'buffer-display-table
)
4633 (fboundp 'make-glyph-code
))
4634 (unless org-display-table
4635 (setq org-display-table
(make-display-table)))
4636 (set-display-table-slot
4639 (lambda (c) (make-glyph-code c
(and (not (stringp org-ellipsis
))
4641 (if (stringp org-ellipsis
) org-ellipsis
"..."))))
4642 (setq buffer-display-table org-display-table
))
4643 (org-set-regexps-and-options)
4644 (when (and org-tag-faces
(not org-tags-special-faces-re
))
4645 ;; tag faces set outside customize.... force initialization.
4646 (org-set-tag-faces 'org-tag-faces org-tag-faces
))
4648 (org-set-local 'calc-embedded-open-mode
"# ")
4649 (modify-syntax-entry ?
@ "w")
4650 (if org-startup-truncated
(setq truncate-lines t
))
4651 (org-set-local 'font-lock-unfontify-region-function
4652 'org-unfontify-region
)
4653 ;; Activate before-change-function
4654 (org-set-local 'org-table-may-need-update t
)
4655 (org-add-hook 'before-change-functions
'org-before-change-function nil
4657 ;; Check for running clock before killing a buffer
4658 (org-add-hook 'kill-buffer-hook
'org-check-running-clock nil
'local
)
4659 ;; Paragraphs and auto-filling
4660 (org-set-autofill-regexps)
4661 (setq indent-line-function
'org-indent-line-function
)
4662 (org-update-radio-target-regexp)
4663 ;; Beginning/end of defun
4664 (org-set-local 'beginning-of-defun-function
'org-beginning-of-defun
)
4665 (org-set-local 'end-of-defun-function
'org-end-of-defun
)
4666 ;; Make sure dependence stuff works reliably, even for users who set it
4668 (if org-enforce-todo-dependencies
4669 (add-hook 'org-blocker-hook
4670 'org-block-todo-from-children-or-siblings-or-parent
)
4671 (remove-hook 'org-blocker-hook
4672 'org-block-todo-from-children-or-siblings-or-parent
))
4673 (if org-enforce-todo-checkbox-dependencies
4674 (add-hook 'org-blocker-hook
4675 'org-block-todo-from-checkboxes
)
4676 (remove-hook 'org-blocker-hook
4677 'org-block-todo-from-checkboxes
))
4679 ;; Comment characters
4680 (org-set-local 'comment-start
"#")
4681 (org-set-local 'comment-padding
" ")
4683 ;; Align options lines
4685 'align-mode-rules-list
4686 '((org-in-buffer-settings
4687 (regexp .
"^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4688 (modes .
'(org-mode)))))
4691 (org-set-local 'imenu-create-index-function
4692 'org-imenu-get-tree
)
4694 ;; Make isearch reveal context
4695 (if (or (featurep 'xemacs
)
4696 (not (boundp 'outline-isearch-open-invisible-function
)))
4697 ;; Emacs 21 and XEmacs make use of the hook
4698 (org-add-hook 'isearch-mode-end-hook
'org-isearch-end
'append
'local
)
4699 ;; Emacs 22 deals with this through a special variable
4700 (org-set-local 'outline-isearch-open-invisible-function
4701 (lambda (&rest ignore
) (org-show-context 'isearch
))))
4703 ;; Turn on org-beamer-mode?
4704 (and org-startup-with-beamer-mode
(org-beamer-mode 1))
4706 ;; If empty file that did not turn on org-mode automatically, make it to.
4707 (if (and org-insert-mode-line-in-empty-file
4709 (= (point-min) (point-max)))
4710 (insert "# -*- mode: org -*-\n\n"))
4711 (unless org-inhibit-startup
4712 (when org-startup-align-all-tables
4713 (let ((bmp (buffer-modified-p)))
4714 (org-table-map-tables 'org-table-align
'quietly
)
4715 (set-buffer-modified-p bmp
)))
4716 (when org-startup-indented
4717 (require 'org-indent
)
4718 (org-indent-mode 1))
4719 (unless org-inhibit-startup-visibility-stuff
4720 (org-set-startup-visibility))))
4722 (when (fboundp 'abbrev-table-put
)
4723 (abbrev-table-put org-mode-abbrev-table
4724 :parents
(list text-mode-abbrev-table
)))
4726 (put 'org-mode
'flyspell-mode-predicate
'org-mode-flyspell-verify
)
4728 (defun org-current-time ()
4729 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4730 (if (> (car org-time-stamp-rounding-minutes
) 1)
4731 (let ((r (car org-time-stamp-rounding-minutes
))
4732 (time (decode-time)))
4734 (append (list 0 (* r
(floor (+ .5 (/ (float (nth 1 time
)) r
)))))
4738 ;;;; Font-Lock stuff, including the activators
4740 (defvar org-mouse-map
(make-sparse-keymap))
4741 (org-defkey org-mouse-map
[mouse-2
] 'org-open-at-mouse
)
4742 (org-defkey org-mouse-map
[mouse-3
] 'org-find-file-at-mouse
)
4743 (when org-mouse-1-follows-link
4744 (org-defkey org-mouse-map
[follow-link
] 'mouse-face
))
4745 (when org-tab-follows-link
4746 (org-defkey org-mouse-map
[(tab)] 'org-open-at-point
)
4747 (org-defkey org-mouse-map
"\C-i" 'org-open-at-point
))
4749 (require 'font-lock
)
4751 (defconst org-non-link-chars
"]\t\n\r<>")
4752 (defvar org-link-types
'("http" "https" "ftp" "mailto" "file" "news"
4753 "shell" "elisp" "doi"))
4754 (defvar org-link-types-re nil
4755 "Matches a link that has a url-like prefix like \"http:\"")
4756 (defvar org-link-re-with-space nil
4757 "Matches a link with spaces, optional angular brackets around it.")
4758 (defvar org-link-re-with-space2 nil
4759 "Matches a link with spaces, optional angular brackets around it.")
4760 (defvar org-link-re-with-space3 nil
4761 "Matches a link with spaces, only for internal part in bracket links.")
4762 (defvar org-angle-link-re nil
4763 "Matches link with angular brackets, spaces are allowed.")
4764 (defvar org-plain-link-re nil
4765 "Matches plain link, without spaces.")
4766 (defvar org-bracket-link-regexp nil
4767 "Matches a link in double brackets.")
4768 (defvar org-bracket-link-analytic-regexp nil
4769 "Regular expression used to analyze links.
4770 Here is what the match groups contain after a match:
4776 (defvar org-bracket-link-analytic-regexp
++ nil
4777 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
4778 (defvar org-any-link-re nil
4779 "Regular expression matching any link.")
4781 (defcustom org-match-sexp-depth
3
4782 "Number of stacked braces for sub/superscript matching.
4783 This has to be set before loading org.el to be effective."
4784 :group
'org-export-translation
; ??????????????????????????/
4787 (defun org-create-multibrace-regexp (left right n
)
4788 "Create a regular expression which will match a balanced sexp.
4789 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
4790 as single character strings.
4791 The regexp returned will match the entire expression including the
4792 delimiters. It will also define a single group which contains the
4793 match except for the outermost delimiters. The maximum depth of
4794 stacked delimiters is N. Escaping delimiters is not possible."
4795 (let* ((nothing (concat "[^" left right
"]*?"))
4798 (next (concat "\\(?:" nothing left nothing right
"\\)+" nothing
)))
4801 re
(concat re or next
)
4802 next
(concat "\\(?:" nothing left next right
"\\)+" nothing
)))
4803 (concat left
"\\(" re
"\\)" right
)))
4805 (defvar org-match-substring-regexp
4807 "\\([^\\]\\)\\([_^]\\)\\("
4808 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth
) "\\)"
4810 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth
) "\\)"
4812 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
4813 "The regular expression matching a sub- or superscript.")
4815 (defvar org-match-substring-with-braces-regexp
4817 "\\([^\\]\\)\\([_^]\\)\\("
4818 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth
) "\\)"
4820 "The regular expression matching a sub- or superscript, forcing braces.")
4822 (defun org-make-link-regexps ()
4823 "Update the link regular expressions.
4824 This should be called after the variable `org-link-types' has changed."
4825 (setq org-link-types-re
4827 "\\`\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):")
4828 org-link-re-with-space
4830 "<?\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):"
4831 "\\([^" org-non-link-chars
" ]"
4832 "[^" org-non-link-chars
"]*"
4833 "[^" org-non-link-chars
" ]\\)>?")
4834 org-link-re-with-space2
4836 "<?\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):"
4837 "\\([^" org-non-link-chars
" ]"
4839 "[^" org-non-link-chars
" ]\\)>?")
4840 org-link-re-with-space3
4842 "<?\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):"
4843 "\\([^" org-non-link-chars
" ]"
4847 "<\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):"
4848 "\\([^" org-non-link-chars
" ]"
4849 "[^" org-non-link-chars
"]*"
4853 "\\<\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):"
4854 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4855 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4856 org-bracket-link-regexp
4857 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4858 org-bracket-link-analytic-regexp
4861 "\\(\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):\\)?"
4864 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4866 org-bracket-link-analytic-regexp
++
4869 "\\(\\(" (mapconcat 'regexp-quote
(cons "coderef" org-link-types
) "\\|") "\\):\\)?"
4872 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4875 (concat "\\(" org-bracket-link-regexp
"\\)\\|\\("
4876 org-angle-link-re
"\\)\\|\\("
4877 org-plain-link-re
"\\)")))
4879 (org-make-link-regexps)
4881 (defconst org-ts-regexp
"<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4882 "Regular expression for fast time stamp matching.")
4883 (defconst org-ts-regexp-both
"[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4884 "Regular expression for fast time stamp matching.")
4885 (defconst org-ts-regexp0
"\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4886 "Regular expression matching time strings for analysis.
4887 This one does not require the space after the date, so it can be used
4888 on a string that terminates immediately after the date.")
4889 (defconst org-ts-regexp1
"\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4890 "Regular expression matching time strings for analysis.")
4891 (defconst org-ts-regexp2
(concat "<" org-ts-regexp1
"[^>\n]\\{0,16\\}>")
4892 "Regular expression matching time stamps, with groups.")
4893 (defconst org-ts-regexp3
(concat "[[<]" org-ts-regexp1
"[^]>\n]\\{0,16\\}[]>]")
4894 "Regular expression matching time stamps (also [..]), with groups.")
4895 (defconst org-tr-regexp
(concat org-ts-regexp
"--?-?" org-ts-regexp
)
4896 "Regular expression matching a time stamp range.")
4897 (defconst org-tr-regexp-both
4898 (concat org-ts-regexp-both
"--?-?" org-ts-regexp-both
)
4899 "Regular expression matching a time stamp range.")
4900 (defconst org-tsr-regexp
(concat org-ts-regexp
"\\(--?-?"
4901 org-ts-regexp
"\\)?")
4902 "Regular expression matching a time stamp or time stamp range.")
4903 (defconst org-tsr-regexp-both
(concat org-ts-regexp-both
"\\(--?-?"
4904 org-ts-regexp-both
"\\)?")
4905 "Regular expression matching a time stamp or time stamp range.
4906 The time stamps may be either active or inactive.")
4908 (defvar org-emph-face nil
)
4910 (defun org-do-emphasis-faces (limit)
4911 "Run through the buffer and add overlays to links."
4913 (while (and (not rtn
) (re-search-forward org-emph-re limit t
))
4914 (if (not (= (char-after (match-beginning 3))
4915 (char-after (match-beginning 4))))
4918 (setq a
(assoc (match-string 3) org-emphasis-alist
))
4919 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4923 (org-remove-flyspell-overlays-in
4924 (match-beginning 0) (match-end 0)))
4925 (add-text-properties (match-beginning 2) (match-end 2)
4926 '(font-lock-multiline t org-emphasis t
))
4927 (when org-hide-emphasis-markers
4928 (add-text-properties (match-end 4) (match-beginning 5)
4929 '(invisible org-link
))
4930 (add-text-properties (match-beginning 3) (match-end 3)
4931 '(invisible org-link
)))))
4935 (defun org-emphasize (&optional char
)
4936 "Insert or change an emphasis, i.e. a font like bold or italic.
4937 If there is an active region, change that region to a new emphasis.
4938 If there is no region, just insert the marker characters and position
4939 the cursor between them.
4940 CHAR should be either the marker character, or the first character of the
4941 HTML tag associated with that emphasis. If CHAR is a space, the means
4942 to remove the emphasis of the selected region.
4943 If char is not given (for example in an interactive call) it
4944 will be prompted for."
4946 (let ((eal org-emphasis-alist
) e det
4947 (erc org-emphasis-regexp-components
)
4949 (string "") beg end move tag c s
)
4950 (if (org-region-active-p)
4951 (setq beg
(region-beginning) end
(region-end)
4952 string
(buffer-substring beg end
))
4955 (while (setq e
(pop eal
))
4956 (setq tag
(car (org-split-string (nth 2 e
) "[ <>/]+"))
4958 (push (cons c
(string-to-char (car e
))) det
)
4959 (setq prompt
(concat prompt
(format " [%s%c]%s" (car e
) c
4960 (substring tag
1)))))
4961 (setq det
(nreverse det
))
4963 (message "%s" (concat "Emphasis marker or tag:" prompt
))
4964 (setq char
(read-char-exclusive)))
4965 (setq char
(or (cdr (assoc char det
)) char
))
4966 (if (equal char ?\
)
4967 (setq s
"" move nil
)
4968 (unless (assoc (char-to-string char
) org-emphasis-alist
)
4969 (error "No such emphasis marker: \"%c\"" char
))
4970 (setq s
(char-to-string char
)))
4971 (while (and (> (length string
) 1)
4972 (equal (substring string
0 1) (substring string -
1))
4973 (assoc (substring string
0 1) org-emphasis-alist
))
4974 (setq string
(substring string
1 -
1)))
4975 (setq string
(concat s string s
))
4976 (if beg
(delete-region beg end
))
4978 (string-match (concat "[" (nth 0 erc
) "\n]")
4979 (char-to-string (char-before (point)))))
4982 (string-match (concat "[" (nth 1 erc
) "\n]")
4983 (char-to-string (char-after (point)))))
4984 (insert " ") (backward-char 1))
4986 (and move
(backward-char 1))))
4988 (defconst org-nonsticky-props
4989 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text
))
4991 (defsubst org-rear-nonsticky-at
(pos)
4992 (add-text-properties (1- pos
) pos
(list 'rear-nonsticky org-nonsticky-props
)))
4994 (defun org-activate-plain-links (limit)
4995 "Run through the buffer and add overlays to links."
4998 (if (re-search-forward org-plain-link-re limit t
)
5000 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5001 (setq f
(get-text-property (match-beginning 0) 'face
))
5002 (if (or (eq f
'org-tag
)
5003 (and (listp f
) (memq 'org-tag f
)))
5005 (add-text-properties (match-beginning 0) (match-end 0)
5006 (list 'mouse-face
'highlight
5008 'keymap org-mouse-map
))
5009 (org-rear-nonsticky-at (match-end 0)))
5012 (defun org-activate-code (limit)
5013 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t
)
5015 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5016 (remove-text-properties (match-beginning 0) (match-end 0)
5017 '(display t invisible t intangible t
))
5020 (defun org-fontify-meta-lines-and-blocks (limit)
5021 "Fontify #+ lines and blocks, in the correct ways."
5022 (let ((case-fold-search t
))
5023 (if (re-search-forward
5024 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
5026 (let ((beg (match-beginning 0))
5027 (beg1 (line-beginning-position 2))
5028 (dc1 (downcase (match-string 2)))
5029 (dc3 (downcase (match-string 3)))
5030 end end1 quoting block-type
)
5032 ((member dc1
'("html:" "ascii:" "latex:" "docbook:"))
5033 ;; a single line of backend-specific content
5034 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5035 (remove-text-properties (match-beginning 0) (match-end 0)
5036 '(display t invisible t intangible t
))
5037 (add-text-properties (match-beginning 1) (match-end 3)
5038 '(font-lock-fontified t face org-meta-line
))
5039 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5040 '(font-lock-fontified t face org-block
))
5041 ; for backend-specific code
5043 ((and (match-end 4) (equal dc3
"begin"))
5045 (setq block-type
(downcase (match-string 5))
5046 quoting
(member block-type org-protecting-blocks
))
5047 (when (re-search-forward
5048 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5049 nil t
) ;; on purpose, we look further than LIMIT
5050 (setq end
(match-end 0) end1
(1- (match-beginning 0)))
5052 (remove-text-properties beg end
5053 '(display t invisible t intangible t
)))
5054 (add-text-properties
5056 '(font-lock-fontified t font-lock-multiline t
))
5057 (add-text-properties beg beg1
'(face org-meta-line
))
5058 (add-text-properties end1
(+ end
1) '(face org-meta-line
))
5062 (add-text-properties beg1
(+ end1
1) '(face
5064 ; end of source block
5065 ((not org-fontify-quote-and-verse-blocks
))
5066 ((string= block-type
"quote")
5067 (add-text-properties beg1 end1
'(face org-quote
)))
5068 ((string= block-type
"verse")
5069 (add-text-properties beg1 end1
'(face org-verse
))))
5071 ((member dc1
'("title:" "author:" "email:" "date:"))
5072 (add-text-properties
5074 (if (member (intern (substring dc1
0 -
1)) org-hidden-keywords
)
5075 '(font-lock-fontified t invisible t
)
5076 '(font-lock-fontified t face org-document-info-keyword
)))
5077 (add-text-properties
5078 (match-beginning 6) (match-end 6)
5079 (if (string-equal dc1
"title:")
5080 '(font-lock-fontified t face org-document-title
)
5081 '(font-lock-fontified t face org-document-info
))))
5082 ((not (member (char-after beg
) '(?\ ?
\t)))
5083 ;; just any other in-buffer setting, but not indented
5084 (add-text-properties
5086 '(font-lock-fontified t face org-meta-line
))
5088 ((or (member dc1
'("begin:" "end:" "caption:" "label:"
5089 "orgtbl:" "tblfm:" "tblname:" "result:"
5090 "results:" "source:" "srcname:" "call:"))
5091 (and (match-end 4) (equal dc3
"attr")))
5092 (add-text-properties
5094 '(font-lock-fontified t face org-meta-line
))
5096 ((member dc3
'(" " ""))
5097 (add-text-properties
5099 '(font-lock-fontified t face font-lock-comment-face
)))
5102 (defun org-activate-angle-links (limit)
5103 "Run through the buffer and add overlays to links."
5104 (if (re-search-forward org-angle-link-re limit t
)
5106 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5107 (add-text-properties (match-beginning 0) (match-end 0)
5108 (list 'mouse-face
'highlight
5109 'keymap org-mouse-map
))
5110 (org-rear-nonsticky-at (match-end 0))
5113 (defun org-activate-footnote-links (limit)
5114 "Run through the buffer and add overlays to links."
5115 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
5118 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5119 (add-text-properties (match-beginning 2) (match-end 2)
5120 (list 'mouse-face
'highlight
5121 'keymap org-mouse-map
5123 (if (= (point-at-bol) (match-beginning 2))
5124 "Footnote definition"
5125 "Footnote reference")
5127 (org-rear-nonsticky-at (match-end 2))
5130 (defun org-activate-bracket-links (limit)
5131 "Run through the buffer and add overlays to bracketed links."
5132 (if (re-search-forward org-bracket-link-regexp limit t
)
5133 (let* ((help (concat "LINK: "
5134 (org-match-string-no-properties 1)))
5135 ;; FIXME: above we should remove the escapes.
5136 ;; but that requires another match, protecting match data,
5137 ;; a lot of overhead for font-lock.
5138 (ip (org-maybe-intangible
5139 (list 'invisible
'org-link
5140 'keymap org-mouse-map
'mouse-face
'highlight
5141 'font-lock-multiline t
'help-echo help
)))
5142 (vp (list 'keymap org-mouse-map
'mouse-face
'highlight
5143 'font-lock-multiline t
'help-echo help
)))
5144 ;; We need to remove the invisible property here. Table narrowing
5145 ;; may have made some of this invisible.
5146 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5147 (remove-text-properties (match-beginning 0) (match-end 0)
5151 (add-text-properties (match-beginning 0) (match-beginning 3) ip
)
5152 (org-rear-nonsticky-at (match-beginning 3))
5153 (add-text-properties (match-beginning 3) (match-end 3) vp
)
5154 (org-rear-nonsticky-at (match-end 3))
5155 (add-text-properties (match-end 3) (match-end 0) ip
)
5156 (org-rear-nonsticky-at (match-end 0)))
5157 (add-text-properties (match-beginning 0) (match-beginning 1) ip
)
5158 (org-rear-nonsticky-at (match-beginning 1))
5159 (add-text-properties (match-beginning 1) (match-end 1) vp
)
5160 (org-rear-nonsticky-at (match-end 1))
5161 (add-text-properties (match-end 1) (match-end 0) ip
)
5162 (org-rear-nonsticky-at (match-end 0)))
5165 (defun org-activate-dates (limit)
5166 "Run through the buffer and add overlays to dates."
5167 (if (re-search-forward org-tsr-regexp-both limit t
)
5169 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5170 (add-text-properties (match-beginning 0) (match-end 0)
5171 (list 'mouse-face
'highlight
5172 'keymap org-mouse-map
))
5173 (org-rear-nonsticky-at (match-end 0))
5174 (when org-display-custom-times
5176 (org-display-custom-time (match-beginning 3) (match-end 3)))
5177 (org-display-custom-time (match-beginning 1) (match-end 1)))
5180 (defvar org-target-link-regexp nil
5181 "Regular expression matching radio targets in plain text.")
5182 (make-variable-buffer-local 'org-target-link-regexp
)
5183 (defvar org-target-regexp
"<<\\([^<>\n\r]+\\)>>"
5184 "Regular expression matching a link target.")
5185 (defvar org-radio-target-regexp
"<<<\\([^<>\n\r]+\\)>>>"
5186 "Regular expression matching a radio target.")
5187 (defvar org-any-target-regexp
"<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5188 "Regular expression matching any target.")
5190 (defun org-activate-target-links (limit)
5191 "Run through the buffer and add overlays to target matches."
5192 (when org-target-link-regexp
5193 (let ((case-fold-search t
))
5194 (if (re-search-forward org-target-link-regexp limit t
)
5196 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5197 (add-text-properties (match-beginning 0) (match-end 0)
5198 (list 'mouse-face
'highlight
5199 'keymap org-mouse-map
5200 'help-echo
"Radio target link"
5201 'org-linked-text t
))
5202 (org-rear-nonsticky-at (match-end 0))
5205 (defun org-update-radio-target-regexp ()
5206 "Find all radio targets in this file and update the regular expression."
5208 (when (memq 'radio org-activate-links
)
5209 (setq org-target-link-regexp
5210 (org-make-target-link-regexp (org-all-targets 'radio
)))
5211 (org-restart-font-lock)))
5213 (defun org-hide-wide-columns (limit)
5215 (setq s
(text-property-any (point) (or limit
(point-max))
5218 (setq e
(next-single-property-change s
'org-cwidth
))
5219 (add-text-properties s e
(org-maybe-intangible '(invisible org-cwidth
)))
5223 (defvar org-latex-and-specials-regexp nil
5224 "Regular expression for highlighting export special stuff.")
5225 (defvar org-match-substring-regexp
)
5226 (defvar org-match-substring-with-braces-regexp
)
5228 ;; This should be with the exporter code, but we also use if for font-locking
5229 (defconst org-export-html-special-string-regexps
5230 '(("\\\\-" .
"­")
5231 ("---\\([^-]\\)" .
"—\\1")
5232 ("--\\([^-]\\)" .
"–\\1")
5233 ("\\.\\.\\." .
"…"))
5234 "Regular expressions for special string conversion.")
5237 (defun org-compute-latex-and-specials-regexp ()
5238 "Compute regular expression for stuff treated specially by exporters."
5239 (if (not org-highlight-latex-fragments-and-specials
)
5240 (org-set-local 'org-latex-and-specials-regexp nil
)
5243 ((matchers (plist-get org-format-latex-options
:matchers
))
5244 (latexs (delq nil
(mapcar (lambda (x) (if (member (car x
) matchers
) x
))
5245 org-latex-regexps
)))
5246 (org-export-allow-BIND nil
)
5247 (options (org-combine-plists (org-default-export-plist)
5248 (org-infile-export-plist)))
5249 (org-export-with-sub-superscripts (plist-get options
:sub-superscript
))
5250 (org-export-with-LaTeX-fragments (plist-get options
:LaTeX-fragments
))
5251 (org-export-with-TeX-macros (plist-get options
:TeX-macros
))
5252 (org-export-html-expand (plist-get options
:expand-quoted-html
))
5253 (org-export-with-special-strings (plist-get options
:special-strings
))
5256 ((equal org-export-with-sub-superscripts
'{})
5257 (list org-match-substring-with-braces-regexp
))
5258 (org-export-with-sub-superscripts
5259 (list org-match-substring-regexp
))
5262 (if org-export-with-LaTeX-fragments
5263 (mapcar (lambda (x) (nth 1 x
)) latexs
)))
5265 (if org-export-with-TeX-macros
5266 (list (concat "\\\\"
5272 (append org-entities-user
5274 (if (boundp 'org-latex-entities
)
5276 (or (car-safe x
) x
))
5281 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5282 (re-special (if org-export-with-special-strings
5283 (mapcar (lambda (x) (car x
))
5284 org-export-html-special-string-regexps
)))
5288 (if org-export-html-expand
"@<[^>\n]+>")
5291 'org-latex-and-specials-regexp
5292 (mapconcat 'identity
(append re-latex re-sub re-macros re-special
5295 (defun org-do-latex-and-special-faces (limit)
5296 "Run through the buffer and add overlays to links."
5297 (when org-latex-and-specials-regexp
5299 (while (and (not rtn
) (re-search-forward org-latex-and-specials-regexp
5301 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5303 '(org-code org-verbatim underline
)))
5306 d
(cond ((member (char-after (1+ (match-beginning 0)))
5309 (font-lock-prepend-text-property
5310 (+ d
(match-beginning 0)) (match-end 0)
5311 'face
'org-latex-and-export-specials
)
5312 (add-text-properties (+ d
(match-beginning 0)) (match-end 0)
5313 '(font-lock-multiline t
)))))
5316 (defun org-restart-font-lock ()
5317 "Restart `font-lock-mode', to force refontification."
5318 (when (and (boundp 'font-lock-mode
) font-lock-mode
)
5320 (font-lock-mode 1)))
5322 (defun org-all-targets (&optional radio
)
5323 "Return a list of all targets in this file.
5324 With optional argument RADIO, only find radio targets."
5325 (let ((re (if radio org-radio-target-regexp org-target-regexp
))
5328 (goto-char (point-min))
5329 (while (re-search-forward re nil t
)
5330 (add-to-list 'rtn
(downcase (org-match-string-no-properties 1))))
5333 (defun org-make-target-link-regexp (targets)
5334 "Make regular expression matching all strings in TARGETS.
5335 The regular expression finds the targets also if there is a line break
5342 (while (string-match " +" x
)
5343 (setq x
(replace-match "\\s-+" t t x
)))
5349 (defun org-activate-tags (limit)
5350 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t
)
5352 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5353 (add-text-properties (match-beginning 1) (match-end 1)
5354 (list 'mouse-face
'highlight
5355 'keymap org-mouse-map
))
5356 (org-rear-nonsticky-at (match-end 1))
5359 (defun org-outline-level ()
5360 "Compute the outline level of the heading at point.
5361 This function assumes that the cursor is at the beginning of a line matched
5362 by `outline-regexp'. Otherwise it returns garbage.
5363 If this is called at a normal headline, the level is the number of stars.
5364 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
5365 For plain list items, if they are matched by `outline-regexp', this returns
5366 1000 plus the line indentation."
5368 (looking-at outline-regexp
)
5369 (if (match-beginning 1)
5370 (+ (org-get-string-indentation (match-string 1)) 1000)
5371 (1- (- (match-end 0) (match-beginning 0))))))
5373 (defvar org-font-lock-keywords nil
)
5375 (defconst org-property-re
(org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5376 "Regular expression matching a property line.")
5378 (defvar org-font-lock-hook nil
5379 "Functions to be called for special font lock stuff.")
5381 (defvar org-font-lock-set-keywords-hook nil
5382 "Functions that can manipulate `org-font-lock-extra-keywords'.
5383 This is calles after `org-font-lock-extra-keywords' is defined, but before
5384 it is installed to be used by font lock. This can be useful if something
5385 needs to be inserted at a specific position in the font-lock sequence.")
5387 (defun org-font-lock-hook (limit)
5388 (run-hook-with-args 'org-font-lock-hook limit
))
5390 (defun org-set-font-lock-defaults ()
5391 (let* ((em org-fontify-emphasized-text
)
5392 (lk org-activate-links
)
5393 (org-font-lock-extra-keywords
5396 '(org-font-lock-hook)
5398 `(,(if org-fontify-whole-heading-line
5399 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5400 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5401 (1 (org-get-level-face 1))
5402 (2 (org-get-level-face 2))
5403 (3 (org-get-level-face 3)))
5405 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5408 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t
))
5409 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t
))
5410 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t
))
5411 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t
))
5413 (list org-drawer-regexp
'(0 'org-special-keyword t
))
5414 (list "^[ \t]*:END:" '(0 'org-special-keyword t
))
5416 (list org-property-re
5417 '(1 'org-special-keyword t
)
5418 '(3 'org-property-value t
))
5420 (if (memq 'tag lk
) '(org-activate-tags (1 'org-tag prepend
)))
5421 (if (memq 'angle lk
) '(org-activate-angle-links (0 'org-link t
)))
5422 (if (memq 'plain lk
) '(org-activate-plain-links))
5423 (if (memq 'bracket lk
) '(org-activate-bracket-links (0 'org-link t
)))
5424 (if (memq 'radio lk
) '(org-activate-target-links (0 'org-link t
)))
5425 (if (memq 'date lk
) '(org-activate-dates (0 'org-date t
)))
5426 (if (memq 'footnote lk
) '(org-activate-footnote-links
5427 (2 'org-footnote t
)))
5428 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t
))
5429 '(org-hide-wide-columns (0 nil append
))
5431 (list (concat "^\\*+[ \t]+" org-todo-regexp
"\\([ \t]\\|$\\)")
5432 '(1 (org-get-todo-face 1) t
))
5434 (if org-fontify-done-headline
5435 (list (concat "^[*]+ +\\<\\("
5436 (mapconcat 'regexp-quote org-done-keywords
"\\|")
5438 '(2 'org-headline-done t
))
5441 '(org-font-lock-add-priority-faces)
5443 '(org-font-lock-add-tag-faces)
5445 (list (concat "\\<" org-deadline-string
) '(0 'org-special-keyword t
))
5446 (list (concat "\\<" org-scheduled-string
) '(0 'org-special-keyword t
))
5447 (list (concat "\\<" org-closed-string
) '(0 'org-special-keyword t
))
5448 (list (concat "\\<" org-clock-string
) '(0 'org-special-keyword t
))
5451 (if (featurep 'xemacs
)
5452 '(org-do-emphasis-faces (0 nil append
))
5453 '(org-do-emphasis-faces)))
5455 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5456 2 'org-checkbox prepend
)
5457 (if org-provide-checkbox-statistics
5458 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5459 (0 (org-get-checkbox-statistics-face) t
)))
5460 ;; Description list items
5461 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
5463 ;; ARCHIVEd headings
5464 (list (concat "^\\*+ \\(.*:" org-archive-tag
":.*\\)")
5465 '(1 'org-archived prepend
))
5467 '(org-do-latex-and-special-faces)
5468 '(org-fontify-entities)
5469 '(org-raise-scripts)
5471 '(org-activate-code (1 'org-code t
))
5473 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5474 "\\|" org-quote-string
"\\)\\>")
5475 '(1 'org-special-keyword t
))
5476 '("^#.*" (0 'font-lock-comment-face t
))
5477 ;; Blocks and meta lines
5478 '(org-fontify-meta-lines-and-blocks)
5480 (setq org-font-lock-extra-keywords
(delq nil org-font-lock-extra-keywords
))
5481 (run-hooks 'org-font-lock-set-keywords-hook
)
5482 ;; Now set the full font-lock-keywords
5483 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords
)
5484 (org-set-local 'font-lock-defaults
5485 '(org-font-lock-keywords t nil nil backward-paragraph
))
5486 (kill-local-variable 'font-lock-keywords
) nil
))
5488 (defun org-toggle-pretty-entities ()
5489 "Toggle the composition display of entities as UTF8 characters."
5491 (org-set-local 'org-pretty-entities
(not org-pretty-entities
))
5492 (org-restart-font-lock)
5493 (if org-pretty-entities
5494 (message "Entities are displayed as UTF8 characers")
5497 (decompose-region (point-min) (point-max))
5498 (message "Entities are displayed plain"))))
5500 (defun org-fontify-entities (limit)
5501 "Find an entity to fontify."
5503 (when org-pretty-entities
5505 (while (re-search-forward
5506 "\\\\\\([a-zA-Z][a-zA-Z0-9]*\\)\\($\\|[^[:alnum:]\n]\\)"
5508 (if (and (not (org-in-indented-comment-line))
5509 (setq ee
(org-entity-get (match-string 1)))
5510 (= (length (nth 6 ee
)) 1))
5512 (add-text-properties
5513 (match-beginning 0) (match-end 1)
5514 (list 'font-lock-fontified t
))
5515 (compose-region (match-beginning 0) (match-end 1)
5521 (defun org-fontify-like-in-org-mode (s &optional odd-levels
)
5522 "Fontify string S like in Org-mode."
5525 (let ((org-odd-levels-only odd-levels
))
5527 (font-lock-fontify-buffer)
5533 (defun org-get-level-face (n)
5534 "Get the right face for match N in font-lock matching of headlines."
5535 (setq org-l
(- (match-end 2) (match-beginning 1) 1))
5536 (if org-odd-levels-only
(setq org-l
(1+ (/ org-l
2))))
5537 (setq org-f
(nth (%
(1- org-l
) org-n-level-faces
) org-level-faces
))
5539 ((eq n
1) (if org-hide-leading-stars
'org-hide org-f
))
5541 (t (if org-level-color-stars-only nil org-f
))))
5543 (defun org-get-todo-face (kwd)
5544 "Get the right face for a TODO keyword KWD.
5545 If KWD is a number, get the corresponding match group."
5546 (if (numberp kwd
) (setq kwd
(match-string kwd
)))
5547 (or (org-face-from-face-or-color
5548 'todo
'org-todo
(cdr (assoc kwd org-todo-keyword-faces
)))
5549 (and (member kwd org-done-keywords
) 'org-done
)
5552 (defun org-face-from-face-or-color (context inherit face-or-color
)
5553 "Create a face list that inherits INHERIT, but sets the foreground color.
5554 When FACE-OR-COLOR is not a string, just return it."
5555 (if (stringp face-or-color
)
5556 (list :inherit inherit
5557 (cdr (assoc context org-faces-easy-properties
))
5561 (defun org-font-lock-add-tag-faces (limit)
5562 "Add the special tag faces."
5563 (when (and org-tag-faces org-tags-special-faces-re
)
5564 (while (re-search-forward org-tags-special-faces-re limit t
)
5565 (add-text-properties (match-beginning 1) (match-end 1)
5566 (list 'face
(org-get-tag-face 1)
5567 'font-lock-fontified t
))
5568 (backward-char 1))))
5570 (defun org-font-lock-add-priority-faces (limit)
5571 "Add the special priority faces."
5572 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t
)
5573 (add-text-properties
5574 (match-beginning 0) (match-end 0)
5575 (list 'face
(or (org-face-from-face-or-color
5576 'priority
'org-special-keyword
5577 (cdr (assoc (char-after (match-beginning 1))
5578 org-priority-faces
)))
5579 'org-special-keyword
)
5580 'font-lock-fontified t
))))
5582 (defun org-get-tag-face (kwd)
5583 "Get the right face for a TODO keyword KWD.
5584 If KWD is a number, get the corresponding match group."
5585 (if (numberp kwd
) (setq kwd
(match-string kwd
)))
5586 (or (org-face-from-face-or-color
5587 'tag
'org-tag
(cdr (assoc kwd org-tag-faces
)))
5590 (defun org-unfontify-region (beg end
&optional maybe_loudly
)
5591 "Remove fontification and activation overlays from links."
5592 (font-lock-default-unfontify-region beg end
)
5593 (let* ((buffer-undo-list t
)
5594 (inhibit-read-only t
) (inhibit-point-motion-hooks t
)
5595 (inhibit-modification-hooks t
)
5596 deactivate-mark buffer-file-name buffer-file-truename
)
5597 (decompose-region beg end
)
5598 (remove-text-properties
5601 ;; also remove line-prefix and wrap-prefix properties
5602 '(mouse-face t keymap t org-linked-text t
5603 invisible t intangible t
5604 line-prefix t wrap-prefix t
5605 org-no-flyspell t org-emphasis t
)
5606 '(mouse-face t keymap t org-linked-text t
5607 invisible t intangible t
5608 org-no-flyspell t org-emphasis t
)))
5609 (org-remove-font-lock-display-properties beg end
)))
5611 (defconst org-script-display
'(((raise -
0.3) (height 0.7))
5612 ((raise 0.3) (height 0.7))
5615 "Display properties for showing superscripts and subscripts.")
5617 (defun org-remove-font-lock-display-properties (beg end
)
5618 "Remove specific display properties that have been added by font lock.
5619 The will remove the raise properties that are used to show superscripts
5623 (setq next
(next-single-property-change beg
'display nil end
)
5624 prop
(get-text-property beg
'display
))
5625 (if (member prop org-script-display
)
5626 (put-text-property beg next
'display nil
))
5629 (defun org-raise-scripts (limit)
5630 "Add raise properties to sub/superscripts."
5631 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
)
5632 (if (re-search-forward
5633 (if (eq org-use-sub-superscripts t
)
5634 org-match-substring-regexp
5635 org-match-substring-with-braces-regexp
)
5637 (let* ((pos (point)) table-p comment-p
5638 (mpos (match-beginning 3))
5639 (emph-p (get-text-property mpos
'org-emphasis
))
5640 (link-p (get-text-property mpos
'mouse-face
))
5641 (keyw-p (eq 'org-special-keyword
(get-text-property mpos
'face
))))
5642 (goto-char (point-at-bol))
5643 (setq table-p
(org-looking-at-p org-table-dataline-regexp
)
5644 comment-p
(org-looking-at-p "[ \t]*#"))
5646 ;; FIXME: Should we go back one character here, for a_b^c
5647 ;; (goto-char (1- pos)) ;????????????????????
5648 (if (or comment-p emph-p link-p keyw-p
)
5650 (put-text-property (match-beginning 3) (match-end 0)
5652 (if (equal (char-after (match-beginning 2)) ?^
)
5653 (nth (if table-p
3 1) org-script-display
)
5654 (nth (if table-p
2 0) org-script-display
)))
5655 (add-text-properties (match-beginning 2) (match-end 2)
5657 'org-dwidth t
'org-dwidth-n
1))
5658 (if (and (eq (char-after (match-beginning 3)) ?
{)
5659 (eq (char-before (match-end 3)) ?
}))
5661 (add-text-properties
5662 (match-beginning 3) (1+ (match-beginning 3))
5663 (list 'invisible t
'org-dwidth t
'org-dwidth-n
1))
5664 (add-text-properties
5665 (1- (match-end 3)) (match-end 3)
5666 (list 'invisible t
'org-dwidth t
'org-dwidth-n
1))))
5669 ;;;; Visibility cycling, including org-goto and indirect buffer
5673 (defvar org-cycle-global-status nil
)
5674 (make-variable-buffer-local 'org-cycle-global-status
)
5675 (defvar org-cycle-subtree-status nil
)
5676 (make-variable-buffer-local 'org-cycle-subtree-status
)
5680 (defvar org-inlinetask-min-level
)
5682 (defun org-cycle (&optional arg
)
5683 "TAB-action and visibility cycling for Org-mode.
5685 This is the command invoked in Org-mode by the TAB key. Its main purpose
5686 is outline visibility cycling, but it also invokes other actions
5687 in special contexts.
5689 - When this function is called with a prefix argument, rotate the entire
5690 buffer through 3 states (global cycling)
5691 1. OVERVIEW: Show only top-level headlines.
5692 2. CONTENTS: Show all headlines of all levels, but no body text.
5693 3. SHOW ALL: Show everything.
5694 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5695 determined by the variable `org-startup-folded', and by any VISIBILITY
5696 properties in the buffer.
5697 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5698 including any drawers.
5700 - When inside a table, re-align the table and move to the next field.
5702 - When point is at the beginning of a headline, rotate the subtree started
5703 by this line through 3 different states (local cycling)
5704 1. FOLDED: Only the main headline is shown.
5705 2. CHILDREN: The main headline and the direct children are shown.
5706 From this state, you can move to one of the children
5707 and zoom in further.
5708 3. SUBTREE: Show the entire subtree, including body text.
5709 If there is no subtree, switch directly from CHILDREN to FOLDED.
5711 - When point is at the beginning of an empty headline and the variable
5712 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5713 of the headline by demoting and promoting it to likely levels. This
5714 speeds up creation document structure by pressing TAB once or several
5715 times right after creating a new headline.
5717 - When there is a numeric prefix, go up to a heading with level ARG, do
5718 a `show-subtree' and return to the previous cursor position. If ARG
5719 is negative, go up that many levels.
5721 - When point is not at the beginning of a headline, execute the global
5722 binding for TAB, which is re-indenting the line. See the option
5723 `org-cycle-emulate-tab' for details.
5725 - Special case: if point is at the beginning of the buffer and there is
5726 no headline in line 1, this function will act as if called with prefix arg.
5727 But only if also the variable `org-cycle-global-at-bob' is t."
5729 (org-load-modules-maybe)
5730 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook
)
5731 (and org-cycle-level-after-item
/entry-creation
5732 (or (org-cycle-level)
5733 (org-cycle-item-indentation))))
5735 (or org-cycle-max-level
5736 (and (boundp 'org-inlinetask-min-level
)
5737 org-inlinetask-min-level
5738 (1- org-inlinetask-min-level
))))
5739 (nstars (and limit-level
5740 (if org-odd-levels-only
5741 (and limit-level
(1- (* limit-level
2)))
5745 ((not (org-mode-p)) outline-regexp
)
5746 ((or (eq org-cycle-include-plain-lists
'integrate
)
5747 (and org-cycle-include-plain-lists
(org-at-item-p)))
5749 (if nstars
(format "\\{1,%d\\}" nstars
) "+")
5750 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5751 (t (concat "\\*" (if nstars
(format "\\{1,%d\\} " nstars
) "+ ")))))
5752 (bob-special (and org-cycle-global-at-bob
(bobp)
5753 (not (looking-at outline-regexp
))))
5756 (delq 'org-optimize-window-after-visibility-change
5757 (copy-sequence org-cycle-hook
))
5761 (if (or bob-special
(equal arg
'(4)))
5762 ;; special case: use global cycling
5768 (org-set-startup-visibility)
5769 (message "Startup visibility, plus VISIBILITY properties"))
5773 (message "Entire buffer visible, including drawers"))
5775 ((org-at-table-p 'any
)
5776 ;; Enter the table or move to the next field in the table
5777 (if (org-at-table.el-p
)
5778 (message "Use C-c ' to edit table.el tables")
5779 (if arg
(org-table-edit-field t
)
5780 (org-table-justify-field-maybe)
5781 (call-interactively 'org-table-next-field
))))
5783 ((run-hook-with-args-until-success
5784 'org-tab-after-check-for-table-hook
))
5786 ((eq arg t
) ;; Global cycling
5787 (org-cycle-internal-global))
5789 ((and org-drawers org-drawer-regexp
5791 (beginning-of-line 1)
5792 (looking-at org-drawer-regexp
)))
5793 ;; Toggle block visibility
5795 (not (get-char-property (match-end 0) 'invisible
))))
5798 ;; Show-subtree, ARG levels up from here.
5800 (org-back-to-heading)
5801 (outline-up-heading (if (< arg
0) (- arg
)
5802 (- (funcall outline-level
) arg
)))
5803 (org-show-subtree)))
5805 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp
))
5806 (or (bolp) (not (eq org-cycle-emulate-tab
'exc-hl-bol
))))
5808 (org-cycle-internal-local))
5810 ;; TAB emulation and template completion
5811 (buffer-read-only (org-back-to-heading))
5813 ((run-hook-with-args-until-success
5814 'org-tab-after-check-for-cycling-hook
))
5816 ((org-try-structure-completion))
5818 ((org-try-cdlatex-tab))
5820 ((run-hook-with-args-until-success
5821 'org-tab-before-tab-emulation-hook
))
5823 ((and (eq org-cycle-emulate-tab
'exc-hl-bol
)
5825 (not (looking-at outline-regexp
))))
5826 (call-interactively (global-key-binding "\t")))
5828 ((if (and (memq org-cycle-emulate-tab
'(white whitestart
))
5829 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5830 (or (and (eq org-cycle-emulate-tab
'white
)
5831 (= (match-end 0) (point-at-eol)))
5832 (and (eq org-cycle-emulate-tab
'whitestart
)
5833 (>= (match-end 0) pos
))))
5835 (eq org-cycle-emulate-tab t
))
5836 (call-interactively (global-key-binding "\t")))
5839 (org-back-to-heading)
5842 (defun org-cycle-internal-global ()
5843 "Do the global cycling action."
5845 ((and (eq last-command this-command
)
5846 (eq org-cycle-global-status
'overview
))
5847 ;; We just created the overview - now do table of contents
5848 ;; This can be slow in very large buffers, so indicate action
5849 (run-hook-with-args 'org-pre-cycle-hook
'contents
)
5850 (message "CONTENTS...")
5852 (message "CONTENTS...done")
5853 (setq org-cycle-global-status
'contents
)
5854 (run-hook-with-args 'org-cycle-hook
'contents
))
5856 ((and (eq last-command this-command
)
5857 (eq org-cycle-global-status
'contents
))
5858 ;; We just showed the table of contents - now show everything
5859 (run-hook-with-args 'org-pre-cycle-hook
'all
)
5861 (message "SHOW ALL")
5862 (setq org-cycle-global-status
'all
)
5863 (run-hook-with-args 'org-cycle-hook
'all
))
5866 ;; Default action: go to overview
5867 (run-hook-with-args 'org-pre-cycle-hook
'overview
)
5869 (message "OVERVIEW")
5870 (setq org-cycle-global-status
'overview
)
5871 (run-hook-with-args 'org-cycle-hook
'overview
))))
5873 (defun org-cycle-internal-local ()
5874 "Do the local cycling action."
5875 (let ((goal-column 0) eoh eol eos level has-children children-skipped
)
5876 ;; First, some boundaries
5878 (org-back-to-heading)
5879 (setq level
(funcall outline-level
))
5881 (beginning-of-line 2)
5882 (if (or (featurep 'xemacs
) (<= emacs-major-version
21))
5883 ; XEmacs does not have `next-single-char-property-change'
5884 ; I'm not sure about Emacs 21.
5885 (while (and (not (eobp)) ;; this is like `next-line'
5886 (get-char-property (1- (point)) 'invisible
))
5887 (beginning-of-line 2))
5888 (while (and (not (eobp)) ;; this is like `next-line'
5889 (get-char-property (1- (point)) 'invisible
))
5890 (goto-char (next-single-char-property-change (point) 'invisible
))
5891 (and (eolp) (beginning-of-line 2))))
5893 (outline-end-of-heading) (setq eoh
(point))
5895 (outline-next-heading)
5896 (setq has-children
(and (org-at-heading-p t
)
5897 (> (funcall outline-level
) level
))))
5898 (org-end-of-subtree t
)
5900 (skip-chars-forward " \t\n")
5901 (beginning-of-line 1) ; in case this is an item
5903 (setq eos
(if (eobp) (point) (1- (point)))))
5904 ;; Find out what to do next and set `this-command'
5907 ;; Nothing is hidden behind this heading
5908 (run-hook-with-args 'org-pre-cycle-hook
'empty
)
5909 (message "EMPTY ENTRY")
5910 (setq org-cycle-subtree-status nil
)
5913 (outline-next-heading)
5914 (if (org-invisible-p) (org-flag-heading nil
))))
5915 ((and (or (>= eol eos
)
5916 (not (string-match "\\S-" (buffer-substring eol eos
))))
5918 (not (setq children-skipped
5919 org-cycle-skip-children-state-if-no-children
))))
5920 ;; Entire subtree is hidden in one line: children view
5921 (run-hook-with-args 'org-pre-cycle-hook
'children
)
5924 (message "CHILDREN")
5927 (outline-next-heading)
5928 (if (org-invisible-p) (org-flag-heading nil
)))
5929 (setq org-cycle-subtree-status
'children
)
5930 (run-hook-with-args 'org-cycle-hook
'children
))
5931 ((or children-skipped
5932 (and (eq last-command this-command
)
5933 (eq org-cycle-subtree-status
'children
)))
5934 ;; We just showed the children, or no children are there,
5935 ;; now show everything.
5936 (run-hook-with-args 'org-pre-cycle-hook
'subtree
)
5938 (message (if children-skipped
"SUBTREE (NO CHILDREN)" "SUBTREE"))
5939 (setq org-cycle-subtree-status
'subtree
)
5940 (run-hook-with-args 'org-cycle-hook
'subtree
))
5942 ;; Default action: hide the subtree.
5943 (run-hook-with-args 'org-pre-cycle-hook
'folded
)
5946 (setq org-cycle-subtree-status
'folded
)
5947 (run-hook-with-args 'org-cycle-hook
'folded
)))))
5950 (defun org-global-cycle (&optional arg
)
5951 "Cycle the global visibility. For details see `org-cycle'.
5952 With \\[universal-argument] prefix arg, switch to startup visibility.
5953 With a numeric prefix, show all headlines up to that level."
5955 (let ((org-cycle-include-plain-lists
5956 (if (org-mode-p) org-cycle-include-plain-lists nil
)))
5960 (hide-sublevels arg
)
5961 (setq org-cycle-global-status
'contents
))
5963 (org-set-startup-visibility)
5964 (message "Startup visibility, plus VISIBILITY properties."))
5966 (org-cycle '(4))))))
5968 (defun org-set-startup-visibility ()
5969 "Set the visibility required by startup options and properties."
5971 ((eq org-startup-folded t
)
5973 ((eq org-startup-folded
'content
)
5974 (let ((this-command 'org-cycle
) (last-command 'org-cycle
))
5975 (org-cycle '(4)) (org-cycle '(4)))))
5976 (unless (eq org-startup-folded
'showeverything
)
5977 (if org-hide-block-startup
(org-hide-block-all))
5978 (org-set-visibility-according-to-property 'no-cleanup
)
5979 (org-cycle-hide-archived-subtrees 'all
)
5980 (org-cycle-hide-drawers 'all
)
5981 (org-cycle-show-empty-lines t
)))
5983 (defun org-set-visibility-according-to-property (&optional no-cleanup
)
5984 "Switch subtree visibilities according to :VISIBILITY: property."
5986 (let (org-show-entry-below state
)
5988 (goto-char (point-max))
5989 (while (re-search-backward
5990 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5992 (setq state
(match-string 1))
5994 (org-back-to-heading t
)
5998 ((equal state
'("fold" "folded"))
6000 ((equal state
"children")
6001 (org-show-hidden-entry)
6003 ((equal state
"content")
6006 (org-narrow-to-subtree)
6008 ((member state
'("all" "showall"))
6011 (org-cycle-hide-archived-subtrees 'all
)
6012 (org-cycle-hide-drawers 'all
)
6013 (org-cycle-show-empty-lines 'all
)))))
6015 (defun org-overview ()
6016 "Switch to overview mode, showing only top-level headlines.
6017 Really, this shows all headlines with level equal or greater than the level
6018 of the first headline in the buffer. This is important, because if the
6019 first headline is not level one, then (hide-sublevels 1) gives confusing
6022 (let ((level (save-excursion
6023 (goto-char (point-min))
6024 (if (re-search-forward (concat "^" outline-regexp
) nil t
)
6026 (goto-char (match-beginning 0))
6027 (funcall outline-level
))))))
6028 (and level
(hide-sublevels level
))))
6030 (defun org-content (&optional arg
)
6031 "Show all headlines in the buffer, like a table of contents.
6032 With numerical argument N, show content up to level N."
6035 ;; Visit all headings and show their offspring
6036 (and (integerp arg
) (org-overview))
6037 (goto-char (point-max))
6039 (while (and (progn (condition-case nil
6040 (outline-previous-visible-heading 1)
6041 (error (goto-char (point-min))))
6043 (looking-at outline-regexp
))
6045 (show-children (1- arg
))
6047 (if (bobp) (throw 'exit nil
))))))
6050 (defun org-optimize-window-after-visibility-change (state)
6051 "Adjust the window after a change in outline visibility.
6052 This function is the default value of the hook `org-cycle-hook'."
6053 (when (get-buffer-window (current-buffer))
6055 ((eq state
'content
) nil
)
6056 ((eq state
'all
) nil
)
6057 ((eq state
'folded
) nil
)
6058 ((eq state
'children
) (or (org-subtree-end-visible-p) (recenter 1)))
6059 ((eq state
'subtree
) (or (org-subtree-end-visible-p) (recenter 1))))))
6061 (defun org-remove-empty-overlays-at (pos)
6062 "Remove outline overlays that do not contain non-white stuff."
6065 (and (eq 'outline
(overlay-get o
'invisible
))
6066 (not (string-match "\\S-" (buffer-substring (overlay-start o
)
6068 (delete-overlay o
)))
6071 (defun org-clean-visibility-after-subtree-move ()
6072 "Fix visibility issues after moving a subtree."
6073 ;; First, find a reasonable region to look at:
6074 ;; Start two siblings above, end three below
6075 (let* ((beg (save-excursion
6076 (and (org-get-last-sibling)
6077 (org-get-last-sibling))
6079 (end (save-excursion
6080 (and (org-get-next-sibling)
6081 (org-get-next-sibling)
6082 (org-get-next-sibling))
6083 (if (org-at-heading-p)
6086 (level (looking-at "\\*+"))
6087 (re (if level
(concat "^" (regexp-quote (match-string 0)) " "))))
6090 (narrow-to-region beg end
)
6092 ;; Properly fold already folded siblings
6093 (goto-char (point-min))
6094 (while (re-search-forward re nil t
)
6095 (if (and (not (org-invisible-p))
6097 (goto-char (point-at-eol)) (org-invisible-p)))
6099 (org-cycle-show-empty-lines 'overview
)
6100 (org-cycle-hide-drawers 'overview
)))))
6102 (defun org-cycle-show-empty-lines (state)
6103 "Show empty lines above all visible headlines.
6104 The region to be covered depends on STATE when called through
6105 `org-cycle-hook'. Lisp program can use t for STATE to get the
6106 entire buffer covered. Note that an empty line is only shown if there
6107 are at least `org-cycle-separator-lines' empty lines before the headline."
6108 (when (not (= org-cycle-separator-lines
0))
6110 (let* ((n (abs org-cycle-separator-lines
))
6112 ((= n
1) "\\(\n[ \t]*\n\\*+\\) ")
6113 ((= n
2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6114 (t (let ((ns (number-to-string (- n
2))))
6115 (concat "^\\(?:[ \t]*\n\\)\\{" ns
"," ns
"\\}"
6116 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6119 ((memq state
'(overview contents t
))
6120 (setq beg
(point-min) end
(point-max)))
6121 ((memq state
'(children folded
))
6122 (setq beg
(point) end
(progn (org-end-of-subtree t t
)
6123 (beginning-of-line 2)
6127 (while (re-search-forward re end t
)
6128 (unless (get-char-property (match-end 1) 'invisible
)
6129 (setq e
(match-end 1))
6130 (if (< org-cycle-separator-lines
0)
6131 (setq b
(save-excursion
6132 (goto-char (match-beginning 0))
6133 (org-back-over-empty-lines)
6135 (goto-char (max (point-min) (1- (point))))
6139 (setq b
(match-beginning 1)))
6140 (outline-flag-region b e nil
)))))))
6141 ;; Never hide empty lines at the end of the file.
6143 (goto-char (point-max))
6144 (outline-previous-heading)
6145 (outline-end-of-heading)
6146 (if (and (looking-at "[ \t\n]+")
6147 (= (match-end 0) (point-max)))
6148 (outline-flag-region (point) (match-end 0) nil
))))
6150 (defun org-show-empty-lines-in-parent ()
6151 "Move to the parent and re-show empty lines before visible headlines."
6153 (let ((context (if (org-up-heading-safe) 'children
'overview
)))
6154 (org-cycle-show-empty-lines context
))))
6156 (defun org-files-list ()
6157 "Return `org-agenda-files' list, plus all open org-mode files.
6158 This is useful for operations that need to scan all of a user's
6159 open and agenda-wise Org files."
6160 (let ((files (mapcar 'expand-file-name
(org-agenda-files))))
6161 (dolist (buf (buffer-list))
6162 (with-current-buffer buf
6163 (if (and (eq major-mode
'org-mode
) (buffer-file-name))
6164 (let ((file (expand-file-name (buffer-file-name))))
6165 (unless (member file files
)
6166 (push file files
))))))
6169 (defsubst org-entry-beginning-position
()
6170 "Return the beginning position of the current entry."
6171 (save-excursion (outline-back-to-heading t
) (point)))
6173 (defsubst org-entry-end-position
()
6174 "Return the end position of the current entry."
6175 (save-excursion (outline-next-heading) (point)))
6177 (defun org-cycle-hide-drawers (state)
6178 "Re-hide all drawers after a visibility state change."
6179 (when (and (org-mode-p)
6180 (not (memq state
'(overview folded contents
))))
6182 (let* ((globalp (memq state
'(contents all
)))
6183 (beg (if globalp
(point-min) (point)))
6184 (end (if globalp
(point-max)
6185 (if (eq state
'children
)
6186 (save-excursion (outline-next-heading) (point))
6187 (org-end-of-subtree t
)))))
6189 (while (re-search-forward org-drawer-regexp end t
)
6190 (org-flag-drawer t
))))))
6192 (defun org-flag-drawer (flag)
6194 (beginning-of-line 1)
6195 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6196 (let ((b (match-end 0))
6197 (outline-regexp org-outline-regexp
))
6198 (if (re-search-forward
6200 (save-excursion (outline-next-heading) (point)) t
)
6201 (outline-flag-region b
(point-at-eol) flag
)
6202 (error ":END: line missing at position %s" b
))))))
6204 (defun org-subtree-end-visible-p ()
6205 "Is the end of the current subtree visible?"
6206 (pos-visible-in-window-p
6207 (save-excursion (org-end-of-subtree t
) (point))))
6209 (defun org-first-headline-recenter (&optional N
)
6210 "Move cursor to the first headline and recenter the headline.
6211 Optional argument N means put the headline into the Nth line of the window."
6212 (goto-char (point-min))
6213 (when (re-search-forward (concat "^\\(" outline-regexp
"\\)") nil t
)
6215 (recenter (prefix-numeric-value N
))))
6217 ;;; Saving and restoring visibility
6219 (defun org-outline-overlay-data (&optional use-markers
)
6220 "Return a list of the locations of all outline overlays.
6221 The are overlays with the `invisible' property value `outline'.
6222 The return values is a list of cons cells, with start and stop
6223 positions for each overlay.
6224 If USE-MARKERS is set, return the positions as markers."
6231 (when (eq (overlay-get o
'invisible
) 'outline
)
6232 (setq beg
(overlay-start o
)
6233 end
(overlay-end o
))
6234 (and beg end
(> end beg
)
6236 (cons (move-marker (make-marker) beg
)
6237 (move-marker (make-marker) end
))
6239 (overlays-in (point-min) (point-max))))))))
6241 (defun org-set-outline-overlay-data (data)
6242 "Create visibility overlays for all positions in DATA.
6243 DATA should have been made by `org-outline-overlay-data'."
6250 (setq o
(make-overlay (car c
) (cdr c
)))
6251 (overlay-put o
'invisible
'outline
))
6254 (defmacro org-save-outline-visibility
(use-markers &rest body
)
6255 "Save and restore outline visibility around BODY.
6256 If USE-MARKERS is non-nil, use markers for the positions.
6257 This means that the buffer may change while running BODY,
6258 but it also means that the buffer should stay alive
6259 during the operation, because otherwise all these markers will
6261 (declare (indent 1))
6262 `(let ((data (org-outline-overlay-data ,use-markers
)))
6266 (org-set-outline-overlay-data data
))
6269 (and (markerp (car c
)) (move-marker (car c
) nil
))
6270 (and (markerp (cdr c
)) (move-marker (cdr c
) nil
)))
6274 ;;; Folding of blocks
6276 (defconst org-block-regexp
6278 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
6279 "Regular expression for hiding blocks.")
6281 (defvar org-hide-block-overlays nil
6282 "Overlays hiding blocks.")
6283 (make-variable-buffer-local 'org-hide-block-overlays
)
6285 (defun org-block-map (function &optional start end
)
6286 "Call FUNCTION at the head of all source blocks in the current buffer.
6287 Optional arguments START and END can be used to limit the range."
6288 (let ((start (or start
(point-min)))
6289 (end (or end
(point-max))))
6292 (while (and (< (point) end
) (re-search-forward org-block-regexp end t
))
6295 (goto-char (match-beginning 0))
6296 (funcall function
)))))))
6298 (defun org-hide-block-toggle-all ()
6299 "Toggle the visibility of all blocks in the current buffer."
6300 (org-block-map #'org-hide-block-toggle
))
6302 (defun org-hide-block-all ()
6303 "Fold all blocks in the current buffer."
6305 (org-show-block-all)
6306 (org-block-map #'org-hide-block-toggle-maybe
))
6308 (defun org-show-block-all ()
6309 "Unfold all blocks in the current buffer."
6311 (mapc 'delete-overlay org-hide-block-overlays
)
6312 (setq org-hide-block-overlays nil
))
6314 (defun org-hide-block-toggle-maybe ()
6315 "Toggle visibility of block at point."
6317 (let ((case-fold-search t
))
6319 (beginning-of-line 1)
6320 (looking-at org-block-regexp
))
6321 (progn (org-hide-block-toggle)
6322 t
) ;; to signal that we took action
6323 nil
))) ;; to signal that we did not
6325 (defun org-hide-block-toggle (&optional force
)
6326 "Toggle the visibility of the current block."
6330 (if (re-search-forward org-block-regexp nil t
)
6331 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6332 (end (match-end 0)) ;; end of entire body
6334 (if (memq t
(mapcar (lambda (overlay)
6335 (eq (overlay-get overlay
'invisible
)
6337 (overlays-at start
)))
6338 (if (or (not force
) (eq force
'off
))
6340 (when (member ov org-hide-block-overlays
)
6341 (setq org-hide-block-overlays
6342 (delq ov org-hide-block-overlays
)))
6343 (when (eq (overlay-get ov
'invisible
)
6345 (delete-overlay ov
)))
6346 (overlays-at start
)))
6347 (setq ov
(make-overlay start end
))
6348 (overlay-put ov
'invisible
'org-hide-block
)
6349 ;; make the block accessible to isearch
6351 ov
'isearch-open-invisible
6353 (when (member ov org-hide-block-overlays
)
6354 (setq org-hide-block-overlays
6355 (delq ov org-hide-block-overlays
)))
6356 (when (eq (overlay-get ov
'invisible
)
6358 (delete-overlay ov
))))
6359 (push ov org-hide-block-overlays
)))
6360 (error "Not looking at a source block"))))
6362 ;; org-tab-after-check-for-cycling-hook
6363 (add-hook 'org-tab-first-hook
'org-hide-block-toggle-maybe
)
6364 ;; Remove overlays when changing major mode
6365 (add-hook 'org-mode-hook
6366 (lambda () (org-add-hook 'change-major-mode-hook
6367 'org-show-block-all
'append
'local
)))
6371 (defvar org-goto-window-configuration nil
)
6372 (defvar org-goto-marker nil
)
6373 (defvar org-goto-map
6374 (let ((map (make-sparse-keymap)))
6375 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur
)) cmd
)
6376 (while (setq cmd
(pop cmds
))
6377 (substitute-key-definition cmd cmd map global-map
)))
6378 (suppress-keymap map
)
6379 (org-defkey map
"\C-m" 'org-goto-ret
)
6380 (org-defkey map
[(return)] 'org-goto-ret
)
6381 (org-defkey map
[(left)] 'org-goto-left
)
6382 (org-defkey map
[(right)] 'org-goto-right
)
6383 (org-defkey map
[(control ?g
)] 'org-goto-quit
)
6384 (org-defkey map
"\C-i" 'org-cycle
)
6385 (org-defkey map
[(tab)] 'org-cycle
)
6386 (org-defkey map
[(down)] 'outline-next-visible-heading
)
6387 (org-defkey map
[(up)] 'outline-previous-visible-heading
)
6388 (if org-goto-auto-isearch
6389 (if (fboundp 'define-key-after
)
6390 (define-key-after map
[t] 'org-goto-local-auto-isearch)
6392 (org-defkey map "q" 'org-goto-quit)
6393 (org-defkey map "n" 'outline-next-visible-heading)
6394 (org-defkey map "p" 'outline-previous-visible-heading)
6395 (org-defkey map "f" 'outline-forward-same-level)
6396 (org-defkey map "b" 'outline-backward-same-level)
6397 (org-defkey map "u" 'outline-up-heading))
6398 (org-defkey map "/" 'org-occur)
6399 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6400 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6401 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6402 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6403 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6406 (defconst org-goto-help
6407 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6408 RET=jump to location [Q]uit and return to previous location
6409 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6411 (defvar org-goto-start-pos) ; dynamically scoped parameter
6413 ;; FIXME: Docstring does not mention both interfaces
6414 (defun org-goto (&optional alternative-interface)
6415 "Look up a different location in the current file, keeping current visibility.
6417 When you want look-up or go to a different location in a document, the
6418 fastest way is often to fold the entire buffer and then dive into the tree.
6419 This method has the disadvantage, that the previous location will be folded,
6420 which may not be what you want.
6422 This command works around this by showing a copy of the current buffer
6423 in an indirect buffer, in overview mode. You can dive into the tree in
6424 that copy, use org-occur and incremental search to find a location.
6425 When pressing RET or `Q', the command returns to the original buffer in
6426 which the visibility is still unchanged. After RET is will also jump to
6427 the location selected in the indirect buffer and expose the
6428 the headline hierarchy above."
6430 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6431 (org-refile-use-outline-path t)
6432 (org-refile-target-verify-function nil)
6434 (if (not alternative-interface)
6436 (if (eq org-goto-interface 'outline)
6437 'outline-path-completion
6439 (org-goto-start-pos (point))
6441 (if (eq interface 'outline)
6442 (car (org-get-location (current-buffer) org-goto-help))
6443 (nth 3 (org-refile-get-location "Goto: ")))))
6446 (org-mark-ring-push org-goto-start-pos)
6447 (goto-char selected-point)
6448 (if (or (org-invisible-p) (org-invisible-p2))
6449 (org-show-context 'org-goto)))
6452 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6453 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6454 (defvar org-goto-local-auto-isearch-map) ; defined below
6456 (defun org-get-location (buf help)
6457 "Let the user select a location in the Org-mode buffer BUF.
6458 This function uses a recursive edit. It returns the selected position
6460 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6461 (isearch-hide-immediately nil)
6462 (isearch-search-fun-function
6463 (lambda () 'org-goto-local-search-headings))
6464 (org-goto-selected-point org-goto-exit-command)
6466 (special-display-buffer-names nil)
6467 (special-display-regexps nil)
6468 (special-display-function nil))
6470 (save-window-excursion
6471 (delete-other-windows)
6472 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6475 (make-indirect-buffer (current-buffer) "*org-goto*")
6476 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6477 (with-output-to-temp-buffer "*Help*"
6479 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6480 (setq buffer-read-only nil)
6481 (let ((org-startup-truncated t)
6482 (org-startup-folded nil)
6483 (org-startup-align-all-tables nil))
6486 (setq buffer-read-only t)
6487 (if (and (boundp 'org-goto-start-pos)
6488 (integer-or-marker-p org-goto-start-pos))
6489 (let ((org-show-hierarchy-above t)
6490 (org-show-siblings t)
6491 (org-show-following-heading t))
6492 (goto-char org-goto-start-pos)
6493 (and (org-invisible-p) (org-show-context)))
6494 (goto-char (point-min)))
6495 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6496 (message "Select location and press RET")
6497 (use-local-map org-goto-map)
6500 (kill-buffer "*org-goto*")
6501 (cons org-goto-selected-point org-goto-exit-command)))
6503 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6504 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6505 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6506 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6508 (defun org-goto-local-search-headings (string bound noerror)
6509 "Search and make sure that any matches are in headlines."
6511 (while (if isearch-forward
6512 (search-forward string bound noerror)
6513 (search-backward string bound noerror))
6514 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6515 (and (member :headline context)
6516 (not (member :tags context))))
6517 (throw 'return (point))))))
6519 (defun org-goto-local-auto-isearch ()
6522 (goto-char (point-min))
6523 (let ((keys (this-command-keys)))
6524 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6526 (isearch-process-search-char (string-to-char keys)))))
6528 (defun org-goto-ret (&optional arg)
6529 "Finish `org-goto' by going to the new location."
6531 (setq org-goto-selected-point (point)
6532 org-goto-exit-command 'return)
6535 (defun org-goto-left ()
6536 "Finish `org-goto' by going to the new location."
6538 (if (org-on-heading-p)
6540 (beginning-of-line 1)
6541 (setq org-goto-selected-point (point)
6542 org-goto-exit-command 'left)
6544 (error "Not on a heading")))
6546 (defun org-goto-right ()
6547 "Finish `org-goto' by going to the new location."
6549 (if (org-on-heading-p)
6551 (setq org-goto-selected-point (point)
6552 org-goto-exit-command 'right)
6554 (error "Not on a heading")))
6556 (defun org-goto-quit ()
6557 "Finish `org-goto' without cursor motion."
6559 (setq org-goto-selected-point nil)
6560 (setq org-goto-exit-command 'quit)
6563 ;;; Indirect buffer display of subtrees
6565 (defvar org-indirect-dedicated-frame nil
6566 "This is the frame being used for indirect tree display.")
6567 (defvar org-last-indirect-buffer nil)
6569 (defun org-tree-to-indirect-buffer (&optional arg)
6570 "Create indirect buffer and narrow it to current subtree.
6571 With numerical prefix ARG, go up to this level and then take that tree.
6572 If ARG is negative, go up that many levels.
6573 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6574 indirect buffer previously made with this command, to avoid proliferation of
6575 indirect buffers. However, when you call the command with a \
6576 \\[universal-argument] prefix, or
6577 when `org-indirect-buffer-display' is `new-frame', the last buffer
6578 is kept so that you can work with several indirect buffers at the same time.
6579 If `org-indirect-buffer-display' is `dedicated-frame', the \
6580 \\[universal-argument] prefix also
6581 requests that a new frame be made for the new buffer, so that the dedicated
6582 frame is not changed."
6584 (let ((cbuf (current-buffer))
6585 (cwin (selected-window))
6587 beg end level heading ibuf)
6589 (org-back-to-heading t)
6591 (setq level (org-outline-level))
6592 (if (< arg 0) (setq arg (+ level arg)))
6593 (while (> (setq level (org-outline-level)) arg)
6594 (outline-up-heading 1 t)))
6596 heading (org-get-heading))
6597 (org-end-of-subtree t t)
6598 (if (org-on-heading-p) (backward-char 1))
6600 (if (and (buffer-live-p org-last-indirect-buffer)
6601 (not (eq org-indirect-buffer-display 'new-frame))
6603 (kill-buffer org-last-indirect-buffer))
6604 (setq ibuf (org-get-indirect-buffer cbuf)
6605 org-last-indirect-buffer ibuf)
6607 ((or (eq org-indirect-buffer-display 'new-frame)
6608 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6609 (select-frame (make-frame))
6610 (delete-other-windows)
6611 (switch-to-buffer ibuf)
6612 (org-set-frame-title heading))
6613 ((eq org-indirect-buffer-display 'dedicated-frame)
6615 (select-frame (or (and org-indirect-dedicated-frame
6616 (frame-live-p org-indirect-dedicated-frame)
6617 org-indirect-dedicated-frame)
6618 (setq org-indirect-dedicated-frame (make-frame)))))
6619 (delete-other-windows)
6620 (switch-to-buffer ibuf)
6621 (org-set-frame-title (concat "Indirect: " heading)))
6622 ((eq org-indirect-buffer-display 'current-window)
6623 (switch-to-buffer ibuf))
6624 ((eq org-indirect-buffer-display 'other-window)
6625 (pop-to-buffer ibuf))
6626 (t (error "Invalid value")))
6627 (if (featurep 'xemacs)
6628 (save-excursion (org-mode) (turn-on-font-lock)))
6629 (narrow-to-region beg end)
6632 (and (window-live-p cwin) (select-window cwin))))
6634 (defun org-get-indirect-buffer (&optional buffer)
6635 (setq buffer (or buffer (current-buffer)))
6636 (let ((n 1) (base (buffer-name buffer)) bname)
6637 (while (buffer-live-p
6638 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6641 (make-indirect-buffer buffer bname 'clone)
6642 (error (make-indirect-buffer buffer bname)))))
6644 (defun org-set-frame-title (title)
6645 "Set the title of the current frame to the string TITLE."
6646 ;; FIXME: how to name a single frame in XEmacs???
6647 (unless (featurep 'xemacs)
6648 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6650 ;;;; Structure editing
6652 ;;; Inserting headlines
6654 (defun org-previous-line-empty-p ()
6657 (or (beginning-of-line 0) t)
6659 (looking-at "[ \t]*$")))))
6661 (defun org-insert-heading (&optional force-heading invisible-ok)
6662 "Insert a new heading or item with same depth at point.
6663 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6664 If point is at the beginning of a headline, insert a sibling before the
6665 current headline. If point is not at the beginning, do not split the line,
6666 but create the new headline after the current line.
6667 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6668 This is important for non-interactive uses of the command."
6670 (if (or (= (buffer-size) 0)
6671 (and (not (save-excursion (and (ignore-errors (org-back-to-heading invisible-ok))
6672 (org-on-heading-p))))
6673 (not (org-in-item-p))))
6675 (when (or force-heading (not (org-insert-item)))
6676 (let* ((empty-line-p nil)
6677 (head (save-excursion
6680 (org-back-to-heading invisible-ok)
6681 (setq empty-line-p (org-previous-line-empty-p))
6684 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6685 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6686 pos hide-previous previous-pos)
6688 ((and (org-on-heading-p) (bolp)
6690 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6691 ;; insert before the current line
6692 (open-line (if blank 2 1)))
6694 (not org-insert-heading-respect-content)
6697 (backward-char 1) (not (org-invisible-p)))))
6698 ;; insert right here
6701 ;; somewhere in the line
6703 (setq previous-pos (point-at-bol))
6705 (setq hide-previous (org-invisible-p)))
6706 (and org-insert-heading-respect-content (org-show-subtree))
6708 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6711 (goto-char (point-at-bol))
6712 (and (looking-at org-complex-heading-regexp)
6713 (> p (match-beginning 4)))))))
6716 (org-insert-heading-respect-content
6717 (org-end-of-subtree nil t)
6718 (or (bolp) (newline))
6719 (or (org-previous-line-empty-p)
6720 (and blank (newline)))
6726 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6727 (setq tags (and (match-end 2) (match-string 2)))
6729 (delete-region (match-beginning 1) (match-end 1)))
6730 (setq pos (point-at-bol))
6731 (or split (end-of-line 1))
6732 (delete-horizontal-space)
6733 (if (string-match "\\`\\*+\\'"
6734 (buffer-substring (point-at-bol) (point)))
6736 (newline (if blank 2 1))
6742 (org-set-tags nil 'align))))
6744 (or split (end-of-line 1))
6745 (newline (if blank 2 1)))))))
6746 (insert head) (just-one-space)
6749 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6750 (when (and org-insert-heading-respect-content hide-previous)
6752 (goto-char previous-pos)
6754 (run-hooks 'org-insert-heading-hook)))))
6756 (defun org-get-heading (&optional no-tags)
6757 "Return the heading of the current entry, without the stars."
6759 (org-back-to-heading t)
6762 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6763 "\\*+[ \t]+\\([^\r\n]*\\)"))
6764 (match-string 1) "")))
6766 (defun org-heading-components ()
6767 "Return the components of the current heading.
6768 This is a list with the following elements:
6769 - the level as an integer
6770 - the reduced level, different if `org-odd-levels-only' is set.
6771 - the TODO keyword, or nil
6772 - the priority character, like ?A, or nil if no priority is given
6773 - the headline text itself, or the tags string if no headline text
6774 - the tags string, or nil."
6776 (org-back-to-heading t)
6777 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6778 (list (length (match-string 1))
6779 (org-reduced-level (length (match-string 1)))
6780 (org-match-string-no-properties 2)
6781 (and (match-end 3) (aref (match-string 3) 2))
6782 (org-match-string-no-properties 4)
6783 (org-match-string-no-properties 5)))))
6785 (defun org-get-entry ()
6786 "Get the entry text, after heading, entire subtree."
6788 (org-back-to-heading t)
6789 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6791 (defun org-insert-heading-after-current ()
6792 "Insert a new heading with same level as current, after current subtree."
6794 (org-back-to-heading)
6795 (org-insert-heading)
6796 (org-move-subtree-down)
6799 (defun org-insert-heading-respect-content ()
6801 (let ((org-insert-heading-respect-content t))
6802 (org-insert-heading t)))
6804 (defun org-insert-todo-heading-respect-content (&optional force-state)
6806 (let ((org-insert-heading-respect-content t))
6807 (org-insert-todo-heading force-state t)))
6809 (defun org-insert-todo-heading (arg &optional force-heading)
6810 "Insert a new heading with the same level and TODO state as current heading.
6811 If the heading has no TODO state, or if the state is DONE, use the first
6812 state (TODO by default). Also with prefix arg, force first state."
6814 (when (or force-heading (not (org-insert-item 'checkbox)))
6815 (org-insert-heading force-heading)
6817 (org-back-to-heading)
6818 (outline-previous-heading)
6819 (looking-at org-todo-line-regexp))
6823 (not (match-beginning 2))
6824 (member (match-string 2) org-done-keywords))
6825 (car org-todo-keywords-1)
6829 (run-hook-with-args-until-success
6830 'org-todo-get-default-hook new-mark-x nil)
6832 (beginning-of-line 1)
6833 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6834 (if org-treat-insert-todo-heading-as-state-change
6836 (insert new-mark " "))))
6837 (when org-provide-todo-statistics
6838 (org-update-parent-todo-statistics))))
6840 (defun org-insert-subheading (arg)
6841 "Insert a new subheading and demote it.
6842 Works for outline headings and for plain lists alike."
6844 (org-insert-heading arg)
6846 ((org-on-heading-p) (org-do-demote))
6847 ((org-at-item-p) (org-indent-item 1))))
6849 (defun org-insert-todo-subheading (arg)
6850 "Insert a new subheading with TODO keyword or checkbox and demote it.
6851 Works for outline headings and for plain lists alike."
6853 (org-insert-todo-heading arg)
6855 ((org-on-heading-p) (org-do-demote))
6856 ((org-at-item-p) (org-indent-item 1))))
6858 ;;; Promotion and Demotion
6860 (defvar org-after-demote-entry-hook nil
6861 "Hook run after an entry has been demoted.
6862 The cursor will be at the beginning of the entry.
6863 When a subtree is being demoted, the hook will be called for each node.")
6865 (defvar org-after-promote-entry-hook nil
6866 "Hook run after an entry has been promoted.
6867 The cursor will be at the beginning of the entry.
6868 When a subtree is being promoted, the hook will be called for each node.")
6870 (defun org-promote-subtree ()
6871 "Promote the entire subtree.
6872 See also `org-promote'."
6875 (org-map-tree 'org-promote))
6876 (org-fix-position-after-promote))
6878 (defun org-demote-subtree ()
6879 "Demote the entire subtree. See `org-demote'.
6880 See also `org-promote'."
6883 (org-map-tree 'org-demote))
6884 (org-fix-position-after-promote))
6887 (defun org-do-promote ()
6888 "Promote the current heading higher up the tree.
6889 If the region is active in `transient-mark-mode', promote all headings
6893 (if (org-region-active-p)
6894 (org-map-region 'org-promote (region-beginning) (region-end))
6896 (org-fix-position-after-promote))
6898 (defun org-do-demote ()
6899 "Demote the current heading lower down the tree.
6900 If the region is active in `transient-mark-mode', demote all headings
6904 (if (org-region-active-p)
6905 (org-map-region 'org-demote (region-beginning) (region-end))
6907 (org-fix-position-after-promote))
6909 (defun org-fix-position-after-promote ()
6910 "Make sure that after pro/demotion cursor position is right."
6911 (let ((pos (point)))
6912 (when (save-excursion
6913 (beginning-of-line 1)
6914 (looking-at org-todo-line-regexp)
6915 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6916 (cond ((eobp) (insert " "))
6917 ((eolp) (insert " "))
6918 ((equal (char-after) ?\ ) (forward-char 1))))))
6920 (defun org-current-level ()
6921 "Return the level of the current entry, or nil if before the first headline.
6922 The level is the number of stars at the beginning of the headline."
6926 (org-back-to-heading t)
6927 (funcall outline-level))
6930 (defun org-get-previous-line-level ()
6931 "Return the outline depth of the last headline before the current line.
6932 Returns 0 for the first headline in the buffer, and nil if before the
6934 (let ((current-level (org-current-level))
6935 (prev-level (when (> (line-number-at-pos) 1)
6937 (beginning-of-line 0)
6938 (org-current-level)))))
6939 (cond ((null current-level) nil) ; Before first headline
6940 ((null prev-level) 0) ; At first headline
6943 (defun org-reduced-level (l)
6944 "Compute the effective level of a heading.
6945 This takes into account the setting of `org-odd-levels-only'."
6946 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6948 (defun org-level-increment ()
6949 "Return the number of stars that will be added or removed at a
6950 time to headlines when structure editing, based on the value of
6951 `org-odd-levels-only'."
6952 (if org-odd-levels-only 2 1))
6954 (defun org-get-valid-level (level &optional change)
6955 "Rectify a level change under the influence of `org-odd-levels-only'
6956 LEVEL is a current level, CHANGE is by how much the level should be
6957 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6958 even level numbers will become the next higher odd number."
6959 (if org-odd-levels-only
6960 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6961 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6962 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6963 (max 1 (+ level (or change 0)))))
6965 (if (boundp 'define-obsolete-function-alias)
6966 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6967 (define-obsolete-function-alias 'org-get-legal-level
6968 'org-get-valid-level)
6969 (define-obsolete-function-alias 'org-get-legal-level
6970 'org-get-valid-level "23.1")))
6972 (defun org-promote ()
6973 "Promote the current heading higher up the tree.
6974 If the region is active in `transient-mark-mode', promote all headings
6976 (org-back-to-heading t)
6977 (let* ((level (save-match-data (funcall outline-level)))
6978 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6979 (diff (abs (- level (length up-head) -1))))
6980 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6981 (replace-match up-head nil t)
6982 ;; Fixup tag positioning
6983 (and org-auto-align-tags (org-set-tags nil t))
6984 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6985 (run-hooks 'org-after-promote-entry-hook)))
6987 (defun org-demote ()
6988 "Demote the current heading lower down the tree.
6989 If the region is active in `transient-mark-mode', demote all headings
6991 (org-back-to-heading t)
6992 (let* ((level (save-match-data (funcall outline-level)))
6993 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6994 (diff (abs (- level (length down-head) -1))))
6995 (replace-match down-head nil t)
6996 ;; Fixup tag positioning
6997 (and org-auto-align-tags (org-set-tags nil t))
6998 (if org-adapt-indentation (org-fixup-indentation diff))
6999 (run-hooks 'org-after-demote-entry-hook)))
7001 (defun org-cycle-level ()
7002 "Cycle the level of an empty headline through possible states.
7003 This goes first to child, then to parent, level, then up the hierarchy.
7004 After top level, it switches back to sibling level."
7006 (let ((org-adapt-indentation nil))
7007 (when (org-point-at-end-of-empty-headline)
7008 (setq this-command 'org-cycle-level) ; Only needed for caching
7009 (let ((cur-level (org-current-level))
7010 (prev-level (org-get-previous-line-level)))
7012 ;; If first headline in file, promote to top-level.
7014 (loop repeat (/ (- cur-level 1) (org-level-increment))
7015 do (org-do-promote)))
7016 ;; If same level as prev, demote one.
7017 ((= prev-level cur-level)
7019 ;; If parent is top-level, promote to top level if not already.
7021 (loop repeat (/ (- cur-level 1) (org-level-increment))
7022 do (org-do-promote)))
7023 ;; If top-level, return to prev-level.
7025 (loop repeat (/ (- prev-level 1) (org-level-increment))
7026 do (org-do-demote)))
7027 ;; If less than prev-level, promote one.
7028 ((< cur-level prev-level)
7030 ;; If deeper than prev-level, promote until higher than
7032 ((> cur-level prev-level)
7033 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7034 do (org-do-promote))))
7037 (defun org-map-tree (fun)
7038 "Call FUN for every heading underneath the current one."
7039 (org-back-to-heading)
7040 (let ((level (funcall outline-level)))
7044 (outline-next-heading)
7045 (> (funcall outline-level) level))
7049 (defun org-map-region (fun beg end)
7050 "Call FUN for every heading between BEG and END."
7051 (let ((org-ignore-region t))
7053 (setq end (copy-marker end))
7055 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
7059 (outline-next-heading)
7064 (defun org-fixup-indentation (diff)
7065 "Change the indentation in the current entry by DIFF.
7066 However, if any line in the current entry has no indentation, or if it
7067 would end up with no indentation after the change, nothing at all is done."
7069 (let ((end (save-excursion (outline-next-heading)
7071 (prohibit (if (> diff 0)
7073 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7075 (unless (save-excursion (end-of-line 1)
7076 (re-search-forward prohibit end t))
7077 (while (and (< (point) end)
7078 (re-search-forward "^[ \t]+" end t))
7079 (goto-char (match-end 0))
7080 (setq col (current-column))
7081 (if (< diff 0) (replace-match ""))
7082 (org-indent-to-column (+ diff col))))
7083 (move-marker end nil))))
7085 (defun org-convert-to-odd-levels ()
7086 "Convert an org-mode file with all levels allowed to one with odd levels.
7087 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7090 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7091 (let ((outline-regexp org-outline-regexp)
7092 (outline-level 'org-outline-level)
7093 (org-odd-levels-only nil) n)
7095 (goto-char (point-min))
7096 (while (re-search-forward "^\\*\\*+ " nil t)
7097 (setq n (- (length (match-string 0)) 2))
7098 (while (>= (setq n (1- n)) 0)
7100 (end-of-line 1))))))
7102 (defun org-convert-to-oddeven-levels ()
7103 "Convert an org-mode file with only odd levels to one with odd/even levels.
7104 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7105 file contains a section with an even level, conversion would
7106 destroy the structure of the file. An error is signaled in this
7109 (goto-char (point-min))
7110 ;; First check if there are no even levels
7111 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7112 (org-show-context t)
7113 (error "Not all levels are odd in this file. Conversion not possible"))
7114 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7115 (let ((outline-regexp org-outline-regexp)
7116 (outline-level 'org-outline-level)
7117 (org-odd-levels-only nil) n)
7119 (goto-char (point-min))
7120 (while (re-search-forward "^\\*\\*+ " nil t)
7121 (setq n (/ (1- (length (match-string 0))) 2))
7122 (while (>= (setq n (1- n)) 0)
7124 (end-of-line 1))))))
7126 (defun org-tr-level (n)
7127 "Make N odd if required."
7128 (if org-odd-levels-only (1+ (/ n 2)) n))
7130 ;;; Vertical tree motion, cutting and pasting of subtrees
7132 (defun org-move-subtree-up (&optional arg)
7133 "Move the current subtree up past ARG headlines of the same level."
7135 (org-move-subtree-down (- (prefix-numeric-value arg))))
7137 (defun org-move-subtree-down (&optional arg)
7138 "Move the current subtree down past ARG headlines of the same level."
7140 (setq arg (prefix-numeric-value arg))
7141 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7142 'org-get-last-sibling))
7143 (ins-point (make-marker))
7145 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7147 (org-back-to-heading)
7150 (setq ne-beg (org-back-over-empty-lines))
7153 (save-excursion (outline-end-of-heading)
7154 (setq folded (org-invisible-p)))
7155 (outline-end-of-subtree))
7156 (outline-next-heading)
7157 (setq ne-end (org-back-over-empty-lines))
7160 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7161 ;; include less whitespace
7164 (forward-line (- ne-beg ne-end))
7165 (setq beg (point))))
7166 ;; Find insertion point, with error handling
7168 (or (and (funcall movfunc) (looking-at outline-regexp))
7169 (progn (goto-char beg0)
7170 (error "Cannot move past superior level or buffer limit")))
7171 (setq cnt (1- cnt)))
7173 ;; Moving forward - still need to move over subtree
7174 (progn (org-end-of-subtree t t)
7176 (org-back-over-empty-lines)
7177 (or (bolp) (newline)))))
7178 (setq ne-ins (org-back-over-empty-lines))
7179 (move-marker ins-point (point))
7180 (setq txt (buffer-substring beg end))
7181 (org-save-markers-in-region beg end)
7182 (delete-region beg end)
7183 (org-remove-empty-overlays-at beg)
7184 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7185 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7186 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7187 (let ((bbb (point)))
7188 (insert-before-markers txt)
7189 (org-reinstall-markers-in-region bbb)
7190 (move-marker ins-point bbb))
7191 (or (bolp) (insert "\n"))
7192 (setq ins-end (point))
7193 (goto-char ins-point)
7194 (org-skip-whitespace)
7195 (when (and (< arg 0)
7196 (org-first-sibling-p)
7198 ;; Move whitespace back to beginning
7201 (let ((kill-whole-line t))
7202 (kill-line (- ne-ins ne-beg)) (point)))
7203 (insert (make-string (- ne-ins ne-beg) ?\n)))
7204 (move-marker ins-point nil)
7209 (org-cycle-hide-drawers 'children))
7210 (org-clean-visibility-after-subtree-move)))
7212 (defvar org-subtree-clip ""
7213 "Clipboard for cut and paste of subtrees.
7214 This is actually only a copy of the kill, because we use the normal kill
7215 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7217 (defvar org-subtree-clip-folded nil
7218 "Was the last copied subtree folded?
7219 This is used to fold the tree back after pasting.")
7221 (defun org-cut-subtree (&optional n)
7222 "Cut the current subtree into the clipboard.
7223 With prefix arg N, cut this many sequential subtrees.
7224 This is a short-hand for marking the subtree and then cutting it."
7226 (org-copy-subtree n 'cut))
7228 (defun org-copy-subtree (&optional n cut force-store-markers)
7229 "Cut the current subtree into the clipboard.
7230 With prefix arg N, cut this many sequential subtrees.
7231 This is a short-hand for marking the subtree and then copying it.
7232 If CUT is non-nil, actually cut the subtree.
7233 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7234 of some markers in the region, even if CUT is non-nil. This is
7235 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7237 (let (beg end folded (beg0 (point)))
7239 (org-back-to-heading nil) ; take what looks like a subtree
7240 (org-back-to-heading t)) ; take what is really there
7241 (org-back-over-empty-lines)
7243 (skip-chars-forward " \t\r\n")
7245 (save-excursion (outline-end-of-heading)
7246 (setq folded (org-invisible-p)))
7248 (org-forward-same-level (1- n) t)
7250 (org-end-of-subtree t t))
7251 (org-back-over-empty-lines)
7255 (setq org-subtree-clip-folded folded)
7256 (when (or cut force-store-markers)
7257 (org-save-markers-in-region beg end))
7258 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7259 (setq org-subtree-clip (current-kill 0))
7260 (message "%s: Subtree(s) with %d characters"
7261 (if cut "Cut" "Copied")
7262 (length org-subtree-clip)))))
7264 (defun org-paste-subtree (&optional level tree for-yank)
7265 "Paste the clipboard as a subtree, with modification of headline level.
7266 The entire subtree is promoted or demoted in order to match a new headline
7269 If the cursor is at the beginning of a headline, the same level as
7270 that headline is used to paste the tree
7272 If not, the new level is derived from the *visible* headings
7273 before and after the insertion point, and taken to be the inferior headline
7274 level of the two. So if the previous visible heading is level 3 and the
7275 next is level 4 (or vice versa), level 4 will be used for insertion.
7276 This makes sure that the subtree remains an independent subtree and does
7277 not swallow low level entries.
7279 You can also force a different level, either by using a numeric prefix
7280 argument, or by inserting the heading marker by hand. For example, if the
7281 cursor is after \"*****\", then the tree will be shifted to level 5.
7283 If optional TREE is given, use this text instead of the kill ring.
7285 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7286 move back over whitespace before inserting, and move point to the end of
7287 the inserted text when done."
7289 (setq tree (or tree (and kill-ring (current-kill 0))))
7290 (unless (org-kill-is-subtree-p tree)
7292 (substitute-command-keys
7293 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7294 (let* ((visp (not (org-invisible-p)))
7296 (^re (concat "^\\(" outline-regexp "\\)"))
7297 (re (concat "\\(" outline-regexp "\\)"))
7298 (^re_ (concat "\\(\\*+\\)[ \t]*"))
7300 (old-level (if (string-match ^re txt)
7301 (- (match-end 0) (match-beginning 0) 1)
7303 (force-level (cond (level (prefix-numeric-value level))
7304 ((and (looking-at "[ \t]*$")
7306 ^re_ (buffer-substring
7307 (point-at-bol) (point))))
7308 (- (match-end 1) (match-beginning 1)))
7310 (looking-at org-outline-regexp))
7311 (- (match-end 0) (point) 1))
7313 (previous-level (save-excursion
7316 (outline-previous-visible-heading 1)
7318 (- (match-end 0) (match-beginning 0) 1)
7321 (next-level (save-excursion
7324 (or (looking-at outline-regexp)
7325 (outline-next-visible-heading 1))
7327 (- (match-end 0) (match-beginning 0) 1)
7330 (new-level (or force-level (max previous-level next-level)))
7331 (shift (if (or (= old-level -1)
7333 (= old-level new-level))
7335 (- new-level old-level)))
7336 (delta (if (> shift 0) -1 1))
7337 (func (if (> shift 0) 'org-demote 'org-promote))
7338 (org-odd-levels-only nil)
7340 ;; Remove the forced level indicator
7342 (delete-region (point-at-bol) (point)))
7344 (beginning-of-line 1)
7345 (unless for-yank (org-back-over-empty-lines))
7347 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7348 (insert-before-markers txt)
7349 (unless (string-match "\n\\'" txt) (insert "\n"))
7350 (setq newend (point))
7351 (org-reinstall-markers-in-region beg)
7354 (skip-chars-forward " \t\n\r")
7356 (if (and (org-invisible-p) visp)
7357 (save-excursion (outline-show-heading)))
7358 ;; Shift if necessary
7361 (narrow-to-region beg end)
7362 (while (not (= shift 0))
7363 (org-map-region func (point-min) (point-max))
7364 (setq shift (+ delta shift)))
7365 (goto-char (point-min))
7366 (setq newend (point-max))))
7367 (when (or (interactive-p) for-yank)
7368 (message "Clipboard pasted as level %d subtree" new-level))
7369 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7371 (eq org-subtree-clip (current-kill 0))
7372 org-subtree-clip-folded)
7373 ;; The tree was folded before it was killed/copied
7375 (and for-yank (goto-char newend))))
7377 (defun org-kill-is-subtree-p (&optional txt)
7378 "Check if the current kill is an outline subtree, or a set of trees.
7379 Returns nil if kill does not start with a headline, or if the first
7380 headline level is not the largest headline level in the tree.
7381 So this will actually accept several entries of equal levels as well,
7382 which is OK for `org-paste-subtree'.
7383 If optional TXT is given, check this string instead of the current kill."
7384 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7385 (start-level (and kill
7386 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
7387 org-outline-regexp "\\)")
7389 (- (match-end 2) (match-beginning 2) 1)))
7390 (re (concat "^" org-outline-regexp))
7391 (start (1+ (or (match-beginning 2) -1))))
7392 (if (not start-level)
7394 nil) ;; does not even start with a heading
7396 (while (setq start (string-match re kill (1+ start)))
7397 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7401 (defvar org-markers-to-move nil
7402 "Markers that should be moved with a cut-and-paste operation.
7403 Those markers are stored together with their positions relative to
7404 the start of the region.")
7406 (defun org-save-markers-in-region (beg end)
7407 "Check markers in region.
7408 If these markers are between BEG and END, record their position relative
7409 to BEG, so that after moving the block of text, we can put the markers back
7411 This function gets called just before an entry or tree gets cut from the
7412 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7413 called immediately, to move the markers with the entries."
7414 (setq org-markers-to-move nil)
7415 (when (featurep 'org-clock)
7416 (org-clock-save-markers-for-cut-and-paste beg end))
7417 (when (featurep 'org-agenda)
7418 (org-agenda-save-markers-for-cut-and-paste beg end)))
7420 (defun org-check-and-save-marker (marker beg end)
7421 "Check if MARKER is between BEG and END.
7422 If yes, remember the marker and the distance to BEG."
7423 (when (and (marker-buffer marker)
7424 (equal (marker-buffer marker) (current-buffer)))
7425 (if (and (>= marker beg) (< marker end))
7426 (push (cons marker (- marker beg)) org-markers-to-move))))
7428 (defun org-reinstall-markers-in-region (beg)
7429 "Move all remembered markers to their position relative to BEG."
7431 (move-marker (car x) (+ beg (cdr x))))
7432 org-markers-to-move)
7433 (setq org-markers-to-move nil))
7435 (defun org-narrow-to-subtree ()
7436 "Narrow buffer to the current subtree."
7441 (progn (org-back-to-heading t) (point))
7442 (progn (org-end-of-subtree t t)
7443 (if (org-on-heading-p) (backward-char 1))
7447 (defvar org-property-drawer-re))
7449 (defun org-clone-subtree-with-time-shift (n &optional shift)
7450 "Clone the task (subtree) at point N times.
7451 The clones will be inserted as siblings.
7453 In interactive use, the user will be prompted for the number of
7454 clones to be produced, and for a time SHIFT, which may be a
7455 repeater as used in time stamps, for example `+3d'.
7457 When a valid repeater is given and the entry contains any time
7458 stamps, the clones will become a sequence in time, with time
7459 stamps in the subtree shifted for each clone produced. If SHIFT
7460 is nil or the empty string, time stamps will be left alone. The
7461 ID property of the original subtree is removed.
7463 If the original subtree did contain time stamps with a repeater,
7464 the following will happen:
7465 - the repeater will be removed in each clone
7466 - an additional clone will be produced, with the current, unshifted
7467 date(s) in the entry.
7468 - the original entry will be placed *after* all the clones, with
7470 - the start days in the repeater in the original entry will be shifted
7471 to past the last clone.
7472 I this way you can spell out a number of instances of a repeating task,
7473 and still retain the repeater to cover future instances of the task."
7474 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7475 (let (beg end template task idprop
7476 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7477 (if (not (and (integerp n) (> n 0)))
7478 (error "Invalid number of replications %s" n))
7479 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7480 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7482 (error "Invalid shift specification %s" shift))
7484 (setq shift-n (string-to-number (match-string 1 shift))
7485 shift-what (cdr (assoc (match-string 2 shift)
7486 '(("d" . day) ("w" . week)
7487 ("m" . month) ("y" . year))))))
7488 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7489 (setq nmin 1 nmax n)
7490 (org-back-to-heading t)
7492 (setq idprop (org-entry-get nil "ID"))
7493 (org-end-of-subtree t t)
7494 (or (bolp) (insert "\n"))
7496 (setq template (buffer-substring beg end))
7498 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7499 (delete-region beg end)
7501 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7503 (loop for n from nmin to nmax do
7508 (goto-char (point-min))
7509 (and idprop (if org-clone-delete-id
7510 (org-entry-delete nil "ID")
7511 (org-id-get-create t)))
7512 (while (re-search-forward org-property-drawer-re nil t)
7513 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7514 (goto-char (point-min))
7516 (while (re-search-forward org-ts-regexp-both nil t)
7517 (org-timestamp-change (* n shift-n) shift-what))
7518 (unless (= n n-no-remove)
7519 (goto-char (point-min))
7520 (while (re-search-forward org-ts-regexp nil t)
7522 (goto-char (match-beginning 0))
7523 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7524 (delete-region (match-beginning 1) (match-end 1)))))))
7525 (setq task (buffer-string)))
7531 (defun org-sort (with-case)
7532 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
7533 Optional argument WITH-CASE means sort case-sensitively.
7534 With a double prefix argument, also remove duplicate entries."
7536 (if (org-at-table-p)
7537 (org-call-with-arg 'org-table-sort-lines with-case)
7538 (org-call-with-arg 'org-sort-entries-or-items with-case)))
7540 (defun org-sort-remove-invisible (s)
7541 (remove-text-properties 0 (length s) org-rm-props s)
7542 (while (string-match org-bracket-link-regexp s)
7543 (setq s (replace-match (if (match-end 2)
7545 (match-string 1 s)) t t s)))
7548 (defvar org-priority-regexp) ; defined later in the file
7550 (defvar org-after-sorting-entries-or-items-hook nil
7551 "Hook that is run after a bunch of entries or items have been sorted.
7552 When children are sorted, the cursor is in the parent line when this
7553 hook gets called. When a region or a plain list is sorted, the cursor
7554 will be in the first entry of the sorted region/list.")
7556 (defun org-sort-entries-or-items
7557 (&optional with-case sorting-type getkey-func compare-func property)
7558 "Sort entries on a certain level of an outline tree, or plain list items.
7559 If there is an active region, the entries in the region are sorted.
7560 Else, if the cursor is before the first entry, sort the top-level items.
7561 Else, the children of the entry at point are sorted.
7562 If the cursor is at the first item in a plain list, the list items will be
7565 Sorting can be alphabetically, numerically, by date/time as given by
7566 a time stamp, by a property or by priority.
7568 The command prompts for the sorting type unless it has been given to the
7569 function through the SORTING-TYPE argument, which needs to be a character,
7570 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7571 precise meaning of each character:
7573 n Numerically, by converting the beginning of the entry/item to a number.
7574 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7575 t By date/time, either the first active time stamp in the entry, or, if
7576 none exist, by the first inactive one.
7577 In items, only the first line will be checked.
7578 s By the scheduled date/time.
7579 d By deadline date/time.
7580 c By creation time, which is assumed to be the first inactive time stamp
7581 at the beginning of a line.
7582 p By priority according to the cookie.
7583 r By the value of a property.
7585 Capital letters will reverse the sort order.
7587 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7588 called with point at the beginning of the record. It must return either
7589 a string or a number that should serve as the sorting key for that record.
7591 Comparing entries ignores case by default. However, with an optional argument
7592 WITH-CASE, the sorting considers case as well."
7594 (let ((case-func (if with-case 'identity 'downcase))
7595 start beg end stars re re2
7596 txt what tmp plain-list-p)
7597 ;; Find beginning and end of region to sort
7599 ((org-region-active-p)
7600 ;; we will sort the region
7601 (setq end (region-end)
7603 (goto-char (region-beginning))
7604 (if (not (org-on-heading-p)) (outline-next-heading))
7605 (setq start (point)))
7607 ;; we will sort this plain list
7608 (org-beginning-of-item-list) (setq start (point))
7609 (org-end-of-item-list)
7610 (or (bolp) (insert "\n"))
7613 (setq plain-list-p t
7615 ((or (org-on-heading-p)
7616 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7617 ;; we will sort the children of the current headline
7618 (org-back-to-heading)
7620 end (progn (org-end-of-subtree t t)
7621 (or (bolp) (insert "\n"))
7622 (org-back-over-empty-lines)
7627 (outline-next-heading))
7629 ;; we will sort the top-level entries in this file
7630 (goto-char (point-min))
7631 (or (org-on-heading-p) (outline-next-heading))
7632 (setq start (point))
7633 (goto-char (point-max))
7634 (beginning-of-line 1)
7635 (when (looking-at ".*?\\S-")
7636 ;; File ends in a non-white line
7639 (setq end (point-max))
7640 (setq what "top-level")
7645 (if (>= beg end) (error "Nothing to sort"))
7647 (unless plain-list-p
7648 (looking-at "\\(\\*+\\)")
7649 (setq stars (match-string 1)
7650 re (concat "^" (regexp-quote stars) " +")
7651 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7652 txt (buffer-substring beg end))
7653 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7654 (if (and (not (equal stars "*")) (string-match re2 txt))
7655 (error "Region to sort contains a level above the first entry")))
7657 (unless sorting-type
7660 "Sort %s: [a]lpha [n]umeric [t]ime
[f]unc A/N/T/F means reversed:"
7661 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7662 [t]ime [s]cheduled [d]eadline [c]reated
7663 A/N/T/S/D/C/P/O/F means reversed:")
7665 (setq sorting-type (read-char-exclusive))
7667 (and (= (downcase sorting-type) ?f)
7669 (org-icompleting-read "Sort using function: "
7670 obarray 'fboundp t nil nil))
7671 (setq getkey-func (intern getkey-func)))
7673 (and (= (downcase sorting-type) ?r)
7675 (org-icompleting-read "Property: "
7676 (mapcar 'list (org-buffer-property-keys t))
7679 (message "Sorting entries...")
7682 (narrow-to-region start end)
7684 (let ((dcst (downcase sorting-type))
7685 (case-fold-search nil)
7686 (now (current-time)))
7688 (/= dcst sorting-type)
7689 ;; This function moves to the beginning character of the "record" to
7693 (if (org-at-item-p) t (goto-char (point-max))))
7695 (if (re-search-forward re nil t)
7696 (goto-char (match-beginning 0))
7697 (goto-char (point-max)))))
7698 ;; This function moves to the last character of the "record" being
7705 (outline-forward-same-level 1)
7707 (goto-char (point-max)))))))
7709 ;; This function returns the value that gets sorted against.
7712 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7715 (string-to-number (buffer-substring (match-end 0)
7718 (buffer-substring (match-end 0) (point-at-eol)))
7720 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7721 (re-search-forward org-ts-regexp-both
7723 (org-time-string-to-seconds (match-string 0))
7724 (org-float-time now)))
7728 (setq tmp (funcall getkey-func))
7729 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7731 (error "Invalid key function `%s'" getkey-func)))
7732 (t (error "Invalid sorting type `%c'" sorting-type)))))
7736 (if (looking-at org-complex-heading-regexp)
7737 (string-to-number (match-string 4))
7740 (if (looking-at org-complex-heading-regexp)
7741 (funcall case-func (match-string 4))
7744 (let ((end (save-excursion (outline-next-heading) (point))))
7745 (if (or (re-search-forward org-ts-regexp end t)
7746 (re-search-forward org-ts-regexp-both end t))
7747 (org-time-string-to-seconds (match-string 0))
7748 (org-float-time now))))
7750 (let ((end (save-excursion (outline-next-heading) (point))))
7751 (if (re-search-forward
7752 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7754 (org-time-string-to-seconds (match-string 0))
7755 (org-float-time now))))
7757 (let ((end (save-excursion (outline-next-heading) (point))))
7758 (if (re-search-forward org-scheduled-time-regexp end t)
7759 (org-time-string-to-seconds (match-string 1))
7760 (org-float-time now))))
7762 (let ((end (save-excursion (outline-next-heading) (point))))
7763 (if (re-search-forward org-deadline-time-regexp end t)
7764 (org-time-string-to-seconds (match-string 1))
7765 (org-float-time now))))
7767 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7768 (string-to-char (match-string 2))
7769 org-default-priority))
7771 (or (org-entry-get nil property) ""))
7773 (if (looking-at org-complex-heading-regexp)
7774 (- 9999 (length (member (match-string 2)
7775 org-todo-keywords-1)))))
7779 (setq tmp (funcall getkey-func))
7780 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7782 (error "Invalid key function `%s'" getkey-func)))
7783 (t (error "Invalid sorting type `%c'" sorting-type)))))
7786 ((= dcst ?a) 'string<)
7787 ((= dcst ?f) compare-func)
7788 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7790 (run-hooks 'org-after-sorting-entries-or-items-hook)
7791 (message "Sorting entries...done")))
7793 (defun org-do-sort (table what &optional with-case sorting-type)
7794 "Sort TABLE of WHAT according to SORTING-TYPE.
7795 The user will be prompted for the SORTING-TYPE if the call to this
7796 function does not specify it. WHAT is only for the prompt, to indicate
7797 what is being sorted. The sorting key will be extracted from
7798 the car of the elements of the table.
7799 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7800 (unless sorting-type
7802 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A
/N
/T means reversed
:"
7804 (setq sorting-type (read-char-exclusive)))
7805 (let ((dcst (downcase sorting-type))
7806 extractfun comparefun)
7807 ;; Define the appropriate functions
7810 (setq extractfun 'string-to-number
7811 comparefun (if (= dcst sorting-type) '< '>)))
7813 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7814 (lambda(x) (downcase (org-sort-remove-invisible x))))
7815 comparefun (if (= dcst sorting-type)
7817 (lambda (a b) (and (not (string< a b))
7818 (not (string= a b)))))))
7822 (if (or (string-match org-ts-regexp x)
7823 (string-match org-ts-regexp-both x))
7825 (org-time-string-to-time (match-string 0 x)))
7827 comparefun (if (= dcst sorting-type) '< '>)))
7828 (t (error "Invalid sorting type
`%c
'" sorting-type)))
7830 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7832 (lambda (a b) (funcall comparefun (car a) (car b))))))
7835 ;;; The orgstruct minor mode
7837 ;; Define a minor mode which can be used in other modes in order to
7838 ;; integrate the org-mode structure editing commands.
7840 ;; This is really a hack, because the org-mode structure commands use
7841 ;; keys which normally belong to the major mode. Here is how it
7842 ;; works: The minor mode defines all the keys necessary to operate the
7843 ;; structure commands, but wraps the commands into a function which
7844 ;; tests if the cursor is currently at a headline or a plain list
7845 ;; item. If that is the case, the structure command is used,
7846 ;; temporarily setting many Org-mode variables like regular
7847 ;; expressions for filling etc. However, when any of those keys is
7848 ;; used at a different location, function uses `key-binding' to look
7849 ;; up if the key has an associated command in another currently active
7850 ;; keymap (minor modes, major mode, global), and executes that
7851 ;; command. There might be problems if any of the keys is otherwise
7852 ;; used as a prefix key.
7854 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7855 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7856 ;; addresses this by checking explicitly for both bindings.
7858 (defvar orgstruct-mode-map (make-sparse-keymap)
7859 "Keymap for the minor
`orgstruct-mode
'.
")
7861 (defvar org-local-vars nil
7862 "List of local variables
, for use by
`orgstruct-mode
'.
")
7865 (define-minor-mode orgstruct-mode
7866 "Toggle the minor mode
`orgstruct-mode
'.
7867 This mode is for using Org-mode structure commands in other
7868 modes. The following keys behave as if Org-mode were active
, if
7869 the cursor is on a headline
, or on a plain list item
(both as
7870 defined by Org-mode
).
7872 M-up Move entry
/item up
7873 M-down Move entry
/item down
7876 M-S-up Move entry
/item up
7877 M-S-down Move entry
/item down
7878 M-S-left Promote subtree
7879 M-S-right Demote subtree
7880 M-q Fill paragraph and items like in Org-mode
7882 C-c - Cycle list bullet
7883 TAB Cycle item visibility
7884 M-RET Insert new heading
/item
7885 S-M-RET Insert new TODO heading
/ Checkbox item
7886 C-c C-c Set tags
/ toggle checkbox
"
7887 nil " OrgStruct
" nil
7888 (org-load-modules-maybe)
7889 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7892 (defun turn-on-orgstruct ()
7893 "Unconditionally turn on
`orgstruct-mode
'.
"
7896 (defun orgstruct++-mode (&optional arg)
7897 "Toggle
`orgstruct-mode
', the enhanced version of it.
7898 In addition to setting orgstruct-mode
, this also exports all indentation
7899 and autofilling variables from org-mode into the buffer. It will also
7900 recognize item context in multiline items.
7901 Note that turning off orgstruct-mode will
*not
* remove the
7902 indentation
/paragraph settings. This can only be done by refreshing the
7903 major mode
, for example with
\\[normal-mode
].
"
7905 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7913 "^
\\(paragraph-\\|auto-fill
\\|fill-paragraph
\\|adaptive-fill
\\|indent-
\\)"
7914 (symbol-name (car x)))
7915 (setq var (car x) val (nth 1 x))
7916 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7918 (org-set-local 'orgstruct-is-++ t))))
7920 (defvar orgstruct-is-++ nil
7921 "Is
`orgstruct-mode
' in
++ version in the current-buffer?
")
7922 (make-variable-buffer-local 'orgstruct-is-++)
7925 (defun turn-on-orgstruct++ ()
7926 "Unconditionally turn on
`orgstruct
++-mode
'.
"
7927 (orgstruct++-mode 1))
7929 (defun orgstruct-error ()
7930 "Error when there is no default binding for a structure key.
"
7932 (error "This key has no function outside structure elements
"))
7934 (defun orgstruct-setup ()
7935 "Setup orgstruct keymaps.
"
7939 '([(meta up)] org-metaup)
7940 '([(meta down)] org-metadown)
7941 '([(meta left)] org-metaleft)
7942 '([(meta right)] org-metaright)
7943 '([(meta shift up)] org-shiftmetaup)
7944 '([(meta shift down)] org-shiftmetadown)
7945 '([(meta shift left)] org-shiftmetaleft)
7946 '([(meta shift right)] org-shiftmetaright)
7947 '([?\e (up)] org-metaup)
7948 '([?\e (down)] org-metadown)
7949 '([?\e (left)] org-metaleft)
7950 '([?\e (right)] org-metaright)
7951 '([?\e (shift up)] org-shiftmetaup)
7952 '([?\e (shift down)] org-shiftmetadown)
7953 '([?\e (shift left)] org-shiftmetaleft)
7954 '([?\e (shift right)] org-shiftmetaright)
7955 '([(shift up)] org-shiftup)
7956 '([(shift down)] org-shiftdown)
7957 '([(shift left)] org-shiftleft)
7958 '([(shift right)] org-shiftright)
7959 '("\C-c\C-c
" org-ctrl-c-ctrl-c)
7960 '("\M-q
" fill-paragraph)
7962 '("\C-c-
" org-cycle-list-bullet)))
7964 (while (setq elt (pop bindings))
7965 (setq nfunc (1+ nfunc))
7966 (setq key (org-key (car elt))
7968 cmd (orgstruct-make-binding fun nfunc key))
7969 (org-defkey orgstruct-mode-map key cmd))
7971 ;; Special treatment needed for TAB and RET
7972 (org-defkey orgstruct-mode-map [(tab)]
7973 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i
"))
7974 (org-defkey orgstruct-mode-map "\C-i
"
7975 (orgstruct-make-binding 'org-cycle 103 "\C-i
" [(tab)]))
7977 (org-defkey orgstruct-mode-map "\M-\C-m
"
7978 (orgstruct-make-binding 'org-insert-heading 105
7979 "\M-\C-m
" [(meta return)]))
7980 (org-defkey orgstruct-mode-map [(meta return)]
7981 (orgstruct-make-binding 'org-insert-heading 106
7982 [(meta return)] "\M-\C-m
"))
7984 (org-defkey orgstruct-mode-map [(shift meta return)]
7985 (orgstruct-make-binding 'org-insert-todo-heading 107
7986 [(meta return)] "\M-\C-m
"))
7988 (org-defkey orgstruct-mode-map "\e\C-m
"
7989 (orgstruct-make-binding 'org-insert-heading 108
7990 "\e\C-m
" [?\e (return)]))
7991 (org-defkey orgstruct-mode-map [?\e (return)]
7992 (orgstruct-make-binding 'org-insert-heading 109
7993 [?\e (return)] "\e\C-m
"))
7994 (org-defkey orgstruct-mode-map [?\e (shift return)]
7995 (orgstruct-make-binding 'org-insert-todo-heading 110
7996 [?\e (return)] "\e\C-m
"))
7998 (unless org-local-vars
7999 (setq org-local-vars (org-get-local-variables)))
8003 (defun orgstruct-make-binding (fun n &rest keys)
8004 "Create a function for binding in the structure minor mode.
8005 FUN is the command to call inside a table. N is used to create a unique
8006 command name. KEYS are keys that should be checked in for a command
8007 to execute outside of tables.
"
8010 (intern (concat "orgstruct-hijacker-command-
" (int-to-string n)))
8012 (concat "In Structure
, run
`" (symbol-name fun) "'.
\n"
8013 "Outside of structure
, run the binding of
`"
8014 (mapconcat (lambda (x) (format "%s
" x)) keys "' or
`")
8018 `(org-context-p 'headline 'item
8019 (and orgstruct-is-++
8020 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8022 (list 'org-run-like-in-org-mode (list 'quote fun))
8023 (list 'let '(orgstruct-mode)
8024 (list 'call-interactively
8027 (list 'key-binding k))
8029 '('orgstruct-error))))))))
8031 (defun org-context-p (&rest contexts)
8032 "Check if local context is any of CONTEXTS.
8033 Possible values in the list of contexts are
`table
', `headline
', and
`item
'.
"
8034 (let ((pos (point)))
8035 (goto-char (point-at-bol))
8036 (prog1 (or (and (memq 'table contexts)
8037 (looking-at "[ \t]*|
"))
8038 (and (memq 'headline contexts)
8039 ;;????????? (looking-at "\\*+"))
8040 (looking-at outline-regexp))
8041 (and (memq 'item contexts)
8042 (looking-at "[ \t]*\\([-
+*] \\|
[0-
9]+[.
)] \\)"))
8043 (and (memq 'item-body contexts)
8047 (defun org-get-local-variables ()
8048 "Return a list of all local variables in an org-mode buffer.
"
8050 (with-current-buffer (get-buffer-create "*Org tmp
*")
8053 (setq varlist (buffer-local-variables)))
8054 (kill-buffer "*Org tmp
*")
8061 (list (car x) (list 'quote (cdr x)))))
8063 "^
\\(org-\\|orgtbl-
\\|outline-
\\|comment-
\\|paragraph-
\\|auto-fill
\\|fill-paragraph
\\|adaptive-fill
\\|indent-
\\)"
8064 (symbol-name (car x)))
8069 (defun org-run-like-in-org-mode (cmd)
8070 "Run a command
, pretending that the current buffer is in Org-mode.
8071 This will temporarily bind local variables that are typically bound in
8072 Org-mode to the values they have in Org-mode
, and then interactively
8074 (org-load-modules-maybe)
8075 (unless org-local-vars
8076 (setq org-local-vars (org-get-local-variables)))
8077 (eval (list 'let org-local-vars
8078 (list 'call-interactively (list 'quote cmd)))))
8082 (defun org-get-category (&optional pos)
8083 "Get the category applying to position POS.
"
8084 (get-text-property (or pos (point)) 'org-category))
8086 (defun org-refresh-category-properties ()
8087 "Refresh category text properties in the buffer.
"
8088 (let ((def-cat (cond
8089 ((null org-category)
8090 (if buffer-file-name
8091 (file-name-sans-extension
8092 (file-name-nondirectory buffer-file-name))
8094 ((symbolp org-category) (symbol-name org-category))
8096 beg end cat pos optionp)
8101 (goto-char (point-min))
8102 (put-text-property (point) (point-max) 'org-category def-cat)
8103 (while (re-search-forward
8104 "^
\\(#\\+CATEGORY
:\\|
[ \t]*:CATEGORY
:\\)\\(.
*\\)" nil t)
8105 (setq pos (match-end 0)
8106 optionp (equal (char-after (match-beginning 0)) ?#)
8107 cat (org-trim (match-string 2)))
8109 (setq beg (point-at-bol) end (point-max))
8110 (org-back-to-heading t)
8111 (setq beg (point) end (org-end-of-subtree t t)))
8112 (put-text-property beg end 'org-category cat)
8113 (goto-char pos)))))))
8118 ;;; Link abbreviations
8120 (defun org-link-expand-abbrev (link)
8121 "Apply replacements as defined in
`org-link-abbrev-alist.
"
8122 (if (string-match "^
\\([a-zA-Z
][-_a-zA-Z0-9
]*\\)\\(::?
\\(.
*\\)\\)?$
" link)
8123 (let* ((key (match-string 1 link))
8124 (as (or (assoc key org-link-abbrev-alist-local)
8125 (assoc key org-link-abbrev-alist)))
8126 (tag (and (match-end 2) (match-string 3 link)))
8132 ((symbolp rpl) (funcall rpl tag))
8133 ((string-match "%s
" rpl) (replace-match (or tag "") t t rpl))
8134 ((string-match "%h
" rpl)
8135 (replace-match (url-hexify-string (or tag "")) t t rpl))
8136 (t (concat rpl tag)))))
8139 ;;; Storing and inserting links
8141 (defvar org-insert-link-history nil
8142 "Minibuffer history for links inserted with
`org-insert-link
'.
")
8144 (defvar org-stored-links nil
8145 "Contains the links stored with
`org-store-link
'.
")
8147 (defvar org-store-link-plist nil
8148 "Plist with info about the most recently link created with
`org-store-link
'.
")
8150 (defvar org-link-protocols nil
8151 "Link protocols added to Org-mode using
`org-add-link-type
'.
")
8153 (defvar org-store-link-functions nil
8154 "List of functions that are called to create and store a link.
8155 Each function will be called in turn until one returns a non-nil
8156 value. Each function should check if it is responsible for creating
8157 this link
(for example by looking at the major mode
).
8158 If not
, it must exit and return nil.
8159 If yes
, it should return a non-nil value after a calling
8160 `org-store-link-props
' with a list of properties and values.
8161 Special properties are
:
8163 :type The link prefix
, like
\"http
\". This must be given.
8164 :link The link
, like
\"http
://www.astro.uva.nl
/~dominik
\".
8165 This is obligatory as well.
8166 :description Optional default description for the second pair
8167 of brackets in an Org-mode link. The user can still change
8168 this when inserting this link into an Org-mode buffer.
8170 In addition to these
, any additional properties can be specified
8171 and then used in remember templates.
")
8173 (defun org-add-link-type (type &optional follow export)
8174 "Add TYPE to the list of
`org-link-types
'.
8175 Re-compute all regular expressions depending on
`org-link-types
'
8177 FOLLOW and EXPORT are two functions.
8179 FOLLOW should take the link path as the single argument and do whatever
8180 is necessary to follow the link
, for example find a file or display
8183 EXPORT should format the link path for export to one of the export formats.
8184 It should be a function accepting three arguments
:
8186 path the path of the link
, the text after the prefix
(like \"http
:\")
8187 desc the description of the link
, if any
, nil if there was no description
8188 format the export format
, a symbol like
`html
' or
`latex
'.
8190 The function may use the FORMAT information to return different values
8191 depending on the format. The return value will be put literally into
8193 Org-mode has a built-in default for exporting links. If you are happy with
8194 this default
, there is no need to define an export function for the link
8195 type. For a simple example of an export function
, see
`org-bbdb.el
'.
"
8196 (add-to-list 'org-link-types type t)
8197 (org-make-link-regexps)
8198 (if (assoc type org-link-protocols)
8199 (setcdr (assoc type org-link-protocols) (list follow export))
8200 (push (list type follow export) org-link-protocols)))
8202 (defvar org-agenda-buffer-name)
8205 (defun org-store-link (arg)
8206 "\\<org-mode-map
>Store an org-link to the current location.
8207 This link is added to
`org-stored-links
' and can later be inserted
8208 into an org-buffer with
\\[org-insert-link
].
8210 For some link types
, a prefix arg is interpreted
:
8211 For links to usenet articles
, arg negates
`org-gnus-prefer-web-links
'.
8212 For file links
, arg negates
`org-context-in-file-links
'.
"
8214 (org-load-modules-maybe)
8215 (setq org-store-link-plist nil) ; reset
8216 (let ((outline-regexp (org-get-limited-outline-regexp))
8217 link cpltxt desc description search txt custom-id)
8220 ((run-hook-with-args-until-success 'org-store-link-functions)
8221 (setq link (plist-get org-store-link-plist :link)
8222 desc (or (plist-get org-store-link-plist :description) link)))
8224 ((equal (buffer-name) "*Org Edit Src Example
*")
8226 (while (or (not label)
8230 (goto-char (point-min))
8232 (regexp-quote (format org-coderef-label-format label))
8234 (when label (message "Label exists already
") (sit-for 2))
8235 (setq label (read-string "Code line label
: " label)))
8237 (setq link (format org-coderef-label-format label))
8238 (setq gc (- 79 (length link)))
8239 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8241 (setq link (concat "(" label ")") desc nil)))
8243 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8244 ;; We are in the agenda, link to referenced location
8245 (let ((m (or (get-text-property (point) 'org-hd-marker)
8246 (get-text-property (point) 'org-marker))))
8248 (org-with-point-at m
8250 (call-interactively 'org-store-link)
8251 (org-store-link nil))))))
8253 ((eq major-mode 'calendar-mode)
8254 (let ((cd (calendar-cursor-to-date)))
8257 (car org-time-stamp-formats)
8259 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8261 (org-store-link-props :type "calendar
" :date cd)))
8263 ((eq major-mode 'w3-mode)
8264 (setq cpltxt (if (and (buffer-name)
8265 (not (string-match "Untitled
" (buffer-name))))
8268 link (org-make-link (url-view-url t)))
8269 (org-store-link-props :type "w3
" :url (url-view-url t)))
8271 ((eq major-mode 'w3m-mode)
8272 (setq cpltxt (or w3m-current-title w3m-current-url)
8273 link (org-make-link w3m-current-url))
8274 (org-store-link-props :type "w3m
" :url (url-view-url t)))
8276 ((setq search (run-hook-with-args-until-success
8277 'org-create-file-search-functions))
8278 (setq link (concat "file
:" (abbreviate-file-name buffer-file-name)
8280 (setq cpltxt (or description link)))
8282 ((eq major-mode 'image-mode)
8283 (setq cpltxt (concat "file
:"
8284 (abbreviate-file-name buffer-file-name))
8285 link (org-make-link cpltxt))
8286 (org-store-link-props :type "image
" :file buffer-file-name))
8288 ((eq major-mode 'dired-mode)
8289 ;; link to the file in the current line
8290 (let ((file (dired-get-filename nil t)))
8292 (abbreviate-file-name
8293 (expand-file-name (dired-get-filename nil t)))
8294 ;; otherwise, no file so use current directory.
8296 (setq cpltxt (concat "file
:" file)
8297 link (org-make-link cpltxt))))
8299 ((and buffer-file-name (org-mode-p))
8300 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID
")))
8302 ((org-in-regexp "<<\\(.
*?
\\)>>")
8305 (abbreviate-file-name buffer-file-name)
8306 "::" (match-string 1))
8307 link (org-make-link cpltxt)))
8308 ((and (featurep 'org-id)
8309 (or (eq org-link-to-org-use-id t)
8310 (and (eq org-link-to-org-use-id 'create-if-interactive)
8312 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
8315 (and org-link-to-org-use-id
8317 (org-entry-get nil "ID
")
8319 ;; We can make a link using the ID.
8320 (setq link (condition-case nil
8321 (prog1 (org-id-store-link)
8322 (setq desc (plist-get org-store-link-plist
8325 ;; probably before first headline, link to file only
8327 (abbreviate-file-name buffer-file-name))))))
8329 ;; Just link to current headline
8330 (setq cpltxt (concat "file
:"
8331 (abbreviate-file-name buffer-file-name)))
8332 ;; Add a context search string
8333 (when (org-xor org-context-in-file-links arg)
8335 ((org-on-heading-p) nil)
8336 ((org-region-active-p)
8337 (buffer-substring (region-beginning) (region-end)))
8339 (when (or (null txt) (string-match "\\S-
" txt))
8343 (org-make-org-heading-search-string txt)
8345 desc (or (nth 4 (ignore-errors
8346 (org-heading-components))) "NONE
"))))
8347 (if (string-match "::\\'" cpltxt)
8348 (setq cpltxt (substring cpltxt 0 -2)))
8349 (setq link (org-make-link cpltxt)))))
8351 ((buffer-file-name (buffer-base-buffer))
8352 ;; Just link to this file here.
8353 (setq cpltxt (concat "file
:"
8354 (abbreviate-file-name
8355 (buffer-file-name (buffer-base-buffer)))))
8356 ;; Add a context string
8357 (when (org-xor org-context-in-file-links arg)
8358 (setq txt (if (org-region-active-p)
8359 (buffer-substring (region-beginning) (region-end))
8360 (buffer-substring (point-at-bol) (point-at-eol))))
8361 ;; Only use search option if there is some text.
8362 (when (string-match "\\S-
" txt)
8364 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8366 (setq link (org-make-link cpltxt)))
8369 (error "Cannot link to a buffer which is not visiting a file
"))
8371 (t (setq link nil)))
8373 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8374 (setq link (or link cpltxt)
8375 desc (or desc cpltxt))
8376 (if (equal desc "NONE
") (setq desc nil))
8378 (if (and (or (interactive-p) executing-kbd-macro) link)
8380 (setq org-stored-links
8381 (cons (list link desc) org-stored-links))
8382 (message "Stored
: %s
" (or desc link))
8384 (setq link (concat "file
:" (abbreviate-file-name (buffer-file-name))
8386 (setq org-stored-links
8387 (cons (list link desc) org-stored-links))))
8388 (and link (org-make-link-string link desc)))))
8390 (defun org-store-link-props (&rest plist)
8391 "Store link properties
, extract names and addresses.
"
8393 (when (setq x (plist-get plist :from))
8394 (setq adr (mail-extract-address-components x))
8395 (setq plist (plist-put plist :fromname (car adr)))
8396 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8397 (when (setq x (plist-get plist :to))
8398 (setq adr (mail-extract-address-components x))
8399 (setq plist (plist-put plist :toname (car adr)))
8400 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8401 (let ((from (plist-get plist :from))
8402 (to (plist-get plist :to)))
8403 (when (and from to org-from-is-user-regexp)
8405 (plist-put plist :fromto
8406 (if (string-match org-from-is-user-regexp from)
8408 (concat "from %f
"))))))
8409 (setq org-store-link-plist plist))
8411 (defun org-add-link-props (&rest plist)
8412 "Add these properties to the link property list.
"
8415 (setq key (pop plist) value (pop plist))
8416 (setq org-store-link-plist
8417 (plist-put org-store-link-plist key value)))))
8419 (defun org-email-link-description (&optional fmt)
8420 "Return the description part of an email link.
8421 This takes information from
`org-store-link-plist
' and formats it
8422 according to FMT
(default from
`org-email-link-description-format
').
"
8423 (setq fmt (or fmt org-email-link-description-format))
8424 (let* ((p org-store-link-plist)
8425 (to (plist-get p :toaddress))
8426 (from (plist-get p :fromaddress))
8429 (cons "%c
" (plist-get p :fromto))
8430 (cons "%F
" (plist-get p :from))
8431 (cons "%f
" (or (plist-get p :fromname) (plist-get p :fromaddress) "?
"))
8432 (cons "%T
" (plist-get p :to))
8433 (cons "%t
" (or (plist-get p :toname) (plist-get p :toaddress) "?
"))
8434 (cons "%s
" (plist-get p :subject))
8435 (cons "%m
" (plist-get p :message-id)))))
8436 (when (string-match "%c
" fmt)
8437 ;; Check if the user wrote this message
8438 (if (and org-from-is-user-regexp from to
8439 (save-match-data (string-match org-from-is-user-regexp from)))
8440 (setq fmt (replace-match "to %t
" t t fmt))
8441 (setq fmt (replace-match "from %f
" t t fmt))))
8442 (org-replace-escapes fmt table)))
8444 (defun org-make-org-heading-search-string (&optional string heading)
8445 "Make search string for STRING or current headline.
"
8447 (let ((s (or string (org-get-heading))))
8448 (unless (and string (not heading))
8449 ;; We are using a headline, clean up garbage in there.
8450 (if (string-match org-todo-regexp s)
8451 (setq s (replace-match "" t t s)))
8452 (if (string-match (org-re ":[[:alnum
:]_
@:]+:[ \t]*$
") s)
8453 (setq s (replace-match "" t t s)))
8454 (setq s (org-trim s))
8455 (if (string-match (concat "^
\\(" org-quote-string "\\|
"
8456 org-comment-string "\\)") s)
8457 (setq s (replace-match "" t t s)))
8458 (while (string-match org-ts-regexp s)
8459 (setq s (replace-match "" t t s))))
8460 (while (string-match "[^a-zA-Z_0-9
\t]+" s)
8461 (setq s (replace-match " " t t s)))
8462 (or string (setq s (concat "*" s))) ; Add * for headlines
8463 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8465 (defun org-make-link (&rest strings)
8466 "Concatenate STRINGS.
"
8467 (apply 'concat strings))
8469 (defun org-make-link-string (link &optional description)
8470 "Make a link with brackets
, consisting of LINK and DESCRIPTION.
"
8471 (unless (string-match "\\S-
" link)
8472 (error "Empty link
"))
8473 (when (and description
8474 (stringp description)
8475 (not (string-match "\\S-
" description)))
8476 (setq description nil))
8477 (when (stringp description)
8478 ;; Remove brackets from the description, they are fatal.
8479 (while (string-match "\\[" description)
8480 (setq description (replace-match "{" t t description)))
8481 (while (string-match "\\]" description)
8482 (setq description (replace-match "}" t t description))))
8483 (when (equal (org-link-escape link) description)
8484 ;; No description needed, it is identical
8485 (setq description nil))
8486 (when (and (not description)
8487 (not (equal link (org-link-escape link))))
8488 (setq description (org-extract-attributes link)))
8489 (concat "[[" (org-link-escape link) "]"
8490 (if description (concat "[" description "]") "")
8493 (defconst org-link-escape-chars
8497 (?\340 . "%E0
") ; `a
8498 (?\342 . "%E2
") ; ^a
8499 (?\347 . "%E7
") ; ,c
8500 (?\350 . "%E8
") ; `e
8501 (?\351 . "%E9
") ; 'e
8502 (?\352 . "%EA
") ; ^e
8503 (?\356 . "%EE
") ; ^i
8504 (?\364 . "%F4
") ; ^o
8505 (?\371 . "%F9
") ; `u
8506 (?\373 . "%FB
") ; ^u
8512 "Association list of escapes for some characters problematic in links.
8513 This is the list that is used for internal purposes.
")
8515 (defvar org-url-encoding-use-url-hexify nil)
8517 (defconst org-link-escape-chars-browser
8518 '((?\ . "%
20")) ; 32 for the SPC char
8519 "Association list of escapes for some characters problematic in links.
8520 This is the list that is used before handing over to the browser.
")
8522 (defun org-link-escape (text &optional table)
8523 "Escape characters in TEXT that are problematic for links.
"
8524 (if (and org-url-encoding-use-url-hexify (not table))
8525 (url-hexify-string text)
8526 (setq table (or table org-link-escape-chars))
8528 (let ((re (mapconcat (lambda (x) (regexp-quote
8529 (char-to-string (car x))))
8531 (while (string-match re text)
8534 (cdr (assoc (string-to-char (match-string 0 text))
8539 (defun org-link-unescape (text &optional table)
8540 "Reverse the action of
`org-link-escape
'.
"
8541 (if (and org-url-encoding-use-url-hexify (not table))
8542 (url-unhex-string text)
8543 (setq table (or table org-link-escape-chars))
8545 (let ((case-fold-search t)
8546 (re (mapconcat (lambda (x) (regexp-quote (downcase (cdr x))))
8548 (while (string-match re text)
8551 (char-to-string (car (rassoc (upcase (match-string 0 text))
8556 (defun org-xor (a b)
8560 (defun org-fixup-message-id-for-http (s)
8561 "Replace special characters in a message id
, so it can be used in an http query.
"
8562 (when (string-match "%
" s)
8563 (setq s (mapconcat (lambda (c)
8566 (char-to-string c)))
8568 (while (string-match "<" s)
8569 (setq s (replace-match "%
3C
" t t s)))
8570 (while (string-match ">" s)
8571 (setq s (replace-match "%
3E
" t t s)))
8572 (while (string-match "@" s)
8573 (setq s (replace-match "%
40" t t s)))
8577 (defun org-insert-link-global ()
8578 "Insert a link like Org-mode does.
8579 This command can be called in any mode to insert a link in Org-mode syntax.
"
8581 (org-load-modules-maybe)
8582 (org-run-like-in-org-mode 'org-insert-link))
8584 (defun org-insert-link (&optional complete-file link-location)
8585 "Insert a link. At the prompt
, enter the link.
8587 Completion can be used to insert any of the link protocol prefixes like
8590 The history can be used to select a link previously stored with
8591 `org-store-link
'. When the empty string is entered
(i.e. if you just
8592 press RET at the prompt
), the link defaults to the most recently
8593 stored link. As SPC triggers completion in the minibuffer
, you need to
8594 use M-SPC or C-q SPC to force the insertion of a space character.
8596 You will also be prompted for a description
, and if one is given
, it will
8597 be displayed in the buffer instead of the link.
8599 If there is already a link at point
, this command will allow you to edit link
8600 and description parts.
8602 With a
\\[universal-argument
] prefix
, prompts for a file to link to. The file name can
8603 be selected using completion. The path to the file will be relative to the
8604 current directory if the file is in the current directory or a subdirectory.
8605 Otherwise
, the link will be the absolute path as completed in the minibuffer
8606 \
(i.e. normally ~
/path
/to
/file
). You can configure this behavior using the
8607 option
`org-link-file-path-type
'.
8609 With two
\\[universal-argument
] prefixes
, enforce an absolute path even if the file is in
8610 the current directory or below.
8612 With three
\\[universal-argument
] prefixes
, negate the meaning of
8613 `org-keep-stored-link-after-insertion
'.
8615 If
`org-make-link-description-function
' is non-nil
, this function will be
8616 called with the link target
, and the result will be the default
8619 If the LINK-LOCATION parameter is non-nil
, this value will be
8620 used as the link location instead of reading one interactively.
"
8622 (let* ((wcf (current-window-configuration))
8623 (region (if (org-region-active-p)
8624 (buffer-substring (region-beginning) (region-end))))
8625 (remove (and region (list (region-beginning) (region-end))))
8627 tmphist ; byte-compile incorrectly complains about this
8628 (link link-location)
8629 entry file all-prefixes)
8631 (link-location) ; specified by arg, just use it.
8632 ((org-in-regexp org-bracket-link-regexp 1)
8633 ;; We do have a link at point, and we are going to edit it.
8634 (setq remove (list (match-beginning 0) (match-end 0)))
8635 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8636 (setq link (read-string "Link
: "
8638 (org-match-string-no-properties 1)))))
8639 ((or (org-in-regexp org-angle-link-re)
8640 (org-in-regexp org-plain-link-re))
8641 ;; Convert to bracket link
8642 (setq remove (list (match-beginning 0) (match-end 0))
8643 link (read-string "Link
: "
8644 (org-remove-angle-brackets (match-string 0)))))
8645 ((member complete-file '((4) (16)))
8646 ;; Completing read for file names.
8647 (setq link (org-file-complete-link complete-file)))
8649 ;; Read link, with completion for stored links.
8650 (with-output-to-temp-buffer "*Org Links
*"
8651 (princ "Insert a link.
8652 Use TAB to complete link prefixes
, then RET for type-specific completion support
\n")
8653 (when org-stored-links
8654 (princ "\nStored links are available with
<up
>/<down
> or M-p
/n
(most recent with RET
):\n\n")
8657 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8658 (reverse org-stored-links) "\n"))))
8659 (let ((cw (selected-window)))
8660 (select-window (get-buffer-window "*Org Links
*" 'visible))
8661 (setq truncate-lines t)
8662 (unless (pos-visible-in-window-p (point-max))
8663 (org-fit-window-to-buffer))
8664 (and (window-live-p cw) (select-window cw)))
8665 ;; Fake a link history, containing the stored links.
8666 (setq tmphist (append (mapcar 'car org-stored-links)
8667 org-insert-link-history))
8668 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8669 (mapcar 'car org-link-abbrev-alist)
8674 (let ((org-completion-use-ido nil)
8675 (org-completion-use-iswitchb nil))
8676 (org-completing-read
8679 (mapcar (lambda (x) (list (concat x ":")))
8681 (mapcar 'car org-stored-links))
8684 (car (car org-stored-links)))))
8685 (if (not (string-match "\\S-
" link))
8686 (error "No link selected
"))
8687 (if (or (member link all-prefixes)
8688 (and (equal ":" (substring link -1))
8689 (member (substring link 0 -1) all-prefixes)
8690 (setq link (substring link 0 -1))))
8691 (setq link (org-link-try-special-completion link))))
8692 (set-window-configuration wcf)
8693 (kill-buffer "*Org Links
*"))
8694 (setq entry (assoc link org-stored-links))
8695 (or entry (push link org-insert-link-history))
8696 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8697 (not org-keep-stored-link-after-insertion))
8698 (setq org-stored-links (delq (assoc link org-stored-links)
8700 (setq desc (or desc (nth 1 entry)))))
8702 (if (string-match org-plain-link-re link)
8703 ;; URL-like link, normalize the use of angular brackets.
8704 (setq link (org-make-link (org-remove-angle-brackets link))))
8706 ;; Check if we are linking to the current file with a search option
8707 ;; If yes, simplify the link by using only the search option.
8708 (when (and buffer-file-name
8709 (string-match "^file
:\\(.
+?
\\)::\\([^
>]+\\)" link))
8710 (let* ((path (match-string 1 link))
8711 (case-fold-search nil)
8712 (search (match-string 2 link)))
8714 (if (equal (file-truename buffer-file-name) (file-truename path))
8715 ;; We are linking to this same file, with a search option
8716 (setq link search)))))
8718 ;; Check if we can/should use a relative path. If yes, simplify the link
8719 (when (string-match "^
\\(file:\\|docview
:\\)\\(.
*\\)" link)
8720 (let* ((type (match-string 1 link))
8721 (path (match-string 2 link))
8723 (case-fold-search nil))
8725 ((or (eq org-link-file-path-type 'absolute)
8726 (equal complete-file '(16)))
8727 (setq path (abbreviate-file-name (expand-file-name path))))
8728 ((eq org-link-file-path-type 'noabbrev)
8729 (setq path (expand-file-name path)))
8730 ((eq org-link-file-path-type 'relative)
8731 (setq path (file-relative-name path)))
8734 (if (string-match (concat "^
" (regexp-quote
8736 (file-name-as-directory
8737 default-directory))))
8738 (expand-file-name path))
8739 ;; We are linking a file with relative path name.
8740 (setq path (substring (expand-file-name path)
8742 (setq path (abbreviate-file-name (expand-file-name path)))))))
8743 (setq link (concat type path))
8744 (if (equal desc origpath)
8747 (if org-make-link-description-function
8748 (setq desc (funcall org-make-link-description-function link desc)))
8750 (setq desc (read-string "Description
: " desc))
8751 (unless (string-match "\\S-
" desc) (setq desc nil))
8752 (if remove (apply 'delete-region remove))
8753 (insert (org-make-link-string link desc))))
8755 (defun org-link-try-special-completion (type)
8756 "If there is completion support for link type TYPE
, offer it.
"
8757 (let ((fun (intern (concat "org-
" type "-complete-link
"))))
8760 (read-string "Link
(no completion support
): " (concat type ":")))))
8762 (defun org-file-complete-link (&optional arg)
8763 "Create a file link using completion.
"
8765 (setq file (read-file-name "File
: "))
8766 (let ((pwd (file-name-as-directory (expand-file-name ".
")))
8767 (pwd1 (file-name-as-directory (abbreviate-file-name
8768 (expand-file-name ".
")))))
8771 (setq link (org-make-link
8773 (abbreviate-file-name (expand-file-name file)))))
8774 ((string-match (concat "^
" (regexp-quote pwd1) "\\(.
+\\)") file)
8775 (setq link (org-make-link "file
:" (match-string 1 file))))
8776 ((string-match (concat "^
" (regexp-quote pwd) "\\(.
+\\)")
8777 (expand-file-name file))
8778 (setq link (org-make-link
8779 "file
:" (match-string 1 (expand-file-name file)))))
8780 (t (setq link (org-make-link "file
:" file)))))
8783 (defun org-completing-read (&rest args)
8784 "Completing-read with SPACE being a normal character.
"
8785 (let ((minibuffer-local-completion-map
8786 (copy-keymap minibuffer-local-completion-map)))
8787 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8788 (org-defkey minibuffer-local-completion-map "?
" 'self-insert-command)
8789 (apply 'org-icompleting-read args)))
8791 (defun org-completing-read-no-i (&rest args)
8792 (let (org-completion-use-ido org-completion-use-iswitchb)
8793 (apply 'org-completing-read args)))
8795 (defun org-iswitchb-completing-read (prompt choices &rest args)
8796 "Use iswitch as a completing-read replacement to choose from choices.
8797 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8799 (let* ((iswitchb-use-virtual-buffers nil)
8800 (iswitchb-make-buflist-hook
8802 (setq iswitchb-temp-buflist choices))))
8803 (iswitchb-read-buffer prompt)))
8805 (defun org-icompleting-read (&rest args)
8806 "Completing-read using
`ido-mode
' or
`iswitchb
' speedups if available.
"
8807 (org-without-partial-completion
8808 (if (and org-completion-use-ido
8809 (fboundp 'ido-completing-read)
8810 (boundp 'ido-mode) ido-mode
8811 (listp (second args)))
8812 (let ((ido-enter-matching-directory nil))
8813 (apply 'ido-completing-read (concat (car args))
8814 (if (consp (car (nth 1 args)))
8815 (mapcar (lambda (x) (car x)) (nth 1 args))
8818 (if (and org-completion-use-iswitchb
8819 (boundp 'iswitchb-mode) iswitchb-mode
8820 (listp (second args)))
8821 (apply 'org-iswitchb-completing-read (concat (car args))
8822 (if (consp (car (nth 1 args)))
8823 (mapcar (lambda (x) (car x)) (nth 1 args))
8826 (apply 'completing-read args)))))
8828 (defun org-extract-attributes (s)
8829 "Extract the attributes cookie from a string and set as text property.
"
8830 (let (a attr (start 0) key value)
8832 (when (string-match "{{\\([^
}]+\\)}}$
" s)
8833 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8834 (while (string-match "\\([a-zA-Z
]+\\)=\"\\([^
\"]*\\)\"" a start)
8835 (setq key (match-string 1 a) value (match-string 2 a)
8837 attr (plist-put attr (intern key) value))))
8838 (org-add-props s nil 'org-attr attr))
8841 (defun org-extract-attributes-from-string (tag)
8842 (let (key value attr)
8843 (while (string-match "\\([a-zA-Z
]+\\)=\"\\([^
\"]*\\)\"\\s-?
" tag)
8844 (setq key (match-string 1 tag) value (match-string 2 tag)
8845 tag (replace-match "" t t tag)
8846 attr (plist-put attr (intern key) value)))
8849 (defun org-attributes-to-string (plist)
8850 "Format a property list into an HTML attribute list.
"
8851 (let ((s "") key value)
8853 (setq key (pop plist) value (pop plist))
8855 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8858 ;;; Opening/following a link
8860 (defvar org-link-search-failed nil)
8862 (defvar org-open-link-functions nil
8863 "Hook for functions finding a plain text link.
8864 These functions must take a single argument
, the link content.
8865 They will be called for links that look like
[[link text
][description]]
8866 when LINK TEXT does not have a protocol like \"http:\" and does not look
8867 like a filename (e.g. \"./blue.png\").
8869 These functions will be called *before* Org attempts to resolve the
8870 link by doing text searches in the current buffer - so if you want a
8871 link \"[[target]]\" to still find \"<<target>>\", your function should
8872 handle this as a special case.
8874 When the function does handle the link, it must return a non-nil value.
8875 If it decides that it is not responsible for this link, it must return
8876 nil to indicate that that Org-mode can continue with other options
8877 like exact and fuzzy text search.")
8879 (defun org-next-link ()
8880 "Move forward to the next link.
8881 If the link is in hidden text, expose it."
8883 (when (and org-link-search-failed (eq this-command last-command))
8884 (goto-char (point-min))
8885 (message "Link search wrapped back to beginning of buffer"))
8886 (setq org-link-search-failed nil)
8887 (let* ((pos (point))
8889 (a (assoc :link ct)))
8890 (if a (goto-char (nth 2 a)))
8891 (if (re-search-forward org-any-link-re nil t)
8893 (goto-char (match-beginning 0))
8894 (if (org-invisible-p) (org-show-context)))
8896 (setq org-link-search-failed t)
8897 (error "No further link found"))))
8899 (defun org-previous-link ()
8900 "Move backward to the previous link.
8901 If the link is in hidden text, expose it."
8903 (when (and org-link-search-failed (eq this-command last-command))
8904 (goto-char (point-max))
8905 (message "Link search wrapped back to end of buffer"))
8906 (setq org-link-search-failed nil)
8907 (let* ((pos (point))
8909 (a (assoc :link ct)))
8910 (if a (goto-char (nth 1 a)))
8911 (if (re-search-backward org-any-link-re nil t)
8913 (goto-char (match-beginning 0))
8914 (if (org-invisible-p) (org-show-context)))
8916 (setq org-link-search-failed t)
8917 (error "No further link found"))))
8919 (defun org-translate-link (s)
8920 "Translate a link string if a translation function has been defined."
8921 (if (and org-link-translation-function
8922 (fboundp org-link-translation-function)
8923 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8925 (setq s (funcall org-link-translation-function
8926 (match-string 1) (match-string 2)))
8927 (concat (car s) ":" (cdr s)))
8930 (defun org-translate-link-from-planner (type path)
8931 "Translate a link from Emacs Planner syntax so that Org can follow it.
8932 This is still an experimental function, your mileage may vary."
8934 ((member type '("http" "https" "news" "ftp"))
8935 ;; standard Internet links are the same.
8937 ((and (equal type "irc") (string-match "^//" path))
8938 ;; Planner has two / at the beginning of an irc link, we have 1.
8939 ;; We should have zero, actually....
8940 (setq path (substring path 1)))
8941 ((and (equal type "lisp") (string-match "^/" path))
8942 ;; Planner has a slash, we do not.
8943 (setq type "elisp" path (substring path 1)))
8944 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8945 ;; A typical message link. Planner has the id after the final slash,
8946 ;; we separate it with a hash mark
8947 (setq path (concat (match-string 1 path) "#"
8948 (org-remove-angle-brackets (match-string 2 path)))))
8952 (defun org-find-file-at-mouse (ev)
8953 "Open file link or URL at mouse."
8955 (mouse-set-point ev)
8956 (org-open-at-point 'in-emacs))
8958 (defun org-open-at-mouse (ev)
8959 "Open file link or URL at mouse."
8961 (mouse-set-point ev)
8962 (if (eq major-mode 'org-agenda-mode)
8963 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8964 (org-open-at-point))
8966 (defvar org-window-config-before-follow-link nil
8967 "The window configuration before following a link.
8968 This is saved in case the need arises to restore it.")
8970 (defvar org-open-link-marker (make-marker)
8971 "Marker pointing to the location where `org-open-at-point; was called.")
8974 (defun org-open-at-point-global ()
8975 "Follow a link like Org-mode does.
8976 This command can be called in any mode to follow a link that has
8979 (org-run-like-in-org-mode 'org-open-at-point))
8982 (defun org-open-link-from-string (s &optional arg reference-buffer)
8983 "Open a link in the string S, as if it was in Org-mode."
8984 (interactive "sLink: \nP")
8985 (let ((reference-buffer (or reference-buffer (current-buffer))))
8987 (let ((org-inhibit-startup t))
8990 (goto-char (point-min))
8991 (when reference-buffer
8992 (setq org-link-abbrev-alist-local
8993 (with-current-buffer reference-buffer
8994 org-link-abbrev-alist-local)))
8995 (org-open-at-point arg reference-buffer)))))
8997 (defvar org-open-at-point-functions nil
8998 "Hook that is run when following a link at point.
9000 Functions in this hook must return t if they identify and follow
9001 a link at point. If they don't find anything interesting at point,
9002 they must return nil.")
9004 (defun org-open-at-point (&optional in-emacs reference-buffer)
9005 "Open link at or after point.
9006 If there is no link at point, this function will search forward up to
9007 the end of the current line.
9008 Normally, files will be opened by an appropriate application. If the
9009 optional argument IN-EMACS is non-nil, Emacs will visit the file.
9010 With a double prefix argument, try to open outside of Emacs, in the
9011 application the system uses for this file type."
9013 ;; if in a code block, then open the block's results
9014 (unless (call-interactively #'org-babel-open-src-block-result)
9015 (org-load-modules-maybe)
9016 (move-marker org-open-link-marker (point))
9017 (setq org-window-config-before-follow-link (current-window-configuration))
9018 (org-remove-occur-highlights nil nil t)
9020 ((and (org-on-heading-p)
9022 (concat org-plain-link-re "\\|"
9023 org-bracket-link-regexp "\\|"
9024 org-angle-link-re "\\|"
9025 "[ \t]:[^ \t\n]+:[ \t]*$")))
9026 (not (get-text-property (point) 'org-linked-text)))
9027 (or (org-offer-links-in-entry in-emacs)
9028 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9029 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9030 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9031 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9032 (org-footnote-action))
9034 (let (type path link line search (pos (point)))
9037 (skip-chars-forward "^]\n\r")
9038 (when (org-in-regexp org-bracket-link-regexp 1)
9039 (setq link (org-extract-attributes
9040 (org-link-unescape (org-match-string-no-properties 1))))
9041 (while (string-match " *\n *" link)
9042 (setq link (replace-match " " t t link)))
9043 (setq link (org-link-expand-abbrev link))
9045 ((or (file-name-absolute-p link)
9046 (string-match "^\\.\\.?/" link))
9047 (setq type "file" path link))
9048 ((string-match org-link-re-with-space3 link)
9049 (setq type (match-string 1 link) path (match-string 2 link)))
9050 (t (setq type "thisfile" path link)))
9053 (when (get-text-property (point) 'org-linked-text)
9054 (setq type "thisfile"
9055 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9056 (1+ (point)) (point))
9057 path (buffer-substring
9058 (previous-single-property-change pos 'org-linked-text)
9059 (next-single-property-change pos 'org-linked-text)))
9063 (when (or (org-in-regexp org-angle-link-re)
9064 (org-in-regexp org-plain-link-re))
9065 (setq type (match-string 1) path (match-string 2))
9068 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
9070 path (match-string 1))
9071 (while (string-match ":" path)
9072 (setq path (replace-match "+" t t path)))
9074 (when (org-in-regexp "<\\([^><\n]+\\)>")
9075 (setq type "tree-match"
9076 path (match-string 1))
9079 (error "No link found"))
9081 ;; switch back to reference buffer
9082 ;; needed when if called in a temporary buffer through
9083 ;; org-open-link-from-string
9084 (with-current-buffer (or reference-buffer (current-buffer))
9086 ;; Remove any trailing spaces in path
9087 (if (string-match " +\\'" path)
9088 (setq path (replace-match "" t t path)))
9089 (if (and org-link-translation-function
9090 (fboundp org-link-translation-function))
9091 ;; Check if we need to translate the link
9092 (let ((tmp (funcall org-link-translation-function type path)))
9093 (setq type (car tmp) path (cdr tmp))))
9097 ((assoc type org-link-protocols)
9098 (funcall (nth 1 (assoc type org-link-protocols)) path))
9100 ((equal type "mailto")
9101 (let ((cmd (car org-link-mailto-program))
9102 (args (cdr org-link-mailto-program)) args1
9103 (address path) (subject "") a)
9104 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9105 (setq address (match-string 1 path)
9106 subject (org-link-escape (match-string 2 path))))
9109 ((not (stringp (car args))) (push (pop args) args1))
9110 (t (setq a (pop args))
9111 (if (string-match "%a" a)
9112 (setq a (replace-match address t t a)))
9113 (if (string-match "%s" a)
9114 (setq a (replace-match subject t t a)))
9116 (apply cmd (nreverse args1))))
9118 ((member type '("http" "https" "ftp" "news"))
9119 (browse-url (concat type ":" (org-link-escape
9120 path org-link-escape-chars-browser))))
9122 ((string= type "doi")
9123 (browse-url (concat "http://dx.doi.org/"
9125 path org-link-escape-chars-browser))))
9127 ((member type '("message"))
9128 (browse-url (concat type ":" path)))
9130 ((string= type "tags")
9131 (org-tags-view in-emacs path))
9133 ((string= type "tree-match")
9134 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9136 ((string= type "file")
9137 (if (string-match "::\\([0-9]+\\)\\'" path)
9138 (setq line (string-to-number (match-string 1 path))
9139 path (substring path 0 (match-beginning 0)))
9140 (if (string-match "::\\(.+\\)\\'" path)
9141 (setq search (match-string 1 path)
9142 path (substring path 0 (match-beginning 0)))))
9143 (if (string-match "[*?{]" (file-name-nondirectory path))
9145 (org-open-file path in-emacs line search)))
9147 ((string= type "news")
9149 (org-gnus-follow-link path))
9151 ((string= type "shell")
9153 (if (or (not org-confirm-shell-link-function)
9154 (funcall org-confirm-shell-link-function
9155 (format "Execute \"%s\" in shell? "
9156 (org-add-props cmd nil
9157 'face 'org-warning))))
9159 (message "Executing %s" cmd)
9160 (shell-command cmd))
9163 ((string= type "elisp")
9165 (if (or (not org-confirm-elisp-link-function)
9166 (funcall org-confirm-elisp-link-function
9167 (format "Execute \"%s\" as elisp? "
9168 (org-add-props cmd nil
9169 'face 'org-warning))))
9170 (message "%s => %s" cmd
9171 (if (equal (string-to-char cmd) ?\()
9173 (call-interactively (read cmd))))
9176 ((and (string= type "thisfile")
9177 (run-hook-with-args-until-success
9178 'org-open-link-functions path)))
9180 ((string= type "thisfile")
9182 (switch-to-buffer-other-window
9183 (org-get-buffer-for-internal-link (current-buffer)))
9184 (org-mark-ring-push))
9185 (let ((cmd `(org-link-search
9187 ,(cond ((equal in-emacs '(4)) 'occur)
9188 ((equal in-emacs '(16)) 'org-occur)
9191 (condition-case nil (eval cmd)
9192 (error (progn (widen) (eval cmd))))))
9195 (browse-url-at-point)))))))
9196 (move-marker org-open-link-marker nil)
9197 (run-hook-with-args 'org-follow-link-hook)))
9199 (defun org-offer-links-in-entry (&optional nth zero)
9200 "Offer links in the current entry and follow the selected link.
9201 If there is only one link, follow it immediately as well.
9202 If NTH is an integer, immediately pick the NTH link found.
9203 If ZERO is a string, check also this string for a link, and if
9204 there is one, offer it as link number zero."
9205 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9206 "\\(" org-angle-link-re "\\)\\|"
9207 "\\(" org-plain-link-re "\\)"))
9209 (in-emacs (if (integerp nth) nil nth))
9210 have-zero end links link c)
9211 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9212 (push (match-string 0 zero) links)
9213 (setq cnt (1- cnt) have-zero t))
9215 (org-back-to-heading t)
9216 (setq end (save-excursion (outline-next-heading) (point)))
9217 (while (re-search-forward re end t)
9218 (push (match-string 0) links))
9219 (setq links (org-uniquify (reverse links))))
9223 (message "No links"))
9224 ((equal (length links) 1)
9225 (setq link (list (car links))))
9226 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9227 (setq link (nth (if have-zero nth (1- nth)) links)))
9228 (t ; we have to select a link
9230 (save-window-excursion
9231 (delete-other-windows)
9232 (with-output-to-temp-buffer "*Select Link*"
9234 (if (not (string-match org-bracket-link-regexp l))
9235 (princ (format "[%c] %s\n" (incf cnt)
9236 (org-remove-angle-brackets l)))
9238 (princ (format "[%c] %s (%s)\n" (incf cnt)
9239 (match-string 3 l) (match-string 1 l)))
9240 (princ (format "[%c] %s\n" (incf cnt)
9241 (match-string 1 l))))))
9243 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9244 (message "Select link to open, RET to open all:")
9245 (setq c (read-char-exclusive))
9246 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9247 (when (equal c ?q) (error "Abort"))
9251 (if have-zero (setq nth (1+ nth)))
9252 (unless (and (integerp nth) (>= (length links) nth))
9253 (error "Invalid link selection"))
9254 (setq link (list (nth (1- nth) links))))))
9256 (let ((buf (current-buffer)))
9258 (org-open-link-from-string l in-emacs buf))
9262 ;; Add special file links that specify the way of opening
9264 (org-add-link-type "file+sys" 'org-open-file-with-system)
9265 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9266 (defun org-open-file-with-system (path)
9267 "Open file at PATH using the system way of opening it."
9268 (org-open-file path 'system))
9269 (defun org-open-file-with-emacs (path)
9270 "Open file at PATH in Emacs."
9271 (org-open-file path 'emacs))
9272 (defun org-remove-file-link-modifiers ()
9273 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9274 (goto-char (point-min))
9275 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9277 (replace-match "file:" t t))))
9278 (eval-after-load "org-exp"
9279 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9280 'org-remove-file-link-modifiers))
9284 (defun org-get-effort (&optional pom)
9285 "Get the effort estimate for the current entry."
9286 (org-entry-get pom org-effort-property))
9290 (defvar org-create-file-search-functions nil
9291 "List of functions to construct the right search string for a file link.
9292 These functions are called in turn with point at the location to
9293 which the link should point.
9295 A function in the hook should first test if it would like to
9296 handle this file type, for example by checking the `major-mode'
9297 or the file extension. If it decides not to handle this file, it
9298 should just return nil to give other functions a chance. If it
9299 does handle the file, it must return the search string to be used
9300 when following the link. The search string will be part of the
9301 file link, given after a double colon, and `org-open-at-point'
9302 will automatically search for it. If special measures must be
9303 taken to make the search successful, another function should be
9304 added to the companion hook `org-execute-file-search-functions',
9307 A function in this hook may also use `setq' to set the variable
9308 `description' to provide a suggestion for the descriptive text to
9309 be used for this link when it gets inserted into an Org-mode
9310 buffer with \\[org-insert-link].")
9312 (defvar org-execute-file-search-functions nil
9313 "List of functions to execute a file search triggered by a link.
9315 Functions added to this hook must accept a single argument, the
9316 search string that was part of the file link, the part after the
9317 double colon. The function must first check if it would like to
9318 handle this search, for example by checking the `major-mode' or
9319 the file extension. If it decides not to handle this search, it
9320 should just return nil to give other functions a chance. If it
9321 does handle the search, it must return a non-nil value to keep
9322 other functions from trying.
9324 Each function can access the current prefix argument through the
9325 variable `current-prefix-argument'. Note that a single prefix is
9326 used to force opening a link in Emacs, so it may be good to only
9327 use a numeric or double prefix to guide the search function.
9329 In case this is needed, a function in this hook can also restore
9330 the window configuration before `org-open-at-point' was called using:
9332 (set-window-configuration org-window-config-before-follow-link)")
9334 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9335 (defun org-link-search (s &optional type avoid-pos)
9336 "Search for a link search option.
9337 If S is surrounded by forward slashes, it is interpreted as a
9338 regular expression. In org-mode files, this will create an `org-occur'
9339 sparse tree. In ordinary files, `occur' will be used to list matches.
9340 If the current buffer is in `dired-mode', grep will be used to search
9341 in all files. If AVOID-POS is given, ignore matches near that position."
9342 (let ((case-fold-search t)
9343 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9344 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9345 (append '(("") (" ") ("\t") ("\n"))
9349 (pre nil) (post nil)
9350 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9352 ;; First check if there are any special search functions
9353 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9354 ;; Now try the builtin stuff
9355 ((and (equal (string-to-char s0) ?#)
9358 (goto-char (point-min))
9361 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9362 (setq type 'dedicated
9363 pos (match-beginning 0))))
9364 ;; There is an exact target for this
9366 (org-back-to-heading t)))
9368 (goto-char (point-min))
9371 (concat "<<" (regexp-quote s0) ">>") nil t)
9372 (setq type 'dedicated
9373 pos (match-beginning 0))))
9374 ;; There is an exact target for this
9376 ((and (string-match "^(\\(.*\\))$" s0)
9378 (goto-char (point-min))
9381 (concat "[^[]" (regexp-quote
9382 (format org-coderef-label-format
9383 (match-string 1 s0))))
9385 (setq type 'dedicated
9386 pos (1+ (match-beginning 0))))))
9387 ;; There is a coderef target for this
9389 ((string-match "^/\\(.*\\)/$" s)
9390 ;; A regular expression
9393 (org-occur (match-string 1 s)))
9394 ;;((eq major-mode 'dired-mode)
9395 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9396 (t (org-do-occur (match-string 1 s)))))
9397 ((and (org-mode-p) org-link-search-must-match-exact-headline)
9398 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9399 (goto-char (point-min))
9401 ((let (case-fold-search)
9402 (re-search-forward (format org-complex-heading-regexp-format
9405 ;; OK, found a match
9406 (goto-char (match-beginning 0)))
9407 ((and (not org-link-search-inhibit-query)
9408 (eq org-link-search-must-match-exact-headline 'query-to-create)
9409 (y-or-n-p "No match - create this as a new heading? "))
9410 (goto-char (point-max))
9411 (or (bolp) (newline))
9412 (insert "* " s "\n")
9413 (beginning-of-line 0))
9416 (error "No match"))))
9418 ;; A normal search string
9419 (when (equal (string-to-char s) ?*)
9420 ;; Anchor on headlines, post may include tags.
9421 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9422 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
9424 (remove-text-properties
9426 '(face nil mouse-face nil keymap nil fontified nil) s)
9427 ;; Make a series of regular expressions to find a match
9428 (setq words (org-split-string s "[ \n\r\t]+")
9430 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9431 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9433 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9434 re2a (concat "[ \t\r\n]" re2a_)
9435 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9436 re4 (concat "[^a-zA-Z_]" re4_)
9438 re1 (concat pre re2 post)
9439 re3 (concat pre (if pre re4_ re4) post)
9440 re5 (concat pre ".*" re4)
9441 re2 (concat pre re2)
9442 re2a (concat pre (if pre re2a_ re2a))
9443 re4 (concat pre (if pre re4_ re4))
9444 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9445 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9449 ((eq type 'org-occur) (org-occur reall))
9450 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9451 (t (goto-char (point-min))
9453 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9454 (org-search-not-self 1 re1 nil t)
9455 (org-search-not-self 1 re2 nil t)
9456 (org-search-not-self 1 re2a nil t)
9457 (org-search-not-self 1 re3 nil t)
9458 (org-search-not-self 1 re4 nil t)
9459 (org-search-not-self 1 re5 nil t)
9461 (goto-char (match-beginning 1))
9463 (error "No match"))))))
9464 (and (org-mode-p) (org-show-context 'link-search))
9467 (defun org-search-not-self (group &rest args)
9468 "Execute `re-search-forward', but only accept matches that do not
9469 enclose the position of `org-open-link-marker'."
9470 (let ((m org-open-link-marker))
9472 (while (apply 're-search-forward args)
9473 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9474 (goto-char (match-end group))
9475 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9476 (> (match-beginning 0) (marker-position m))
9477 (< (match-end 0) (marker-position m)))
9479 (or (not (org-in-regexp
9480 org-bracket-link-analytic-regexp 1))
9481 (not (match-end 4)) ; no description
9482 (and (<= (match-beginning 4) (point))
9483 (>= (match-end 4) (point))))))
9484 (throw 'exit (point))))))))
9486 (defun org-get-buffer-for-internal-link (buffer)
9487 "Return a buffer to be used for displaying the link target of internal links."
9489 ((not org-display-internal-link-with-indirect-buffer)
9491 ((string-match "(Clone)$" (buffer-name buffer))
9492 (message "Buffer is already a clone, not making another one")
9493 ;; we also do not modify visibility in this case
9495 (t ; make a new indirect buffer for displaying the link
9496 (let* ((bn (buffer-name buffer))
9497 (ibn (concat bn "(Clone)"))
9498 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9499 (with-current-buffer ib (org-overview))
9502 (defun org-do-occur (regexp &optional cleanup)
9503 "Call the Emacs command `occur'.
9504 If CLEANUP is non-nil, remove the printout of the regular expression
9505 in the *Occur* buffer. This is useful if the regex is long and not useful
9509 (let ((cwin (selected-window)) win beg end)
9510 (when (setq win (get-buffer-window "*Occur*"))
9511 (select-window win))
9512 (goto-char (point-min))
9513 (when (re-search-forward "match[a-z]+" nil t)
9514 (setq beg (match-end 0))
9515 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9516 (setq end (1- (match-beginning 0)))))
9517 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9518 (goto-char (point-min))
9519 (select-window cwin))))
9521 ;;; The mark ring for links jumps
9523 (defvar org-mark-ring nil
9524 "Mark ring for positions before jumps in Org-mode.")
9525 (defvar org-mark-ring-last-goto nil
9526 "Last position in the mark ring used to go back.")
9527 ;; Fill and close the ring
9528 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9529 (loop for i from 1 to org-mark-ring-length do
9530 (push (make-marker) org-mark-ring))
9531 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9534 (defun org-mark-ring-push (&optional pos buffer)
9535 "Put the current position or POS into the mark ring and rotate it."
9537 (setq pos (or pos (point)))
9538 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9539 (move-marker (car org-mark-ring)
9541 (or buffer (current-buffer)))
9543 (substitute-command-keys
9544 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9546 (defun org-mark-ring-goto (&optional n)
9547 "Jump to the previous position in the mark ring.
9548 With prefix arg N, jump back that many stored positions. When
9549 called several times in succession, walk through the entire ring.
9550 Org-mode commands jumping to a different position in the current file,
9551 or to another Org-mode file, automatically push the old position
9555 (if (eq last-command this-command)
9556 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9557 (setq p org-mark-ring))
9558 (setq org-mark-ring-last-goto p)
9560 (switch-to-buffer (marker-buffer m))
9562 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9564 (defun org-remove-angle-brackets (s)
9565 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9566 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9568 (defun org-add-angle-brackets (s)
9569 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9570 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9572 (defun org-remove-double-quotes (s)
9573 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9574 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9577 ;;; Following specific links
9579 (defun org-follow-timestamp-link ()
9581 ((org-at-date-range-p t)
9582 (let ((org-agenda-start-on-weekday)
9583 (t1 (match-string 1))
9584 (t2 (match-string 2)))
9585 (setq t1 (time-to-days (org-time-string-to-time t1))
9586 t2 (time-to-days (org-time-string-to-time t2)))
9587 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9588 ((org-at-timestamp-p t)
9589 (org-agenda-list nil (time-to-days (org-time-string-to-time
9590 (substring (match-string 1) 0 10)))
9592 (t (error "This should not happen"))))
9595 ;;; Following file links
9596 (defvar org-wait nil)
9597 (defun org-open-file (path &optional in-emacs line search)
9598 "Open the file at PATH.
9599 First, this expands any special file name abbreviations. Then the
9600 configuration variable `org-file-apps' is checked if it contains an
9601 entry for this file type, and if yes, the corresponding command is launched.
9603 If no application is found, Emacs simply visits the file.
9605 With optional prefix argument IN-EMACS, Emacs will visit the file.
9606 With a double \\[universal-argument] \\[universal-argument] \
9607 prefix arg, Org tries to avoid opening in Emacs
9608 and to use an external application to visit the file.
9610 Optional LINE specifies a line to go to, optional SEARCH a string
9611 to search for. If LINE or SEARCH is given, the file will be
9612 opened in Emacs, unless an entry from org-file-apps that makes
9613 use of groups in a regexp matches.
9614 If the file does not exist, an error is thrown."
9615 (let* ((file (if (equal path "")
9617 (substitute-in-file-name (expand-file-name path))))
9618 (file-apps (append org-file-apps (org-default-apps)))
9619 (apps (org-remove-if
9620 'org-file-apps-entry-match-against-dlink-p file-apps))
9621 (apps-dlink (org-remove-if-not
9622 'org-file-apps-entry-match-against-dlink-p file-apps))
9623 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9624 (dirp (if remp nil (file-directory-p file)))
9625 (file (if (and dirp org-open-directory-means-index-dot-org)
9626 (concat (file-name-as-directory file) "index.org")
9628 (a-m-a-p (assq 'auto-mode apps))
9629 (dfile (downcase file))
9630 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9631 (link (cond ((and (eq line nil)
9635 (concat file "::" (number-to-string line)))
9637 (concat file "::" search))))
9638 (dlink (downcase link))
9639 (old-buffer (current-buffer))
9641 (old-mode major-mode)
9642 ext cmd link-match-data)
9643 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9644 (setq ext (match-string 1 dfile))
9645 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9646 (setq ext (match-string 1 dfile))))
9648 ((member in-emacs '((16) system))
9649 (setq cmd (cdr (assoc 'system apps))))
9650 (in-emacs (setq cmd 'emacs))
9652 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9653 (and dirp (cdr (assoc 'directory apps)))
9654 ; first, try matching against apps-dlink
9655 ; if we get a match here, store the match data for later
9656 (let ((match (assoc-default dlink apps-dlink
9659 (progn (setq link-match-data (match-data))
9661 (progn (setq in-emacs (or in-emacs line search))
9662 nil))) ; if we have no match in apps-dlink,
9663 ; always open the file in emacs if line or search
9664 ; is given (for backwards compatibility)
9665 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
9667 (cdr (assoc ext apps))
9668 (cdr (assoc t apps))))))
9669 (when (eq cmd 'system)
9670 (setq cmd (cdr (assoc 'system apps))))
9671 (when (eq cmd 'default)
9672 (setq cmd (cdr (assoc t apps))))
9673 (when (eq cmd 'mailcap)
9675 (mailcap-parse-mailcaps)
9676 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9677 (command (mailcap-mime-info mime-type)))
9678 (if (stringp command)
9680 (setq cmd 'emacs))))
9681 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9682 (not (file-exists-p file))
9683 (not org-open-non-existing-files))
9684 (error "No such file: %s" file))
9686 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9687 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9688 (while (string-match "['\"]%s['\"]" cmd)
9689 (setq cmd (replace-match "%s" t t cmd)))
9690 (while (string-match "%s" cmd)
9691 (setq cmd (replace-match
9693 (shell-quote-argument
9694 (convert-standard-filename file)))
9697 ;; Replace "%1", "%2" etc. in command with group matches from regex
9699 (let ((match-index 1)
9700 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9701 (set-match-data link-match-data)
9702 (while (<= match-index number-of-groups)
9703 (let ((regex (concat "%" (number-to-string match-index)))
9704 (replace-with (match-string match-index dlink)))
9705 (while (string-match regex cmd)
9706 (setq cmd (replace-match replace-with t t cmd))))
9707 (setq match-index (+ match-index 1)))))
9709 (save-window-excursion
9710 (start-process-shell-command cmd nil cmd)
9711 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9715 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9717 (if line (org-goto-line line)
9718 (if search (org-link-search search))))
9720 (let ((file (convert-standard-filename file)))
9722 (set-match-data link-match-data)
9724 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9725 (and (org-mode-p) (eq old-mode 'org-mode)
9726 (or (not (equal old-buffer (current-buffer)))
9727 (not (equal old-pos (point))))
9728 (org-mark-ring-push old-pos old-buffer))))
9730 (defun org-file-apps-entry-match-against-dlink-p (entry)
9731 "This function returns non-nil if `entry' uses a regular
9732 expression which should be matched against the whole link by
9735 It assumes that is the case when the entry uses a regular
9736 expression which has at least one grouping construct and the
9737 action is either a lisp form or a command string containing
9738 '%1', i.e. using at least one subexpression match as a
9740 (let ((selector (car entry))
9741 (action (cdr entry)))
9742 (if (stringp selector)
9743 (and (> (regexp-opt-depth selector) 0)
9744 (or (and (stringp action)
9745 (string-match "%[0-9]" action))
9749 (defun org-default-apps ()
9750 "Return the default applications for this operating system."
9752 ((eq system-type 'darwin)
9753 org-file-apps-defaults-macosx)
9754 ((eq system-type 'windows-nt)
9755 org-file-apps-defaults-windowsnt)
9756 (t org-file-apps-defaults-gnu)))
9758 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9759 "Convert extensions to regular expressions in the cars of LIST.
9760 Also, weed out any non-string entries, because the return value is used
9761 only for regexp matching.
9762 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9763 point to the symbol `emacs', indicating that the file should
9764 be opened in Emacs."
9768 (if (not (stringp (car x)))
9770 (if (string-match "\\W" (car x))
9772 (cons (concat "\\." (car x) "\\'") (cdr x)))))
9775 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9777 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9778 (defun org-file-remote-p (file)
9779 "Test whether FILE specifies a location on a remote system.
9780 Return non-nil if the location is indeed remote.
9782 For example, the filename \"/user@host:/foo\" specifies a location
9783 on the system \"/user@host:\"."
9784 (cond ((fboundp 'file-remote-p)
9785 (file-remote-p file))
9786 ((fboundp 'tramp-handle-file-remote-p)
9787 (tramp-handle-file-remote-p file))
9788 ((and (boundp 'ange-ftp-name-format)
9789 (string-match (car ange-ftp-name-format) file))
9796 (defun org-get-org-file ()
9797 "Read a filename, with default directory `org-directory'."
9798 (let ((default (or org-default-notes-file remember-data-file)))
9799 (read-file-name (format "File name [%s]: " default)
9800 (file-name-as-directory org-directory)
9803 (defun org-notes-order-reversed-p ()
9804 "Check if the current file should receive notes in reversed order."
9806 ((not org-reverse-note-order) nil)
9807 ((eq t org-reverse-note-order) t)
9808 ((not (listp org-reverse-note-order)) nil)
9810 (let ((all org-reverse-note-order)
9812 (while (setq entry (pop all))
9813 (if (string-match (car entry) buffer-file-name)
9814 (throw 'exit (cdr entry))))
9817 (defvar org-refile-target-table nil
9818 "The list of refile targets, created by `org-refile'.")
9820 (defvar org-agenda-new-buffers nil
9821 "Buffers created to visit agenda files.")
9823 (defvar org-refile-cache nil
9824 "Cache for refile targets.")
9827 (defvar org-refile-markers nil
9828 "All the markers used for caching refile locations.")
9830 (defun org-refile-marker (pos)
9831 "Get a new refile marker, but only if caching is in use."
9832 (if (not org-refile-use-cache)
9834 (let ((m (make-marker)))
9836 (push m org-refile-markers)
9839 (defun org-refile-cache-clear ()
9840 "Clear the refile cache and disable all the markers."
9841 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
9842 (setq org-refile-markers nil)
9843 (setq org-refile-cache nil)
9844 (message "Refile cache has been cleared"))
9846 (defun org-refile-cache-check-set (set)
9847 "Check if all the markers in the cache still have live buffers."
9850 (while (and set (setq marker (nth 3 (pop set))))
9851 ;; if org-refile-use-outline-path is 'file, marker may be nil
9852 (when (and marker (null (marker-buffer marker)))
9853 (message "not found") (sit-for 3)
9857 (defun org-refile-cache-put (set &rest identifiers)
9858 "Push the refile targets SET into the cache, under IDENTIFIERS."
9859 (let* ((key (sha1 (prin1-to-string identifiers)))
9860 (entry (assoc key org-refile-cache)))
9863 (push (cons key set) org-refile-cache))))
9865 (defun org-refile-cache-get (&rest identifiers)
9866 "Retrieve the cached value for refile targets given by IDENTIFIERS."
9868 ((not org-refile-cache) nil)
9869 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
9871 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
9872 org-refile-cache))))
9873 (and set (org-refile-cache-check-set set) set)))))
9875 (defun org-get-refile-targets (&optional default-buffer)
9876 "Produce a table with refile targets."
9877 (let ((case-fold-search nil)
9878 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9879 (entries (or org-refile-targets '((nil . (:level . 1)))))
9880 targets tgs txt re files f desc descre fast-path-p level pos0)
9881 (message "Getting targets...")
9882 (with-current-buffer (or default-buffer (current-buffer))
9883 (while (setq entry (pop entries))
9884 (setq files (car entry) desc (cdr entry))
9885 (setq fast-path-p nil)
9887 ((null files) (setq files (list (current-buffer))))
9888 ((eq files 'org-agenda-files)
9889 (setq files (org-agenda-files 'unrestricted)))
9890 ((and (symbolp files) (fboundp files))
9891 (setq files (funcall files)))
9892 ((and (symbolp files) (boundp files))
9893 (setq files (symbol-value files))))
9894 (if (stringp files) (setq files (list files)))
9896 ((eq (car desc) :tag)
9897 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9898 ((eq (car desc) :todo)
9899 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9900 ((eq (car desc) :regexp)
9901 (setq descre (cdr desc)))
9902 ((eq (car desc) :level)
9903 (setq descre (concat "^\\*\\{" (number-to-string
9904 (if org-odd-levels-only
9905 (1- (* 2 (cdr desc)))
9908 ((eq (car desc) :maxlevel)
9909 (setq fast-path-p t)
9910 (setq descre (concat "^\\*\\{1," (number-to-string
9911 (if org-odd-levels-only
9912 (1- (* 2 (cdr desc)))
9915 (t (error "Bad refiling target description %s" desc)))
9916 (while (setq f (pop files))
9917 (with-current-buffer
9918 (if (bufferp f) f (org-get-agenda-file-buffer f))
9920 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
9922 (if (bufferp f) (setq f (buffer-file-name
9923 (buffer-base-buffer f))))
9924 (setq f (and f (expand-file-name f)))
9925 (if (eq org-refile-use-outline-path 'file)
9926 (push (list (file-name-nondirectory f) f nil nil) tgs))
9930 (goto-char (point-min))
9931 (while (re-search-forward descre nil t)
9932 (goto-char (setq pos0 (point-at-bol)))
9934 (when org-refile-target-verify-function
9936 (or (funcall org-refile-target-verify-function)
9938 (when (looking-at org-complex-heading-regexp)
9939 (setq level (org-reduced-level
9940 (- (match-end 1) (match-beginning 1)))
9941 txt (org-link-display-format (match-string 4))
9942 re (concat "^" (regexp-quote
9946 (if (match-end 5) (setq re (concat
9949 (match-string 5)))))
9950 (setq re (concat re "[ \t]*$"))
9951 (when org-refile-use-outline-path
9952 (setq txt (mapconcat
9955 (if (eq org-refile-use-outline-path
9957 (list (file-name-nondirectory
9959 (buffer-base-buffer))))
9960 (if (eq org-refile-use-outline-path
9962 (list (buffer-file-name
9963 (buffer-base-buffer)))))
9964 (org-get-outline-path fast-path-p
9968 (push (list txt f re (org-refile-marker (point)))
9970 (when (= (point) pos0)
9971 ;; verification function has not moved point
9972 (goto-char (point-at-eol))))))))
9973 (when org-refile-use-cache
9974 (org-refile-cache-put tgs (buffer-file-name) descre))
9975 (setq targets (append tgs targets))
9977 (message "Getting targets...done")
9978 (nreverse targets)))
9980 (defun org-protect-slash (s)
9981 (while (string-match "/" s)
9982 (setq s (replace-match "\\" t t s)))
9985 (defvar org-olpa (make-vector 20 nil))
9987 (defun org-get-outline-path (&optional fastp level heading)
9988 "Return the outline path to the current entry, as a list.
9990 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
9991 routine which makes outline path derivations for an entire file,
9992 avoiding backtracing. Refile target collection makes use of that."
9996 (error "Outline path failure, more than 19 levels"))
9997 (loop for i from level upto 19 do
9998 (aset org-olpa i nil))
10000 (delq nil (append org-olpa nil))
10001 (aset org-olpa level heading)))
10002 (let (rtn case-fold-search)
10006 (while (org-up-heading-safe)
10007 (when (looking-at org-complex-heading-regexp)
10008 (push (org-match-string-no-properties 4) rtn)))
10011 (defun org-format-outline-path (path &optional width prefix)
10012 "Format the outline path PATH for display.
10013 Width is the maximum number of characters that is available.
10014 Prefix is a prefix to be included in the returned string,
10015 such as the file name."
10016 (setq width (or width 79))
10017 (if prefix (setq width (- width (length prefix))))
10020 (let* ((nsteps (length path))
10021 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10022 (maxwidth (if (<= total-width width)
10023 10000 ;; everything fits
10024 ;; we need to shorten the level headings
10025 (/ (- width nsteps) nsteps)))
10026 (org-odd-levels-only nil)
10028 (total (1+ (length prefix))))
10029 (setq maxwidth (max maxwidth 10))
10034 (if (and (= n nsteps) (< maxwidth 10000))
10035 (setq maxwidth (- total-width total)))
10036 (if (< (length h) maxwidth)
10037 (progn (setq total (+ total (length h) 1)) h)
10038 (setq h (substring h 0 (- maxwidth 2))
10039 total (+ total maxwidth 1))
10040 (if (string-match "[ \t]+\\'" h)
10041 (setq h (substring h 0 (match-beginning 0))))
10042 (setq h (concat h "..")))
10043 (org-add-props h nil 'face
10044 (nth (% (1- n) org-n-level-faces)
10049 (defun org-display-outline-path (&optional file current)
10050 "Display the current outline path in the echo area."
10052 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10053 (case-fold-search nil)
10054 (path (and (org-mode-p) (org-get-outline-path))))
10055 (if current (setq path (append path
10057 (org-back-to-heading t)
10058 (if (looking-at org-complex-heading-regexp)
10059 (list (match-string 4)))))))
10061 (org-format-outline-path
10064 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10066 (defvar org-refile-history nil
10067 "History for refiling operations.")
10069 (defvar org-after-refile-insert-hook nil
10070 "Hook run after `org-refile' has inserted its stuff at the new location.
10071 Note that this is still *before* the stuff will be removed from
10072 the *old* location.")
10074 (defvar org-capture-last-stored-marker)
10075 (defun org-refile (&optional goto default-buffer rfloc)
10076 "Move the entry at point to another heading.
10077 The list of target headings is compiled using the information in
10078 `org-refile-targets', which see. This list is created before each use
10079 and will therefore always be up-to-date.
10081 At the target location, the entry is filed as a subitem of the target heading.
10082 Depending on `org-reverse-note-order', the new subitem will either be the
10083 first or the last subitem.
10085 If there is an active region, all entries in that region will be moved.
10086 However, the region must fulfill the requirement that the first heading
10087 is the first one sets the top-level of the moved text - at most siblings
10088 below it are allowed.
10090 With prefix arg GOTO, the command will only visit the target location,
10091 not actually move anything.
10092 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10093 go to the location where the last refiling
10094 operation has put the subtree.
10095 With a prefix argument of `2', refile to the running clock.
10097 RFLOC can be a refile location obtained in a different way.
10099 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10101 If you are using target caching (see `org-refile-use-cache'),
10102 You have to clear the target cache in order to find new targets.
10103 This can be done with a 0 prefix: `C-0 C-c C-w'"
10105 (if (member goto '(0 (64)))
10106 (org-refile-cache-clear)
10107 (let* ((cbuf (current-buffer))
10108 (regionp (org-region-active-p))
10109 (region-start (and regionp (region-beginning)))
10110 (region-end (and regionp (region-end)))
10111 (region-length (and regionp (- region-end region-start)))
10112 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10113 pos it nbuf file re level reversed)
10114 (setq last-command nil)
10116 (goto-char region-start)
10117 (or (bolp) (goto-char (point-at-bol)))
10118 (setq region-start (point))
10119 (unless (org-kill-is-subtree-p
10120 (buffer-substring region-start region-end))
10121 (error "The region is not a (sequence of) subtree(s)")))
10122 (if (equal goto '(16))
10123 (org-refile-goto-last-stored)
10125 (and (equal goto 2)
10126 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10128 (setq it (list (or org-clock-heading "running clock")
10130 (marker-buffer org-clock-hd-marker))
10132 (marker-position org-clock-hd-marker)))
10136 (org-refile-get-location
10137 (if goto "Goto: " "Refile to: ") default-buffer
10138 org-refile-allow-creating-parent-nodes)))))
10139 (setq file (nth 1 it)
10142 (if (and (not goto)
10144 (equal (buffer-file-name) file)
10146 (and (>= pos region-start)
10147 (<= pos region-end))
10148 (and (>= pos (point))
10149 (< pos (save-excursion
10150 (org-end-of-subtree t t))))))
10151 (error "Cannot refile to position inside the tree or region"))
10153 (setq nbuf (or (find-buffer-visiting file)
10154 (find-file-noselect file)))
10157 (switch-to-buffer nbuf)
10159 (org-show-context 'org-goto))
10162 (org-kill-new (buffer-substring region-start region-end))
10163 (org-save-markers-in-region region-start region-end))
10164 (org-copy-subtree 1 nil t))
10165 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10166 (find-file-noselect file)))
10167 (setq reversed (org-notes-order-reversed-p))
10174 (looking-at outline-regexp)
10175 (setq level (org-get-valid-level (funcall outline-level) 1))
10178 (or (outline-next-heading) (point-max))
10179 (or (save-excursion (org-get-next-sibling))
10180 (org-end-of-subtree t t)
10184 (goto-char (point-max))
10185 (goto-char (point-min))
10186 (or (outline-next-heading) (goto-char (point-max)))))
10187 (if (not (bolp)) (newline))
10188 (org-paste-subtree level)
10189 (when org-log-refile
10190 (org-add-log-setup 'refile nil nil 'findpos
10192 (unless (eq org-log-refile 'note)
10193 (save-excursion (org-add-log-note))))
10194 (and org-auto-align-tags (org-set-tags nil t))
10195 (bookmark-set "org-refile-last-stored")
10196 ;; If we are refiling for capture, make sure that the
10197 ;; last-capture pointers point here
10198 (when (org-bound-and-true-p org-refile-for-capture)
10199 (bookmark-set "org-capture-last-stored-marker")
10200 (move-marker org-capture-last-stored-marker (point)))
10201 (if (fboundp 'deactivate-mark) (deactivate-mark))
10202 (run-hooks 'org-after-refile-insert-hook))))
10204 (delete-region (point) (+ (point) region-length))
10206 (when (featurep 'org-inlinetask)
10207 (org-inlinetask-remove-END-maybe))
10208 (setq org-markers-to-move nil)
10209 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10211 (defun org-refile-goto-last-stored ()
10212 "Go to the location where the last refile was stored."
10214 (bookmark-jump "org-refile-last-stored")
10215 (message "This is the location of the last refile"))
10217 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
10218 "Prompt the user for a refile location, using PROMPT."
10219 (let ((org-refile-targets org-refile-targets)
10220 (org-refile-use-outline-path org-refile-use-outline-path))
10221 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
10222 (unless org-refile-target-table
10223 (error "No refile targets"))
10224 (let* ((cbuf (current-buffer))
10225 (partial-completion-mode nil)
10226 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10227 (cfunc (if (and org-refile-use-outline-path
10228 org-outline-path-complete-in-steps)
10229 'org-olpath-completing-read
10230 'org-icompleting-read))
10231 (extra (if org-refile-use-outline-path "/" ""))
10232 (filename (and cfn (expand-file-name cfn)))
10235 (if (and (not (member org-refile-use-outline-path
10236 '(file full-file-path)))
10237 (not (equal filename (nth 1 x))))
10238 (cons (concat (car x) extra " ("
10239 (file-name-nondirectory (nth 1 x)) ")")
10241 (cons (concat (car x) extra) (cdr x))))
10242 org-refile-target-table))
10243 (completion-ignore-case t)
10244 pa answ parent-target child parent old-hist)
10245 (setq old-hist org-refile-history)
10246 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10247 nil 'org-refile-history))
10248 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10251 (when (or (not org-refile-history)
10252 (not (eq old-hist org-refile-history))
10253 (not (equal (car pa) (car org-refile-history))))
10254 (setq org-refile-history
10255 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10257 (cdr org-refile-history))))
10258 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10259 (pop org-refile-history)))
10261 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10263 (setq parent (match-string 1 answ)
10264 child (match-string 2 answ))
10265 (setq parent-target (or (assoc parent tbl)
10266 (assoc (concat parent "/") tbl)))
10267 (when (and parent-target
10268 (or (eq new-nodes t)
10269 (and (eq new-nodes 'confirm)
10270 (y-or-n-p (format "Create new node \"%s\"? "
10272 (org-refile-new-child parent-target child)))
10273 (error "Invalid target location")))))
10275 (defun org-refile-new-child (parent-target child)
10276 "Use refile target PARENT-TARGET to add new CHILD below it."
10277 (unless parent-target
10278 (error "Cannot find parent for new node"))
10279 (let ((file (nth 1 parent-target))
10280 (pos (nth 3 parent-target))
10282 (with-current-buffer (or (find-buffer-visiting file)
10283 (find-file-noselect file))
10289 (goto-char (point-max))
10290 (if (not (bolp)) (newline)))
10291 (when (looking-at outline-regexp)
10292 (setq level (funcall outline-level))
10293 (org-end-of-subtree t t))
10294 (org-back-over-empty-lines)
10295 (insert "\n" (make-string
10296 (if pos (org-get-valid-level level 1) 1) ?*)
10298 (beginning-of-line 0)
10299 (list (concat (car parent-target) "/" child) file "" (point)))))))
10301 (defun org-olpath-completing-read (prompt collection &rest args)
10302 "Read an outline path like a file name."
10303 (let ((thetable collection)
10304 (org-completion-use-ido nil) ; does not work with ido.
10305 (org-completion-use-iswitchb nil)) ; or iswitchb
10307 'org-icompleting-read prompt
10308 (lambda (string predicate &optional flag)
10309 (let (rtn r f (l (length string)))
10313 (try-completion string thetable))
10316 (setq rtn (all-completions string thetable predicate))
10319 (setq r (substring x l))
10320 (if (string-match " ([^)]*)$" x)
10321 (setq f (match-string 0 x))
10323 (if (string-match "/" r)
10324 (concat string (substring r 0 (match-end 0)) f)
10329 (assoc string thetable)))
10333 ;;;; Dynamic blocks
10335 (defun org-find-dblock (name)
10336 "Find the first dynamic block with name NAME in the buffer.
10337 If not found, stay at current position and return nil."
10340 (goto-char (point-min))
10341 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
10343 (match-beginning 0))))
10344 (if pos (goto-char pos))
10347 (defconst org-dblock-start-re
10348 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10349 "Matches the start line of a dynamic block, with parameters.")
10351 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10352 "Matches the end of a dynamic block.")
10354 (defun org-create-dblock (plist)
10355 "Create a dynamic block section, with parameters taken from PLIST.
10356 PLIST must contain a :name entry which is used as name of the block."
10357 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10360 (let ((col (current-column))
10361 (name (plist-get plist :name)))
10362 (insert "#+BEGIN: " name)
10364 (if (eq (car plist) :name)
10365 (setq plist (cddr plist))
10366 (insert " " (prin1-to-string (pop plist)))))
10367 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10368 (beginning-of-line -2)))
10370 (defun org-prepare-dblock ()
10371 "Prepare dynamic block for refresh.
10372 This empties the block, puts the cursor at the insert position and returns
10373 the property list including an extra property :name with the block name."
10374 (unless (looking-at org-dblock-start-re)
10375 (error "Not at a dynamic block"))
10376 (let* ((begdel (1+ (match-end 0)))
10377 (name (org-no-properties (match-string 1)))
10378 (params (append (list :name name)
10379 (read (concat "(" (match-string 3) ")")))))
10381 (beginning-of-line 1)
10382 (skip-chars-forward " \t")
10383 (setq params (plist-put params :indentation-column (current-column))))
10384 (unless (re-search-forward org-dblock-end-re nil t)
10385 (error "Dynamic block not terminated"))
10388 (list :content (buffer-substring
10389 begdel (match-beginning 0)))))
10390 (delete-region begdel (match-beginning 0))
10395 (defun org-map-dblocks (&optional command)
10396 "Apply COMMAND to all dynamic blocks in the current buffer.
10397 If COMMAND is not given, use `org-update-dblock'."
10398 (let ((cmd (or command 'org-update-dblock)))
10400 (goto-char (point-min))
10401 (while (re-search-forward org-dblock-start-re nil t)
10402 (goto-char (match-beginning 0))
10404 (condition-case nil
10406 (error (message "Error during update of dynamic block"))))
10407 (unless (re-search-forward org-dblock-end-re nil t)
10408 (error "Dynamic block not terminated"))))))
10410 (defun org-dblock-update (&optional arg)
10411 "User command for updating dynamic blocks.
10412 Update the dynamic block at point. With prefix ARG, update all dynamic
10413 blocks in the buffer."
10416 (org-update-all-dblocks)
10417 (or (looking-at org-dblock-start-re)
10418 (org-beginning-of-dblock))
10419 (org-update-dblock)))
10421 (defun org-update-dblock ()
10422 "Update the dynamic block at point.
10423 This means to empty the block, parse for parameters and then call
10424 the correct writing function."
10425 (save-window-excursion
10426 (let* ((pos (point))
10427 (line (org-current-line))
10428 (params (org-prepare-dblock))
10429 (name (plist-get params :name))
10430 (indent (plist-get params :indentation-column))
10431 (cmd (intern (concat "org-dblock-write:" name))))
10432 (message "Updating dynamic block `%s' at line %d..." name line)
10433 (funcall cmd params)
10434 (message "Updating dynamic block `%s' at line %d...done" name line)
10436 (when (and indent (> indent 0))
10437 (setq indent (make-string indent ?\ ))
10439 (org-beginning-of-dblock)
10441 (while (not (looking-at org-dblock-end-re))
10443 (beginning-of-line 2))
10444 (when (looking-at org-dblock-end-re)
10445 (and (looking-at "[ \t]+")
10446 (replace-match ""))
10447 (insert indent)))))))
10449 (defun org-beginning-of-dblock ()
10450 "Find the beginning of the dynamic block at point.
10451 Error if there is no such block at point."
10452 (let ((pos (point))
10455 (if (and (re-search-backward org-dblock-start-re nil t)
10456 (setq beg (match-beginning 0))
10457 (re-search-forward org-dblock-end-re nil t)
10458 (> (match-end 0) pos))
10461 (error "Not in a dynamic block"))))
10463 (defun org-update-all-dblocks ()
10464 "Update all dynamic blocks in the buffer.
10465 This function can be used in a hook."
10467 (org-map-dblocks 'org-update-dblock)))
10472 (defconst org-additional-option-like-keywords
10473 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
10474 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
10475 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10476 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
10478 "ORGTBL" "TBLFM:" "TBLNAME:"
10479 "BEGIN_EXAMPLE" "END_EXAMPLE"
10480 "BEGIN_QUOTE" "END_QUOTE"
10481 "BEGIN_VERSE" "END_VERSE"
10482 "BEGIN_CENTER" "END_CENTER"
10483 "BEGIN_SRC" "END_SRC"
10484 "CATEGORY" "COLUMNS"
10490 (defcustom org-structure-template-alist
10492 ("s" "#+begin_src ?\n\n#+end_src"
10493 "<src lang=\"?\">\n\n</src>")
10494 ("e" "#+begin_example\n?\n#+end_example"
10495 "<example>\n?\n</example>")
10496 ("q" "#+begin_quote\n?\n#+end_quote"
10497 "<quote>\n?\n</quote>")
10498 ("v" "#+begin_verse\n?\n#+end_verse"
10499 "<verse>\n?\n/verse>")
10500 ("c" "#+begin_center\n?\n#+end_center"
10501 "<center>\n?\n/center>")
10502 ("l" "#+begin_latex\n?\n#+end_latex"
10503 "<literal style=\"latex\">\n?\n</literal>")
10505 "<literal style=\"latex\">?</literal>")
10506 ("h" "#+begin_html\n?\n#+end_html"
10507 "<literal style=\"html\">\n?\n</literal>")
10509 "<literal style=\"html\">?</literal>")
10510 ("a" "#+begin_ascii\n?\n#+end_ascii")
10512 ("i" "#+include %file ?"
10513 "<include file=%file markup=\"?\">")
10515 "Structure completion elements.
10516 This is a list of abbreviation keys and values. The value gets inserted
10517 if you type `<' followed by the key and then press the completion key,
10518 usually `M-TAB'. %file will be replaced by a file name after prompting
10519 for the file using completion.
10520 There are two templates for each key, the first uses the original Org syntax,
10521 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
10522 the default when the /org-mtags.el/ module has been loaded. See also the
10523 variable `org-mtags-prefer-muse-templates'.
10524 This is an experimental feature, it is undecided if it is going to stay in."
10525 :group 'org-completion
10527 (string :tag "Key")
10528 (string :tag "Template")
10529 (string :tag "Muse Template")))
10531 (defun org-try-structure-completion ()
10532 "Try to complete a structure template before point.
10533 This looks for strings like \"<e\" on an otherwise empty line and
10535 (let ((l (buffer-substring (point-at-bol) (point)))
10537 (when (and (looking-at "[ \t]*$")
10538 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
10539 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
10540 (org-complete-expand-structure-template (+ -1 (point-at-bol)
10541 (match-beginning 1)) a)
10544 (defun org-complete-expand-structure-template (start cell)
10545 "Expand a structure template."
10546 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10547 (rpl (nth (if musep 2 1) cell))
10549 (delete-region start (point))
10550 (when (string-match "\\`#\\+" rpl)
10553 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
10554 (setq ind (buffer-substring (point-at-bol) (point))))
10556 (setq start (point))
10557 (if (string-match "%file" rpl)
10558 (setq rpl (replace-match
10562 (abbreviate-file-name (read-file-name "Include file: ")))
10565 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10566 (concat "\n" ind)))
10568 (if (re-search-backward "\\?" start t) (delete-char 1))))
10571 (defun org-complete (&optional arg)
10572 "Perform completion on word at point.
10573 At the beginning of a headline, this completes TODO keywords as given in
10574 `org-todo-keywords'.
10575 If the current word is preceded by a backslash, completes the TeX symbols
10576 that are supported for HTML support.
10577 If the current word is preceded by \"#+\", completes special words for
10578 setting file options.
10579 In the line after \"#+STARTUP:, complete valid keywords.\"
10580 At all other locations, this simply calls the value of
10581 `org-completion-fallback-command'."
10583 (org-without-partial-completion
10587 (beg1 (save-excursion
10588 (skip-chars-backward (org-re "[:alnum:]_@"))
10590 (beg (save-excursion
10591 (skip-chars-backward "a-zA-Z0-9_:$")
10593 (confirm (lambda (x) (stringp (car x))))
10594 (searchhead (equal (char-before beg) ?*))
10596 (when (and (member (char-before beg1) '(?. ?<))
10597 (setq a (assoc (buffer-substring beg1 (point))
10598 org-structure-template-alist)))
10599 (org-complete-expand-structure-template (1- beg1) a)
10601 (tag (and (equal (char-before beg1) ?:)
10602 (equal (char-after (point-at-bol)) ?*)))
10603 (prop (and (equal (char-before beg1) ?:)
10604 (not (equal (char-after (point-at-bol)) ?*))))
10605 (texp (equal (char-before beg) ?\\))
10606 (link (equal (char-before beg) ?\[))
10607 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
10610 (startup (string-match "^#\\+STARTUP:.*"
10611 (buffer-substring (point-at-bol) (point))))
10612 (completion-ignore-case opt)
10624 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
10625 (cons (match-string 2 x)
10626 (match-string 1 x))))
10627 (org-split-string (org-get-current-options) "\n")))
10628 (mapcar 'list org-additional-option-like-keywords)))
10630 (setq type :startup)
10631 org-startup-options)
10632 (link (append org-link-abbrev-alist-local
10633 org-link-abbrev-alist))
10636 (append org-entities-user org-entities))
10637 ((string-match "\\`\\*+[ \t]+\\'"
10638 (buffer-substring (point-at-bol) beg))
10640 (mapcar 'list org-todo-keywords-1))
10642 (setq type :searchhead)
10644 (goto-char (point-min))
10645 (while (re-search-forward org-todo-line-regexp nil t)
10647 (org-make-org-heading-search-string
10648 (match-string 3) t))
10651 (tag (setq type :tag beg beg1)
10652 (or org-tag-alist (org-get-buffer-tags)))
10653 (prop (setq type :prop beg beg1)
10654 (mapcar 'list (org-buffer-property-keys nil t t)))
10656 (call-interactively org-completion-fallback-command)
10657 (throw 'exit nil)))))
10658 (pattern (buffer-substring-no-properties beg end))
10659 (completion (try-completion pattern table confirm)))
10660 (cond ((eq completion t)
10661 (if (not (assoc (upcase pattern) table))
10662 (message "Already complete")
10663 (if (and (equal type :opt)
10664 (not (member (car (assoc (upcase pattern) table))
10665 org-additional-option-like-keywords)))
10666 (insert (substring (cdr (assoc (upcase pattern) table))
10668 (if (memq type '(:tag :prop)) (insert ":")))))
10670 (message "Can't find completion for \"%s\"" pattern)
10672 ((not (string= pattern completion))
10673 (delete-region beg end)
10674 (if (string-match " +$" completion)
10675 (setq completion (replace-match "" t t completion)))
10676 (insert completion)
10677 (if (get-buffer-window "*Completions*")
10678 (delete-window (get-buffer-window "*Completions*")))
10679 (if (assoc completion table)
10680 (if (eq type :todo) (insert " ")
10681 (if (memq type '(:tag :prop)) (insert ":"))))
10682 (if (and (equal type :opt) (assoc completion table))
10683 (message "%s" (substitute-command-keys
10684 "Press \\[org-complete] again to insert example settings"))))
10686 (message "Making completion list...")
10687 (let ((list (sort (all-completions pattern table confirm)
10689 (with-output-to-temp-buffer "*Completions*"
10690 (condition-case nil
10691 ;; Protection needed for XEmacs and emacs 21
10692 (display-completion-list list pattern)
10693 (error (display-completion-list list)))))
10694 (message "Making completion list...%s" "done")))))))
10696 ;;;; TODO, DEADLINE, Comments
10698 (defun org-toggle-comment ()
10699 "Change the COMMENT state of an entry."
10702 (org-back-to-heading)
10703 (let (case-fold-search)
10704 (if (looking-at (concat outline-regexp
10705 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10706 (replace-match "" t t nil 1)
10707 (if (looking-at outline-regexp)
10709 (goto-char (match-end 0))
10710 (insert org-comment-string " ")))))))
10712 (defvar org-last-todo-state-is-todo nil
10713 "This is non-nil when the last TODO state change led to a TODO state.
10714 If the last change removed the TODO tag or switched to DONE, then
10717 (defvar org-setting-tags nil) ; dynamically skipped
10719 (defun org-parse-local-options (string var)
10720 "Parse STRING for startup setting relevant for variable VAR."
10721 (let ((rtn (symbol-value var))
10724 (if (or (not string) (not (string-match "\\S-" string)))
10726 (setq opts (delq nil (mapcar (lambda (x)
10727 (setq e (assoc x org-startup-options))
10728 (if (eq (nth 1 e) var) e nil))
10729 (org-split-string string "[ \t]+"))))
10733 (while (setq e (pop opts))
10734 (if (not (nth 3 e))
10735 (setq rtn (nth 2 e))
10736 (if (not (listp rtn)) (setq rtn nil))
10737 (push (nth 2 e) rtn)))
10740 (defvar org-todo-setup-filter-hook nil
10741 "Hook for functions that pre-filter todo specs.
10742 Each function takes a todo spec and returns either nil or the spec
10743 transformed into canonical form." )
10745 (defvar org-todo-get-default-hook nil
10746 "Hook for functions that get a default item for todo.
10747 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10748 nil or a string to be used for the todo mark." )
10750 (defvar org-agenda-headline-snapshot-before-repeat)
10752 (defun org-todo (&optional arg)
10753 "Change the TODO state of an item.
10754 The state of an item is given by a keyword at the start of the heading,
10756 *** TODO Write paper
10759 The different keywords are specified in the variable `org-todo-keywords'.
10760 By default the available states are \"TODO\" and \"DONE\".
10761 So for this example: when the item starts with TODO, it is changed to DONE.
10762 When it starts with DONE, the DONE is removed. And when neither TODO nor
10763 DONE are present, add TODO at the beginning of the heading.
10765 With \\[universal-argument] prefix arg, use completion to determine the new \
10767 With numeric prefix arg, switch to that state.
10768 With a double \\[universal-argument] prefix, switch to the next set of TODO \
10769 keywords (nextset).
10770 With a triple \\[universal-argument] prefix, circumvent any state blocking.
10772 For calling through lisp, arg is also interpreted in the following way:
10773 'none -> empty state
10774 \"\"(empty string) -> switch to empty state
10775 'done -> switch to DONE
10776 'nextset -> switch to the next set of keywords
10777 'previousset -> switch to the previous set of keywords
10778 \"WAITING\" -> switch to the specified keyword, but only if it
10779 really is a member of `org-todo-keywords'."
10781 (if (equal arg '(16)) (setq arg 'nextset))
10782 (let ((org-blocker-hook org-blocker-hook)
10783 (case-fold-search nil))
10784 (when (equal arg '(64))
10785 (setq arg nil org-blocker-hook nil))
10786 (when (and org-blocker-hook
10787 (or org-inhibit-blocking
10788 (org-entry-get nil "NOBLOCKING")))
10789 (setq org-blocker-hook nil))
10792 (org-back-to-heading t)
10793 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10794 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10796 (let* ((match-data (match-data))
10797 (startpos (point-at-bol))
10798 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
10799 (org-log-done org-log-done)
10800 (org-log-repeat org-log-repeat)
10801 (org-todo-log-states org-todo-log-states)
10802 (this (match-string 1))
10803 (hl-pos (match-beginning 0))
10804 (head (org-get-todo-sequence-head this))
10805 (ass (assoc head org-todo-kwd-alist))
10806 (interpret (nth 1 ass))
10807 (done-word (nth 3 ass))
10808 (final-done-word (nth 4 ass))
10809 (last-state (or this ""))
10810 (completion-ignore-case t)
10811 (member (member this org-todo-keywords-1))
10812 (tail (cdr member))
10814 ((and org-todo-key-trigger
10815 (or (and (equal arg '(4))
10816 (eq org-use-fast-todo-selection 'prefix))
10817 (and (not arg) org-use-fast-todo-selection
10818 (not (eq org-use-fast-todo-selection
10820 ;; Use fast selection
10821 (org-fast-todo-selection))
10822 ((and (equal arg '(4))
10823 (or (not org-use-fast-todo-selection)
10824 (not org-todo-key-trigger)))
10825 ;; Read a state with completion
10826 (org-icompleting-read
10827 "State: " (mapcar (lambda(x) (list x))
10828 org-todo-keywords-1)
10832 (if tail (car tail) nil)
10833 (car org-todo-keywords-1)))
10835 (if (equal member org-todo-keywords-1)
10838 (nth (- (length org-todo-keywords-1)
10840 org-todo-keywords-1)
10841 (org-last org-todo-keywords-1))))
10842 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10843 (setq arg nil))) ; hack to fall back to cycling
10845 ;; user or caller requests a specific state
10847 ((equal arg "") nil)
10848 ((eq arg 'none) nil)
10849 ((eq arg 'done) (or done-word (car org-done-keywords)))
10851 (or (car (cdr (member head org-todo-heads)))
10852 (car org-todo-heads)))
10853 ((eq arg 'previousset)
10854 (let ((org-todo-heads (reverse org-todo-heads)))
10855 (or (car (cdr (member head org-todo-heads)))
10856 (car org-todo-heads))))
10857 ((car (member arg org-todo-keywords-1)))
10859 (error "State `%s' not valid in this file" arg))
10860 ((nth (1- (prefix-numeric-value arg))
10861 org-todo-keywords-1))))
10862 ((null member) (or head (car org-todo-keywords-1)))
10863 ((equal this final-done-word) nil) ;; -> make empty
10864 ((null tail) nil) ;; -> first entry
10865 ((memq interpret '(type priority))
10866 (if (eq this-command last-command)
10868 (if (> (length tail) 0)
10869 (or done-word (car org-done-keywords))
10874 (run-hook-with-args-until-success
10875 'org-todo-get-default-hook state last-state)
10877 (next (if state (concat " " state " ") " "))
10878 (change-plist (list :type 'todo-state-change :from this :to state
10879 :position startpos))
10881 (when org-blocker-hook
10882 (setq org-last-todo-state-is-todo
10883 (not (member this org-done-keywords)))
10884 (unless (save-excursion
10886 (run-hook-with-args-until-failure
10887 'org-blocker-hook change-plist)))
10888 (if (interactive-p)
10889 (error "TODO state change from %s to %s blocked" this state)
10891 (message "TODO state change from %s to %s blocked" this state)
10892 (throw 'exit nil))))
10893 (store-match-data match-data)
10894 (replace-match next t t)
10895 (unless (pos-visible-in-window-p hl-pos)
10896 (message "TODO state changed to %s" (org-trim next)))
10898 (setq head (org-get-todo-sequence-head state)
10899 ass (assoc head org-todo-kwd-alist)
10900 interpret (nth 1 ass)
10901 done-word (nth 3 ass)
10902 final-done-word (nth 4 ass)))
10903 (when (memq arg '(nextset previousset))
10904 (message "Keyword-Set %d/%d: %s"
10905 (- (length org-todo-sets) -1
10906 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10907 (length org-todo-sets)
10908 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10909 (setq org-last-todo-state-is-todo
10910 (not (member state org-done-keywords)))
10911 (setq now-done-p (and (member state org-done-keywords)
10912 (not (member this org-done-keywords))))
10913 (and logging (org-local-logging logging))
10914 (when (and (or org-todo-log-states org-log-done)
10915 (not (eq org-inhibit-logging t))
10916 (not (memq arg '(nextset previousset))))
10917 ;; we need to look at recording a time and note
10918 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10919 (nth 2 (assoc this org-todo-log-states))))
10920 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10921 (setq dolog 'time))
10923 (member state org-not-done-keywords)
10924 (not (member this org-not-done-keywords)))
10925 ;; This is now a todo state and was not one before
10926 ;; If there was a CLOSED time stamp, get rid of it.
10927 (org-add-planning-info nil nil 'closed))
10928 (when (and now-done-p org-log-done)
10929 ;; It is now done, and it was not done before
10930 (org-add-planning-info 'closed (org-current-time))
10931 (if (and (not dolog) (eq 'note org-log-done))
10932 (org-add-log-setup 'done state this 'findpos 'note)))
10933 (when (and state dolog)
10934 ;; This is a non-nil state, and we need to log it
10935 (org-add-log-setup 'state state this 'findpos dolog)))
10936 ;; Fixup tag positioning
10937 (org-todo-trigger-tag-changes state)
10938 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10939 (when org-provide-todo-statistics
10940 (org-update-parent-todo-statistics))
10941 (run-hooks 'org-after-todo-state-change-hook)
10942 (if (and arg (not (member state org-done-keywords)))
10943 (setq head (org-get-todo-sequence-head state)))
10944 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10945 ;; Do we need to trigger a repeat?
10947 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10948 ;; This is for the agenda, take a snapshot of the headline.
10950 (setq org-agenda-headline-snapshot-before-repeat
10951 (org-get-heading))))
10952 (org-auto-repeat-maybe state))
10953 ;; Fixup cursor location if close to the keyword
10954 (if (and (outline-on-heading-p)
10956 (save-excursion (beginning-of-line 1)
10957 (looking-at org-todo-line-regexp))
10958 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10960 (goto-char (or (match-end 2) (match-end 1)))
10961 (and (looking-at " ") (just-one-space))))
10962 (when org-trigger-hook
10964 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10966 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10967 "Block turning an entry into a TODO, using the hierarchy.
10968 This checks whether the current task should be blocked from state
10969 changes. Such blocking occurs when:
10971 1. The task has children which are not all in a completed state.
10973 2. A task has a parent with the property :ORDERED:, and there
10974 are siblings prior to the current task with incomplete
10977 3. The parent of the task is blocked because it has siblings that should
10978 be done first, or is child of a block grandparent TODO entry."
10980 (if (not org-enforce-todo-dependencies)
10981 t ; if locally turned off don't block
10983 ;; If this is not a todo state change, or if this entry is already DONE,
10985 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10986 (member (plist-get change-plist :from)
10987 (cons 'done org-done-keywords))
10988 (member (plist-get change-plist :to)
10989 (cons 'todo org-not-done-keywords))
10990 (not (plist-get change-plist :to)))
10991 (throw 'dont-block t))
10992 ;; If this task has children, and any are undone, it's blocked
10994 (org-back-to-heading t)
10995 (let ((this-level (funcall outline-level)))
10996 (outline-next-heading)
10997 (let ((child-level (funcall outline-level)))
10998 (while (and (not (eobp))
10999 (> child-level this-level))
11000 ;; this todo has children, check whether they are all
11002 (if (and (not (org-entry-is-done-p))
11003 (org-entry-is-todo-p))
11004 (throw 'dont-block nil))
11005 (outline-next-heading)
11006 (setq child-level (funcall outline-level))))))
11007 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11008 ;; any previous siblings are undone, it's blocked
11010 (org-back-to-heading t)
11011 (let* ((pos (point))
11012 (parent-pos (and (org-up-heading-safe) (point))))
11013 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11014 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11016 (re-search-forward org-not-done-heading-regexp pos t))
11017 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11018 ;; Search further up the hierarchy, to see if an anchestor is blocked
11020 (goto-char parent-pos)
11021 (if (not (looking-at org-not-done-heading-regexp))
11022 (throw 'dont-block t)) ; do not block, parent is not a TODO
11024 (setq parent-pos (and (org-up-heading-safe) (point)))
11025 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11026 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11028 (re-search-forward org-not-done-heading-regexp pos t))
11029 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11031 (defcustom org-track-ordered-property-with-tag nil
11032 "Should the ORDERED property also be shown as a tag?
11033 The ORDERED property decides if an entry should require subtasks to be
11034 completed in sequence. Since a property is not very visible, setting
11035 this option means that toggling the ORDERED property with the command
11036 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11037 not relevant for the behavior, but it makes things more visible.
11039 Note that toggling the tag with tags commands will not change the property
11040 and therefore not influence behavior!
11042 This can be t, meaning the tag ORDERED should be used, It can also be a
11043 string to select a different tag for this task."
11046 (const :tag "No tracking" nil)
11047 (const :tag "Track with ORDERED tag" t)
11048 (string :tag "Use other tag")))
11050 (defun org-toggle-ordered-property ()
11051 "Toggle the ORDERED property of the current entry.
11052 For better visibility, you can track the value of this property with a tag.
11053 See variable `org-track-ordered-property-with-tag'."
11055 (let* ((t1 org-track-ordered-property-with-tag)
11056 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11058 (org-back-to-heading)
11059 (if (org-entry-get nil "ORDERED")
11061 (org-delete-property "ORDERED")
11062 (and tag (org-toggle-tag tag 'off))
11063 (message "Subtasks can be completed in arbitrary order"))
11064 (org-entry-put nil "ORDERED" "t")
11065 (and tag (org-toggle-tag tag 'on))
11066 (message "Subtasks must be completed in sequence")))))
11068 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11069 (defun org-block-todo-from-checkboxes (change-plist)
11070 "Block turning an entry into a TODO, using checkboxes.
11071 This checks whether the current task should be blocked from state
11072 changes because there are unchecked boxes in this entry."
11073 (if (not org-enforce-todo-checkbox-dependencies)
11074 t ; if locally turned off don't block
11076 ;; If this is not a todo state change, or if this entry is already DONE,
11078 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11079 (member (plist-get change-plist :from)
11080 (cons 'done org-done-keywords))
11081 (member (plist-get change-plist :to)
11082 (cons 'todo org-not-done-keywords))
11083 (not (plist-get change-plist :to)))
11084 (throw 'dont-block t))
11085 ;; If this task has checkboxes that are not checked, it's blocked
11087 (org-back-to-heading t)
11088 (let ((beg (point)) end)
11089 (outline-next-heading)
11092 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
11095 (if (boundp 'org-blocked-by-checkboxes)
11096 (setq org-blocked-by-checkboxes t))
11097 (throw 'dont-block nil)))))
11098 t))) ; do not block
11100 (defun org-entry-blocked-p ()
11101 "Is the current entry blocked?"
11102 (if (org-entry-get nil "NOBLOCKING")
11103 nil ;; Never block this entry
11105 (run-hook-with-args-until-failure
11107 (list :type 'todo-state-change
11112 (defun org-update-statistics-cookies (all)
11113 "Update the statistics cookie, either from TODO or from checkboxes.
11114 This should be called with the cursor in a line with a statistics cookie."
11118 (org-update-checkbox-count 'all)
11119 (org-map-entries 'org-update-parent-todo-statistics))
11120 (if (not (org-on-heading-p))
11121 (org-update-checkbox-count)
11122 (let ((pos (move-marker (make-marker) (point)))
11124 (ignore-errors (org-back-to-heading t))
11125 (if (not (org-on-heading-p))
11126 (org-update-checkbox-count)
11127 (setq l1 (org-outline-level))
11128 (setq end (save-excursion
11129 (outline-next-heading)
11130 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11132 (if (and (save-excursion
11134 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11135 (not (save-excursion (re-search-forward
11136 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11137 (org-update-checkbox-count)
11138 (if (and l2 (> l2 l1))
11141 (org-update-parent-todo-statistics))
11143 (beginning-of-line 1)
11144 (while (re-search-forward
11145 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11147 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11149 (move-marker pos nil)))))
11151 (defvar org-entry-property-inherited-from) ;; defined below
11152 (defun org-update-parent-todo-statistics ()
11153 "Update any statistics cookie in the parent of the current headline.
11154 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11155 the entire subtree and this will travel up the hierarchy and update
11156 statistics everywhere."
11158 (let* ((lim 0) prop
11159 (recursive (or (not org-hierarchical-todo-statistics)
11162 (or (setq prop (org-entry-get
11163 nil "COOKIE_DATA" 'inherit)) ""))))
11164 (lim (or (and prop (marker-position
11165 org-entry-property-inherited-from))
11168 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11169 level ltoggle l1 new ndel
11170 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
11173 (beginning-of-line 1)
11174 (if (org-at-heading-p)
11175 (setq ltoggle (funcall outline-level))
11176 (error "This should not happen"))
11177 (while (and (setq level (org-up-heading-safe))
11178 (or recursive first)
11180 (setq first nil cookie-present nil)
11189 (while (re-search-forward box-re (point-at-eol) t)
11190 (setq cnt-all 0 cnt-done 0 cookie-present t)
11191 (setq is-percent (match-end 2))
11193 (unless (outline-next-heading) (throw 'exit nil))
11194 (while (and (looking-at org-complex-heading-regexp)
11195 (> (setq l1 (length (match-string 1))) level))
11196 (setq kwd (and (or recursive (= l1 ltoggle))
11198 (if (or (eq org-provide-todo-statistics 'all-headlines)
11199 (and (listp org-provide-todo-statistics)
11200 (or (member kwd org-provide-todo-statistics)
11201 (member kwd org-done-keywords))))
11202 (setq cnt-all (1+ cnt-all))
11203 (if (eq org-provide-todo-statistics t)
11204 (and kwd (setq cnt-all (1+ cnt-all)))))
11205 (and (member kwd org-done-keywords)
11206 (setq cnt-done (1+ cnt-done)))
11207 (outline-next-heading)))
11210 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11211 (format "[%d/%d]" cnt-done cnt-all))
11212 ndel (- (match-end 0) (match-beginning 0)))
11213 (goto-char (match-beginning 0))
11215 (delete-region (point) (+ (point) ndel)))
11216 (when cookie-present
11217 (run-hook-with-args 'org-after-todo-statistics-hook
11218 cnt-done (- cnt-all cnt-done))))))
11219 (run-hooks 'org-todo-statistics-hook)))
11221 (defvar org-after-todo-statistics-hook nil
11222 "Hook that is called after a TODO statistics cookie has been updated.
11223 Each function is called with two arguments: the number of not-done entries
11224 and the number of done entries.
11226 For example, the following function, when added to this hook, will switch
11227 an entry to DONE when all children are done, and back to TODO when new
11228 entries are set to a TODO status. Note that this hook is only called
11229 when there is a statistics cookie in the headline!
11231 (defun org-summary-todo (n-done n-not-done)
11232 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11233 (let (org-log-done org-log-states) ; turn off logging
11234 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11237 (defvar org-todo-statistics-hook nil
11238 "Hook that is run whenever Org thinks TODO statistics should be updated.
11239 This hook runs even if there is no statistics cookie present, in which case
11240 `org-after-todo-statistics-hook' would not run.")
11242 (defun org-todo-trigger-tag-changes (state)
11243 "Apply the changes defined in `org-todo-state-tags-triggers'."
11244 (let ((l org-todo-state-tags-triggers)
11246 (when (or (not state) (equal state ""))
11247 (setq changes (append changes (cdr (assoc "" l)))))
11248 (when (and (stringp state) (> (length state) 0))
11249 (setq changes (append changes (cdr (assoc state l)))))
11250 (when (member state org-not-done-keywords)
11251 (setq changes (append changes (cdr (assoc 'todo l)))))
11252 (when (member state org-done-keywords)
11253 (setq changes (append changes (cdr (assoc 'done l)))))
11254 (dolist (c changes)
11255 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11257 (defun org-local-logging (value)
11258 "Get logging settings from a property VALUE."
11260 ;; directly set the variables, they are already local.
11261 (setq org-log-done nil
11263 org-todo-log-states nil)
11264 (setq words (org-split-string value))
11265 (while (setq w (pop words))
11267 ((setq a (assoc w org-startup-options))
11268 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11269 (set (nth 1 a) (nth 2 a))))
11270 ((setq a (org-extract-log-state-settings w))
11271 (and (member (car a) org-todo-keywords-1)
11272 (push a org-todo-log-states)))))))
11274 (defun org-get-todo-sequence-head (kwd)
11275 "Return the head of the TODO sequence to which KWD belongs.
11276 If KWD is not set, check if there is a text property remembering the
11281 (or (get-text-property (point-at-bol) 'org-todo-head)
11283 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11284 nil (point-at-eol)))
11285 (get-text-property p 'org-todo-head))))
11286 ((not (member kwd org-todo-keywords-1))
11287 (car org-todo-keywords-1))
11288 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11290 (defun org-fast-todo-selection ()
11291 "Fast TODO keyword selection with single keys.
11292 Returns the new TODO keyword, or nil if no state change should occur."
11293 (let* ((fulltable org-todo-key-alist)
11294 (done-keywords org-done-keywords) ;; needed for the faces.
11295 (maxlen (apply 'max (mapcar
11297 (if (stringp (car x)) (string-width (car x)) 0))
11300 (fwidth (+ maxlen 3 1 3))
11301 (ncol (/ (- (window-width) 4) fwidth))
11305 (save-window-excursion
11307 (set-buffer (get-buffer-create " *Org todo*"))
11308 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11310 (org-set-local 'org-done-keywords done-keywords)
11311 (setq tbl fulltable cnt 0)
11312 (while (setq e (pop tbl))
11314 ((equal e '(:startgroup))
11315 (push '() groups) (setq ingroup t)
11316 (when (not (= cnt 0))
11320 ((equal e '(:endgroup))
11321 (setq ingroup nil cnt 0)
11323 ((equal e '(:newline))
11324 (when (not (= cnt 0))
11328 (while (equal (car tbl) '(:newline))
11330 (setq tbl (cdr tbl)))))
11332 (setq tg (car e) c (cdr e))
11333 (if ingroup (push tg (car groups)))
11334 (setq tg (org-add-props tg nil 'face
11335 (org-get-todo-face tg)))
11336 (if (and (= cnt 0) (not ingroup)) (insert " "))
11337 (insert "[" c "] " tg (make-string
11338 (- fwidth 4 (length tg)) ?\ ))
11339 (when (= (setq cnt (1+ cnt)) ncol)
11341 (if ingroup (insert " "))
11344 (goto-char (point-min))
11345 (if (not expert) (org-fit-window-to-buffer))
11346 (message "[a-z..]:Set [SPC]:clear")
11347 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11350 (and (= c ?q) (not (rassoc c fulltable))))
11351 (setq quit-flag t))
11353 ((setq e (rassoc c fulltable) tg (car e))
11355 (t (setq quit-flag t)))))))
11357 (defun org-entry-is-todo-p ()
11358 (member (org-get-todo-state) org-not-done-keywords))
11360 (defun org-entry-is-done-p ()
11361 (member (org-get-todo-state) org-done-keywords))
11363 (defun org-get-todo-state ()
11365 (org-back-to-heading t)
11366 (and (looking-at org-todo-line-regexp)
11368 (match-string 2))))
11370 (defun org-at-date-range-p (&optional inactive-ok)
11371 "Is the cursor inside a date range?"
11375 (let ((pos (point)))
11376 (skip-chars-backward "^[<\r\n")
11377 (skip-chars-backward "<[")
11378 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11379 (>= (match-end 0) pos)
11381 (skip-chars-backward "^<[\r\n")
11382 (skip-chars-backward "<[")
11383 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11384 (>= (match-end 0) pos)
11388 (defun org-get-repeat (&optional tagline)
11389 "Check if there is a deadline/schedule with repeater in this entry."
11392 (org-back-to-heading t)
11393 (and (re-search-forward (if tagline
11394 (concat tagline "\\s-*" org-repeat-re)
11396 (org-entry-end-position) t)
11397 (match-string-no-properties 1)))))
11399 (defvar org-last-changed-timestamp)
11400 (defvar org-last-inserted-timestamp)
11401 (defvar org-log-post-message)
11402 (defvar org-log-note-purpose)
11403 (defvar org-log-note-how)
11404 (defvar org-log-note-extra)
11405 (defun org-auto-repeat-maybe (done-word)
11406 "Check if the current headline contains a repeated deadline/schedule.
11407 If yes, set TODO state back to what it was and change the base date
11408 of repeating deadline/scheduled time stamps to new date.
11409 This function is run automatically after each state change to a DONE state."
11410 ;; last-state is dynamically scoped into this function
11411 (let* ((repeat (org-get-repeat))
11412 (aa (assoc last-state org-todo-kwd-alist))
11413 (interpret (nth 1 aa))
11415 (whata '(("d" . day) ("m" . month) ("y" . year)))
11416 (msg "Entry repeats: ")
11418 (org-todo-log-states nil)
11419 (nshiftmax 10) (nshift 0)
11420 re type n what ts time to-state)
11422 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11423 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11424 org-todo-repeat-to-state))
11425 (unless (and to-state (member to-state org-todo-keywords-1))
11426 (setq to-state (if (eq interpret 'type) last-state head)))
11427 (org-todo to-state)
11428 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11429 (org-entry-put nil "LAST_REPEAT" (format-time-string
11430 (org-time-stamp-format t t))))
11431 (when org-log-repeat
11432 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11433 (memq 'org-add-log-note post-command-hook))
11434 ;; OK, we are already setup for some record
11435 (if (eq org-log-repeat 'note)
11436 ;; make sure we take a note, not only a time stamp
11437 (setq org-log-note-how 'note))
11438 ;; Set up for taking a record
11439 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11441 'findpos org-log-repeat)))
11442 (org-back-to-heading t)
11443 (org-add-planning-info nil nil 'closed)
11444 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11445 org-deadline-time-regexp "\\)\\|\\("
11446 org-ts-regexp "\\)"))
11447 (while (re-search-forward
11448 re (save-excursion (outline-next-heading) (point)) t)
11449 (setq type (if (match-end 1) org-scheduled-string
11450 (if (match-end 3) org-deadline-string "Plain:"))
11451 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11452 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11453 (setq n (string-to-number (match-string 2 ts))
11454 what (match-string 3 ts))
11455 (if (equal what "w") (setq n (* n 7) what "d"))
11456 ;; Preparation, see if we need to modify the start date for the change
11457 (when (match-end 1)
11458 (setq time (save-match-data (org-time-string-to-time ts)))
11460 ((equal (match-string 1 ts) ".")
11461 ;; Shift starting date to today
11462 (org-timestamp-change
11463 (- (time-to-days (current-time)) (time-to-days time))
11465 ((equal (match-string 1 ts) "+")
11466 (while (or (= nshift 0)
11467 (<= (time-to-days time) (time-to-days (current-time))))
11468 (when (= (incf nshift) nshiftmax)
11469 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11471 (org-timestamp-change n (cdr (assoc what whata)))
11472 (org-at-timestamp-p t)
11473 (setq ts (match-string 1))
11474 (setq time (save-match-data (org-time-string-to-time ts))))
11475 (org-timestamp-change (- n) (cdr (assoc what whata)))
11476 ;; rematch, so that we have everything in place for the real shift
11477 (org-at-timestamp-p t)
11478 (setq ts (match-string 1))
11479 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11480 (org-timestamp-change n (cdr (assoc what whata)))
11481 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11482 (setq org-log-post-message msg)
11483 (message "%s" msg))))
11485 (defun org-show-todo-tree (arg)
11486 "Make a compact tree which shows all headlines marked with TODO.
11487 The tree will show the lines where the regexp matches, and all higher
11488 headlines above the match.
11489 With a \\[universal-argument] prefix, prompt for a regexp to match.
11490 With a numeric prefix N, construct a sparse tree for the Nth element
11491 of `org-todo-keywords-1'."
11493 (let ((case-fold-search nil)
11495 (cond ((null arg) org-not-done-regexp)
11497 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11498 (mapcar 'list org-todo-keywords-1))))
11500 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11502 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11503 (regexp-quote (nth (1- (prefix-numeric-value arg))
11504 org-todo-keywords-1)))
11505 (t (error "Invalid prefix argument: %s" arg)))))
11506 (message "%d TODO entries found"
11507 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
11509 (defun org-deadline (&optional remove time)
11510 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11511 With argument REMOVE, remove any deadline from the item.
11512 When TIME is set, it should be an internal time specification, and the
11513 scheduling will use the corresponding date."
11515 (let* ((old-date (org-entry-get nil "DEADLINE"))
11516 (repeater (and old-date
11517 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
11518 (match-string 1 old-date))))
11521 (when (and old-date org-log-redeadline)
11522 (org-add-log-setup 'deldeadline nil old-date 'findpos
11523 org-log-redeadline))
11524 (org-remove-timestamp-with-keyword org-deadline-string)
11525 (message "Item no longer has a deadline."))
11526 (org-add-planning-info 'deadline time 'closed)
11527 (when (and old-date org-log-redeadline
11528 (not (equal old-date
11529 (substring org-last-inserted-timestamp 1 -1))))
11530 (org-add-log-setup 'redeadline nil old-date 'findpos
11531 org-log-redeadline))
11534 (org-back-to-heading t)
11535 (when (re-search-forward (concat org-deadline-string " "
11536 org-last-inserted-timestamp)
11538 (outline-next-heading) (point)) t)
11539 (goto-char (1- (match-end 0)))
11540 (insert " " repeater)
11541 (setq org-last-inserted-timestamp
11542 (concat (substring org-last-inserted-timestamp 0 -1)
11544 (substring org-last-inserted-timestamp -1))))))
11545 (message "Deadline on %s" org-last-inserted-timestamp))))
11547 (defun org-schedule (&optional remove time)
11548 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11549 With argument REMOVE, remove any scheduling date from the item.
11550 When TIME is set, it should be an internal time specification, and the
11551 scheduling will use the corresponding date."
11553 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11554 (repeater (and old-date
11555 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
11556 (match-string 1 old-date))))
11559 (when (and old-date org-log-reschedule)
11560 (org-add-log-setup 'delschedule nil old-date 'findpos
11561 org-log-reschedule))
11562 (org-remove-timestamp-with-keyword org-scheduled-string)
11563 (message "Item is no longer scheduled."))
11564 (org-add-planning-info 'scheduled time 'closed)
11565 (when (and old-date org-log-reschedule
11566 (not (equal old-date
11567 (substring org-last-inserted-timestamp 1 -1))))
11568 (org-add-log-setup 'reschedule nil old-date 'findpos
11569 org-log-reschedule))
11572 (org-back-to-heading t)
11573 (when (re-search-forward (concat org-scheduled-string " "
11574 org-last-inserted-timestamp)
11576 (outline-next-heading) (point)) t)
11577 (goto-char (1- (match-end 0)))
11578 (insert " " repeater)
11579 (setq org-last-inserted-timestamp
11580 (concat (substring org-last-inserted-timestamp 0 -1)
11582 (substring org-last-inserted-timestamp -1))))))
11583 (message "Scheduled to %s" org-last-inserted-timestamp))))
11585 (defun org-get-scheduled-time (pom &optional inherit)
11586 "Get the scheduled time as a time tuple, of a format suitable
11587 for calling org-schedule with, or if there is no scheduling,
11589 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11591 (apply 'encode-time (org-parse-time-string time)))))
11593 (defun org-get-deadline-time (pom &optional inherit)
11594 "Get the deadline as a time tuple, of a format suitable for
11595 calling org-deadline with, or if there is no scheduling, returns
11597 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11599 (apply 'encode-time (org-parse-time-string time)))))
11601 (defun org-remove-timestamp-with-keyword (keyword)
11602 "Remove all time stamps with KEYWORD in the current entry."
11603 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11606 (org-back-to-heading t)
11608 (outline-next-heading)
11609 (while (re-search-backward re beg t)
11611 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11612 (equal (char-before) ?\ ))
11613 (backward-delete-char 1)
11614 (if (string-match "^[ \t]*$" (buffer-substring
11615 (point-at-bol) (point-at-eol)))
11616 (delete-region (point-at-bol)
11617 (min (point-max) (1+ (point-at-eol))))))))))
11619 (defun org-add-planning-info (what &optional time &rest remove)
11620 "Insert new timestamp with keyword in the line directly after the headline.
11621 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11622 If non is given, the user is prompted for a date.
11623 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11626 (let (org-time-was-given org-end-time-was-given ts
11627 end default-time default-input)
11630 (when (and (not time) (memq what '(scheduled deadline)))
11631 ;; Try to get a default date/time from existing timestamp
11633 (org-back-to-heading t)
11634 (setq end (save-excursion (outline-next-heading) (point)))
11635 (when (re-search-forward (if (eq what 'scheduled)
11636 org-scheduled-time-regexp
11637 org-deadline-time-regexp)
11639 (setq ts (match-string 1)
11641 (apply 'encode-time (org-parse-time-string ts))
11642 default-input (and ts (org-get-compact-tod ts))))))
11644 ;; If necessary, get the time from the user
11645 (setq time (or time (org-read-date nil 'to-time nil nil
11646 default-time default-input))))
11648 (when (and org-insert-labeled-timestamps-at-point
11649 (member what '(scheduled deadline)))
11651 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11652 (org-insert-time-stamp time org-time-was-given
11653 nil nil nil (list org-end-time-was-given))
11657 (let (col list elt ts buffer-invisibility-spec)
11658 (org-back-to-heading t)
11659 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11660 (goto-char (match-end 1))
11661 (setq col (current-column))
11662 (goto-char (match-end 0))
11663 (if (eobp) (insert "\n") (forward-char 1))
11664 (when (and (not what)
11667 org-keyword-time-not-clock-regexp))))
11668 ;; Nothing to add, nothing to remove...... :-)
11670 (if (and (not (looking-at outline-regexp))
11671 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11673 (not (equal (match-string 1) org-clock-string)))
11674 (narrow-to-region (match-beginning 0) (match-end 0))
11675 (insert-before-markers "\n")
11677 (narrow-to-region (point) (point))
11678 (and org-adapt-indentation (org-indent-to-column col)))
11679 ;; Check if we have to remove something.
11680 (setq list (cons what remove))
11682 (setq elt (pop list))
11683 (goto-char (point-min))
11684 (when (or (and (eq elt 'scheduled)
11685 (re-search-forward org-scheduled-time-regexp nil t))
11686 (and (eq elt 'deadline)
11687 (re-search-forward org-deadline-time-regexp nil t))
11688 (and (eq elt 'closed)
11689 (re-search-forward org-closed-time-regexp nil t)))
11691 (if (looking-at "--+<[^>]+>") (replace-match ""))
11692 (skip-chars-backward " ")
11693 (if (looking-at " +") (replace-match ""))))
11694 (goto-char (point-max))
11695 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11698 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11699 (cond ((eq what 'scheduled) org-scheduled-string)
11700 ((eq what 'deadline) org-deadline-string)
11701 ((eq what 'closed) org-closed-string))
11703 (setq ts (org-insert-time-stamp
11705 (or org-time-was-given
11706 (and (eq what 'closed) org-log-done-with-time))
11708 nil nil (list org-end-time-was-given)))
11710 (goto-char (point-min))
11712 (if (and (looking-at "[ \t]*\n")
11713 (equal (char-before) ?\n))
11714 (delete-region (1- (point)) (point-at-eol)))
11717 (defvar org-log-note-marker (make-marker))
11718 (defvar org-log-note-purpose nil)
11719 (defvar org-log-note-state nil)
11720 (defvar org-log-note-previous-state nil)
11721 (defvar org-log-note-how nil)
11722 (defvar org-log-note-extra nil)
11723 (defvar org-log-note-window-configuration nil)
11724 (defvar org-log-note-return-to (make-marker))
11725 (defvar org-log-post-message nil
11726 "Message to be displayed after a log note has been stored.
11727 The auto-repeater uses this.")
11729 (defun org-add-note ()
11730 "Add a note to the current entry.
11731 This is done in the same way as adding a state change note."
11733 (org-add-log-setup 'note nil nil 'findpos nil))
11735 (defvar org-property-end-re)
11736 (defun org-add-log-setup (&optional purpose state prev-state
11737 findpos how &optional extra)
11738 "Set up the post command hook to take a note.
11739 If this is about to TODO state change, the new state is expected in STATE.
11740 When FINDPOS is non-nil, find the correct position for the note in
11741 the current entry. If not, assume that it can be inserted at point.
11742 HOW is an indicator what kind of note should be created.
11743 EXTRA is additional text that will be inserted into the notes buffer."
11744 (let* ((org-log-into-drawer (org-log-into-drawer))
11745 (drawer (cond ((stringp org-log-into-drawer)
11746 org-log-into-drawer)
11747 (org-log-into-drawer "LOGBOOK")
11752 (org-back-to-heading t)
11753 (narrow-to-region (point) (save-excursion
11754 (outline-next-heading) (point)))
11755 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11756 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11758 (goto-char (match-end 0))
11761 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11764 (goto-char (match-end 0))
11765 (or org-log-states-order-reversed
11766 (and (re-search-forward org-property-end-re nil t)
11767 (goto-char (1- (match-beginning 0))))))
11768 (insert "\n:" drawer ":\n:END:")
11769 (beginning-of-line 0)
11770 (org-indent-line-function)
11771 (beginning-of-line 2)
11772 (org-indent-line-function)
11774 ((and org-log-state-notes-insert-after-drawers
11776 (forward-line) (looking-at org-drawer-regexp)))
11778 (while (looking-at org-drawer-regexp)
11779 (goto-char (match-end 0))
11780 (re-search-forward org-property-end-re (point-max) t)
11782 (forward-line -1)))
11783 (unless org-log-states-order-reversed
11784 (and (= (char-after) ?\n) (forward-char 1))
11785 (org-skip-over-state-notes)
11786 (skip-chars-backward " \t\n\r")))
11787 (move-marker org-log-note-marker (point))
11788 (setq org-log-note-purpose purpose
11789 org-log-note-state state
11790 org-log-note-previous-state prev-state
11791 org-log-note-how how
11792 org-log-note-extra extra)
11793 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11795 (defun org-skip-over-state-notes ()
11796 "Skip past the list of State notes in an entry."
11797 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11798 (while (looking-at "[ \t]*- State")
11799 (condition-case nil
11801 (error (org-end-of-item)))))
11803 (defun org-add-log-note (&optional purpose)
11804 "Pop up a window for taking a note, and add this note later at point."
11805 (remove-hook 'post-command-hook 'org-add-log-note)
11806 (setq org-log-note-window-configuration (current-window-configuration))
11807 (delete-other-windows)
11808 (move-marker org-log-note-return-to (point))
11809 (switch-to-buffer (marker-buffer org-log-note-marker))
11810 (goto-char org-log-note-marker)
11811 (org-switch-to-buffer-other-window "*Org Note*")
11813 (if (memq org-log-note-how '(time state))
11814 (let (current-prefix-arg) (org-store-log-note))
11815 (let ((org-inhibit-startup t)) (org-mode))
11816 (insert (format "# Insert note for %s.
11817 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11819 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11820 ((eq org-log-note-purpose 'done) "closed todo item")
11821 ((eq org-log-note-purpose 'state)
11822 (format "state change from \"%s\" to \"%s\""
11823 (or org-log-note-previous-state "")
11824 (or org-log-note-state "")))
11825 ((eq org-log-note-purpose 'reschedule)
11827 ((eq org-log-note-purpose 'delschedule)
11828 "no longer scheduled")
11829 ((eq org-log-note-purpose 'redeadline)
11830 "changing deadline")
11831 ((eq org-log-note-purpose 'deldeadline)
11832 "removing deadline")
11833 ((eq org-log-note-purpose 'refile)
11835 ((eq org-log-note-purpose 'note)
11837 (t (error "This should not happen")))))
11838 (if org-log-note-extra (insert org-log-note-extra))
11839 (org-set-local 'org-finish-function 'org-store-log-note)))
11841 (defvar org-note-abort nil) ; dynamically scoped
11842 (defun org-store-log-note ()
11843 "Finish taking a log note, and insert it to where it belongs."
11844 (let ((txt (buffer-string))
11845 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11847 (kill-buffer (current-buffer))
11848 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11849 (setq txt (replace-match "" t t txt)))
11850 (if (string-match "\\s-+\\'" txt)
11851 (setq txt (replace-match "" t t txt)))
11852 (setq lines (org-split-string txt "\n"))
11853 (when (and note (string-match "\\S-" note))
11855 (org-replace-escapes
11857 (list (cons "%u" (user-login-name))
11858 (cons "%U" user-full-name)
11859 (cons "%t" (format-time-string
11860 (org-time-stamp-format 'long 'inactive)
11862 (cons "%T" (format-time-string
11863 (org-time-stamp-format 'long nil)
11865 (cons "%s" (if org-log-note-state
11866 (concat "\"" org-log-note-state "\"")
11868 (cons "%S" (if org-log-note-previous-state
11869 (concat "\"" org-log-note-previous-state "\"")
11871 (if lines (setq note (concat note " \\\\")))
11873 (when (or current-prefix-arg org-note-abort)
11874 (when org-log-into-drawer
11875 (org-remove-empty-drawer-at
11876 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11877 org-log-note-marker))
11880 (with-current-buffer (marker-buffer org-log-note-marker)
11882 (goto-char org-log-note-marker)
11883 (move-marker org-log-note-marker nil)
11885 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11886 (insert "- " (pop lines))
11887 (org-indent-line-function)
11888 (beginning-of-line 1)
11889 (looking-at "[ \t]*")
11890 (setq ind (concat (match-string 0) " "))
11892 (while lines (insert "\n" ind (pop lines)))
11893 (message "Note stored")
11894 (org-back-to-heading t)
11895 (org-cycle-hide-drawers 'children)))))
11896 (set-window-configuration org-log-note-window-configuration)
11897 (with-current-buffer (marker-buffer org-log-note-return-to)
11898 (goto-char org-log-note-return-to))
11899 (move-marker org-log-note-return-to nil)
11900 (and org-log-post-message (message "%s" org-log-post-message)))
11902 (defun org-remove-empty-drawer-at (drawer pos)
11903 "Remove an empty drawer DRAWER at position POS.
11904 POS may also be a marker."
11905 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11911 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11912 (replace-match ""))))))
11914 (defun org-sparse-tree (&optional arg)
11915 "Create a sparse tree, prompt for the details.
11916 This command can create sparse trees. You first need to select the type
11917 of match used to create the tree:
11919 t Show all TODO entries.
11920 T Show entries with a specific TODO keyword.
11921 m Show entries selected by a tags/property match.
11922 p Enter a property name and its value (both with completion on existing
11923 names/values) and show entries with that property.
11924 / Show entries matching a regular expression (`r' can be used as well)
11925 d Show deadlines due within `org-deadline-warning-days'.
11926 b Show deadlines and scheduled items before a date.
11927 a Show deadlines and scheduled items after a date."
11929 (let (ans kwd value)
11930 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty [d]eadlines\n [b]efore-date [a]fter-date")
11931 (setq ans (read-char-exclusive))
11934 (call-interactively 'org-check-deadlines))
11936 (call-interactively 'org-check-before-date))
11938 (call-interactively 'org-check-after-date))
11940 (org-show-todo-tree nil))
11942 (org-show-todo-tree '(4)))
11943 ((member ans '(?T ?m))
11944 (call-interactively 'org-match-sparse-tree))
11945 ((member ans '(?p ?P))
11946 (setq kwd (org-icompleting-read "Property: "
11947 (mapcar 'list (org-buffer-property-keys))))
11948 (setq value (org-icompleting-read "Value: "
11949 (mapcar 'list (org-property-values kwd))))
11950 (unless (string-match "\\`{.*}\\'" value)
11951 (setq value (concat "\"" value "\"")))
11952 (org-match-sparse-tree arg (concat kwd "=" value)))
11953 ((member ans '(?r ?R ?/))
11954 (call-interactively 'org-occur))
11955 (t (error "No such sparse tree command \"%c\"" ans)))))
11957 (defvar org-occur-highlights nil
11958 "List of overlays used for occur matches.")
11959 (make-variable-buffer-local 'org-occur-highlights)
11960 (defvar org-occur-parameters nil
11961 "Parameters of the active org-occur calls.
11962 This is a list, each call to org-occur pushes as cons cell,
11963 containing the regular expression and the callback, onto the list.
11964 The list can contain several entries if `org-occur' has been called
11965 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11966 will only contain one set of parameters. When the highlights are
11967 removed (for example with `C-c C-c', or with the next edit (depending
11968 on `org-remove-highlights-with-change'), this variable is emptied
11970 (make-variable-buffer-local 'org-occur-parameters)
11972 (defun org-occur (regexp &optional keep-previous callback)
11973 "Make a compact tree which shows all matches of REGEXP.
11974 The tree will show the lines where the regexp matches, and all higher
11975 headlines above the match. It will also show the heading after the match,
11976 to make sure editing the matching entry is easy.
11977 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11978 call to `org-occur' will be kept, to allow stacking of calls to this
11980 If CALLBACK is non-nil, it is a function which is called to confirm
11981 that the match should indeed be shown."
11982 (interactive "sRegexp: \nP")
11983 (when (equal regexp "")
11984 (error "Regexp cannot be empty"))
11985 (unless keep-previous
11986 (org-remove-occur-highlights nil nil t))
11987 (push (cons regexp callback) org-occur-parameters)
11990 (goto-char (point-min))
11991 (if (or (not keep-previous) ; do not want to keep
11992 (not org-occur-highlights)) ; no previous matches
11995 (while (re-search-forward regexp nil t)
11996 (when (or (not callback)
11997 (save-match-data (funcall callback)))
11998 (setq cnt (1+ cnt))
11999 (when org-highlight-sparse-tree-matches
12000 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12001 (org-show-context 'occur-tree))))
12002 (when org-remove-highlights-with-change
12003 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12005 (unless org-sparse-tree-open-archived-trees
12006 (org-hide-archived-subtrees (point-min) (point-max)))
12007 (run-hooks 'org-occur-hook)
12008 (if (interactive-p)
12009 (message "%d match(es) for regexp %s" cnt regexp))
12012 (defun org-show-context (&optional key)
12013 "Make sure point and context are visible.
12014 How much context is shown depends upon the variables
12015 `org-show-hierarchy-above', `org-show-following-heading'. and
12016 `org-show-siblings'."
12017 (let ((heading-p (org-on-heading-p t))
12018 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12019 (following-p (org-get-alist-option org-show-following-heading key))
12020 (entry-p (org-get-alist-option org-show-entry-below key))
12021 (siblings-p (org-get-alist-option org-show-siblings key)))
12023 ;; Show heading or entry text
12024 (if (and heading-p (not entry-p))
12025 (org-flag-heading nil) ; only show the heading
12026 (and (or entry-p (org-invisible-p) (org-invisible-p2))
12027 (org-show-hidden-entry))) ; show entire entry
12029 ;; Show next sibling, or heading below text
12031 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12032 (org-flag-heading nil))))
12033 (when siblings-p (org-show-siblings))
12035 ;; show all higher headings, possibly with siblings
12037 (while (and (condition-case nil
12038 (progn (org-up-heading-all 1) t)
12041 (org-flag-heading nil)
12042 (when siblings-p (org-show-siblings))))))))
12044 (defvar org-reveal-start-hook nil
12045 "Hook run before revealing a location.")
12047 (defun org-reveal (&optional siblings)
12048 "Show current entry, hierarchy above it, and the following headline.
12049 This can be used to show a consistent set of context around locations
12050 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12051 not t for the search context.
12053 With optional argument SIBLINGS, on each level of the hierarchy all
12054 siblings are shown. This repairs the tree structure to what it would
12055 look like when opened with hierarchical calls to `org-cycle'.
12056 With double optional argument \\[universal-argument] \\[universal-argument], \
12057 go to the parent and show the
12060 (run-hooks 'org-reveal-start-hook)
12061 (let ((org-show-hierarchy-above t)
12062 (org-show-following-heading t)
12063 (org-show-siblings (if siblings t org-show-siblings)))
12064 (org-show-context nil))
12065 (when (equal siblings '(16))
12067 (when (org-up-heading-safe)
12069 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12071 (defun org-highlight-new-match (beg end)
12072 "Highlight from BEG to END and mark the highlight is an occur headline."
12073 (let ((ov (make-overlay beg end)))
12074 (overlay-put ov 'face 'secondary-selection)
12075 (push ov org-occur-highlights)))
12077 (defun org-remove-occur-highlights (&optional beg end noremove)
12078 "Remove the occur highlights from the buffer.
12079 BEG and END are ignored. If NOREMOVE is nil, remove this function
12080 from the `before-change-functions' in the current buffer."
12082 (unless org-inhibit-highlight-removal
12083 (mapc 'delete-overlay org-occur-highlights)
12084 (setq org-occur-highlights nil)
12085 (setq org-occur-parameters nil)
12087 (remove-hook 'before-change-functions
12088 'org-remove-occur-highlights 'local))))
12092 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12093 "Regular expression matching the priority indicator.")
12095 (defvar org-remove-priority-next-time nil)
12097 (defun org-priority-up ()
12098 "Increase the priority of the current item."
12100 (org-priority 'up))
12102 (defun org-priority-down ()
12103 "Decrease the priority of the current item."
12105 (org-priority 'down))
12107 (defun org-priority (&optional action)
12108 "Change the priority of an item by ARG.
12109 ACTION can be `set', `up', `down', or a character."
12111 (unless org-enable-priority-commands
12112 (error "Priority commands are disabled"))
12113 (setq action (or action 'set))
12114 (let (current new news have remove)
12116 (org-back-to-heading t)
12117 (if (looking-at org-priority-regexp)
12118 (setq current (string-to-char (match-string 2))
12120 (setq current org-default-priority))
12122 ((eq action 'remove)
12123 (setq remove t new ?\ ))
12124 ((or (eq action 'set)
12125 (if (featurep 'xemacs) (characterp action) (integerp action)))
12126 (if (not (eq action 'set))
12128 (message "Priority %c-%c, SPC to remove: "
12129 org-highest-priority org-lowest-priority)
12130 (setq new (read-char-exclusive)))
12131 (if (and (= (upcase org-highest-priority) org-highest-priority)
12132 (= (upcase org-lowest-priority) org-lowest-priority))
12133 (setq new (upcase new)))
12134 (cond ((equal new ?\ ) (setq remove t))
12135 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12136 (error "Priority must be between `%c' and `%c'"
12137 org-highest-priority org-lowest-priority))))
12139 (if (and (not have) (eq last-command this-command))
12140 (setq new org-lowest-priority)
12141 (setq new (if (and org-priority-start-cycle-with-default (not have))
12142 org-default-priority (1- current)))))
12144 (if (and (not have) (eq last-command this-command))
12145 (setq new org-highest-priority)
12146 (setq new (if (and org-priority-start-cycle-with-default (not have))
12147 org-default-priority (1+ current)))))
12148 (t (error "Invalid action")))
12149 (if (or (< (upcase new) org-highest-priority)
12150 (> (upcase new) org-lowest-priority))
12152 (setq news (format "%c" new))
12155 (replace-match "" t t nil 1)
12156 (replace-match news t t nil 2))
12158 (error "No priority cookie found in line")
12159 (let ((case-fold-search nil))
12160 (looking-at org-todo-line-regexp))
12163 (goto-char (match-end 2))
12164 (insert " [#" news "]"))
12165 (goto-char (match-beginning 3))
12166 (insert "[#" news "] "))))
12167 (org-preserve-lc (org-set-tags nil 'align)))
12169 (message "Priority removed")
12170 (message "Priority of current item set to %s" news))))
12172 (defun org-get-priority (s)
12173 "Find priority cookie and return priority."
12175 (if (not (string-match org-priority-regexp s))
12176 (* 1000 (- org-lowest-priority org-default-priority))
12177 (* 1000 (- org-lowest-priority
12178 (string-to-char (match-string 2 s)))))))
12182 (defvar org-agenda-archives-mode)
12183 (defvar org-map-continue-from nil
12184 "Position from where mapping should continue.
12185 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12187 (defvar org-scanner-tags nil
12188 "The current tag list while the tags scanner is running.")
12189 (defvar org-trust-scanner-tags nil
12190 "Should `org-get-tags-at' use the tags fro the scanner.
12191 This is for internal dynamical scoping only.
12192 When this is non-nil, the function `org-get-tags-at' will return the value
12193 of `org-scanner-tags' instead of building the list by itself. This
12194 can lead to large speed-ups when the tags scanner is used in a file with
12195 many entries, and when the list of tags is retrieved, for example to
12196 obtain a list of properties. Building the tags list for each entry in such
12197 a file becomes an N^2 operation - but with this variable set, it scales
12200 (defun org-scan-tags (action matcher &optional todo-only)
12201 "Scan headline tags with inheritance and produce output ACTION.
12203 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12204 or `agenda' to produce an entry list for an agenda view. It can also be
12205 a Lisp form or a function that should be called at each matched headline, in
12206 this case the return value is a list of all return values from these calls.
12208 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12209 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12210 only lines with a TODO keyword are included in the output."
12211 (require 'org-agenda)
12212 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
12213 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12215 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
12216 (props (list 'face 'default
12217 'done-face 'org-agenda-done
12218 'undone-face 'default
12219 'mouse-face 'highlight
12220 'org-not-done-regexp org-not-done-regexp
12221 'org-todo-regexp org-todo-regexp
12223 (format "mouse-2 or RET jump to org file %s"
12224 (abbreviate-file-name
12225 (or (buffer-file-name (buffer-base-buffer))
12226 (buffer-name (buffer-base-buffer)))))))
12227 (case-fold-search nil)
12228 (org-map-continue-from nil)
12229 lspos tags tags-list
12230 (tags-alist (list (cons 0 org-file-tags)))
12231 (llast 0) rtn rtn1 level category i txt
12232 todo marker entry priority)
12233 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12234 (setq action (list 'lambda nil action)))
12236 (goto-char (point-min))
12237 (when (eq action 'sparse-tree)
12239 (org-remove-occur-highlights))
12240 (while (re-search-forward re nil t)
12242 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12243 tags (if (match-end 4) (org-match-string-no-properties 4)))
12244 (goto-char (setq lspos (match-beginning 0)))
12245 (setq level (org-reduced-level (funcall outline-level))
12246 category (org-get-category))
12247 (setq i llast llast level)
12248 ;; remove tag lists from same and sublevels
12249 (while (>= i level)
12250 (when (setq entry (assoc i tags-alist))
12251 (setq tags-alist (delete entry tags-alist)))
12253 ;; add the next tags
12255 (setq tags (org-split-string tags ":")
12257 (cons (cons level tags) tags-alist)))
12258 ;; compile tags for current headline
12260 (if org-use-tag-inheritance
12261 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12263 org-scanner-tags tags-list)
12264 (when org-use-tag-inheritance
12265 (setcdr (car tags-alist)
12266 (mapcar (lambda (x)
12267 (setq x (copy-sequence x))
12268 (org-add-prop-inherited x))
12269 (cdar tags-alist))))
12270 (when (and tags org-use-tag-inheritance
12271 (or (not (eq t org-use-tag-inheritance))
12272 org-tags-exclude-from-inheritance))
12273 ;; selective inheritance, remove uninherited ones
12274 (setcdr (car tags-alist)
12275 (org-remove-uniherited-tags (cdar tags-alist))))
12276 (when (and (or (not todo-only)
12277 (and (member todo org-not-done-keywords)
12278 (or (not org-agenda-tags-todo-honor-ignore-options)
12279 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12280 (let ((case-fold-search t)) (eval matcher))
12282 (not (member org-archive-tag tags-list))
12283 ;; we have an archive tag, should we use this anyway?
12284 (or (not org-agenda-skip-archived-trees)
12285 (and (eq action 'agenda) org-agenda-archives-mode))))
12286 (unless (eq action 'sparse-tree) (org-agenda-skip))
12288 ;; select this headline
12291 ((eq action 'sparse-tree)
12292 (and org-highlight-sparse-tree-matches
12293 (org-get-heading) (match-end 0)
12294 (org-highlight-new-match
12295 (match-beginning 0) (match-beginning 1)))
12296 (org-show-context 'tags-tree))
12297 ((eq action 'agenda)
12298 (setq txt (org-format-agenda-item
12301 (if (eq org-tags-match-list-sublevels 'indented)
12302 (make-string (1- level) ?.) "")
12307 priority (org-get-priority txt))
12309 (setq marker (org-agenda-new-marker))
12310 (org-add-props txt props
12311 'org-marker marker 'org-hd-marker marker 'org-category category
12313 'priority priority 'type "tagsmatch")
12315 ((functionp action)
12316 (setq org-map-continue-from nil)
12318 (setq rtn1 (funcall action))
12320 (t (error "Invalid action")))
12322 ;; if we are to skip sublevels, jump to end of subtree
12323 (unless org-tags-match-list-sublevels
12324 (org-end-of-subtree t)
12325 (backward-char 1))))
12326 ;; Get the correct position from where to continue
12327 (if org-map-continue-from
12328 (goto-char org-map-continue-from)
12329 (and (= (point) lspos) (end-of-line 1)))))
12330 (when (and (eq action 'sparse-tree)
12331 (not org-sparse-tree-open-archived-trees))
12332 (org-hide-archived-subtrees (point-min) (point-max)))
12335 (defun org-remove-uniherited-tags (tags)
12336 "Remove all tags that are not inherited from the list TAGS."
12338 ((eq org-use-tag-inheritance t)
12339 (if org-tags-exclude-from-inheritance
12340 (org-delete-all org-tags-exclude-from-inheritance tags)
12342 ((not org-use-tag-inheritance) nil)
12343 ((stringp org-use-tag-inheritance)
12346 (if (and (string-match org-use-tag-inheritance x)
12347 (not (member x org-tags-exclude-from-inheritance)))
12350 ((listp org-use-tag-inheritance)
12353 (if (member x org-use-tag-inheritance) x nil))
12356 (defvar todo-only) ;; dynamically scoped
12358 (defun org-match-sparse-tree (&optional todo-only match)
12359 "Create a sparse tree according to tags string MATCH.
12360 MATCH can contain positive and negative selection of tags, like
12361 \"+WORK+URGENT-WITHBOSS\".
12362 If optional argument TODO-ONLY is non-nil, only select lines that are
12365 (org-prepare-agenda-buffers (list (current-buffer)))
12366 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12368 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12370 (defvar org-cached-props nil)
12371 (defun org-cached-entry-get (pom property)
12372 (if (or (eq t org-use-property-inheritance)
12373 (and (stringp org-use-property-inheritance)
12374 (string-match org-use-property-inheritance property))
12375 (and (listp org-use-property-inheritance)
12376 (member property org-use-property-inheritance)))
12377 ;; Caching is not possible, check it directly
12378 (org-entry-get pom property 'inherit)
12379 ;; Get all properties, so that we can do complicated checks easily
12380 (cdr (assoc property (or org-cached-props
12381 (setq org-cached-props
12382 (org-entry-properties pom)))))))
12384 (defun org-global-tags-completion-table (&optional files)
12385 "Return the list of all tags in all agenda buffer/files."
12392 (set-buffer (find-file-noselect file))
12393 (append (org-get-buffer-tags)
12394 (mapcar (lambda (x) (if (stringp (car-safe x))
12395 (list (car-safe x)) nil))
12397 (if (and files (car files))
12399 (org-agenda-files))))))))
12401 (defun org-make-tags-matcher (match)
12402 "Create the TAGS//TODO matcher form for the selection string MATCH."
12403 ;; todo-only is scoped dynamically into this function, and the function
12404 ;; may change it if the matcher asks for it.
12406 ;; Get a new match request, with completion
12407 (let ((org-last-tags-completion-table
12408 (org-global-tags-completion-table)))
12409 (setq match (org-completing-read-no-i
12410 "Match: " 'org-tags-completion-function nil nil nil
12411 'org-tags-history))))
12413 ;; Parse the string and create a lisp form
12414 (let ((match0 match)
12415 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
12417 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12418 orterms term orlist re-p str-p level-p level-op time-p
12419 prop-p pn pv po cat-p gv rest)
12420 (if (string-match "/+" match)
12421 ;; match contains also a todo-matching request
12423 (setq tagsmatch (substring match 0 (match-beginning 0))
12424 todomatch (substring match (match-end 0)))
12425 (if (string-match "^!" todomatch)
12426 (setq todo-only t todomatch (substring todomatch 1)))
12427 (if (string-match "^\\s-*$" todomatch)
12428 (setq todomatch nil)))
12429 ;; only matching tags
12430 (setq tagsmatch match todomatch nil))
12432 ;; Make the tags matcher
12433 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12434 (setq tagsmatcher t)
12435 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12436 (while (setq term (pop orterms))
12437 (while (and (equal (substring term -1) "\\") orterms)
12438 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12439 (while (string-match re term)
12440 (setq rest (substring term (match-end 0))
12441 minus (and (match-end 1)
12442 (equal (match-string 1 term) "-"))
12443 tag (match-string 2 term)
12444 re-p (equal (string-to-char tag) ?{)
12445 level-p (match-end 4)
12446 prop-p (match-end 5)
12448 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12450 (setq level-op (org-op-to-function (match-string 3 term)))
12451 `(,level-op level ,(string-to-number
12452 (match-string 4 term))))
12454 (setq pn (match-string 5 term)
12455 po (match-string 6 term)
12456 pv (match-string 7 term)
12457 cat-p (equal pn "CATEGORY")
12458 re-p (equal (string-to-char pv) ?{)
12459 str-p (equal (string-to-char pv) ?\")
12460 time-p (save-match-data
12461 (string-match "^\"[[<].*[]>]\"$" pv))
12462 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12463 (if time-p (setq pv (org-matcher-time pv)))
12464 (setq po (org-op-to-function po (if time-p 'time str-p)))
12466 ((equal pn "CATEGORY")
12467 (setq gv '(get-text-property (point) 'org-category)))
12471 (setq gv `(org-cached-entry-get nil ,pn))))
12474 `(not (string-match ,pv (or ,gv "")))
12475 `(string-match ,pv (or ,gv "")))
12477 `(,po (or ,gv "") ,pv)
12478 `(,po (string-to-number (or ,gv ""))
12479 ,(string-to-number pv) ))))
12480 (t `(member ,tag tags-list)))
12481 mm (if minus (list 'not mm) mm)
12483 (push mm tagsmatcher))
12484 (push (if (> (length tagsmatcher) 1)
12485 (cons 'and tagsmatcher)
12488 (setq tagsmatcher nil))
12489 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12491 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12492 ;; Make the todo matcher
12493 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12494 (setq todomatcher t)
12495 (setq orterms (org-split-string todomatch "|") orlist nil)
12496 (while (setq term (pop orterms))
12497 (while (string-match re term)
12498 (setq minus (and (match-end 1)
12499 (equal (match-string 1 term) "-"))
12500 kwd (match-string 2 term)
12501 re-p (equal (string-to-char kwd) ?{)
12502 term (substring term (match-end 0))
12504 `(string-match ,(substring kwd 1 -1) todo)
12505 (list 'equal 'todo kwd))
12506 mm (if minus (list 'not mm) mm))
12507 (push mm todomatcher))
12508 (push (if (> (length todomatcher) 1)
12509 (cons 'and todomatcher)
12512 (setq todomatcher nil))
12513 (setq todomatcher (if (> (length orlist) 1)
12514 (cons 'or orlist) (car orlist))))
12516 ;; Return the string and lisp forms of the matcher
12517 (setq matcher (if todomatcher
12518 (list 'and tagsmatcher todomatcher)
12520 (cons match0 matcher)))
12522 (defun org-op-to-function (op &optional stringp)
12523 "Turn an operator into the appropriate function."
12526 ((equal op "<" ) '(< string< org-time<))
12527 ((equal op ">" ) '(> org-string> org-time>))
12528 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12529 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12530 ((member op '("=" "==")) '(= string= org-time=))
12531 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
12532 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12534 (defun org<> (a b) (not (= a b)))
12535 (defun org-string<= (a b) (or (string= a b) (string< a b)))
12536 (defun org-string>= (a b) (not (string< a b)))
12537 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
12538 (defun org-string<> (a b) (not (string= a b)))
12539 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
12540 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
12541 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
12542 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
12543 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
12544 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
12546 "Convert S to a floating point time.
12547 If S is already a number, just return it. If it is a string, parse
12548 it as a time string and apply `float-time' to it. If S is nil, just return 0."
12552 (condition-case nil
12553 (float-time (apply 'encode-time (org-parse-time-string s)))
12557 (defun org-time-today ()
12558 "Time in seconds today at 0:00.
12559 Returns the float number of seconds since the beginning of the
12560 epoch to the beginning of today (00:00)."
12561 (float-time (apply 'encode-time
12562 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12564 (defun org-matcher-time (s)
12565 "Interpret a time comparison value."
12568 ((string= s "<now>") (float-time))
12569 ((string= s "<today>") (org-time-today))
12570 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12571 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12572 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12573 (+ (org-time-today)
12574 (* (string-to-number (match-string 1 s))
12575 (cdr (assoc (match-string 2 s)
12576 '(("d" . 86400.0) ("w" . 604800.0)
12577 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12580 (defun org-match-any-p (re list)
12581 "Does re match any element of list?"
12582 (setq list (mapcar (lambda (x) (string-match re x)) list))
12585 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12586 (defvar org-tags-overlay (make-overlay 1 1))
12587 (org-detach-overlay org-tags-overlay)
12589 (defun org-get-local-tags-at (&optional pos)
12590 "Get a list of tags defined in the current headline."
12591 (org-get-tags-at pos 'local))
12593 (defun org-get-local-tags ()
12594 "Get a list of tags defined in the current headline."
12595 (org-get-tags-at nil 'local))
12597 (defun org-get-tags-at (&optional pos local)
12598 "Get a list of all headline tags applicable at POS.
12599 POS defaults to point. If tags are inherited, the list contains
12600 the targets in the same sequence as the headlines appear, i.e.
12601 the tags of the current headline come last.
12602 When LOCAL is non-nil, only return tags from the current headline,
12603 ignore inherited ones."
12605 (if (and org-trust-scanner-tags
12606 (or (not pos) (equal pos (point)))
12609 (let (tags ltags lastpos parent)
12613 (goto-char (or pos (point)))
12616 (condition-case nil
12618 (org-back-to-heading t)
12619 (while (not (equal lastpos (point)))
12620 (setq lastpos (point))
12622 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
12623 (setq ltags (org-split-string
12624 (org-match-string-no-properties 1) ":"))
12626 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12629 (org-remove-uniherited-tags ltags)
12632 (or org-use-tag-inheritance (throw 'done t))
12633 (if local (throw 'done t))
12634 (or (org-up-heading-safe) (error nil))
12637 (append (org-remove-uniherited-tags org-file-tags) tags)))))
12639 (defun org-add-prop-inherited (s)
12640 (add-text-properties 0 (length s) '(inherited t) s)
12643 (defun org-toggle-tag (tag &optional onoff)
12644 "Toggle the tag TAG for the current line.
12645 If ONOFF is `on' or `off', don't toggle but set to this state."
12648 (org-back-to-heading t)
12649 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
12652 (setq current (match-string 1))
12653 (replace-match ""))
12655 (setq current (nreverse (org-split-string current ":")))
12659 (or (member tag current) (push tag current)))
12661 (or (not (member tag current)) (setq current (delete tag current))))
12662 (t (if (member tag current)
12663 (setq current (delete tag current))
12665 (push tag current))))
12669 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12670 (org-set-tags nil t))
12671 (delete-horizontal-space))
12672 (run-hooks 'org-after-tags-change-hook))
12675 (defun org-align-tags-here (to-col)
12676 ;; Assumes that this is a headline
12677 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12678 (beginning-of-line 1)
12679 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12680 (< pos (match-beginning 2)))
12682 (setq tags-l (- (match-end 2) (match-beginning 2)))
12683 (goto-char (match-beginning 1))
12685 (delete-region (point) (1+ (match-beginning 2)))
12686 (setq ncol (max (1+ (current-column))
12690 (- (abs to-col) tags-l))))
12692 (insert (make-string (- ncol (current-column)) ?\ ))
12693 (setq ncol (current-column))
12694 (when indent-tabs-mode (tabify p (point-at-eol)))
12695 (org-move-to-column (min ncol col) t))
12698 (defun org-set-tags-command (&optional arg just-align)
12699 "Call the set-tags command for the current entry."
12701 (if (org-on-heading-p)
12702 (org-set-tags arg just-align)
12704 (org-back-to-heading t)
12705 (org-set-tags arg just-align))))
12707 (defun org-set-tags-to (data)
12708 "Set the tags of the current entry to DATA, replacing the current tags.
12709 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12710 If DATA is nil or the empty string, any tags will be removed."
12711 (interactive "sTags: ")
12715 ((equal data "") "")
12717 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12720 (concat ":" (mapconcat 'identity data ":") ":"))
12724 (org-back-to-heading t)
12725 (when (looking-at org-complex-heading-regexp)
12728 (goto-char (match-beginning 5))
12730 (delete-region (point) (point-at-eol))
12731 (org-set-tags nil 'align))
12732 (goto-char (point-at-eol))
12734 (org-set-tags nil 'align)))
12735 (beginning-of-line 1)
12736 (if (looking-at ".*?\\([ \t]+\\)$")
12737 (delete-region (match-beginning 1) (match-end 1))))))
12739 (defun org-align-all-tags ()
12740 "Align the tags i all headings."
12743 (or (ignore-errors (org-back-to-heading t))
12744 (outline-next-heading))
12745 (if (org-on-heading-p)
12747 (message "No headings"))))
12749 (defun org-set-tags (&optional arg just-align)
12750 "Set the tags for the current headline.
12751 With prefix ARG, realign all tags in headings in the current buffer."
12753 (let* ((re (concat "^" outline-regexp))
12754 (current (org-get-tags-string))
12755 (col (current-column))
12756 (org-setting-tags t)
12757 table current-tags inherited-tags ; computed below when needed
12761 (goto-char (point-min))
12762 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12763 (while (re-search-forward re nil t)
12764 (org-set-tags nil t)
12766 (message "All tags realigned to column %d" org-tags-column))
12768 (setq tags current)
12769 ;; Get a new set of tags from the user
12771 (setq table (append org-tag-persistent-alist
12772 (or org-tag-alist (org-get-buffer-tags))
12773 (and org-complete-tags-always-offer-all-agenda-tags
12774 (org-global-tags-completion-table (org-agenda-files))))
12775 org-last-tags-completion-table table
12776 current-tags (org-split-string current ":")
12777 inherited-tags (nreverse
12778 (nthcdr (length current-tags)
12779 (nreverse (org-get-tags-at))))
12781 (if (or (eq t org-use-fast-tag-selection)
12782 (and org-use-fast-tag-selection
12783 (delq nil (mapcar 'cdr table))))
12784 (org-fast-tag-selection
12785 current-tags inherited-tags table
12786 (if org-fast-tag-selection-include-todo org-todo-key-alist))
12787 (let ((org-add-colon-after-tag-completion t))
12789 (org-without-partial-completion
12790 (org-icompleting-read "Tags: " 'org-tags-completion-function
12791 nil nil current 'org-tags-history)))))))
12792 (while (string-match "[-+&]+" tags)
12793 ;; No boolean logic, just a list
12794 (setq tags (replace-match ":" t t tags))))
12796 (if org-tags-sort-function
12797 (setq tags (mapconcat 'identity
12798 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
12799 org-tags-sort-function) ":")))
12801 (if (string-match "\\`[\t ]*\\'" tags)
12803 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
12804 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
12806 ;; Insert new tags at the correct column
12807 (beginning-of-line 1)
12809 ((and (equal current "") (equal tags "")))
12810 ((re-search-forward
12811 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
12813 (if (equal tags "")
12815 (goto-char (match-beginning 0))
12816 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
12817 (1+ (point)) (point))
12818 c1 (max (1+ c0) (if (> org-tags-column 0)
12820 (- (- org-tags-column) (length tags))))
12821 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
12822 (replace-match rpl t t)
12823 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
12825 (t (error "Tags alignment failed")))
12826 (org-move-to-column col)
12828 (run-hooks 'org-after-tags-change-hook)))))
12830 (defun org-change-tag-in-region (beg end tag off)
12831 "Add or remove TAG for each entry in the region.
12832 This works in the agenda, and also in an org-mode buffer."
12834 (list (region-beginning) (region-end)
12835 (let ((org-last-tags-completion-table
12837 (org-get-buffer-tags)
12838 (org-global-tags-completion-table))))
12839 (org-icompleting-read
12840 "Tag: " 'org-tags-completion-function nil nil nil
12841 'org-tags-history))
12843 (message "[s]et or [r]emove? ")
12844 (equal (read-char-exclusive) ?r))))
12845 (if (fboundp 'deactivate-mark) (deactivate-mark))
12846 (let ((agendap (equal major-mode 'org-agenda-mode))
12847 l1 l2 m buf pos newhead (cnt 0))
12849 (setq l2 (1- (org-current-line)))
12851 (setq l1 (org-current-line))
12852 (loop for l from l1 to l2 do
12854 (setq m (get-text-property (point) 'org-hd-marker))
12855 (when (or (and (org-mode-p) (org-on-heading-p))
12857 (setq buf (if agendap (marker-buffer m) (current-buffer))
12858 pos (if agendap m (point)))
12859 (with-current-buffer buf
12863 (setq cnt (1+ cnt))
12864 (org-toggle-tag tag (if off 'off 'on))
12865 (setq newhead (org-get-heading)))))
12866 (and agendap (org-agenda-change-all-lines newhead m))))
12867 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
12869 (defun org-tags-completion-function (string predicate &optional flag)
12870 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12871 (confirm (lambda (x) (stringp (car x)))))
12872 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
12873 (setq s1 (match-string 1 string)
12874 s2 (match-string 2 string))
12875 (setq s1 "" s2 string))
12879 (setq rtn (try-completion s2 ctable confirm))
12882 (concat s1 s2 (substring rtn (length s2))
12883 (if (and org-add-colon-after-tag-completion
12884 (assoc rtn ctable))
12889 (all-completions s2 ctable confirm)
12893 (assoc s2 ctable)))
12896 (defun org-fast-tag-insert (kwd tags face &optional end)
12897 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12898 (insert (format "%-12s" (concat kwd ":"))
12899 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12902 (defun org-fast-tag-show-exit (flag)
12905 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12906 (replace-match ""))
12909 (org-move-to-column (- (window-width) 19) t)
12910 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12912 (defun org-set-current-tags-overlay (current prefix)
12913 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12914 (if (featurep 'xemacs)
12915 (org-overlay-display org-tags-overlay (concat prefix s)
12916 'secondary-selection)
12917 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12918 (org-overlay-display org-tags-overlay (concat prefix s)))))
12920 (defvar org-last-tag-selection-key nil)
12921 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12922 "Fast tag selection with single keys.
12923 CURRENT is the current list of tags in the headline, INHERITED is the
12924 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12925 possibly with grouping information. TODO-TABLE is a similar table with
12926 TODO keywords, should these have keys assigned to them.
12927 If the keys are nil, a-z are automatically assigned.
12928 Returns the new tags string, or nil to not change the current settings."
12929 (let* ((fulltable (append table todo-table))
12930 (maxlen (apply 'max (mapcar
12932 (if (stringp (car x)) (string-width (car x)) 0))
12934 (buf (current-buffer))
12935 (expert (eq org-fast-tag-selection-single-key 'expert))
12937 (fwidth (+ maxlen 3 1 3))
12938 (ncol (/ (- (window-width) 4) fwidth))
12941 tg cnt e c char c1 c2 ntable tbl rtn
12942 ov-start ov-end ov-prefix
12943 (exit-after-next org-fast-tag-selection-single-key)
12944 (done-keywords org-done-keywords)
12947 (beginning-of-line 1)
12949 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12950 (setq ov-start (match-beginning 1)
12951 ov-end (match-end 1)
12953 (setq ov-start (1- (point-at-eol))
12954 ov-end (1+ ov-start))
12955 (skip-chars-forward "^\n\r")
12958 (buffer-substring (1- (point)) (point))
12959 (if (> (current-column) org-tags-column)
12961 (make-string (- org-tags-column (current-column)) ?\ ))))))
12962 (move-overlay org-tags-overlay ov-start ov-end)
12963 (save-window-excursion
12965 (set-buffer (get-buffer-create " *Org tags*"))
12966 (delete-other-windows)
12967 (split-window-vertically)
12968 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12970 (org-set-local 'org-done-keywords done-keywords)
12971 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12972 (org-fast-tag-insert "Current" current c-face "\n\n")
12973 (org-fast-tag-show-exit exit-after-next)
12974 (org-set-current-tags-overlay current ov-prefix)
12975 (setq tbl fulltable char ?a cnt 0)
12976 (while (setq e (pop tbl))
12978 ((equal (car e) :startgroup)
12979 (push '() groups) (setq ingroup t)
12980 (when (not (= cnt 0))
12983 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12984 ((equal (car e) :endgroup)
12985 (setq ingroup nil cnt 0)
12986 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12987 ((equal e '(:newline))
12988 (when (not (= cnt 0))
12992 (while (equal (car tbl) '(:newline))
12994 (setq tbl (cdr tbl)))))
12996 (setq tg (copy-sequence (car e)) c2 nil)
12999 ;; automatically assign a character.
13000 (setq c1 (string-to-char
13001 (downcase (substring
13002 tg (if (= (string-to-char tg) ?@) 1 0)))))
13003 (if (or (rassoc c1 ntable) (rassoc c1 table))
13004 (while (or (rassoc char ntable) (rassoc char table))
13005 (setq char (1+ char)))
13007 (setq c (or c2 char)))
13008 (if ingroup (push tg (car groups)))
13009 (setq tg (org-add-props tg nil 'face
13011 ((not (assoc tg table))
13012 (org-get-todo-face tg))
13013 ((member tg current) c-face)
13014 ((member tg inherited) i-face)
13016 (if (and (= cnt 0) (not ingroup)) (insert " "))
13017 (insert "[" c "] " tg (make-string
13018 (- fwidth 4 (length tg)) ?\ ))
13019 (push (cons tg c) ntable)
13020 (when (= (setq cnt (1+ cnt)) ncol)
13022 (if ingroup (insert " "))
13024 (setq ntable (nreverse ntable))
13026 (goto-char (point-min))
13027 (if (not expert) (org-fit-window-to-buffer))
13031 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13032 (if (not groups) "no " "")
13033 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13034 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13035 (setq org-last-tag-selection-key c)
13037 ((= c ?\r) (throw 'exit t))
13039 (setq groups (not groups))
13040 (goto-char (point-min))
13041 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13044 (org-fast-tag-show-exit
13045 (setq exit-after-next (not exit-after-next)))
13047 (delete-other-windows)
13048 (split-window-vertically)
13049 (org-switch-to-buffer-other-window " *Org tags*")
13050 (org-fit-window-to-buffer)))
13052 (and (= c ?q) (not (rassoc c ntable))))
13053 (org-detach-overlay org-tags-overlay)
13054 (setq quit-flag t))
13057 (if exit-after-next (setq exit-after-next 'now)))
13059 (condition-case nil
13060 (setq tg (org-icompleting-read
13063 (with-current-buffer buf
13064 (org-get-buffer-tags)))))
13065 (quit (setq tg "")))
13066 (when (string-match "\\S-" tg)
13067 (add-to-list 'buffer-tags (list tg))
13068 (if (member tg current)
13069 (setq current (delete tg current))
13070 (push tg current)))
13071 (if exit-after-next (setq exit-after-next 'now)))
13072 ((setq e (rassoc c todo-table) tg (car e))
13073 (with-current-buffer buf
13074 (save-excursion (org-todo tg)))
13075 (if exit-after-next (setq exit-after-next 'now)))
13076 ((setq e (rassoc c ntable) tg (car e))
13077 (if (member tg current)
13078 (setq current (delete tg current))
13079 (loop for g in groups do
13082 (setq current (delete x current)))
13085 (if exit-after-next (setq exit-after-next 'now))))
13087 ;; Create a sorted list
13091 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13092 (if (eq exit-after-next 'now) (throw 'exit t))
13093 (goto-char (point-min))
13094 (beginning-of-line 2)
13095 (delete-region (point) (point-at-eol))
13096 (org-fast-tag-insert "Current" current c-face)
13097 (org-set-current-tags-overlay current ov-prefix)
13098 (while (re-search-forward
13099 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
13100 (setq tg (match-string 1))
13101 (add-text-properties
13102 (match-beginning 1) (match-end 1)
13105 ((member tg current) c-face)
13106 ((member tg inherited) i-face)
13107 (t (get-text-property (match-beginning 1) 'face))))))
13108 (goto-char (point-min)))))
13109 (org-detach-overlay org-tags-overlay)
13111 (mapconcat 'identity current ":")
13114 (defun org-get-tags-string ()
13115 "Get the TAGS string in the current headline."
13116 (unless (org-on-heading-p t)
13117 (error "Not on a heading"))
13119 (beginning-of-line 1)
13120 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13121 (org-match-string-no-properties 1)
13124 (defun org-get-tags ()
13125 "Get the list of tags specified in the current headline."
13126 (org-split-string (org-get-tags-string) ":"))
13128 (defun org-get-buffer-tags ()
13129 "Get a table of all tags used in the buffer, for completion."
13132 (goto-char (point-min))
13133 (while (re-search-forward
13134 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
13135 (when (equal (char-after (point-at-bol 0)) ?*)
13136 (mapc (lambda (x) (add-to-list 'tags x))
13137 (org-split-string (org-match-string-no-properties 1) ":")))))
13138 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13139 (mapcar 'list tags)))
13141 ;;;; The mapping API
13144 (defun org-map-entries (func &optional match scope &rest skip)
13145 "Call FUNC at each headline selected by MATCH in SCOPE.
13147 FUNC is a function or a lisp form. The function will be called without
13148 arguments, with the cursor positioned at the beginning of the headline.
13149 The return values of all calls to the function will be collected and
13150 returned as a list.
13152 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13153 does not need to preserve point. After evaluation, the cursor will be
13154 moved to the end of the line (presumably of the headline of the
13155 processed entry) and search continues from there. Under some
13156 circumstances, this may not produce the wanted results. For example,
13157 if you have removed (e.g. archived) the current (sub)tree it could
13158 mean that the next entry will be skipped entirely. In such cases, you
13159 can specify the position from where search should continue by making
13160 FUNC set the variable `org-map-continue-from' to the desired buffer
13163 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13164 Only headlines that are matched by this query will be considered during
13165 the iteration. When MATCH is nil or t, all headlines will be
13166 visited by the iteration.
13168 SCOPE determines the scope of this command. It can be any of:
13170 nil The current buffer, respecting the restriction if any
13171 tree The subtree started with the entry at point
13172 file The current buffer, without restriction
13174 The current buffer, and any archives associated with it
13175 agenda All agenda files
13176 agenda-with-archives
13177 All agenda files with any archive files associated with them
13179 If this is a list, all files in the list will be scanned
13181 The remaining args are treated as settings for the skipping facilities of
13182 the scanner. The following items can be given here:
13184 archive skip trees with the archive tag.
13185 comment skip trees with the COMMENT keyword
13186 function or Emacs Lisp form:
13187 will be used as value for `org-agenda-skip-function', so whenever
13188 the function returns t, FUNC will not be called for that
13189 entry and search will continue from the point where the
13190 function leaves it.
13192 If your function needs to retrieve the tags including inherited tags
13193 at the *current* entry, you can use the value of the variable
13194 `org-scanner-tags' which will be much faster than getting the value
13195 with `org-get-tags-at'. If your function gets properties with
13196 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13197 to t around the call to `org-entry-properties' to get the same speedup.
13198 Note that if your function moves around to retrieve tags and properties at
13199 a *different* entry, you cannot use these techniques."
13200 (let* ((org-agenda-archives-mode nil) ; just to make sure
13201 (org-agenda-skip-archived-trees (memq 'archive skip))
13202 (org-agenda-skip-comment-trees (memq 'comment skip))
13203 (org-agenda-skip-function
13204 (car (org-delete-all '(comment archive) skip)))
13205 (org-tags-match-list-sublevels t)
13207 org-todo-keywords-for-agenda
13208 org-done-keywords-for-agenda
13209 org-todo-keyword-alist-for-agenda
13210 org-drawers-for-agenda
13211 org-tag-alist-for-agenda)
13214 ((eq match t) (setq matcher t))
13215 ((eq match nil) (setq matcher t))
13216 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13220 (when (eq scope 'tree)
13221 (org-back-to-heading t)
13222 (org-narrow-to-subtree)
13227 (org-prepare-agenda-buffers
13228 (list (buffer-file-name (current-buffer))))
13229 (setq res (org-scan-tags func matcher)))
13230 ;; Get the right scope
13232 ((and scope (listp scope) (symbolp (car scope)))
13233 (setq scope (eval scope)))
13234 ((eq scope 'agenda)
13235 (setq scope (org-agenda-files t)))
13236 ((eq scope 'agenda-with-archives)
13237 (setq scope (org-agenda-files t))
13238 (setq scope (org-add-archive-files scope)))
13240 (setq scope (list (buffer-file-name))))
13241 ((eq scope 'file-with-archives)
13242 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13243 (org-prepare-agenda-buffers scope)
13244 (while (setq file (pop scope))
13245 (with-current-buffer (org-find-base-buffer-visiting file)
13249 (goto-char (point-min))
13250 (setq res (append res (org-scan-tags func matcher))))))))))
13255 ;;; Setting and retrieving properties
13257 (defconst org-special-properties
13258 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13259 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
13260 "The special properties valid in Org-mode.
13262 These are properties that are not defined in the property drawer,
13263 but in some other way.")
13265 (defconst org-default-properties
13266 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13267 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13268 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13269 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13270 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13271 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13272 "Some properties that are used by Org-mode for various purposes.
13273 Being in this list makes sure that they are offered for completion.")
13275 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13276 "Regular expression matching the first line of a property drawer.")
13278 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13279 "Regular expression matching the last line of a property drawer.")
13281 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13282 "Regular expression matching the first line of a property drawer.")
13284 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13285 "Regular expression matching the first line of a property drawer.")
13287 (defconst org-property-drawer-re
13288 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13289 org-property-end-re "\\)\n?")
13290 "Matches an entire property drawer.")
13292 (defconst org-clock-drawer-re
13293 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13294 org-property-end-re "\\)\n?")
13295 "Matches an entire clock drawer.")
13297 (defun org-property-action ()
13298 "Do an action on properties."
13301 (org-at-property-p)
13302 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13303 (setq c (read-char-exclusive))
13306 (call-interactively 'org-set-property))
13308 (call-interactively 'org-delete-property))
13310 (call-interactively 'org-delete-property-globally))
13312 (call-interactively 'org-compute-property-at-point))
13313 (t (error "No such property action %c" c)))))
13315 (defun org-set-effort (&optional value)
13316 "Set the effort property of the current entry.
13317 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13320 (if (equal value 0) (setq value 10))
13321 (let* ((completion-ignore-case t)
13322 (prop org-effort-property)
13323 (cur (org-entry-get nil prop))
13324 (allowed (org-property-get-allowed-values nil prop 'table))
13325 (existing (mapcar 'list (org-property-values prop)))
13328 ((stringp value) value)
13329 ((and allowed (integerp value))
13330 (or (car (nth (1- value) allowed))
13331 (car (org-last allowed))))
13333 (message "Select 1-9,0, [RET%s]: %s"
13334 (if cur (concat "=" cur) "")
13335 (mapconcat 'car allowed " "))
13336 (setq rpl (read-char-exclusive))
13337 (if (equal rpl ?\r)
13339 (setq rpl (- rpl ?0))
13340 (if (equal rpl 0) (setq rpl 10))
13341 (if (and (> rpl 0) (<= rpl (length allowed)))
13342 (car (nth (1- rpl) allowed))
13343 (org-completing-read "Effort: " allowed nil))))
13345 (let (org-completion-use-ido org-completion-use-iswitchb)
13346 (org-completing-read
13347 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13348 (concat "[" cur "]") "")
13350 existing nil nil "" nil cur))))))
13351 (unless (equal (org-entry-get nil prop) val)
13352 (org-entry-put nil prop val))
13353 (message "%s is now %s" prop val)))
13355 (defun org-at-property-p ()
13356 "Is cursor inside a property drawer?"
13358 (beginning-of-line 1)
13359 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13360 (save-match-data ;; Used by calling procedures
13362 (range (unless (org-before-first-heading-p)
13363 (org-get-property-block))))
13364 (and range (<= (car range) p) (< p (cdr range))))))))
13366 (defun org-get-property-block (&optional beg end force)
13367 "Return the (beg . end) range of the body of the property drawer.
13368 BEG and END can be beginning and end of subtree, if not given
13369 they will be found.
13370 If the drawer does not exist and FORCE is non-nil, create the drawer."
13373 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13374 (end (or end (progn (outline-next-heading) (point)))))
13376 (if (re-search-forward org-property-start-re end t)
13377 (setq beg (1+ (match-end 0)))
13380 (org-insert-property-drawer)
13381 (setq end (progn (outline-next-heading) (point))))
13384 (if (re-search-forward org-property-start-re end t)
13385 (setq beg (1+ (match-end 0)))))
13386 (if (re-search-forward org-property-end-re end t)
13387 (setq end (match-beginning 0))
13388 (or force (throw 'exit nil))
13391 (org-indent-line-function)
13392 (insert ":END:\n"))
13395 (defun org-entry-properties (&optional pom which specific)
13396 "Get all properties of the entry at point-or-marker POM.
13397 This includes the TODO keyword, the tags, time strings for deadline,
13398 scheduled, and clocking, and any additional properties defined in the
13399 entry. The return value is an alist, keys may occur multiple times
13400 if the property key was used several times.
13401 POM may also be nil, in which case the current entry is used.
13402 If WHICH is nil or `all', get all properties. If WHICH is
13403 `special' or `standard', only get that subclass. If WHICH
13404 is a string only get exactly this property. Specific can be a string, the
13405 specific property we are interested in. Specifying it can speed
13406 things up because then unnecessary parsing is avoided."
13407 (setq which (or which 'all))
13408 (org-with-point-at pom
13409 (let ((clockstr (substring org-clock-string 0 -1))
13410 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13411 (case-fold-search nil)
13412 beg end range props sum-props key key1 value string clocksum)
13414 (when (condition-case nil
13415 (and (org-mode-p) (org-back-to-heading t))
13418 (setq sum-props (get-text-property (point) 'org-summaries))
13419 (setq clocksum (get-text-property (point) :org-clock-minutes))
13420 (outline-next-heading)
13422 (when (memq which '(all special))
13423 ;; Get the special properties, like TODO and tags
13425 (when (and (or (not specific) (string= specific "TODO"))
13426 (looking-at org-todo-line-regexp) (match-end 2))
13427 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13428 (when (and (or (not specific) (string= specific "PRIORITY"))
13429 (looking-at org-priority-regexp))
13430 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13431 (when (and (or (not specific) (string= specific "TAGS"))
13432 (setq value (org-get-tags-string))
13433 (string-match "\\S-" value))
13434 (push (cons "TAGS" value) props))
13435 (when (and (or (not specific) (string= specific "ALLTAGS"))
13436 (setq value (org-get-tags-at)))
13437 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13440 (when (or (not specific) (string= specific "BLOCKED"))
13441 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13442 (when (or (not specific)
13444 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
13445 "TIMESTAMP" "TIMESTAMP_IA")))
13446 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13447 (setq key (if (match-end 1)
13448 (substring (org-match-string-no-properties 1)
13450 string (if (equal key clockstr)
13454 (match-beginning 3) (goto-char
13456 (substring (org-match-string-no-properties 3)
13458 ;; Get the correct property name from the key. This is
13459 ;; necessary if the user has configured time keywords.
13460 (setq key1 (concat key ":"))
13464 (if (= (char-after (match-beginning 3)) ?\[)
13465 "TIMESTAMP_IA" "TIMESTAMP")))
13466 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
13467 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
13468 ((equal key1 org-closed-string) (setq key "CLOSED"))
13469 ((equal key1 org-clock-string) (setq key "CLOCK")))
13470 (when (or (equal key "CLOCK") (not (assoc key props)))
13471 (push (cons key string) props))))
13474 (when (memq which '(all standard))
13475 ;; Get the standard properties, like :PROP: ...
13476 (setq range (org-get-property-block beg end))
13478 (goto-char (car range))
13479 (while (re-search-forward
13480 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
13482 (setq key (org-match-string-no-properties 1)
13483 value (org-trim (or (org-match-string-no-properties 2) "")))
13484 (unless (member key excluded)
13485 (push (cons key (or value "")) props)))))
13487 (push (cons "CLOCKSUM"
13488 (org-columns-number-to-string (/ (float clocksum) 60.)
13491 (unless (assoc "CATEGORY" props)
13492 (setq value (or (org-get-category)
13493 (progn (org-refresh-category-properties)
13494 (org-get-category))))
13495 (push (cons "CATEGORY" value) props))
13496 (append sum-props (nreverse props)))))))
13498 (defun org-entry-get (pom property &optional inherit literal-nil)
13499 "Get value of PROPERTY for entry at point-or-marker POM.
13500 If INHERIT is non-nil and the entry does not have the property,
13501 then also check higher levels of the hierarchy.
13502 If INHERIT is the symbol `selective', use inheritance only if the setting
13503 in `org-use-property-inheritance' selects PROPERTY for inheritance.
13504 If the property is present but empty, the return value is the empty string.
13505 If the property is not present at all, nil is returned.
13507 If LITERAL-NIL is set, return the string value \"nil\" as a string,
13508 do not interpret it as the list atom nil. This is used for inheritance
13509 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
13510 (org-with-point-at pom
13511 (if (and inherit (if (eq inherit 'selective)
13512 (org-property-inherit-p property)
13514 (org-entry-get-with-inheritance property literal-nil)
13515 (if (member property org-special-properties)
13516 ;; We need a special property. Use `org-entry-properties' to
13517 ;; retrieve it, but specify the wanted property
13518 (cdr (assoc property (org-entry-properties nil 'special property)))
13519 (let ((range (org-get-property-block)))
13521 (goto-char (car range))
13523 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
13525 ;; Found the property, return it.
13528 (org-match-string-no-properties 1)
13529 (org-not-nil (org-match-string-no-properties 1)))
13532 (defun org-property-or-variable-value (var &optional inherit)
13533 "Check if there is a property fixing the value of VAR.
13534 If yes, return this value. If not, return the current value of the variable."
13535 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13536 (if (and prop (stringp prop) (string-match "\\S-" prop))
13538 (symbol-value var))))
13540 (defun org-entry-delete (pom property)
13541 "Delete the property PROPERTY from entry at point-or-marker POM."
13542 (org-with-point-at pom
13543 (if (member property org-special-properties)
13544 nil ; cannot delete these properties.
13545 (let ((range (org-get-property-block)))
13547 (goto-char (car range))
13549 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
13552 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13556 ;; Multi-values properties are properties that contain multiple values
13557 ;; These values are assumed to be single words, separated by whitespace.
13558 (defun org-entry-add-to-multivalued-property (pom property value)
13559 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
13560 (let* ((old (org-entry-get pom property))
13561 (values (and old (org-split-string old "[ \t]"))))
13562 (setq value (org-entry-protect-space value))
13563 (unless (member value values)
13564 (setq values (cons value values))
13565 (org-entry-put pom property
13566 (mapconcat 'identity values " ")))))
13568 (defun org-entry-remove-from-multivalued-property (pom property value)
13569 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13570 (let* ((old (org-entry-get pom property))
13571 (values (and old (org-split-string old "[ \t]"))))
13572 (setq value (org-entry-protect-space value))
13573 (when (member value values)
13574 (setq values (delete value values))
13575 (org-entry-put pom property
13576 (mapconcat 'identity values " ")))))
13578 (defun org-entry-member-in-multivalued-property (pom property value)
13579 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
13580 (let* ((old (org-entry-get pom property))
13581 (values (and old (org-split-string old "[ \t]"))))
13582 (setq value (org-entry-protect-space value))
13583 (member value values)))
13585 (defun org-entry-get-multivalued-property (pom property)
13586 "Return a list of values in a multivalued property."
13587 (let* ((value (org-entry-get pom property))
13588 (values (and value (org-split-string value "[ \t]"))))
13589 (mapcar 'org-entry-restore-space values)))
13591 (defun org-entry-put-multivalued-property (pom property &rest values)
13592 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
13593 VALUES should be a list of strings. Spaces will be protected."
13594 (org-entry-put pom property
13595 (mapconcat 'org-entry-protect-space values " "))
13596 (let* ((value (org-entry-get pom property))
13597 (values (and value (org-split-string value "[ \t]"))))
13598 (mapcar 'org-entry-restore-space values)))
13600 (defun org-entry-protect-space (s)
13601 "Protect spaces and newline in string S."
13602 (while (string-match " " s)
13603 (setq s (replace-match "%20" t t s)))
13604 (while (string-match "\n" s)
13605 (setq s (replace-match "%0A" t t s)))
13608 (defun org-entry-restore-space (s)
13609 "Restore spaces and newline in string S."
13610 (while (string-match "%20" s)
13611 (setq s (replace-match " " t t s)))
13612 (while (string-match "%0A" s)
13613 (setq s (replace-match "\n" t t s)))
13616 (defvar org-entry-property-inherited-from (make-marker)
13617 "Marker pointing to the entry from where a property was inherited.
13618 Each call to `org-entry-get-with-inheritance' will set this marker to the
13619 location of the entry where the inheritance search matched. If there was
13620 no match, the marker will point nowhere.
13621 Note that also `org-entry-get' calls this function, if the INHERIT flag
13624 (defun org-entry-get-with-inheritance (property &optional literal-nil)
13625 "Get entry property, and search higher levels if not present.
13626 The search will stop at the first ancestor which has the property defined.
13627 If the value found is \"nil\", return nil to show that the property
13628 should be considered as undefined (this is the meaning of nil here).
13629 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
13630 (move-marker org-entry-property-inherited-from nil)
13637 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
13638 (org-back-to-heading t)
13639 (move-marker org-entry-property-inherited-from (point))
13641 (or (org-up-heading-safe) (throw 'ex nil)))))
13643 (cdr (assoc property org-file-properties))
13644 (cdr (assoc property org-global-properties))
13645 (cdr (assoc property org-global-properties-fixed))))
13646 (if literal-nil tmp (org-not-nil tmp)))))
13648 (defvar org-property-changed-functions nil
13649 "Hook called when the value of a property has changed.
13650 Each hook function should accept two arguments, the name of the property
13651 and the new value.")
13653 (defun org-entry-put (pom property value)
13654 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13655 (org-with-point-at pom
13656 (org-back-to-heading t)
13657 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13660 ((equal property "TODO")
13661 (when (and (stringp value) (string-match "\\S-" value)
13662 (not (member value org-todo-keywords-1)))
13663 (error "\"%s\" is not a valid TODO state" value))
13664 (if (or (not value)
13665 (not (string-match "\\S-" value)))
13666 (setq value 'none))
13668 (org-set-tags nil 'align))
13669 ((equal property "PRIORITY")
13670 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13671 (string-to-char value) ?\ ))
13672 (org-set-tags nil 'align))
13673 ((equal property "SCHEDULED")
13674 (if (re-search-forward org-scheduled-time-regexp end t)
13676 ((eq value 'earlier) (org-timestamp-change -1 'day))
13677 ((eq value 'later) (org-timestamp-change 1 'day))
13678 (t (call-interactively 'org-schedule)))
13679 (call-interactively 'org-schedule)))
13680 ((equal property "DEADLINE")
13681 (if (re-search-forward org-deadline-time-regexp end t)
13683 ((eq value 'earlier) (org-timestamp-change -1 'day))
13684 ((eq value 'later) (org-timestamp-change 1 'day))
13685 (t (call-interactively 'org-deadline)))
13686 (call-interactively 'org-deadline)))
13687 ((member property org-special-properties)
13688 (error "The %s property can not yet be set with `org-entry-put'"
13690 (t ; a non-special property
13691 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13692 (setq range (org-get-property-block beg end 'force))
13693 (goto-char (car range))
13694 (if (re-search-forward
13695 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
13697 (delete-region (match-beginning 1) (match-end 1))
13698 (goto-char (match-beginning 1)))
13699 (goto-char (cdr range))
13702 (org-indent-line-function)
13703 (insert ":" property ":"))
13704 (and value (insert " " value))
13705 (org-indent-line-function)))))
13706 (run-hook-with-args 'org-property-changed-functions property value)))
13708 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13709 "Get all property keys in the current buffer.
13710 With INCLUDE-SPECIALS, also list the special properties that reflect things
13711 like tags and TODO state.
13712 With INCLUDE-DEFAULTS, also include properties that has special meaning
13713 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
13714 With INCLUDE-COLUMNS, also include property names given in COLUMN
13715 formats in the current buffer."
13716 (let (rtn range cfmt s p)
13720 (goto-char (point-min))
13721 (while (re-search-forward org-property-start-re nil t)
13722 (setq range (org-get-property-block))
13723 (goto-char (car range))
13724 (while (re-search-forward
13725 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13727 (add-to-list 'rtn (org-match-string-no-properties 1)))
13728 (outline-next-heading))))
13730 (when include-specials
13731 (setq rtn (append org-special-properties rtn)))
13733 (when include-defaults
13734 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13735 (add-to-list 'rtn org-effort-property))
13737 (when include-columns
13741 (goto-char (point-min))
13742 (while (re-search-forward
13743 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13745 (setq cfmt (match-string 2) s 0)
13746 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13748 (setq s (match-end 0)
13749 p (match-string 1 cfmt))
13750 (unless (or (equal p "ITEM")
13751 (member p org-special-properties))
13752 (add-to-list 'rtn (match-string 1 cfmt))))))))
13754 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13756 (defun org-property-values (key)
13757 "Return a list of all values of property KEY."
13761 (goto-char (point-min))
13762 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
13764 (while (re-search-forward re nil t)
13765 (add-to-list 'values (org-trim (match-string 1))))
13766 (delete "" values)))))
13768 (defun org-insert-property-drawer ()
13769 "Insert a property drawer into the current entry."
13771 (org-back-to-heading t)
13772 (looking-at outline-regexp)
13773 (let ((indent (if org-adapt-indentation
13774 (- (match-end 0)(match-beginning 0))
13777 (re (concat "^[ \t]*" org-keyword-time-regexp))
13779 (outline-next-heading)
13782 (while (re-search-forward re end t))
13783 (setq hiddenp (org-invisible-p))
13785 (and (equal (char-after) ?\n) (forward-char 1))
13786 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
13787 (if (member (match-string 1) '("CLOCK:" ":END:"))
13788 ;; just skip this line
13789 (beginning-of-line 2)
13790 ;; Drawer start, find the end
13791 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
13792 (beginning-of-line 1)))
13793 (org-skip-over-state-notes)
13794 (skip-chars-backward " \t\n\r")
13795 (if (eq (char-before) ?*) (forward-char 1))
13796 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
13797 (beginning-of-line 0)
13798 (org-indent-to-column indent)
13799 (beginning-of-line 2)
13800 (org-indent-to-column indent)
13801 (beginning-of-line 0)
13804 (org-back-to-heading t)
13806 (org-flag-drawer t))))
13808 (defun org-set-property (property value)
13809 "In the current entry, set PROPERTY to VALUE.
13810 When called interactively, this will prompt for a property name, offering
13811 completion on existing and default properties. And then it will prompt
13812 for a value, offering completion either on allowed values (via an inherited
13813 xxx_ALL property) or on existing values in other instances of this property
13814 in the current file."
13816 (let* ((completion-ignore-case t)
13817 (keys (org-buffer-property-keys nil t t))
13818 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
13819 (prop (if (member prop0 keys)
13821 (or (cdr (assoc (downcase prop0)
13822 (mapcar (lambda (x) (cons (downcase x) x))
13825 (cur (org-entry-get nil prop))
13826 (prompt (concat prop " value"
13827 (if (and cur (string-match "\\S-" cur))
13828 (concat " [" cur "]") "") ": "))
13829 (allowed (org-property-get-allowed-values nil prop 'table))
13830 (existing (mapcar 'list (org-property-values prop)))
13832 (org-completing-read prompt allowed nil
13833 (not (get-text-property 0 'org-unrestricted
13835 (let (org-completion-use-ido org-completion-use-iswitchb)
13836 (org-completing-read prompt existing nil nil "" nil cur)))))
13837 (list prop (if (equal val "") cur val))))
13838 (unless (equal (org-entry-get nil property) value)
13839 (org-entry-put nil property value)))
13841 (defun org-delete-property (property)
13842 "In the current entry, delete PROPERTY."
13844 (let* ((completion-ignore-case t)
13845 (prop (org-icompleting-read "Property: "
13846 (org-entry-properties nil 'standard))))
13848 (message "Property %s %s" property
13849 (if (org-entry-delete nil property)
13851 "was not present in the entry")))
13853 (defun org-delete-property-globally (property)
13854 "Remove PROPERTY globally, from all entries."
13856 (let* ((completion-ignore-case t)
13857 (prop (org-icompleting-read
13858 "Globally remove property: "
13859 (mapcar 'list (org-buffer-property-keys)))))
13864 (goto-char (point-min))
13866 (while (re-search-forward
13867 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
13869 (setq cnt (1+ cnt))
13870 (replace-match ""))
13871 (message "Property \"%s\" removed from %d entries" property cnt)))))
13873 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
13875 (defun org-compute-property-at-point ()
13876 "Compute the property at point.
13877 This looks for an enclosing column format, extracts the operator and
13878 then applies it to the property in the column format's scope."
13880 (unless (org-at-property-p)
13881 (error "Not at a property"))
13882 (let ((prop (org-match-string-no-properties 2)))
13883 (org-columns-get-format-and-top-level)
13884 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
13885 (error "No operator defined for property %s" prop))
13886 (org-columns-compute prop)))
13888 (defvar org-property-allowed-value-functions nil
13889 "Hook for functions supplying allowed values for a specific property.
13890 The functions must take a single argument, the name of the property, and
13891 return a flat list of allowed values. If \":ETC\" is one of
13892 the values, this means that these values are intended as defaults for
13893 completion, but that other values should be allowed too.
13894 The functions must return nil if they are not responsible for this
13897 (defun org-property-get-allowed-values (pom property &optional table)
13898 "Get allowed values for the property PROPERTY.
13899 When TABLE is non-nil, return an alist that can directly be used for
13903 ((equal property "TODO")
13904 (setq vals (org-with-point-at pom
13905 (append org-todo-keywords-1 '("")))))
13906 ((equal property "PRIORITY")
13907 (let ((n org-lowest-priority))
13908 (while (>= n org-highest-priority)
13909 (push (char-to-string n) vals)
13911 ((member property org-special-properties))
13912 ((setq vals (run-hook-with-args-until-success
13913 'org-property-allowed-value-functions property)))
13915 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13916 (when (and vals (string-match "\\S-" vals))
13917 (setq vals (car (read-from-string (concat "(" vals ")"))))
13918 (setq vals (mapcar (lambda (x)
13919 (cond ((stringp x) x)
13920 ((numberp x) (number-to-string x))
13921 ((symbolp x) (symbol-name x))
13924 (when (member ":ETC" vals)
13925 (setq vals (remove ":ETC" vals))
13926 (org-add-props (car vals) '(org-unrestricted t)))
13927 (if table (mapcar 'list vals) vals)))
13929 (defun org-property-previous-allowed-value (&optional previous)
13930 "Switch to the next allowed value for this property."
13932 (org-property-next-allowed-value t))
13934 (defun org-property-next-allowed-value (&optional previous)
13935 "Switch to the next allowed value for this property."
13937 (unless (org-at-property-p)
13938 (error "Not at a property"))
13939 (let* ((key (match-string 2))
13940 (value (match-string 3))
13941 (allowed (or (org-property-get-allowed-values (point) key)
13942 (and (member value '("[ ]" "[-]" "[X]"))
13946 (error "Allowed values for this property have not been defined"))
13947 (if previous (setq allowed (reverse allowed)))
13948 (if (member value allowed)
13949 (setq nval (car (cdr (member value allowed)))))
13950 (setq nval (or nval (car allowed)))
13951 (if (equal nval value)
13952 (error "Only one allowed value for this property"))
13953 (org-at-property-p)
13954 (replace-match (concat " :" key ": " nval) t t)
13955 (org-indent-line-function)
13956 (beginning-of-line 1)
13957 (skip-chars-forward " \t")
13958 (run-hook-with-args 'org-property-changed-functions key nval)))
13960 (defun org-find-olp (path &optional this-buffer)
13961 "Return a marker pointing to the entry at outline path OLP.
13962 If anything goes wrong, throw an error.
13963 You can wrap this call to catch the error like this:
13965 (condition-case msg
13966 (org-mobile-locate-entry (match-string 4))
13967 (error (nth 1 msg)))
13969 The return value will then be either a string with the error message,
13970 or a marker if everything is OK.
13972 If THIS-BUFFER is set, the outline path does not contain a file,
13974 (let* ((file (if this-buffer buffer-file-name (pop path)))
13975 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
13979 limit re end found pos heading cnt)
13980 (unless buffer (error "File not found :%s" file))
13981 (with-current-buffer buffer
13985 (setq limit (point-max))
13986 (goto-char (point-min))
13987 (while (setq heading (pop path))
13988 (setq re (format org-complex-heading-regexp-format
13989 (regexp-quote heading)))
13990 (setq cnt 0 pos (point))
13991 (while (re-search-forward re end t)
13992 (setq level (- (match-end 1) (match-beginning 1)))
13993 (if (and (>= level lmin) (<= level lmax))
13994 (setq found (match-beginning 0) cnt (1+ cnt))))
13995 (when (= cnt 0) (error "Heading not found on level %d: %s"
13997 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14000 (setq lmin (1+ level) lmax (+ lmin (if org-odd-levels-only 1 0)))
14001 (setq end (save-excursion (org-end-of-subtree t t))))
14002 (when (org-on-heading-p)
14003 (move-marker (make-marker) (point))))))))
14005 (defun org-find-exact-headling-in-buffer (heading &optional buffer pos-only)
14006 "Find node HEADING in BUFFER.
14007 Return a marker to the heading if it was found, or nil if not.
14008 If POS-ONLY is set, return just the position instead of a marker.
14010 The heading text must match exact, but it may have a TODO keyword,
14011 a priority cookie and tags in the standard locations."
14012 (with-current-buffer (or buffer (current-buffer))
14016 (goto-char (point-min))
14017 (let (case-fold-search)
14018 (if (re-search-forward
14019 (format org-complex-heading-regexp-format
14020 (regexp-quote heading)) nil t)
14022 (match-beginning 0)
14023 (move-marker (make-marker) (match-beginning 0)))))))))
14025 (defun org-find-exact-heading-in-directory (heading &optional dir)
14026 "Find Org node headline HEADING in all .org files in directory DIR.
14027 When the target headline is found, return a marker to this location."
14028 (let ((files (directory-files (or dir default-directory)
14029 nil "\\`[^.#].*\\.org\\'"))
14030 file visiting m buffer)
14032 (while (setq file (pop files))
14033 (message "trying %s" file)
14034 (setq visiting (org-find-base-buffer-visiting file))
14035 (setq buffer (or visiting (find-file-noselect file)))
14036 (setq m (org-find-exact-headling-in-buffer
14038 (when (and (not m) (not visiting)) (kill-buffer buffer))
14039 (and m (throw 'found m))))))
14041 (defun org-find-entry-with-id (ident)
14042 "Locate the entry that contains the ID property with exact value IDENT.
14043 IDENT can be a string, a symbol or a number, this function will search for
14044 the string representation of it.
14045 Return the position where this entry starts, or nil if there is no such entry."
14046 (interactive "sID: ")
14048 ((stringp ident) ident)
14049 ((symbol-name ident) (symbol-name ident))
14050 ((numberp ident) (number-to-string ident))
14051 (t (error "IDENT %s must be a string, symbol or number" ident))))
14052 (case-fold-search nil))
14056 (goto-char (point-min))
14057 (when (re-search-forward
14058 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14060 (org-back-to-heading t)
14065 (defvar org-last-changed-timestamp nil)
14066 (defvar org-last-inserted-timestamp nil
14067 "The last time stamp inserted with `org-insert-time-stamp'.")
14068 (defvar org-time-was-given) ; dynamically scoped parameter
14069 (defvar org-end-time-was-given) ; dynamically scoped parameter
14070 (defvar org-ts-what) ; dynamically scoped parameter
14072 (defun org-time-stamp (arg &optional inactive)
14073 "Prompt for a date/time and insert a time stamp.
14074 If the user specifies a time like HH:MM, or if this command is called
14075 with a prefix argument, the time stamp will contain date and time.
14076 Otherwise, only the date will be included. All parts of a date not
14077 specified by the user will be filled in from the current date/time.
14078 So if you press just return without typing anything, the time stamp
14079 will represent the current date/time. If there is already a timestamp
14080 at the cursor, it will be modified."
14084 ;; Default time is either today, or, when entering a range,
14085 ;; the range start.
14086 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14088 (re-search-backward
14089 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14090 (- (point) 20) t)))
14091 (apply 'encode-time (org-parse-time-string (match-string 1)))
14093 (default-input (and ts (org-get-compact-tod ts)))
14094 org-time-was-given org-end-time-was-given time)
14096 ((and (org-at-timestamp-p t)
14097 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14098 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14100 (setq time (let ((this-command this-command))
14101 (org-read-date arg 'totime nil nil
14102 default-time default-input)))
14103 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14104 ((org-at-timestamp-p t)
14105 (setq time (let ((this-command this-command))
14106 (org-read-date arg 'totime nil nil default-time default-input)))
14107 (when (org-at-timestamp-p t) ; just to get the match data
14108 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14110 (setq org-last-changed-timestamp
14111 (org-insert-time-stamp
14112 time (or org-time-was-given arg)
14113 inactive nil nil (list org-end-time-was-given))))
14114 (message "Timestamp updated"))
14116 (setq time (let ((this-command this-command))
14117 (org-read-date arg 'totime nil nil default-time default-input)))
14118 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14119 nil nil (list org-end-time-was-given))))))
14121 ;; FIXME: can we use this for something else, like computing time differences?
14122 (defun org-get-compact-tod (s)
14123 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14124 (let* ((t1 (match-string 1 s))
14125 (h1 (string-to-number (match-string 2 s)))
14126 (m1 (string-to-number (match-string 3 s)))
14127 (t2 (and (match-end 4) (match-string 5 s)))
14128 (h2 (and t2 (string-to-number (match-string 6 s))))
14129 (m2 (and t2 (string-to-number (match-string 7 s))))
14133 (setq dh (- h2 h1) dm (- m2 m1))
14134 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14135 (concat t1 "+" (number-to-string dh)
14136 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14138 (defun org-time-stamp-inactive (&optional arg)
14139 "Insert an inactive time stamp.
14140 An inactive time stamp is enclosed in square brackets instead of angle
14141 brackets. It is inactive in the sense that it does not trigger agenda entries,
14142 does not link to the calendar and cannot be changed with the S-cursor keys.
14143 So these are more for recording a certain time/date."
14145 (org-time-stamp arg 'inactive))
14147 (defvar org-date-ovl (make-overlay 1 1))
14148 (overlay-put org-date-ovl 'face 'org-warning)
14149 (org-detach-overlay org-date-ovl)
14151 (defvar org-ans1) ; dynamically scoped parameter
14152 (defvar org-ans2) ; dynamically scoped parameter
14154 (defvar org-plain-time-of-day-regexp) ; defined below
14156 (defvar org-overriding-default-time nil) ; dynamically scoped
14157 (defvar org-read-date-overlay nil)
14158 (defvar org-dcst nil) ; dynamically scoped
14159 (defvar org-read-date-history nil)
14160 (defvar org-read-date-final-answer nil)
14162 (defun org-read-date (&optional with-time to-time from-string prompt
14163 default-time default-input)
14164 "Read a date, possibly a time, and make things smooth for the user.
14165 The prompt will suggest to enter an ISO date, but you can also enter anything
14166 which will at least partially be understood by `parse-time-string'.
14167 Unrecognized parts of the date will default to the current day, month, year,
14168 hour and minute. If this command is called to replace a timestamp at point,
14169 of to enter the second timestamp of a range, the default time is taken
14170 from the existing stamp. Furthermore, the command prefers the future,
14171 so if you are giving a date where the year is not given, and the day-month
14172 combination is already past in the current year, it will assume you
14173 mean next year. For details, see the manual. A few examples:
14175 3-2-5 --> 2003-02-05
14176 feb 15 --> currentyear-02-15
14177 2/15 --> currentyear-02-15
14178 sep 12 9 --> 2009-09-12
14179 12:45 --> today 12:45
14180 22 sept 0:34 --> currentyear-09-22 0:34
14181 12 --> currentyear-currentmonth-12
14182 Fri --> nearest Friday (today or later)
14185 Furthermore you can specify a relative date by giving, as the *first* thing
14186 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14187 change in days weeks, months, years.
14188 With a single plus or minus, the date is relative to today. With a double
14189 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14190 +4d --> four days from today
14191 +4 --> same as above
14192 +2w --> two weeks from today
14193 ++5 --> five days from default date
14195 The function understands only English month and weekday abbreviations,
14196 but this can be configured with the variables `parse-time-months' and
14197 `parse-time-weekdays'.
14199 While prompting, a calendar is popped up - you can also select the
14200 date with the mouse (button 1). The calendar shows a period of three
14201 months. To scroll it to other months, use the keys `>' and `<'.
14202 If you don't like the calendar, turn it off with
14203 \(setq org-read-date-popup-calendar nil)
14205 With optional argument TO-TIME, the date will immediately be converted
14206 to an internal time.
14207 With an optional argument WITH-TIME, the prompt will suggest to also
14208 insert a time. Note that when WITH-TIME is not set, you can still
14209 enter a time, and this function will inform the calling routine about
14210 this change. The calling routine may then choose to change the format
14211 used to insert the time stamp into the buffer to include the time.
14212 With optional argument FROM-STRING, read from this string instead from
14213 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14214 the time/date that is used for everything that is not specified by the
14216 (require 'parse-time)
14217 (let* ((org-time-stamp-rounding-minutes
14218 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14219 (org-dcst org-display-custom-times)
14220 (ct (org-current-time))
14221 (def (or org-overriding-default-time default-time ct))
14222 (defdecode (decode-time def))
14224 (when (< (nth 2 defdecode) org-extend-today-until)
14225 (setcar (nthcdr 2 defdecode) -1)
14226 (setcar (nthcdr 1 defdecode) 59)
14227 (setq def (apply 'encode-time defdecode)
14228 defdecode (decode-time def)))))
14229 (calendar-frame-setup nil)
14230 (calendar-setup nil)
14231 (calendar-move-hook nil)
14232 (calendar-view-diary-initially-flag nil)
14233 (calendar-view-holidays-initially-flag nil)
14234 (timestr (format-time-string
14235 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14236 (prompt (concat (if prompt (concat prompt " ") "")
14237 (format "Date+time [%s]: " timestr)))
14238 ans (org-ans0 "") org-ans1 org-ans2 final)
14241 (from-string (setq ans from-string))
14242 (org-read-date-popup-calendar
14244 (save-window-excursion
14246 (calendar-forward-day (- (time-to-days def)
14247 (calendar-absolute-from-gregorian
14248 (calendar-current-date))))
14249 (org-eval-in-calendar nil t)
14250 (let* ((old-map (current-local-map))
14251 (map (copy-keymap calendar-mode-map))
14252 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14253 (org-defkey map (kbd "RET") 'org-calendar-select)
14254 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14255 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14256 (org-defkey minibuffer-local-map [(meta shift left)]
14257 (lambda () (interactive)
14258 (org-eval-in-calendar '(calendar-backward-month 1))))
14259 (org-defkey minibuffer-local-map [(meta shift right)]
14260 (lambda () (interactive)
14261 (org-eval-in-calendar '(calendar-forward-month 1))))
14262 (org-defkey minibuffer-local-map [(meta shift up)]
14263 (lambda () (interactive)
14264 (org-eval-in-calendar '(calendar-backward-year 1))))
14265 (org-defkey minibuffer-local-map [(meta shift down)]
14266 (lambda () (interactive)
14267 (org-eval-in-calendar '(calendar-forward-year 1))))
14268 (org-defkey minibuffer-local-map [?\e (shift left)]
14269 (lambda () (interactive)
14270 (org-eval-in-calendar '(calendar-backward-month 1))))
14271 (org-defkey minibuffer-local-map [?\e (shift right)]
14272 (lambda () (interactive)
14273 (org-eval-in-calendar '(calendar-forward-month 1))))
14274 (org-defkey minibuffer-local-map [?\e (shift up)]
14275 (lambda () (interactive)
14276 (org-eval-in-calendar '(calendar-backward-year 1))))
14277 (org-defkey minibuffer-local-map [?\e (shift down)]
14278 (lambda () (interactive)
14279 (org-eval-in-calendar '(calendar-forward-year 1))))
14280 (org-defkey minibuffer-local-map [(shift up)]
14281 (lambda () (interactive)
14282 (org-eval-in-calendar '(calendar-backward-week 1))))
14283 (org-defkey minibuffer-local-map [(shift down)]
14284 (lambda () (interactive)
14285 (org-eval-in-calendar '(calendar-forward-week 1))))
14286 (org-defkey minibuffer-local-map [(shift left)]
14287 (lambda () (interactive)
14288 (org-eval-in-calendar '(calendar-backward-day 1))))
14289 (org-defkey minibuffer-local-map [(shift right)]
14290 (lambda () (interactive)
14291 (org-eval-in-calendar '(calendar-forward-day 1))))
14292 (org-defkey minibuffer-local-map ">"
14293 (lambda () (interactive)
14294 (org-eval-in-calendar '(scroll-calendar-left 1))))
14295 (org-defkey minibuffer-local-map "<"
14296 (lambda () (interactive)
14297 (org-eval-in-calendar '(scroll-calendar-right 1))))
14298 (org-defkey minibuffer-local-map "\C-v"
14299 (lambda () (interactive)
14300 (org-eval-in-calendar
14301 '(calendar-scroll-left-three-months 1))))
14302 (org-defkey minibuffer-local-map "\M-v"
14303 (lambda () (interactive)
14304 (org-eval-in-calendar
14305 '(calendar-scroll-right-three-months 1))))
14306 (run-hooks 'org-read-date-minibuffer-setup-hook)
14309 (use-local-map map)
14310 (add-hook 'post-command-hook 'org-read-date-display)
14311 (setq org-ans0 (read-string prompt default-input
14312 'org-read-date-history nil))
14313 ;; org-ans0: from prompt
14314 ;; org-ans1: from mouse click
14315 ;; org-ans2: from calendar motion
14316 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14317 (remove-hook 'post-command-hook 'org-read-date-display)
14318 (use-local-map old-map)
14319 (when org-read-date-overlay
14320 (delete-overlay org-read-date-overlay)
14321 (setq org-read-date-overlay nil)))))))
14323 (t ; Naked prompt only
14325 (setq ans (read-string prompt default-input
14326 'org-read-date-history timestr))
14327 (when org-read-date-overlay
14328 (delete-overlay org-read-date-overlay)
14329 (setq org-read-date-overlay nil)))))
14331 (setq final (org-read-date-analyze ans def defdecode))
14332 (setq org-read-date-final-answer ans)
14335 (apply 'encode-time final)
14336 (if (and (boundp 'org-time-was-given) org-time-was-given)
14337 (format "%04d-%02d-%02d %02d:%02d"
14338 (nth 5 final) (nth 4 final) (nth 3 final)
14339 (nth 2 final) (nth 1 final))
14340 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14345 (defvar org-read-date-analyze-futurep nil)
14346 (defun org-read-date-display ()
14347 "Display the current date prompt interpretation in the minibuffer."
14348 (when org-read-date-display-live
14349 (when org-read-date-overlay
14350 (delete-overlay org-read-date-overlay))
14353 (while (not (equal (buffer-substring
14354 (max (point-min) (- (point) 4)) (point))
14358 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14359 " " (or org-ans1 org-ans2)))
14360 (org-end-time-was-given nil)
14361 (f (org-read-date-analyze ans def defdecode))
14363 org-time-stamp-custom-formats
14364 org-time-stamp-formats))
14365 (fmt (if (or with-time
14366 (and (boundp 'org-time-was-given) org-time-was-given))
14369 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14370 (when (and org-end-time-was-given
14371 (string-match org-plain-time-of-day-regexp txt))
14372 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14373 org-end-time-was-given
14374 (substring txt (match-end 0)))))
14375 (when org-read-date-analyze-futurep
14376 (setq txt (concat txt " (=>F)")))
14377 (setq org-read-date-overlay
14378 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14379 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14381 (defun org-read-date-analyze (ans def defdecode)
14382 "Analyze the combined answer of the date prompt."
14383 ;; FIXME: cleanup and comment
14384 (let ((nowdecode (decode-time (current-time)))
14385 delta deltan deltaw deltadef year month day
14386 hour minute second wday pm h2 m2 tl wday1
14387 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
14388 (setq org-read-date-analyze-futurep nil)
14389 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14392 (when (setq delta (org-read-date-get-relative ans (current-time) def))
14393 (setq ans (replace-match "" t t ans)
14395 deltaw (nth 1 delta)
14396 deltadef (nth 2 delta)))
14398 ;; Check if there is an iso week date in there
14399 ;; If yes, store the info and postpone interpreting it until the rest
14400 ;; of the parsing is done
14401 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
14402 (setq iso-year (if (match-end 1)
14403 (org-small-year-to-year
14404 (string-to-number (match-string 1 ans))))
14405 iso-weekday (if (match-end 3)
14406 (string-to-number (match-string 3 ans)))
14407 iso-week (string-to-number (match-string 2 ans)))
14408 (setq ans (replace-match "" t t ans)))
14410 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
14411 (when (string-match
14412 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
14413 (setq year (if (match-end 2)
14414 (string-to-number (match-string 2 ans))
14415 (progn (setq kill-year t)
14416 (string-to-number (format-time-string "%Y"))))
14417 month (string-to-number (match-string 3 ans))
14418 day (string-to-number (match-string 4 ans)))
14419 (if (< year 100) (setq year (+ 2000 year)))
14420 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14422 ;; Help matching american dates, like 5/30 or 5/30/7
14423 (when (string-match
14424 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
14425 (setq year (if (match-end 4)
14426 (string-to-number (match-string 4 ans))
14427 (progn (setq kill-year t)
14428 (string-to-number (format-time-string "%Y"))))
14429 month (string-to-number (match-string 1 ans))
14430 day (string-to-number (match-string 2 ans)))
14431 (if (< year 100) (setq year (+ 2000 year)))
14432 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14434 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14435 ;; If there is a time with am/pm, and *no* time without it, we convert
14436 ;; so that matching will be successful.
14437 (loop for i from 1 to 2 do ; twice, for end time as well
14438 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
14439 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
14440 (setq hour (string-to-number (match-string 1 ans))
14441 minute (if (match-end 3)
14442 (string-to-number (match-string 3 ans))
14445 (string-to-char (downcase (match-string 4 ans)))))
14446 (if (and (= hour 12) (not pm))
14448 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
14449 (setq ans (replace-match (format "%02d:%02d" hour minute)
14452 ;; Check if a time range is given as a duration
14453 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
14454 (setq hour (string-to-number (match-string 1 ans))
14455 h2 (+ hour (string-to-number (match-string 3 ans)))
14456 minute (string-to-number (match-string 2 ans))
14457 m2 (+ minute (if (match-end 5) (string-to-number
14458 (match-string 5 ans))0)))
14459 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
14460 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
14463 ;; Check if there is a time range
14464 (when (boundp 'org-end-time-was-given)
14465 (setq org-time-was-given nil)
14466 (when (and (string-match org-plain-time-of-day-regexp ans)
14468 (setq org-end-time-was-given (match-string 8 ans))
14469 (setq ans (concat (substring ans 0 (match-beginning 7))
14470 (substring ans (match-end 7))))))
14472 (setq tl (parse-time-string ans)
14473 day (or (nth 3 tl) (nth 3 defdecode))
14474 month (or (nth 4 tl)
14475 (if (and org-read-date-prefer-future
14476 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
14477 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
14478 (nth 4 defdecode)))
14479 year (or (and (not kill-year) (nth 5 tl))
14480 (if (and org-read-date-prefer-future
14481 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
14482 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
14483 (nth 5 defdecode)))
14484 hour (or (nth 2 tl) (nth 2 defdecode))
14485 minute (or (nth 1 tl) (nth 1 defdecode))
14486 second (or (nth 0 tl) 0)
14489 (when (and (eq org-read-date-prefer-future 'time)
14490 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
14491 (equal day (nth 3 nowdecode))
14492 (equal month (nth 4 nowdecode))
14493 (equal year (nth 5 nowdecode))
14495 (or (< (nth 2 tl) (nth 2 nowdecode))
14496 (and (= (nth 2 tl) (nth 2 nowdecode))
14498 (< (nth 1 tl) (nth 1 nowdecode)))))
14502 ;; Special date definitions below
14505 ;; There was an iso week
14508 (setq year (or iso-year year)
14509 day (or iso-weekday wday 1)
14510 wday nil ; to make sure that the trigger below does not match
14511 iso-date (calendar-gregorian-from-absolute
14512 (calendar-absolute-from-iso
14513 (list iso-week day year))))
14514 ; FIXME: Should we also push ISO weeks into the future?
14515 ; (when (and org-read-date-prefer-future
14517 ; (< (calendar-absolute-from-gregorian iso-date)
14518 ; (time-to-days (current-time))))
14519 ; (setq year (1+ year)
14520 ; iso-date (calendar-gregorian-from-absolute
14521 ; (calendar-absolute-from-iso
14522 ; (list iso-week day year)))))
14523 (setq month (car iso-date)
14524 year (nth 2 iso-date)
14525 day (nth 1 iso-date)))
14529 (let ((now (decode-time (current-time))))
14530 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
14531 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
14532 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
14533 ((equal deltaw "m") (setq month (+ month deltan)))
14534 ((equal deltaw "y") (setq year (+ year deltan)))))
14535 ((and wday (not (nth 3 tl)))
14537 ;; Weekday was given, but no day, so pick that day in the week
14538 ;; on or after the derived date.
14539 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
14540 (unless (equal wday wday1)
14541 (setq day (+ day (% (- wday wday1 -7) 7))))))
14542 (if (and (boundp 'org-time-was-given)
14544 (setq org-time-was-given t))
14545 (if (< year 100) (setq year (+ 2000 year)))
14546 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
14547 (setq org-read-date-analyze-futurep futurep)
14548 (list second minute hour day month year)))
14550 (defvar parse-time-weekdays)
14552 (defun org-read-date-get-relative (s today default)
14553 "Check string S for special relative date string.
14554 TODAY and DEFAULT are internal times, for today and for a default.
14555 Return shift list (N what def-flag)
14556 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
14557 N is the number of WHATs to shift.
14558 DEF-FLAG is t when a double ++ or -- indicates shift relative to
14559 the DEFAULT date rather than TODAY."
14563 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
14565 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
14566 "\\([ \t]\\|$\\)") s)
14567 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
14568 (let* ((dir (if (> (match-end 1) (match-beginning 1))
14569 (string-to-char (substring (match-string 1 s) -1))
14571 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
14572 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
14573 (what (if (match-end 3) (match-string 3 s) "d"))
14574 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
14575 (date (if rel default today))
14576 (wday (nth 6 (decode-time date)))
14580 (setq delta (mod (+ 7 (- wday1 wday)) 7))
14581 (if (= dir ?-) (setq delta (- delta 7)))
14582 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
14583 (list delta "d" rel))
14584 (list (* n (if (= dir ?-) -1 1)) what rel)))))
14586 (defun org-order-calendar-date-args (arg1 arg2 arg3)
14587 "Turn a user-specified date into the internal representation.
14588 The internal representation needed by the calendar is (month day year).
14589 This is a wrapper to handle the brain-dead convention in calendar that
14590 user function argument order change dependent on argument order."
14591 (if (boundp 'calendar-date-style)
14593 ((eq calendar-date-style 'american)
14594 (list arg1 arg2 arg3))
14595 ((eq calendar-date-style 'european)
14596 (list arg2 arg1 arg3))
14597 ((eq calendar-date-style 'iso)
14598 (list arg2 arg3 arg1)))
14599 (if (org-bound-and-true-p european-calendar-style)
14600 (list arg2 arg1 arg3)
14601 (list arg1 arg2 arg3))))
14603 (defun org-eval-in-calendar (form &optional keepdate)
14604 "Eval FORM in the calendar window and return to current window.
14605 Also, store the cursor date in variable org-ans2."
14606 (let ((sf (selected-frame))
14607 (sw (selected-window)))
14608 (select-window (get-buffer-window "*Calendar*" t))
14610 (when (and (not keepdate) (calendar-cursor-to-date))
14611 (let* ((date (calendar-cursor-to-date))
14612 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14613 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
14614 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
14616 (org-select-frame-set-input-focus sf)))
14618 (defun org-calendar-select ()
14619 "Return to `org-read-date' with the date currently selected.
14620 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14622 (when (calendar-cursor-to-date)
14623 (let* ((date (calendar-cursor-to-date))
14624 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14625 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14626 (if (active-minibuffer-window) (exit-minibuffer))))
14628 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
14629 "Insert a date stamp for the date given by the internal TIME.
14630 WITH-HM means use the stamp format that includes the time of the day.
14631 INACTIVE means use square brackets instead of angular ones, so that the
14632 stamp will not contribute to the agenda.
14633 PRE and POST are optional strings to be inserted before and after the
14635 The command returns the inserted time stamp."
14636 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
14638 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
14639 (insert-before-markers (or pre ""))
14640 (when (listp extra)
14641 (setq extra (car extra))
14642 (if (and (stringp extra)
14643 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
14644 (setq extra (format "-%02d:%02d"
14645 (string-to-number (match-string 1 extra))
14646 (string-to-number (match-string 2 extra))))
14649 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
14650 (insert-before-markers (setq stamp (format-time-string fmt time)))
14651 (insert-before-markers (or post ""))
14652 (setq org-last-inserted-timestamp stamp)))
14654 (defun org-toggle-time-stamp-overlays ()
14655 "Toggle the use of custom time stamp formats."
14657 (setq org-display-custom-times (not org-display-custom-times))
14658 (unless org-display-custom-times
14659 (let ((p (point-min)) (bmp (buffer-modified-p)))
14660 (while (setq p (next-single-property-change p 'display))
14661 (if (and (get-text-property p 'display)
14662 (eq (get-text-property p 'face) 'org-date))
14663 (remove-text-properties
14664 p (setq p (next-single-property-change p 'display))
14666 (set-buffer-modified-p bmp)))
14667 (if (featurep 'xemacs)
14668 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
14669 (org-restart-font-lock)
14670 (setq org-table-may-need-update t)
14671 (if org-display-custom-times
14672 (message "Time stamps are overlayed with custom format")
14673 (message "Time stamp overlays removed")))
14675 (defun org-display-custom-time (beg end)
14676 "Overlay modified time stamp format over timestamp between BEG and END."
14677 (let* ((ts (buffer-substring beg end))
14678 t1 w1 with-hm tf time str w2 (off 0))
14680 (setq t1 (org-parse-time-string ts t))
14681 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
14682 (setq off (- (match-end 0) (match-beginning 0)))))
14683 (setq end (- end off))
14684 (setq w1 (- end beg)
14685 with-hm (and (nth 1 t1) (nth 2 t1))
14686 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
14687 time (org-fix-decoded-time t1)
14689 (format-time-string
14690 (substring tf 1 -1) (apply 'encode-time time))
14691 nil 'mouse-face 'highlight)
14693 (if (not (= w2 w1))
14694 (add-text-properties (1+ beg) (+ 2 beg)
14695 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
14696 (if (featurep 'xemacs)
14698 (put-text-property beg end 'invisible t)
14699 (put-text-property beg end 'end-glyph (make-glyph str)))
14700 (put-text-property beg end 'display str))))
14702 (defun org-translate-time (string)
14703 "Translate all timestamps in STRING to custom format.
14704 But do this only if the variable `org-display-custom-times' is set."
14705 (when org-display-custom-times
14708 (re org-ts-regexp-both)
14709 t1 with-hm inactive tf time str beg end)
14710 (while (setq start (string-match re string start))
14711 (setq beg (match-beginning 0)
14713 t1 (save-match-data
14714 (org-parse-time-string (substring string beg end) t))
14715 with-hm (and (nth 1 t1) (nth 2 t1))
14716 inactive (equal (substring string beg (1+ beg)) "[")
14717 tf (funcall (if with-hm 'cdr 'car)
14718 org-time-stamp-custom-formats)
14719 time (org-fix-decoded-time t1)
14720 str (format-time-string
14722 (if inactive "[" "<") (substring tf 1 -1)
14723 (if inactive "]" ">"))
14724 (apply 'encode-time time))
14725 string (replace-match str t t string)
14726 start (+ start (length str)))))))
14729 (defun org-fix-decoded-time (time)
14730 "Set 0 instead of nil for the first 6 elements of time.
14731 Don't touch the rest."
14733 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
14735 (defun org-days-to-time (timestamp-string)
14736 "Difference between TIMESTAMP-STRING and now in days."
14737 (- (time-to-days (org-time-string-to-time timestamp-string))
14738 (time-to-days (current-time))))
14740 (defun org-deadline-close (timestamp-string &optional ndays)
14741 "Is the time in TIMESTAMP-STRING close to the current date?"
14742 (setq ndays (or ndays (org-get-wdays timestamp-string)))
14743 (and (< (org-days-to-time timestamp-string) ndays)
14744 (not (org-entry-is-done-p))))
14746 (defun org-get-wdays (ts)
14747 "Get the deadline lead time appropriate for timestring TS."
14749 ((<= org-deadline-warning-days 0)
14750 ;; 0 or negative, enforce this value no matter what
14751 (- org-deadline-warning-days))
14752 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
14753 ;; lead time is specified.
14754 (floor (* (string-to-number (match-string 1 ts))
14755 (cdr (assoc (match-string 2 ts)
14756 '(("d" . 1) ("w" . 7)
14757 ("m" . 30.4) ("y" . 365.25)))))))
14758 ;; go for the default.
14759 (t org-deadline-warning-days)))
14761 (defun org-calendar-select-mouse (ev)
14762 "Return to `org-read-date' with the date currently selected.
14763 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14765 (mouse-set-point ev)
14766 (when (calendar-cursor-to-date)
14767 (let* ((date (calendar-cursor-to-date))
14768 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14769 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14770 (if (active-minibuffer-window) (exit-minibuffer))))
14772 (defun org-check-deadlines (ndays)
14773 "Check if there are any deadlines due or past due.
14774 A deadline is considered due if it happens within `org-deadline-warning-days'
14775 days from today's date. If the deadline appears in an entry marked DONE,
14776 it is not shown. The prefix arg NDAYS can be used to test that many
14777 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
14779 (let* ((org-warn-days
14781 ((equal ndays '(4)) 100000)
14782 (ndays (prefix-numeric-value ndays))
14783 (t (abs org-deadline-warning-days))))
14784 (case-fold-search nil)
14785 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
14787 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
14789 (message "%d deadlines past-due or due within %d days"
14790 (org-occur regexp nil callback)
14793 (defun org-check-before-date (date)
14794 "Check if there are deadlines or scheduled entries before DATE."
14795 (interactive (list (org-read-date)))
14796 (let ((case-fold-search nil)
14797 (regexp (concat "\\<\\(" org-deadline-string
14798 "\\|" org-scheduled-string
14799 "\\) *<\\([^>]+\\)>"))
14801 (lambda () (time-less-p
14802 (org-time-string-to-time (match-string 2))
14803 (org-time-string-to-time date)))))
14804 (message "%d entries before %s"
14805 (org-occur regexp nil callback) date)))
14807 (defun org-check-after-date (date)
14808 "Check if there are deadlines or scheduled entries after DATE."
14809 (interactive (list (org-read-date)))
14810 (let ((case-fold-search nil)
14811 (regexp (concat "\\<\\(" org-deadline-string
14812 "\\|" org-scheduled-string
14813 "\\) *<\\([^>]+\\)>"))
14817 (org-time-string-to-time (match-string 2))
14818 (org-time-string-to-time date))))))
14819 (message "%d entries after %s"
14820 (org-occur regexp nil callback) date)))
14822 (defun org-evaluate-time-range (&optional to-buffer)
14823 "Evaluate a time range by computing the difference between start and end.
14824 Normally the result is just printed in the echo area, but with prefix arg
14825 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
14826 If the time range is actually in a table, the result is inserted into the
14828 For time difference computation, a year is assumed to be exactly 365
14829 days in order to avoid rounding problems."
14832 (org-clock-update-time-maybe)
14834 (unless (org-at-date-range-p t)
14835 (goto-char (point-at-bol))
14836 (re-search-forward org-tr-regexp-both (point-at-eol) t))
14837 (if (not (org-at-date-range-p t))
14838 (error "Not at a time-stamp range, and none found in current line")))
14839 (let* ((ts1 (match-string 1))
14840 (ts2 (match-string 2))
14841 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
14842 (match-end (match-end 0))
14843 (time1 (org-time-string-to-time ts1))
14844 (time2 (org-time-string-to-time ts2))
14845 (t1 (org-float-time time1))
14846 (t2 (org-float-time time2))
14847 (diff (abs (- t2 t1)))
14848 (negative (< (- t2 t1) 0))
14849 ;; (ys (floor (* 365 24 60 60)))
14852 (fy "%dy %dd %02d:%02d")
14854 (fd "%dd %02d:%02d")
14859 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14861 d (floor (/ diff ds)) diff (mod diff ds)
14862 h (floor (/ diff hs)) diff (mod diff hs)
14863 m (floor (/ diff 60)))
14864 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14866 d (floor (+ (/ diff ds) 0.5))
14868 (if (not to-buffer)
14869 (message "%s" (org-make-tdiff-string y d h m))
14870 (if (org-at-table-p)
14872 (goto-char match-end)
14874 (and (looking-at " *|") (goto-char (match-end 0))))
14875 (goto-char match-end))
14877 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
14878 (replace-match ""))
14879 (if negative (insert " -"))
14880 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
14881 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
14882 (insert " " (format fh h m))))
14883 (if align (org-table-align))
14884 (message "Time difference inserted")))))
14886 (defun org-make-tdiff-string (y d h m)
14889 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
14891 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
14893 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
14895 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
14897 (apply 'format fmt (nreverse l))))
14899 (defun org-time-string-to-time (s)
14900 (apply 'encode-time (org-parse-time-string s)))
14901 (defun org-time-string-to-seconds (s)
14902 (org-float-time (org-time-string-to-time s)))
14904 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
14905 "Convert a time stamp to an absolute day number.
14906 If there is a specifier for a cyclic time stamp, get the closest date to
14908 PREFER and SHOW-ALL are passed through to `org-closest-date'.
14909 the variable date is bound by the calendar when this is called."
14911 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
14912 (if (org-diary-sexp-entry (match-string 1 s) "" date)
14915 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
14916 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
14917 (time-to-days (current-time))) (match-string 0 s)
14919 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
14921 (defun org-days-to-iso-week (days)
14922 "Return the iso week number."
14924 (car (calendar-iso-from-absolute days)))
14926 (defun org-small-year-to-year (year)
14927 "Convert 2-digit years into 4-digit years.
14928 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
14929 The year 2000 cannot be abbreviated. Any year larger than 99
14930 is returned unchanged."
14932 (setq year (+ 2000 year))
14934 (setq year (+ 1900 year))))
14937 (defun org-time-from-absolute (d)
14938 "Return the time corresponding to date D.
14939 D may be an absolute day number, or a calendar-type list (month day year)."
14940 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
14941 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
14943 (defun org-calendar-holiday ()
14944 "List of holidays, for Diary display in Org-mode."
14945 (require 'holidays)
14947 (if (fboundp 'calendar-check-holidays)
14948 'calendar-check-holidays 'check-calendar-holidays) date)))
14949 (if hl (mapconcat 'identity hl "; "))))
14951 (defun org-diary-sexp-entry (sexp entry date)
14952 "Process a SEXP diary ENTRY for DATE."
14953 (require 'diary-lib)
14954 (let ((result (if calendar-debug-sexp
14955 (let ((stack-trace-on-error t))
14956 (eval (car (read-from-string sexp))))
14957 (condition-case nil
14958 (eval (car (read-from-string sexp)))
14961 (message "Bad sexp at line %d in %s: %s"
14963 (buffer-file-name) sexp)
14965 (cond ((stringp result) result)
14966 ((and (consp result)
14967 (stringp (cdr result))) (cdr result))
14971 (defun org-diary-to-ical-string (frombuf)
14972 "Get iCalendar entries from diary entries in buffer FROMBUF.
14973 This uses the icalendar.el library."
14974 (let* ((tmpdir (if (featurep 'xemacs)
14976 temporary-file-directory))
14977 (tmpfile (make-temp-name
14978 (expand-file-name "orgics" tmpdir)))
14980 (with-current-buffer frombuf
14981 (icalendar-export-region (point-min) (point-max) tmpfile)
14982 (setq buf (find-buffer-visiting tmpfile))
14984 (goto-char (point-min))
14985 (if (re-search-forward "^BEGIN:VEVENT" nil t)
14986 (setq b (match-beginning 0)))
14987 (goto-char (point-max))
14988 (if (re-search-backward "^END:VEVENT" nil t)
14989 (setq e (match-end 0)))
14990 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
14992 (delete-file tmpfile)
14995 (defun org-closest-date (start current change prefer show-all)
14996 "Find the date closest to CURRENT that is consistent with START and CHANGE.
14997 When PREFER is `past' return a date that is either CURRENT or past.
14998 When PREFER is `future', return a date that is either CURRENT or future.
14999 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15000 ;; Make the proper lists from the dates
15002 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15003 dn dw sday cday n1 n2 n0
15004 d m y y1 y2 date1 date2 nmonths nm ny m2)
15006 (setq start (org-date-to-gregorian start)
15007 current (org-date-to-gregorian
15010 (time-to-days (current-time))))
15011 sday (calendar-absolute-from-gregorian start)
15012 cday (calendar-absolute-from-gregorian current))
15014 (if (<= cday sday) (throw 'exit sday))
15016 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15017 (setq dn (string-to-number (match-string 1 change))
15018 dw (cdr (assoc (match-string 2 change) a1)))
15019 (error "Invalid change specifier: %s" change))
15020 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15023 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15026 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15027 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15028 (setq date1 (list m d y1)
15029 n1 (calendar-absolute-from-gregorian date1)
15030 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15031 n2 (calendar-absolute-from-gregorian date2)))
15033 ;; approx number of month between the two dates
15034 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15035 ;; How often does dn fit in there?
15036 (setq d (nth 1 start) m (car start) y (nth 2 start)
15037 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15039 ny (floor (/ m 12))
15042 (while (> m 12) (setq m (- m 12) y (1+ y)))
15043 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15044 (setq m2 (+ m dn) y2 y)
15045 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15046 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15047 (while (<= n2 cday)
15048 (setq n1 n2 m m2 y y2)
15049 (setq m2 (+ m dn) y2 y)
15050 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15051 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15052 ;; Make sure n1 is the earlier date
15053 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15056 ((eq prefer 'past) (if (= cday n2) n2 n1))
15057 ((eq prefer 'future) (if (= cday n1) n1 n2))
15058 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15060 ((eq prefer 'past) (if (= cday n2) n2 n1))
15061 ((eq prefer 'future) (if (= cday n1) n1 n2))
15062 (t (if (= cday n1) n1 n2)))))))
15064 (defun org-date-to-gregorian (date)
15065 "Turn any specification of DATE into a Gregorian date for the calendar."
15066 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15067 ((and (listp date) (= (length date) 3)) date)
15069 (setq date (org-parse-time-string date))
15070 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15072 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15074 (defun org-parse-time-string (s &optional nodefault)
15075 "Parse the standard Org-mode time string.
15076 This should be a lot faster than the normal `parse-time-string'.
15077 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15078 hour and minute fields will be nil if not given."
15079 (if (string-match org-ts-regexp0 s)
15081 (if (or (match-beginning 8) (not nodefault))
15082 (string-to-number (or (match-string 8 s) "0")))
15083 (if (or (match-beginning 7) (not nodefault))
15084 (string-to-number (or (match-string 7 s) "0")))
15085 (string-to-number (match-string 4 s))
15086 (string-to-number (match-string 3 s))
15087 (string-to-number (match-string 2 s))
15089 (error "Not a standard Org-mode time string: %s" s)))
15091 (defun org-timestamp-up (&optional arg)
15092 "Increase the date item at the cursor by one.
15093 If the cursor is on the year, change the year. If it is on the month or
15094 the day, change that.
15095 With prefix ARG, change by that many units."
15097 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15099 (defun org-timestamp-down (&optional arg)
15100 "Decrease the date item at the cursor by one.
15101 If the cursor is on the year, change the year. If it is on the month or
15102 the day, change that.
15103 With prefix ARG, change by that many units."
15105 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15107 (defun org-timestamp-up-day (&optional arg)
15108 "Increase the date in the time stamp by one day.
15109 With prefix ARG, change that many days."
15111 (if (and (not (org-at-timestamp-p t))
15112 (org-on-heading-p))
15114 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15116 (defun org-timestamp-down-day (&optional arg)
15117 "Decrease the date in the time stamp by one day.
15118 With prefix ARG, change that many days."
15120 (if (and (not (org-at-timestamp-p t))
15121 (org-on-heading-p))
15123 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15125 (defun org-at-timestamp-p (&optional inactive-ok)
15126 "Determine if the cursor is in or at a timestamp."
15128 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15130 (ans (or (looking-at tsr)
15132 (skip-chars-backward "^[<\n\r\t")
15133 (if (> (point) (point-min)) (backward-char 1))
15134 (and (looking-at tsr)
15135 (> (- (match-end 0) pos) -1))))))
15137 (boundp 'org-ts-what)
15140 ((= pos (match-beginning 0)) 'bracket)
15141 ((= pos (1- (match-end 0))) 'bracket)
15142 ((org-pos-in-match-range pos 2) 'year)
15143 ((org-pos-in-match-range pos 3) 'month)
15144 ((org-pos-in-match-range pos 7) 'hour)
15145 ((org-pos-in-match-range pos 8) 'minute)
15146 ((or (org-pos-in-match-range pos 4)
15147 (org-pos-in-match-range pos 5)) 'day)
15148 ((and (> pos (or (match-end 8) (match-end 5)))
15149 (< pos (match-end 0)))
15150 (- pos (or (match-end 8) (match-end 5))))
15154 (defun org-toggle-timestamp-type ()
15155 "Toggle the type (<active> or [inactive]) of a time stamp."
15157 (when (org-at-timestamp-p t)
15158 (let ((beg (match-beginning 0)) (end (match-end 0))
15159 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15162 (while (re-search-forward "[][<>]" end t)
15163 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15165 (message "Timestamp is now %sactive"
15166 (if (equal (char-after beg) ?<) "" "in")))))
15168 (defun org-timestamp-change (n &optional what updown)
15169 "Change the date in the time stamp at point.
15170 The date will be changed by N times WHAT. WHAT can be `day', `month',
15171 `year', `minute', `second'. If WHAT is not given, the cursor position
15172 in the timestamp determines what will be changed."
15173 (let ((pos (point))
15175 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15179 (if (not (org-at-timestamp-p t))
15180 (error "Not at a timestamp"))
15181 (if (and (not what) (eq org-ts-what 'bracket))
15182 (org-toggle-timestamp-type)
15183 (if (and (not what) (not (eq org-ts-what 'day))
15184 org-display-custom-times
15185 (get-text-property (point) 'display)
15186 (not (get-text-property (1- (point)) 'display)))
15187 (setq org-ts-what 'day))
15188 (setq org-ts-what (or what org-ts-what)
15189 inactive (= (char-after (match-beginning 0)) ?\[)
15190 ts (match-string 0))
15193 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15195 (setq extra (match-string 1 ts)))
15196 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15198 (setq time0 (org-parse-time-string ts))
15200 (eq org-ts-what 'minute)
15201 (not current-prefix-arg))
15202 ;; This looks like s-up and s-down. Change by one rounding step.
15203 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15204 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15205 (setcar (cdr time0) (+ (nth 1 time0)
15206 (if (> n 0) (- rem) (- dm rem))))))
15208 (encode-time (or (car time0) 0)
15209 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15210 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15211 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15212 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15213 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15215 (when (and (member org-ts-what '(hour minute))
15217 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15218 (setq extra (org-modify-ts-extra
15220 (if (eq org-ts-what 'hour) 2 5)
15222 (when (integerp org-ts-what)
15223 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15224 (if (eq what 'calendar)
15225 (let ((cal-date (org-get-date-from-calendar)))
15226 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15227 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15228 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15229 (setcar time0 (or (car time0) 0))
15230 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15231 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15232 (setq time (apply 'encode-time time0))))
15233 (setq org-last-changed-timestamp
15234 (org-insert-time-stamp time with-hm inactive nil nil extra))
15235 (org-clock-update-time-maybe)
15237 ;; Try to recenter the calendar window, if any
15238 (if (and org-calendar-follow-timestamp-change
15239 (get-buffer-window "*Calendar*" t)
15240 (memq org-ts-what '(day month year)))
15241 (org-recenter-calendar (time-to-days time))))))
15243 (defun org-modify-ts-extra (s pos n dm)
15244 "Change the different parts of the lead-time and repeat fields in timestamp."
15245 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15247 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15249 ((or (org-pos-in-match-range pos 2)
15250 (org-pos-in-match-range pos 3))
15251 (setq m (string-to-number (match-string 3 s))
15252 h (string-to-number (match-string 2 s)))
15253 (if (org-pos-in-match-range pos 2)
15255 (setq n (* dm (org-no-warnings (signum n))))
15256 (when (not (= 0 (setq rem (% m dm))))
15257 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15259 (if (< m 0) (setq m (+ m 60) h (1- h)))
15260 (if (> m 59) (setq m (- m 60) h (1+ h)))
15261 (setq h (min 24 (max 0 h)))
15262 (setq ng 1 new (format "-%02d:%02d" h m)))
15263 ((org-pos-in-match-range pos 6)
15264 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15265 ((org-pos-in-match-range pos 5)
15266 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15268 ((org-pos-in-match-range pos 9)
15269 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15270 ((org-pos-in-match-range pos 8)
15271 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15275 (substring s 0 (match-beginning ng))
15277 (substring s (match-end ng))))))
15280 (defun org-recenter-calendar (date)
15281 "If the calendar is visible, recenter it to DATE."
15282 (let* ((win (selected-window))
15283 (cwin (get-buffer-window "*Calendar*" t))
15284 (calendar-move-hook nil))
15286 (select-window cwin)
15287 (calendar-goto-date (if (listp date) date
15288 (calendar-gregorian-from-absolute date)))
15289 (select-window win))))
15291 (defun org-goto-calendar (&optional arg)
15292 "Go to the Emacs calendar at the current date.
15293 If there is a time stamp in the current line, go to that date.
15294 A prefix ARG can be used to force the current date."
15296 (let ((tsr org-ts-regexp) diff
15297 (calendar-move-hook nil)
15298 (calendar-view-holidays-initially-flag nil)
15299 (calendar-view-diary-initially-flag nil))
15300 (if (or (org-at-timestamp-p)
15302 (beginning-of-line 1)
15303 (looking-at (concat ".*" tsr))))
15304 (let ((d1 (time-to-days (current-time)))
15306 (org-time-string-to-time (match-string 1)))))
15307 (setq diff (- d2 d1))))
15309 (calendar-goto-today)
15310 (if (and diff (not arg)) (calendar-forward-day diff))))
15312 (defun org-get-date-from-calendar ()
15313 "Return a list (month day year) of date at point in calendar."
15314 (with-current-buffer "*Calendar*"
15316 (calendar-cursor-to-date))))
15318 (defun org-date-from-calendar ()
15319 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15320 If there is already a time stamp at the cursor position, update it."
15322 (if (org-at-timestamp-p t)
15323 (org-timestamp-change 0 'calendar)
15324 (let ((cal-date (org-get-date-from-calendar)))
15325 (org-insert-time-stamp
15326 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
15328 (defun org-minutes-to-hh:mm-string (m)
15329 "Compute H:MM from a number of minutes."
15330 (let ((h (/ m 60)))
15331 (setq m (- m (* 60 h)))
15332 (format org-time-clocksum-format h m)))
15334 (defun org-hh:mm-string-to-minutes (s)
15335 "Convert a string H:MM to a number of minutes.
15336 If the string is just a number, interpret it as minutes.
15337 In fact, the first hh:mm or number in the string will be taken,
15338 there can be extra stuff in the string.
15339 If no number is found, the return value is 0."
15341 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
15342 (+ (* (string-to-number (match-string 1 s)) 60)
15343 (string-to-number (match-string 2 s))))
15344 ((string-match "\\([0-9]+\\)" s)
15345 (string-to-number (match-string 1 s)))
15350 (defun org-save-all-org-buffers ()
15351 "Save all Org-mode buffers without user confirmation."
15353 (message "Saving all Org-mode buffers...")
15354 (save-some-buffers t 'org-mode-p)
15355 (when (featurep 'org-id) (org-id-locations-save))
15356 (message "Saving all Org-mode buffers... done"))
15358 (defun org-revert-all-org-buffers ()
15359 "Revert all Org-mode buffers.
15360 Prompt for confirmation when there are unsaved changes.
15361 Be sure you know what you are doing before letting this function
15362 overwrite your changes.
15364 This function is useful in a setup where one tracks org files
15365 with a version control system, to revert on one machine after pulling
15366 changes from another. I believe the procedure must be like this:
15368 1. M-x org-save-all-org-buffers
15369 2. Pull changes from the other machine, resolve conflicts
15370 3. M-x org-revert-all-org-buffers"
15372 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
15375 (save-window-excursion
15378 (when (and (with-current-buffer b (org-mode-p))
15379 (with-current-buffer b buffer-file-name))
15380 (switch-to-buffer b)
15381 (revert-buffer t 'no-confirm)))
15383 (when (and (featurep 'org-id) org-id-track-globally)
15384 (org-id-locations-load)))))
15389 (defun org-switchb (&optional arg)
15390 "Switch between Org buffers.
15391 With a prefix argument, restrict available to files.
15392 With two prefix arguments, restrict available buffers to agenda files.
15394 Defaults to `iswitchb' for buffer name completion.
15395 Set `org-completion-use-ido' to make it use ido instead."
15397 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
15398 ((equal arg '(16)) (org-buffer-list 'agenda))
15399 (t (org-buffer-list))))
15400 (org-completion-use-iswitchb org-completion-use-iswitchb)
15401 (org-completion-use-ido org-completion-use-ido))
15402 (unless (or org-completion-use-ido org-completion-use-iswitchb)
15403 (setq org-completion-use-iswitchb t))
15405 (org-icompleting-read "Org buffer: "
15406 (mapcar 'list (mapcar 'buffer-name blist))
15409 ;;; Define some older names previously used for this functionality
15411 (defalias 'org-ido-switchb 'org-switchb)
15413 (defalias 'org-iswitchb 'org-switchb)
15415 (defun org-buffer-list (&optional predicate exclude-tmp)
15416 "Return a list of Org buffers.
15417 PREDICATE can be `export', `files' or `agenda'.
15419 export restrict the list to Export buffers.
15420 files restrict the list to buffers visiting Org files.
15421 agenda restrict the list to buffers visiting agenda files.
15423 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
15425 (agenda-files (and (eq predicate 'agenda)
15426 (mapcar 'file-truename (org-agenda-files t))))
15429 ((eq predicate 'files)
15430 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
15431 ((eq predicate 'export)
15432 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
15433 ((eq predicate 'agenda)
15435 (with-current-buffer b
15436 (and (eq major-mode 'org-mode)
15437 (setq bfn (buffer-file-name b))
15438 (member (file-truename bfn) agenda-files)))))
15439 (t (lambda (b) (with-current-buffer b
15440 (or (eq major-mode 'org-mode)
15441 (string-match "\*Org .*Export"
15442 (buffer-name b)))))))))
15446 (if (and (funcall filter b)
15447 (or (not exclude-tmp)
15448 (not (string-match "tmp" (buffer-name b)))))
15453 (defun org-agenda-files (&optional unrestricted archives)
15454 "Get the list of agenda files.
15455 Optional UNRESTRICTED means return the full list even if a restriction
15456 is currently in place.
15457 When ARCHIVES is t, include all archive files that are really being
15458 used by the agenda files. If ARCHIVE is `ifmode', do this only if
15459 `org-agenda-archives-mode' is t."
15462 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
15463 ((stringp org-agenda-files) (org-read-agenda-file-list))
15464 ((listp org-agenda-files) org-agenda-files)
15465 (t (error "Invalid value of `org-agenda-files'")))))
15466 (setq files (apply 'append
15467 (mapcar (lambda (f)
15468 (if (file-directory-p f)
15470 f t org-agenda-file-regexp)
15473 (when org-agenda-skip-unavailable-files
15474 (setq files (delq nil
15477 (and (file-readable-p file) file)))
15479 (when (or (eq archives t)
15480 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
15481 (setq files (org-add-archive-files files)))
15484 (defun org-agenda-file-p (&optional file)
15485 "Return non-nil, if FILE is an agenda file.
15486 If FILE is omitted, use the file associated with the current
15488 (member (or file (buffer-file-name))
15489 (org-agenda-files t)))
15491 (defun org-edit-agenda-file-list ()
15492 "Edit the list of agenda files.
15493 Depending on setup, this either uses customize to edit the variable
15494 `org-agenda-files', or it visits the file that is holding the list. In the
15495 latter case, the buffer is set up in a way that saving it automatically kills
15496 the buffer and restores the previous window configuration."
15498 (if (stringp org-agenda-files)
15499 (let ((cw (current-window-configuration)))
15500 (find-file org-agenda-files)
15501 (org-set-local 'org-window-configuration cw)
15502 (org-add-hook 'after-save-hook
15504 (set-window-configuration
15505 (prog1 org-window-configuration
15506 (kill-buffer (current-buffer))))
15507 (org-install-agenda-files-menu)
15508 (message "New agenda file list installed"))
15510 (message "%s" (substitute-command-keys
15511 "Edit list and finish with \\[save-buffer]")))
15512 (customize-variable 'org-agenda-files)))
15514 (defun org-store-new-agenda-file-list (list)
15515 "Set new value for the agenda file list and save it correctly."
15516 (if (stringp org-agenda-files)
15517 (let ((fe (org-read-agenda-file-list t)) b u)
15518 (while (setq b (find-buffer-visiting org-agenda-files))
15520 (with-temp-file org-agenda-files
15523 (lambda (f) ;; Keep un-expanded entries.
15524 (if (setq u (assoc f fe))
15529 (let ((org-mode-hook nil) (org-inhibit-startup t)
15530 (org-insert-mode-line-in-empty-file nil))
15531 (setq org-agenda-files list)
15532 (customize-save-variable 'org-agenda-files org-agenda-files))))
15534 (defun org-read-agenda-file-list (&optional pair-with-expansion)
15535 "Read the list of agenda files from a file.
15536 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
15537 filenames, used by `org-store-new-agenda-file-list' to write back
15538 un-expanded file names."
15539 (when (file-directory-p org-agenda-files)
15540 (error "`org-agenda-files' cannot be a single directory"))
15541 (when (stringp org-agenda-files)
15543 (insert-file-contents org-agenda-files)
15546 (let ((e (expand-file-name (substitute-in-file-name f)
15548 (if pair-with-expansion
15551 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
15554 (defun org-cycle-agenda-files ()
15555 "Cycle through the files in `org-agenda-files'.
15556 If the current buffer visits an agenda file, find the next one in the list.
15557 If the current buffer does not, find the first agenda file."
15559 (let* ((fs (org-agenda-files t))
15560 (files (append fs (list (car fs))))
15561 (tcf (if buffer-file-name (file-truename buffer-file-name)))
15563 (unless files (error "No agenda files"))
15565 (while (setq file (pop files))
15566 (if (equal (file-truename file) tcf)
15568 (find-file (car files))
15570 (find-file (car fs)))
15571 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
15573 (defun org-agenda-file-to-front (&optional to-end)
15574 "Move/add the current file to the top of the agenda file list.
15575 If the file is not present in the list, it is added to the front. If it is
15576 present, it is moved there. With optional argument TO-END, add/move to the
15579 (let ((org-agenda-skip-unavailable-files nil)
15580 (file-alist (mapcar (lambda (x)
15581 (cons (file-truename x) x))
15582 (org-agenda-files t)))
15583 (ctf (file-truename buffer-file-name))
15585 (setq x (assoc ctf file-alist) had x)
15587 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
15589 (setq file-alist (append (delq x file-alist) (list x)))
15590 (setq file-alist (cons x (delq x file-alist))))
15591 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
15592 (org-install-agenda-files-menu)
15593 (message "File %s to %s of agenda file list"
15594 (if had "moved" "added") (if to-end "end" "front"))))
15596 (defun org-remove-file (&optional file)
15597 "Remove current file from the list of files in variable `org-agenda-files'.
15598 These are the files which are being checked for agenda entries.
15599 Optional argument FILE means use this file instead of the current."
15601 (let* ((org-agenda-skip-unavailable-files nil)
15602 (file (or file buffer-file-name))
15603 (true-file (file-truename file))
15604 (afile (abbreviate-file-name file))
15605 (files (delq nil (mapcar
15607 (if (equal true-file
15610 (org-agenda-files t)))))
15611 (if (not (= (length files) (length (org-agenda-files t))))
15613 (org-store-new-agenda-file-list files)
15614 (org-install-agenda-files-menu)
15615 (message "Removed file: %s" afile))
15616 (message "File was not in list: %s (not removed)" afile))))
15618 (defun org-file-menu-entry (file)
15619 (vector file (list 'find-file file) t))
15621 (defun org-check-agenda-file (file)
15622 "Make sure FILE exists. If not, ask user what to do."
15623 (when (not (file-exists-p file))
15624 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
15625 (abbreviate-file-name file))
15626 (let ((r (downcase (read-char-exclusive))))
15629 (org-remove-file file)
15630 (throw 'nextfile t))
15631 (t (error "Abort"))))))
15633 (defun org-get-agenda-file-buffer (file)
15634 "Get a buffer visiting FILE. If the buffer needs to be created, add
15635 it to the list of buffers which might be released later."
15636 (let ((buf (org-find-base-buffer-visiting file)))
15638 buf ; just return it
15639 ;; Make a new buffer and remember it
15640 (setq buf (find-file-noselect file))
15641 (if buf (push buf org-agenda-new-buffers))
15644 (defun org-release-buffers (blist)
15645 "Release all buffers in list, asking the user for confirmation when needed.
15646 When a buffer is unmodified, it is just killed. When modified, it is saved
15647 \(if the user agrees) and then killed."
15649 (while (setq buf (pop blist))
15650 (setq file (buffer-file-name buf))
15651 (when (and (buffer-modified-p buf)
15653 (y-or-n-p (format "Save file %s? " file)))
15654 (with-current-buffer buf (save-buffer)))
15655 (kill-buffer buf))))
15657 (defun org-prepare-agenda-buffers (files)
15658 "Create buffers for all agenda files, protect archived trees and comments."
15660 (let ((pa '(:org-archived t))
15661 (pc '(:org-comment t))
15662 (pall '(:org-archived t :org-comment t))
15663 (inhibit-read-only t)
15664 (rea (concat ":" org-archive-tag ":"))
15668 (while (setq file (pop files))
15672 (org-check-agenda-file file)
15673 (set-buffer (org-get-agenda-file-buffer file)))
15675 (setq bmp (buffer-modified-p))
15676 (org-refresh-category-properties)
15677 (setq org-todo-keywords-for-agenda
15678 (append org-todo-keywords-for-agenda org-todo-keywords-1))
15679 (setq org-done-keywords-for-agenda
15680 (append org-done-keywords-for-agenda org-done-keywords))
15681 (setq org-todo-keyword-alist-for-agenda
15682 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
15683 (setq org-drawers-for-agenda
15684 (append org-drawers-for-agenda org-drawers))
15685 (setq org-tag-alist-for-agenda
15686 (append org-tag-alist-for-agenda org-tag-alist))
15689 (remove-text-properties (point-min) (point-max) pall)
15690 (when org-agenda-skip-archived-trees
15691 (goto-char (point-min))
15692 (while (re-search-forward rea nil t)
15693 (if (org-on-heading-p t)
15694 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
15695 (goto-char (point-min))
15696 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
15697 (while (re-search-forward re nil t)
15698 (add-text-properties
15699 (match-beginning 0) (org-end-of-subtree t) pc)))
15700 (set-buffer-modified-p bmp)))))
15701 (setq org-todo-keywords-for-agenda
15702 (org-uniquify org-todo-keywords-for-agenda))
15703 (setq org-todo-keyword-alist-for-agenda
15704 (org-uniquify org-todo-keyword-alist-for-agenda)
15705 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
15707 ;;;; Embedded LaTeX
15709 (defvar org-cdlatex-mode-map (make-sparse-keymap)
15710 "Keymap for the minor `org-cdlatex-mode'.")
15712 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
15713 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
15714 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
15715 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
15716 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
15718 (defvar org-cdlatex-texmathp-advice-is-done nil
15719 "Flag remembering if we have applied the advice to texmathp already.")
15721 (define-minor-mode org-cdlatex-mode
15722 "Toggle the minor `org-cdlatex-mode'.
15723 This mode supports entering LaTeX environment and math in LaTeX fragments
15725 \\{org-cdlatex-mode-map}"
15727 (when org-cdlatex-mode (require 'cdlatex))
15728 (unless org-cdlatex-texmathp-advice-is-done
15729 (setq org-cdlatex-texmathp-advice-is-done t)
15730 (defadvice texmathp (around org-math-always-on activate)
15731 "Always return t in org-mode buffers.
15732 This is because we want to insert math symbols without dollars even outside
15733 the LaTeX math segments. If Orgmode thinks that point is actually inside
15734 an embedded LaTeX fragment, let texmathp do its job.
15735 \\[org-cdlatex-mode-map]"
15739 ((not (org-mode-p)) ad-do-it)
15740 ((eq this-command 'cdlatex-math-symbol)
15741 (setq ad-return-value t
15742 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
15744 (let ((p (org-inside-LaTeX-fragment-p)))
15745 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
15746 (setq ad-return-value t
15747 texmathp-why '("Org-mode embedded math" . 0))
15748 (if p ad-do-it)))))))))
15750 (defun turn-on-org-cdlatex ()
15751 "Unconditionally turn on `org-cdlatex-mode'."
15752 (org-cdlatex-mode 1))
15754 (defun org-inside-LaTeX-fragment-p ()
15755 "Test if point is inside a LaTeX fragment.
15756 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
15757 sequence appearing also before point.
15758 Even though the matchers for math are configurable, this function assumes
15759 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
15760 delimiters are skipped when they have been removed by customization.
15761 The return value is nil, or a cons cell with the delimiter and
15762 and the position of this delimiter.
15764 This function does a reasonably good job, but can locally be fooled by
15765 for example currency specifications. For example it will assume being in
15766 inline math after \"$22.34\". The LaTeX fragment formatter will only format
15767 fragments that are properly closed, but during editing, we have to live
15768 with the uncertainty caused by missing closing delimiters. This function
15769 looks only before point, not after."
15771 (let ((pos (point))
15772 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
15774 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
15776 dd-on str (start 0) m re)
15779 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
15780 re (nth 1 (assoc "$" org-latex-regexps)))
15781 (while (string-match re str start)
15783 ((= (match-end 0) (length str))
15784 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
15785 ((= (match-end 0) (- (length str) 5))
15787 (t (setq start (match-end 0))))))
15788 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
15790 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
15791 (and (match-beginning 2) (throw 'exit nil))
15793 (while (re-search-backward "\\$\\$" lim t)
15794 (setq dd-on (not dd-on)))
15796 (if dd-on (cons "$$" m))))))
15798 (defun org-inside-latex-macro-p ()
15799 "Is point inside a LaTeX macro or its arguments?"
15802 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
15804 (defun org-try-cdlatex-tab ()
15805 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15806 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15807 - inside a LaTeX fragment, or
15808 - after the first word in a line, where an abbreviation expansion could
15809 insert a LaTeX environment."
15810 (when org-cdlatex-mode
15813 (skip-chars-backward "a-zA-Z0-9*")
15814 (skip-chars-backward " \t")
15817 ((org-inside-LaTeX-fragment-p)
15821 (defun org-cdlatex-underscore-caret (&optional arg)
15822 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15823 Revert to the normal definition outside of these fragments."
15825 (if (org-inside-LaTeX-fragment-p)
15826 (call-interactively 'cdlatex-sub-superscript)
15827 (let (org-cdlatex-mode)
15828 (call-interactively (key-binding (vector last-input-event))))))
15830 (defun org-cdlatex-math-modify (&optional arg)
15831 "Execute `cdlatex-math-modify' in LaTeX fragments.
15832 Revert to the normal definition outside of these fragments."
15834 (if (org-inside-LaTeX-fragment-p)
15835 (call-interactively 'cdlatex-math-modify)
15836 (let (org-cdlatex-mode)
15837 (call-interactively (key-binding (vector last-input-event))))))
15839 (defvar org-latex-fragment-image-overlays nil
15840 "List of overlays carrying the images of latex fragments.")
15841 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15843 (defun org-remove-latex-fragment-image-overlays ()
15844 "Remove all overlays with LaTeX fragment images in current buffer."
15845 (mapc 'delete-overlay org-latex-fragment-image-overlays)
15846 (setq org-latex-fragment-image-overlays nil))
15848 (defun org-preview-latex-fragment (&optional subtree)
15849 "Preview the LaTeX fragment at point, or all locally or globally.
15850 If the cursor is in a LaTeX fragment, create the image and overlay
15851 it over the source code. If there is no fragment at point, display
15852 all fragments in the current text, from one headline to the next. With
15853 prefix SUBTREE, display all fragments in the current subtree. With a
15854 double prefix arg \\[universal-argument] \\[universal-argument], or when \
15855 the cursor is before the first headline,
15856 display all fragments in the buffer.
15857 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15859 (org-remove-latex-fragment-image-overlays)
15862 (let (beg end at msg)
15864 ((or (equal subtree '(16))
15865 (not (save-excursion
15866 (re-search-backward (concat "^" outline-regexp) nil t))))
15867 (setq beg (point-min) end (point-max)
15868 msg "Creating images for buffer...%s"))
15869 ((equal subtree '(4))
15870 (org-back-to-heading)
15871 (setq beg (point) end (org-end-of-subtree t)
15872 msg "Creating images for subtree...%s"))
15874 (if (setq at (org-inside-LaTeX-fragment-p))
15875 (goto-char (max (point-min) (- (cdr at) 2)))
15876 (org-back-to-heading))
15877 (setq beg (point) end (progn (outline-next-heading) (point))
15878 msg (if at "Creating image...%s"
15879 "Creating images for entry...%s"))))
15881 (narrow-to-region beg end)
15884 (concat "ltxpng/" (file-name-sans-extension
15885 (file-name-nondirectory
15886 buffer-file-name)))
15887 default-directory 'overlays msg at 'forbuffer 'dvipng)
15888 (message msg "done. Use `C-c C-c' to remove images.")))))
15890 (defvar org-latex-regexps
15891 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15892 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15893 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15894 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15895 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15896 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15897 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
15898 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
15899 "Regular expressions for matching embedded LaTeX.")
15901 (defvar org-export-have-math nil) ;; dynamic scoping
15902 (defun org-format-latex (prefix &optional dir overlays msg at
15903 forbuffer processing-type)
15904 "Replace LaTeX fragments with links to an image, and produce images.
15905 Some of the options can be changed using the variable
15906 `org-format-latex-options'."
15907 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15908 (let* ((prefixnodir (file-name-nondirectory prefix))
15909 (absprefix (expand-file-name prefix dir))
15910 (todir (file-name-directory absprefix))
15911 (opt org-format-latex-options)
15912 (matchers (plist-get opt :matchers))
15913 (re-list org-latex-regexps)
15914 (org-format-latex-header-extra
15915 (plist-get (org-infile-export-plist) :latex-header-extra))
15916 (cnt 0) txt hash link beg end re e checkdir
15917 executables-checked string
15918 m n block linkfile movefile ov)
15919 ;; Check the different regular expressions
15920 (while (setq e (pop re-list))
15921 (setq m (car e) re (nth 1 e) n (nth 2 e)
15922 block (if (nth 3 e) "\n\n" ""))
15923 (when (member m matchers)
15924 (goto-char (point-min))
15925 (while (re-search-forward re nil t)
15926 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
15927 (not (get-text-property (match-beginning n)
15930 (not (eq (get-char-property (match-beginning n)
15932 'org-latex-overlay))))
15933 (setq org-export-have-math t)
15935 ((eq processing-type 'verbatim)
15936 ;; Leave the text verbatim, just protect it
15937 (add-text-properties (match-beginning n) (match-end n)
15938 '(org-protected t)))
15939 ((eq processing-type 'mathjax)
15940 ;; Prepare for MathJax processing
15941 (setq string (match-string n))
15944 (delete-region (match-beginning n) (match-end n))
15945 (goto-char (match-beginning n))
15946 (insert (org-add-props (concat "\\(" (substring string 1 -1)
15948 '(org-protected t))))
15949 (add-text-properties (match-beginning n) (match-end n)
15950 '(org-protected t))))
15951 ((or (eq processing-type 'dvipng) t)
15952 ;; Process to an image
15953 (setq txt (match-string n)
15954 beg (match-beginning n) end (match-end n)
15956 (let (print-length print-level) ; make sure full list is printed
15957 (setq hash (sha1 (prin1-to-string
15958 (list org-format-latex-header
15959 org-format-latex-header-extra
15960 org-export-latex-default-packages-alist
15961 org-export-latex-packages-alist
15962 org-format-latex-options
15964 linkfile (format "%s_%s.png" prefix hash)
15965 movefile (format "%s_%s.png" absprefix hash)))
15966 (setq link (concat block "[[file:" linkfile "]]" block))
15967 (if msg (message msg cnt))
15969 (unless checkdir ; make sure the directory exists
15971 (or (file-directory-p todir) (make-directory todir t)))
15973 (unless executables-checked
15974 (org-check-external-command
15975 "latex" "needed to convert LaTeX fragments to images")
15976 (org-check-external-command
15977 "dvipng" "needed to convert LaTeX fragments to images")
15978 (setq executables-checked t))
15980 (unless (file-exists-p movefile)
15981 (org-create-formula-image
15982 txt movefile opt forbuffer))
15986 (if (eq (overlay-get o 'org-overlay-type)
15987 'org-latex-overlay)
15988 (delete-overlay o)))
15989 (overlays-in beg end))
15990 (setq ov (make-overlay beg end))
15991 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
15992 (if (featurep 'xemacs)
15994 (overlay-put ov 'invisible t)
15997 (make-glyph (vector 'png :file movefile))))
16000 (list 'image :type 'png :file movefile :ascent 'center)))
16001 (push ov org-latex-fragment-image-overlays)
16003 (delete-region beg end)
16004 (insert (org-add-props link
16005 (list 'org-latex-src
16006 (replace-regexp-in-string
16007 "\"" "" txt)))))))))))))
16009 ;; This function borrows from Ganesh Swami's latex2png.el
16010 (defun org-create-formula-image (string tofile options buffer)
16011 "This calls dvipng."
16012 (require 'org-latex)
16013 (let* ((tmpdir (if (featurep 'xemacs)
16015 temporary-file-directory))
16016 (texfilebase (make-temp-name
16017 (expand-file-name "orgtex" tmpdir)))
16018 (texfile (concat texfilebase ".tex"))
16019 (dvifile (concat texfilebase ".dvi"))
16020 (pngfile (concat texfilebase ".png"))
16021 (fnh (if (featurep 'xemacs)
16022 (font-height (get-face-font 'default))
16023 (face-attribute 'default :height nil)))
16024 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16025 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16026 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16028 (bg (or (plist-get options (if buffer :background :html-background))
16030 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16031 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16032 (with-temp-file texfile
16033 (insert (org-splice-latex-header
16034 org-format-latex-header
16035 org-export-latex-default-packages-alist
16036 org-export-latex-packages-alist t
16037 org-format-latex-header-extra))
16038 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16039 (require 'org-latex)
16040 (org-export-latex-fix-inputenc))
16041 (let ((dir default-directory))
16042 (condition-case nil
16045 (call-process "latex" nil nil nil texfile))
16048 (if (not (file-exists-p dvifile))
16049 (progn (message "Failed to create dvi file from %s" texfile) nil)
16050 (condition-case nil
16051 (call-process "dvipng" nil nil nil
16054 ;;"-x" scale "-y" scale
16059 (if (not (file-exists-p pngfile))
16060 (if org-format-latex-signal-error
16061 (error "Failed to create png file from %s" texfile)
16062 (message "Failed to create png file from %s" texfile)
16064 ;; Use the requested file name and clean up
16065 (copy-file pngfile tofile 'replace)
16066 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16067 (delete-file (concat texfilebase e)))
16070 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16071 "Fill a LaTeX header template TPL.
16072 In the template, the following place holders will be recognized:
16074 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16075 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16076 [PACKAGES] \\usepackage statements for PKG
16077 [NO-PACKAGES] do not include PKG
16078 [EXTRA] the string EXTRA
16079 [NO-EXTRA] do not include EXTRA
16081 For backward compatibility, if both the positive and the negative place
16082 holder is missing, the positive one (without the \"NO-\") will be
16083 assumed to be present at the end of the template.
16084 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16086 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16087 (let (rpl (end ""))
16088 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16089 (setq rpl (if (or (match-end 1) (not def-pkg))
16090 "" (org-latex-packages-to-string def-pkg snippets-p t))
16091 tpl (replace-match rpl t t tpl))
16092 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16094 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16095 (setq rpl (if (or (match-end 1) (not pkg))
16096 "" (org-latex-packages-to-string pkg snippets-p t))
16097 tpl (replace-match rpl t t tpl))
16100 (org-latex-packages-to-string pkg snippets-p)))))
16102 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16103 (setq rpl (if (or (match-end 1) (not extra))
16104 "" (concat extra "\n"))
16105 tpl (replace-match rpl t t tpl))
16106 (if (and extra (string-match "\\S-" extra))
16107 (setq end (concat end "\n" extra))))
16109 (if (string-match "\\S-" end)
16110 (concat tpl "\n" end)
16113 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16114 "Turn an alist of packages into a string with the \\usepackage macros."
16115 (setq pkg (mapconcat (lambda(p)
16118 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16119 (format "%% Package %s omitted" (cadr p)))
16120 ((equal "" (car p))
16121 (format "\\usepackage{%s}" (cadr p)))
16123 (format "\\usepackage[%s]{%s}"
16124 (car p) (cadr p)))))
16127 (if newline (concat pkg "\n") pkg))
16129 (defun org-dvipng-color (attr)
16130 "Return an rgb color specification for dvipng."
16131 (apply 'format "rgb %s %s %s"
16132 (mapcar 'org-normalize-color
16133 (color-values (face-attribute 'default attr nil)))))
16135 (defun org-normalize-color (value)
16136 "Return string to be used as color value for an RGB component."
16137 (format "%g" (/ value 65535.0)))
16142 (defvar org-inline-image-overlays nil)
16143 (make-variable-buffer-local 'org-inline-image-overlays)
16145 (defun org-toggle-inline-images (&optional include-linked)
16146 "Toggle the display of inline images.
16147 INCLUDE-LINKED is passed to `org-display-inline-images'."
16149 (if org-inline-image-overlays
16151 (org-remove-inline-images)
16152 (message "Inline image display turned off"))
16153 (org-display-inline-images include-linked)
16154 (if org-inline-image-overlays
16155 (message "%d images displayed inline"
16156 (length org-inline-image-overlays))
16157 (message "No images to display inline"))))
16159 (defun org-display-inline-images (&optional include-linked refresh beg end)
16160 "Display inline images.
16161 Normally only links without a description part are inlined, because this
16162 is how it will work for export. When INCLUDE-LINKED is set, also links
16163 with a description part will be inlined. This can be nice for a quick
16164 look at those images, but it does not reflect what exported files will look
16166 When REFRESH is set, refresh existing images between BEG and END.
16167 This will create new image displays only if necessary.
16168 BEG and END default to the buffer boundaries."
16171 (org-remove-inline-images)
16172 (clear-image-cache))
16176 (setq beg (or beg (point-min)) end (or end (point-max)))
16177 (goto-char (point-min))
16178 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([-+~.:/\\_0-9a-zA-Z ]+"
16179 (substring (org-image-file-name-regexp) 0 -2)
16180 "\\)\\]" (if include-linked "" "\\]")))
16182 (while (re-search-forward re end t)
16183 (setq old (get-char-property-and-overlay (match-beginning 1)
16184 'org-image-overlay))
16185 (setq file (expand-file-name
16186 (concat (or (match-string 3) "") (match-string 4))))
16187 (when (file-exists-p file)
16188 (if (and (car-safe old) refresh)
16189 (image-refresh (overlay-get (cdr old) 'display))
16190 (setq img (create-image file))
16192 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
16193 (overlay-put ov 'display img)
16194 (overlay-put ov 'face 'default)
16195 (overlay-put ov 'org-image-overlay t)
16196 (overlay-put ov 'modification-hooks
16197 (list 'org-display-inline-modification-hook))
16198 (push ov org-inline-image-overlays)))))))))
16200 (defun org-display-inline-modification-hook (ov after beg end &optional len)
16201 "Remove inline-display overlay if a corresponding region is modified."
16202 (let ((inhibit-modification-hooks t))
16203 (when (and ov after)
16204 (delete ov org-inline-image-overlays)
16205 (delete-overlay ov))))
16207 (defun org-remove-inline-images ()
16208 "Remove inline display of images."
16210 (mapc 'delete-overlay org-inline-image-overlays)
16211 (setq org-inline-image-overlays nil))
16215 ;; Make `C-c C-x' a prefix key
16216 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
16218 ;; TAB key with modifiers
16219 (org-defkey org-mode-map "\C-i" 'org-cycle)
16220 (org-defkey org-mode-map [(tab)] 'org-cycle)
16221 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
16222 (org-defkey org-mode-map [(meta tab)] 'org-complete)
16223 (org-defkey org-mode-map "\M-\t" 'org-complete)
16224 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
16225 ;; The following line is necessary under Suse GNU/Linux
16226 (unless (featurep 'xemacs)
16227 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
16228 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
16229 (define-key org-mode-map [backtab] 'org-shifttab)
16231 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
16232 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
16233 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
16235 ;; Cursor keys with modifiers
16236 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
16237 (org-defkey org-mode-map [(meta right)] 'org-metaright)
16238 (org-defkey org-mode-map [(meta up)] 'org-metaup)
16239 (org-defkey org-mode-map [(meta down)] 'org-metadown)
16241 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
16242 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
16243 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
16244 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
16246 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
16247 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
16248 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
16249 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
16251 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
16252 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
16255 (define-key org-mode-map org-babel-key-prefix org-babel-map)
16256 (mapc (lambda (pair)
16257 (define-key org-babel-map (car pair) (cdr pair)))
16258 org-babel-key-bindings)
16260 ;;; Extra keys for tty access.
16261 ;; We only set them when really needed because otherwise the
16262 ;; menus don't show the simple keys
16264 (when (or org-use-extra-keys
16265 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
16266 (not window-system))
16267 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
16268 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
16269 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
16270 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
16271 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
16272 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
16273 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
16274 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
16275 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
16276 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
16277 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
16278 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
16279 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
16280 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
16281 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
16282 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
16283 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
16284 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
16285 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
16286 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
16287 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
16288 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
16289 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
16290 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
16291 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
16292 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
16293 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
16294 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
16296 ;; All the other keys
16298 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
16299 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
16300 (if (boundp 'narrow-map)
16301 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
16302 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
16303 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
16304 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
16305 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
16306 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
16307 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
16308 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
16309 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
16310 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
16311 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
16312 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
16313 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
16314 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
16315 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
16316 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
16317 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
16318 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
16319 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
16320 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
16321 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
16322 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
16323 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
16324 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
16325 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
16326 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
16327 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
16328 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
16329 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
16330 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
16331 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
16332 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
16333 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
16334 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
16335 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
16336 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
16337 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
16338 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
16339 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
16340 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
16341 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
16342 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
16343 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16344 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
16345 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
16346 (org-defkey org-mode-map "\C-c^" 'org-sort)
16347 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
16348 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
16349 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
16350 (org-defkey org-mode-map "\C-m" 'org-return)
16351 (org-defkey org-mode-map "\C-j" 'org-return-indent)
16352 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
16353 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
16354 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
16355 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
16356 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
16357 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
16358 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
16359 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
16360 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
16361 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
16362 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
16363 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
16364 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
16365 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
16366 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
16367 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
16368 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
16369 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
16370 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
16371 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
16373 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
16374 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
16375 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
16376 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
16378 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
16379 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
16380 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
16381 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
16382 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
16383 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
16384 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
16385 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
16386 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
16387 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
16388 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
16389 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
16390 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
16391 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
16392 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
16393 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
16394 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
16396 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
16397 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
16398 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
16399 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
16401 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
16403 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
16405 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
16406 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
16408 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
16411 (when (featurep 'xemacs)
16412 (org-defkey org-mode-map 'button3 'popup-mode-menu))
16415 (defconst org-speed-commands-default
16417 ("Outline Navigation")
16418 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
16419 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
16420 ("f" . (org-speed-move-safe 'org-forward-same-level))
16421 ("b" . (org-speed-move-safe 'org-backward-same-level))
16422 ("u" . (org-speed-move-safe 'outline-up-heading))
16424 ("g" . (org-refile t))
16425 ("Outline Visibility")
16427 ("C" . org-shifttab)
16428 (" " . org-display-outline-path)
16429 ("Outline Structure Editing")
16430 ("U" . org-shiftmetaup)
16431 ("D" . org-shiftmetadown)
16432 ("r" . org-metaright)
16433 ("l" . org-metaleft)
16434 ("R" . org-shiftmetaright)
16435 ("L" . org-shiftmetaleft)
16436 ("i" . (progn (forward-char 1) (call-interactively
16437 'org-insert-heading-respect-content)))
16440 ("a" . org-archive-subtree-default-with-confirmation)
16441 ("." . outline-mark-subtree)
16443 ("I" . org-clock-in)
16444 ("O" . org-clock-out)
16445 ("Meta Data Editing")
16447 ("0" . (org-priority ?\ ))
16448 ("1" . (org-priority ?A))
16449 ("2" . (org-priority ?B))
16450 ("3" . (org-priority ?C))
16451 (";" . org-set-tags-command)
16452 ("e" . org-set-effort)
16453 ("Agenda Views etc")
16455 ("/" . org-sparse-tree)
16457 ("o" . org-open-at-point)
16458 ("?" . org-speed-command-help)
16459 ("<" . (org-agenda-set-restriction-lock 'subtree))
16460 (">" . (org-agenda-remove-restriction-lock))
16462 "The default speed commands.")
16464 (defun org-print-speed-command (e)
16465 (if (> (length (car e)) 1)
16470 (princ (make-string (length (car e)) ?-))
16474 (if (symbolp (cdr e))
16475 (princ (symbol-name (cdr e)))
16479 (defun org-speed-command-help ()
16480 "Show the available speed commands."
16482 (if (not org-use-speed-commands)
16483 (error "Speed commands are not activated, customize `org-use-speed-commands'")
16484 (with-output-to-temp-buffer "*Help*"
16485 (princ "User-defined Speed commands\n===========================\n")
16486 (mapc 'org-print-speed-command org-speed-commands-user)
16488 (princ "Built-in Speed commands\n=======================\n")
16489 (mapc 'org-print-speed-command org-speed-commands-default))
16490 (with-current-buffer "*Help*"
16491 (setq truncate-lines t))))
16493 (defun org-speed-move-safe (cmd)
16494 "Execute CMD, but make sure that the cursor always ends up in a headline.
16495 If not, return to the original position and throw an error."
16497 (let ((pos (point)))
16498 (call-interactively cmd)
16499 (unless (and (bolp) (org-on-heading-p))
16501 (error "Boundary reached while executing %s" cmd))))
16503 (defvar org-self-insert-command-undo-counter 0)
16505 (defvar org-table-auto-blank-field) ; defined in org-table.el
16506 (defvar org-speed-command nil)
16507 (defun org-self-insert-command (N)
16508 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
16509 If the cursor is in a table looking at whitespace, the whitespace is
16510 overwritten, and the table is not marked as requiring realignment."
16513 ((and org-use-speed-commands
16514 (or (and (bolp) (looking-at outline-regexp))
16515 (and (functionp org-use-speed-commands)
16516 (funcall org-use-speed-commands)))
16519 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
16520 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
16522 ((commandp org-speed-command)
16523 (setq this-command org-speed-command)
16524 (call-interactively org-speed-command))
16525 ((functionp org-speed-command)
16526 (funcall org-speed-command))
16527 ((and org-speed-command (listp org-speed-command))
16528 (eval org-speed-command))
16529 (t (let (org-use-speed-commands)
16530 (call-interactively 'org-self-insert-command)))))
16534 ;; check if we blank the field, and if that triggers align
16535 (and (featurep 'org-table) org-table-auto-blank-field
16536 (member last-command
16537 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
16538 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
16539 ;; got extra space, this field does not determine column width
16540 (let (org-table-may-need-update) (org-table-blank-field))
16541 ;; no extra space, this field may determine column width
16542 (org-table-blank-field)))
16545 (looking-at "[^|\n]* |"))
16546 (let (org-table-may-need-update)
16547 (goto-char (1- (match-end 0)))
16548 (delete-backward-char 1)
16549 (goto-char (match-beginning 0))
16550 (self-insert-command N)))
16552 (setq org-table-may-need-update t)
16553 (self-insert-command N)
16554 (org-fix-tags-on-the-fly)
16555 (if org-self-insert-cluster-for-undo
16556 (if (not (eq last-command 'org-self-insert-command))
16557 (setq org-self-insert-command-undo-counter 1)
16558 (if (>= org-self-insert-command-undo-counter 20)
16559 (setq org-self-insert-command-undo-counter 1)
16560 (and (> org-self-insert-command-undo-counter 0)
16562 (not (cadr buffer-undo-list)) ; remove nil entry
16563 (setcdr buffer-undo-list (cddr buffer-undo-list)))
16564 (setq org-self-insert-command-undo-counter
16565 (1+ org-self-insert-command-undo-counter))))))))
16567 (defun org-fix-tags-on-the-fly ()
16568 (when (and (equal (char-after (point-at-bol)) ?*)
16569 (org-on-heading-p))
16570 (org-align-tags-here org-tags-column)))
16572 (defun org-delete-backward-char (N)
16573 "Like `delete-backward-char', insert whitespace at field end in tables.
16574 When deleting backwards, in tables this function will insert whitespace in
16575 front of the next \"|\" separator, to keep the table aligned. The table will
16576 still be marked for re-alignment if the field did fill the entire column,
16577 because, in this case the deletion might narrow the column."
16579 (if (and (org-table-p)
16581 (string-match "|" (buffer-substring (point-at-bol) (point)))
16582 (looking-at ".*?|"))
16583 (let ((pos (point))
16584 (noalign (looking-at "[^|\n\r]* |"))
16585 (c org-table-may-need-update))
16586 (backward-delete-char N)
16587 (skip-chars-forward "^|")
16589 (goto-char (1- pos))
16590 ;; noalign: if there were two spaces at the end, this field
16591 ;; does not determine the width of the column.
16592 (if noalign (setq org-table-may-need-update c)))
16593 (backward-delete-char N)
16594 (org-fix-tags-on-the-fly)))
16596 (defun org-delete-char (N)
16597 "Like `delete-char', but insert whitespace at field end in tables.
16598 When deleting characters, in tables this function will insert whitespace in
16599 front of the next \"|\" separator, to keep the table aligned. The table will
16600 still be marked for re-alignment if the field did fill the entire column,
16601 because, in this case the deletion might narrow the column."
16603 (if (and (org-table-p)
16605 (not (= (char-after) ?|))
16607 (if (looking-at ".*?|")
16608 (let ((pos (point))
16609 (noalign (looking-at "[^|\n\r]* |"))
16610 (c org-table-may-need-update))
16611 (replace-match (concat
16612 (substring (match-string 0) 1 -1)
16615 ;; noalign: if there were two spaces at the end, this field
16616 ;; does not determine the width of the column.
16617 (if noalign (setq org-table-may-need-update c)))
16620 (org-fix-tags-on-the-fly)))
16622 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
16623 (put 'org-self-insert-command 'delete-selection t)
16624 (put 'orgtbl-self-insert-command 'delete-selection t)
16625 (put 'org-delete-char 'delete-selection 'supersede)
16626 (put 'org-delete-backward-char 'delete-selection 'supersede)
16627 (put 'org-yank 'delete-selection 'yank)
16629 ;; Make `flyspell-mode' delay after some commands
16630 (put 'org-self-insert-command 'flyspell-delayed t)
16631 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
16632 (put 'org-delete-char 'flyspell-delayed t)
16633 (put 'org-delete-backward-char 'flyspell-delayed t)
16635 ;; Make pabbrev-mode expand after org-mode commands
16636 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
16637 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
16639 ;; How to do this: Measure non-white length of current string
16640 ;; If equal to column width, we should realign.
16642 (defun org-remap (map &rest commands)
16643 "In MAP, remap the functions given in COMMANDS.
16644 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
16647 (setq old (pop commands) new (pop commands))
16648 (if (fboundp 'command-remapping)
16649 (org-defkey map (vector 'remap old) new)
16650 (substitute-key-definition old new map global-map)))))
16652 (when (eq org-enable-table-editor 'optimized)
16653 ;; If the user wants maximum table support, we need to hijack
16654 ;; some standard editing functions
16655 (org-remap org-mode-map
16656 'self-insert-command 'org-self-insert-command
16657 'delete-char 'org-delete-char
16658 'delete-backward-char 'org-delete-backward-char)
16659 (org-defkey org-mode-map "|" 'org-force-self-insert))
16661 (defvar org-ctrl-c-ctrl-c-hook nil
16662 "Hook for functions attaching themselves to `C-c C-c'.
16663 This can be used to add additional functionality to the C-c C-c key which
16664 executes context-dependent commands.
16665 Each function will be called with no arguments. The function must check
16666 if the context is appropriate for it to act. If yes, it should do its
16667 thing and then return a non-nil value. If the context is wrong,
16668 just do nothing and return nil.")
16670 (defvar org-tab-first-hook nil
16671 "Hook for functions to attach themselves to TAB.
16672 See `org-ctrl-c-ctrl-c-hook' for more information.
16673 This hook runs as the first action when TAB is pressed, even before
16674 `org-cycle' messes around with the `outline-regexp' to cater for
16675 inline tasks and plain list item folding.
16676 If any function in this hook returns t, any other actions that
16677 would have been caused by TAB (such as table field motion or visibility
16678 cycling) will not occur.")
16680 (defvar org-tab-after-check-for-table-hook nil
16681 "Hook for functions to attach themselves to TAB.
16682 See `org-ctrl-c-ctrl-c-hook' for more information.
16683 This hook runs after it has been established that the cursor is not in a
16684 table, but before checking if the cursor is in a headline or if global cycling
16686 If any function in this hook returns t, not other actions like visibility
16687 cycling will be done.")
16689 (defvar org-tab-after-check-for-cycling-hook nil
16690 "Hook for functions to attach themselves to TAB.
16691 See `org-ctrl-c-ctrl-c-hook' for more information.
16692 This hook runs after it has been established that not table field motion and
16693 not visibility should be done because of current context. This is probably
16694 the place where a package like yasnippets can hook in.")
16696 (defvar org-tab-before-tab-emulation-hook nil
16697 "Hook for functions to attach themselves to TAB.
16698 See `org-ctrl-c-ctrl-c-hook' for more information.
16699 This hook runs after every other options for TAB have been exhausted, but
16700 before indentation and \t insertion takes place.")
16702 (defvar org-metaleft-hook nil
16703 "Hook for functions attaching themselves to `M-left'.
16704 See `org-ctrl-c-ctrl-c-hook' for more information.")
16705 (defvar org-metaright-hook nil
16706 "Hook for functions attaching themselves to `M-right'.
16707 See `org-ctrl-c-ctrl-c-hook' for more information.")
16708 (defvar org-metaup-hook nil
16709 "Hook for functions attaching themselves to `M-up'.
16710 See `org-ctrl-c-ctrl-c-hook' for more information.")
16711 (defvar org-metadown-hook nil
16712 "Hook for functions attaching themselves to `M-down'.
16713 See `org-ctrl-c-ctrl-c-hook' for more information.")
16714 (defvar org-shiftmetaleft-hook nil
16715 "Hook for functions attaching themselves to `M-S-left'.
16716 See `org-ctrl-c-ctrl-c-hook' for more information.")
16717 (defvar org-shiftmetaright-hook nil
16718 "Hook for functions attaching themselves to `M-S-right'.
16719 See `org-ctrl-c-ctrl-c-hook' for more information.")
16720 (defvar org-shiftmetaup-hook nil
16721 "Hook for functions attaching themselves to `M-S-up'.
16722 See `org-ctrl-c-ctrl-c-hook' for more information.")
16723 (defvar org-shiftmetadown-hook nil
16724 "Hook for functions attaching themselves to `M-S-down'.
16725 See `org-ctrl-c-ctrl-c-hook' for more information.")
16726 (defvar org-metareturn-hook nil
16727 "Hook for functions attaching themselves to `M-RET'.
16728 See `org-ctrl-c-ctrl-c-hook' for more information.")
16729 (defvar org-shiftup-hook nil
16730 "Hook for functions attaching themselves to `S-up'.
16731 See `org-ctrl-c-ctrl-c-hook' for more information.")
16732 (defvar org-shiftup-final-hook nil
16733 "Hook for functions attaching themselves to `S-up'.
16734 This one runs after all other options except shift-select have been excluded.
16735 See `org-ctrl-c-ctrl-c-hook' for more information.")
16736 (defvar org-shiftdown-hook nil
16737 "Hook for functions attaching themselves to `S-down'.
16738 See `org-ctrl-c-ctrl-c-hook' for more information.")
16739 (defvar org-shiftdown-final-hook nil
16740 "Hook for functions attaching themselves to `S-down'.
16741 This one runs after all other options except shift-select have been excluded.
16742 See `org-ctrl-c-ctrl-c-hook' for more information.")
16743 (defvar org-shiftleft-hook nil
16744 "Hook for functions attaching themselves to `S-left'.
16745 See `org-ctrl-c-ctrl-c-hook' for more information.")
16746 (defvar org-shiftleft-final-hook nil
16747 "Hook for functions attaching themselves to `S-left'.
16748 This one runs after all other options except shift-select have been excluded.
16749 See `org-ctrl-c-ctrl-c-hook' for more information.")
16750 (defvar org-shiftright-hook nil
16751 "Hook for functions attaching themselves to `S-right'.
16752 See `org-ctrl-c-ctrl-c-hook' for more information.")
16753 (defvar org-shiftright-final-hook nil
16754 "Hook for functions attaching themselves to `S-right'.
16755 This one runs after all other options except shift-select have been excluded.
16756 See `org-ctrl-c-ctrl-c-hook' for more information.")
16758 (defun org-modifier-cursor-error ()
16759 "Throw an error, a modified cursor command was applied in wrong context."
16760 (error "This command is active in special context like tables, headlines or items"))
16762 (defun org-shiftselect-error ()
16763 "Throw an error because Shift-Cursor command was applied in wrong context."
16764 (if (and (boundp 'shift-select-mode) shift-select-mode)
16765 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
16766 (error "This command works only in special context like headlines or timestamps")))
16768 (defun org-call-for-shift-select (cmd)
16769 (let ((this-command-keys-shift-translated t))
16770 (call-interactively cmd)))
16772 (defun org-shifttab (&optional arg)
16773 "Global visibility cycling or move to previous table field.
16774 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
16776 See the individual commands for more information."
16779 ((org-at-table-p) (call-interactively 'org-table-previous-field))
16781 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
16782 (message "Content view to level: %d" arg)
16783 (org-content (prefix-numeric-value arg2))
16784 (setq org-cycle-global-status 'overview)))
16785 (t (call-interactively 'org-global-cycle))))
16787 (defun org-shiftmetaleft ()
16788 "Promote subtree or delete table column.
16789 Calls `org-promote-subtree', `org-outdent-item',
16790 or `org-table-delete-column', depending on context.
16791 See the individual commands for more information."
16794 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
16795 ((org-at-table-p) (call-interactively 'org-table-delete-column))
16796 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
16797 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
16798 (t (org-modifier-cursor-error))))
16800 (defun org-shiftmetaright ()
16801 "Demote subtree or insert table column.
16802 Calls `org-demote-subtree', `org-indent-item',
16803 or `org-table-insert-column', depending on context.
16804 See the individual commands for more information."
16807 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
16808 ((org-at-table-p) (call-interactively 'org-table-insert-column))
16809 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
16810 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
16811 (t (org-modifier-cursor-error))))
16813 (defun org-shiftmetaup (&optional arg)
16814 "Move subtree up or kill table row.
16815 Calls `org-move-subtree-up' or `org-table-kill-row' or
16816 `org-move-item-up' depending on context. See the individual commands
16817 for more information."
16820 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
16821 ((org-at-table-p) (call-interactively 'org-table-kill-row))
16822 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16823 ((org-at-item-p) (call-interactively 'org-move-item-up))
16824 (t (org-modifier-cursor-error))))
16826 (defun org-shiftmetadown (&optional arg)
16827 "Move subtree down or insert table row.
16828 Calls `org-move-subtree-down' or `org-table-insert-row' or
16829 `org-move-item-down', depending on context. See the individual
16830 commands for more information."
16833 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
16834 ((org-at-table-p) (call-interactively 'org-table-insert-row))
16835 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16836 ((org-at-item-p) (call-interactively 'org-move-item-down))
16837 (t (org-modifier-cursor-error))))
16839 (defsubst org-hidden-tree-error ()
16841 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
16843 (defun org-metaleft (&optional arg)
16844 "Promote heading or move table column to left.
16845 Calls `org-do-promote' or `org-table-move-column', depending on context.
16846 With no specific context, calls the Emacs default `backward-word'.
16847 See the individual commands for more information."
16850 ((run-hook-with-args-until-success 'org-metaleft-hook))
16851 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
16852 ((or (org-on-heading-p)
16853 (and (org-region-active-p)
16855 (goto-char (region-beginning))
16856 (org-on-heading-p))))
16857 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
16858 (call-interactively 'org-do-promote))
16859 ((or (org-at-item-p)
16860 (and (org-region-active-p)
16862 (goto-char (region-beginning))
16864 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
16865 (call-interactively 'org-outdent-item))
16866 (t (call-interactively 'backward-word))))
16868 (defun org-metaright (&optional arg)
16869 "Demote subtree or move table column to right.
16870 Calls `org-do-demote' or `org-table-move-column', depending on context.
16871 With no specific context, calls the Emacs default `forward-word'.
16872 See the individual commands for more information."
16875 ((run-hook-with-args-until-success 'org-metaright-hook))
16876 ((org-at-table-p) (call-interactively 'org-table-move-column))
16877 ((or (org-on-heading-p)
16878 (and (org-region-active-p)
16880 (goto-char (region-beginning))
16881 (org-on-heading-p))))
16882 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
16883 (call-interactively 'org-do-demote))
16884 ((or (org-at-item-p)
16885 (and (org-region-active-p)
16887 (goto-char (region-beginning))
16889 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
16890 (call-interactively 'org-indent-item))
16891 (t (call-interactively 'forward-word))))
16893 (defun org-check-for-hidden (what)
16894 "Check if there are hidden headlines/items in the current visual line.
16895 WHAT can be either `headlines' or `items'. If the current line is
16896 an outline or item heading and it has a folded subtree below it,
16897 this function returns t, nil otherwise."
16899 ((eq what 'headlines) (concat "^" org-outline-regexp))
16900 ((eq what 'items) (concat "^" (org-item-re t)))
16901 (t (error "This should not happen"))))
16905 (unless (org-region-active-p)
16906 (setq beg (point-at-bol))
16907 (beginning-of-line 2)
16908 (while (and (not (eobp)) ;; this is like `next-line'
16909 (get-char-property (1- (point)) 'invisible))
16910 (beginning-of-line 2))
16913 (goto-char (point-at-eol))
16914 (setq end (max end (point)))
16915 (while (re-search-forward re end t)
16916 (if (get-char-property (match-beginning 0) 'invisible)
16920 (defun org-metaup (&optional arg)
16921 "Move subtree up or move table row up.
16922 Calls `org-move-subtree-up' or `org-table-move-row' or
16923 `org-move-item-up', depending on context. See the individual commands
16924 for more information."
16927 ((run-hook-with-args-until-success 'org-metaup-hook))
16928 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
16929 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16930 ((org-at-item-p) (call-interactively 'org-move-item-up))
16931 (t (transpose-lines 1) (beginning-of-line -1))))
16933 (defun org-metadown (&optional arg)
16934 "Move subtree down or move table row down.
16935 Calls `org-move-subtree-down' or `org-table-move-row' or
16936 `org-move-item-down', depending on context. See the individual
16937 commands for more information."
16940 ((run-hook-with-args-until-success 'org-metadown-hook))
16941 ((org-at-table-p) (call-interactively 'org-table-move-row))
16942 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16943 ((org-at-item-p) (call-interactively 'org-move-item-down))
16944 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
16946 (defun org-shiftup (&optional arg)
16947 "Increase item in timestamp or increase priority of current headline.
16948 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
16949 depending on context. See the individual commands for more information."
16952 ((run-hook-with-args-until-success 'org-shiftup-hook))
16953 ((and org-support-shift-select (org-region-active-p))
16954 (org-call-for-shift-select 'previous-line))
16955 ((org-at-timestamp-p t)
16956 (call-interactively (if org-edit-timestamp-down-means-later
16957 'org-timestamp-down 'org-timestamp-up)))
16958 ((and (not (eq org-support-shift-select 'always))
16959 org-enable-priority-commands
16960 (org-on-heading-p))
16961 (call-interactively 'org-priority-up))
16962 ((and (not org-support-shift-select) (org-at-item-p))
16963 (call-interactively 'org-previous-item))
16964 ((org-clocktable-try-shift 'up arg))
16965 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
16966 (org-support-shift-select
16967 (org-call-for-shift-select 'previous-line))
16968 (t (org-shiftselect-error))))
16970 (defun org-shiftdown (&optional arg)
16971 "Decrease item in timestamp or decrease priority of current headline.
16972 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
16973 depending on context. See the individual commands for more information."
16976 ((run-hook-with-args-until-success 'org-shiftdown-hook))
16977 ((and org-support-shift-select (org-region-active-p))
16978 (org-call-for-shift-select 'next-line))
16979 ((org-at-timestamp-p t)
16980 (call-interactively (if org-edit-timestamp-down-means-later
16981 'org-timestamp-up 'org-timestamp-down)))
16982 ((and (not (eq org-support-shift-select 'always))
16983 org-enable-priority-commands
16984 (org-on-heading-p))
16985 (call-interactively 'org-priority-down))
16986 ((and (not org-support-shift-select) (org-at-item-p))
16987 (call-interactively 'org-next-item))
16988 ((org-clocktable-try-shift 'down arg))
16989 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
16990 (org-support-shift-select
16991 (org-call-for-shift-select 'next-line))
16992 (t (org-shiftselect-error))))
16994 (defun org-shiftright (&optional arg)
16995 "Cycle the thing at point or in the current line, depending on context.
16996 Depending on context, this does one of the following:
16998 - switch a timestamp at point one day into the future
16999 - on a headline, switch to the next TODO keyword.
17000 - on an item, switch entire list to the next bullet type
17001 - on a property line, switch to the next allowed value
17002 - on a clocktable definition line, move time block into the future"
17005 ((run-hook-with-args-until-success 'org-shiftright-hook))
17006 ((and org-support-shift-select (org-region-active-p))
17007 (org-call-for-shift-select 'forward-char))
17008 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
17009 ((and (not (eq org-support-shift-select 'always))
17010 (org-on-heading-p))
17011 (let ((org-inhibit-logging
17012 (not org-treat-S-cursor-todo-selection-as-state-change))
17013 (org-inhibit-blocking
17014 (not org-treat-S-cursor-todo-selection-as-state-change)))
17015 (org-call-with-arg 'org-todo 'right)))
17016 ((or (and org-support-shift-select
17017 (not (eq org-support-shift-select 'always))
17018 (org-at-item-bullet-p))
17019 (and (not org-support-shift-select) (org-at-item-p)))
17020 (org-call-with-arg 'org-cycle-list-bullet nil))
17021 ((and (not (eq org-support-shift-select 'always))
17022 (org-at-property-p))
17023 (call-interactively 'org-property-next-allowed-value))
17024 ((org-clocktable-try-shift 'right arg))
17025 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
17026 (org-support-shift-select
17027 (org-call-for-shift-select 'forward-char))
17028 (t (org-shiftselect-error))))
17030 (defun org-shiftleft (&optional arg)
17031 "Cycle the thing at point or in the current line, depending on context.
17032 Depending on context, this does one of the following:
17034 - switch a timestamp at point one day into the past
17035 - on a headline, switch to the previous TODO keyword.
17036 - on an item, switch entire list to the previous bullet type
17037 - on a property line, switch to the previous allowed value
17038 - on a clocktable definition line, move time block into the past"
17041 ((run-hook-with-args-until-success 'org-shiftleft-hook))
17042 ((and org-support-shift-select (org-region-active-p))
17043 (org-call-for-shift-select 'backward-char))
17044 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
17045 ((and (not (eq org-support-shift-select 'always))
17046 (org-on-heading-p))
17047 (let ((org-inhibit-logging
17048 (not org-treat-S-cursor-todo-selection-as-state-change))
17049 (org-inhibit-blocking
17050 (not org-treat-S-cursor-todo-selection-as-state-change)))
17051 (org-call-with-arg 'org-todo 'left)))
17052 ((or (and org-support-shift-select
17053 (not (eq org-support-shift-select 'always))
17054 (org-at-item-bullet-p))
17055 (and (not org-support-shift-select) (org-at-item-p)))
17056 (org-call-with-arg 'org-cycle-list-bullet 'previous))
17057 ((and (not (eq org-support-shift-select 'always))
17058 (org-at-property-p))
17059 (call-interactively 'org-property-previous-allowed-value))
17060 ((org-clocktable-try-shift 'left arg))
17061 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
17062 (org-support-shift-select
17063 (org-call-for-shift-select 'backward-char))
17064 (t (org-shiftselect-error))))
17066 (defun org-shiftcontrolright ()
17067 "Switch to next TODO set."
17070 ((and org-support-shift-select (org-region-active-p))
17071 (org-call-for-shift-select 'forward-word))
17072 ((and (not (eq org-support-shift-select 'always))
17073 (org-on-heading-p))
17074 (org-call-with-arg 'org-todo 'nextset))
17075 (org-support-shift-select
17076 (org-call-for-shift-select 'forward-word))
17077 (t (org-shiftselect-error))))
17079 (defun org-shiftcontrolleft ()
17080 "Switch to previous TODO set."
17083 ((and org-support-shift-select (org-region-active-p))
17084 (org-call-for-shift-select 'backward-word))
17085 ((and (not (eq org-support-shift-select 'always))
17086 (org-on-heading-p))
17087 (org-call-with-arg 'org-todo 'previousset))
17088 (org-support-shift-select
17089 (org-call-for-shift-select 'backward-word))
17090 (t (org-shiftselect-error))))
17092 (defun org-ctrl-c-ret ()
17093 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
17096 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
17097 (t (call-interactively 'org-insert-heading))))
17099 (defun org-copy-special ()
17100 "Copy region in table or copy current subtree.
17101 Calls `org-table-copy' or `org-copy-subtree', depending on context.
17102 See the individual commands for more information."
17104 (call-interactively
17105 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
17107 (defun org-cut-special ()
17108 "Cut region in table or cut current subtree.
17109 Calls `org-table-copy' or `org-cut-subtree', depending on context.
17110 See the individual commands for more information."
17112 (call-interactively
17113 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
17115 (defun org-paste-special (arg)
17116 "Paste rectangular region into table, or past subtree relative to level.
17117 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
17118 See the individual commands for more information."
17120 (if (org-at-table-p)
17121 (org-table-paste-rectangle)
17122 (org-paste-subtree arg)))
17124 (defun org-edit-special (&optional arg)
17125 "Call a special editor for the stuff at point.
17126 When at a table, call the formula editor with `org-table-edit-formulas'.
17127 When at the first line of an src example, call `org-edit-src-code'.
17128 When in an #+include line, visit the include file. Otherwise call
17129 `ffap' to visit the file at point."
17131 ;; possibly prep session before editing source
17133 (let* ((info (org-babel-get-src-block-info))
17134 (lang (nth 0 info))
17135 (params (nth 2 info))
17136 (session (cdr (assoc :session params))))
17137 (when (and info session) ;; we are in a source-code block with a session
17139 (intern (concat "org-babel-prep-session:" lang)) session params))))
17140 (cond ;; proceed with `org-edit-special'
17142 (beginning-of-line 1)
17143 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
17144 (find-file (org-trim (match-string 1))))
17145 ((org-edit-src-code))
17146 ((org-edit-fixed-width-region))
17147 ((org-at-table.el-p)
17148 (org-edit-src-code))
17150 (call-interactively 'org-table-edit-formulas))
17151 (t (call-interactively 'ffap))))
17154 (defun org-ctrl-c-ctrl-c (&optional arg)
17155 "Set tags in headline, or update according to changed information at point.
17157 This command does many different things, depending on context:
17159 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
17160 this is what we do.
17162 - If the cursor is on a statistics cookie, update it.
17164 - If the cursor is in a headline, prompt for tags and insert them
17165 into the current line, aligned to `org-tags-column'. When called
17166 with prefix arg, realign all tags in the current buffer.
17168 - If the cursor is in one of the special #+KEYWORD lines, this
17169 triggers scanning the buffer for these lines and updating the
17172 - If the cursor is inside a table, realign the table. This command
17173 works even if the automatic table editor has been turned off.
17175 - If the cursor is on a #+TBLFM line, re-apply the formulas to
17178 - If the cursor is at a footnote reference or definition, jump to
17179 the corresponding definition or references, respectively.
17181 - If the cursor is a the beginning of a dynamic block, update it.
17183 - If the current buffer is a capture buffer, close note and file it.
17185 - If the cursor is on a <<<target>>>, update radio targets and
17186 corresponding links in this buffer.
17188 - If the cursor is on a numbered item in a plain list, renumber the
17191 - If the cursor is on a checkbox, toggle it.
17193 - If the cursor is on a code block, evaluate it. The variable
17194 `org-confirm-babel-evaluate' can be used to control prompting
17195 before code block evaluation, by default every code block
17196 evaluation requires confirmation. Code block evaluation can be
17197 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
17199 (let ((org-enable-table-editor t))
17201 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
17202 org-occur-highlights
17203 org-latex-fragment-image-overlays)
17204 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
17205 (org-remove-occur-highlights)
17206 (org-remove-latex-fragment-image-overlays)
17207 (message "Temporary highlights/overlays removed from current buffer"))
17208 ((and (local-variable-p 'org-finish-function (current-buffer))
17209 (fboundp org-finish-function))
17210 (funcall org-finish-function))
17211 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
17212 ((or (looking-at org-property-start-re)
17213 (org-at-property-p))
17214 (call-interactively 'org-property-action))
17215 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
17216 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
17217 (or (org-on-heading-p) (org-at-item-p)))
17218 (call-interactively 'org-update-statistics-cookies))
17219 ((org-on-heading-p) (call-interactively 'org-set-tags))
17220 ((org-at-table.el-p)
17221 (message "Use C-c ' to edit table.el tables"))
17223 (org-table-maybe-eval-formula)
17225 (call-interactively 'org-table-recalculate)
17226 (org-table-maybe-recalculate-line))
17227 (call-interactively 'org-table-align))
17228 ((or (org-footnote-at-reference-p)
17229 (org-footnote-at-definition-p))
17230 (call-interactively 'org-footnote-action))
17231 ((org-at-item-checkbox-p)
17232 (call-interactively 'org-toggle-checkbox)
17233 (org-list-send-list 'maybe))
17236 (call-interactively 'org-toggle-checkbox)
17237 (call-interactively 'org-maybe-renumber-ordered-list))
17238 (org-list-send-list 'maybe))
17239 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
17241 (beginning-of-line 1)
17242 (save-excursion (org-update-dblock)))
17244 (beginning-of-line 1)
17245 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
17247 ((equal (match-string 1) "TBLFM")
17248 ;; Recalculate the table before this line
17250 (beginning-of-line 1)
17251 (skip-chars-backward " \r\n\t")
17252 (if (org-at-table-p)
17253 (org-call-with-arg 'org-table-recalculate (or arg t)))))
17255 (let ((org-inhibit-startup-visibility-stuff t)
17256 (org-startup-align-all-tables nil))
17257 (org-save-outline-visibility 'use-markers (org-mode-restart)))
17258 (message "Local setup has been refreshed"))))
17259 ((org-clock-update-time-maybe))
17260 (t (error "C-c C-c can do nothing useful at this location")))))
17262 (defun org-mode-restart ()
17263 "Restart Org-mode, to scan again for special lines.
17264 Also updates the keyword regular expressions."
17267 (message "Org-mode restarted"))
17269 (defun org-kill-note-or-show-branches ()
17270 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
17272 (if (not org-finish-function)
17275 (call-interactively 'show-branches))
17276 (let ((org-note-abort t))
17277 (funcall org-finish-function))))
17279 (defun org-return (&optional indent)
17280 "Goto next table row or insert a newline.
17281 Calls `org-table-next-row' or `newline', depending on context.
17282 See the individual commands for more information."
17285 ((bobp) (if indent (newline-and-indent) (newline)))
17287 (org-table-justify-field-maybe)
17288 (call-interactively 'org-table-next-row))
17289 ((and org-return-follows-link
17290 (eq (get-text-property (point) 'face) 'org-link))
17291 (call-interactively 'org-open-at-point))
17292 ((and (org-at-heading-p)
17294 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
17298 (t (if indent (newline-and-indent) (newline)))))
17300 (defun org-return-indent ()
17301 "Goto next table row or insert a newline and indent.
17302 Calls `org-table-next-row' or `newline-and-indent', depending on
17303 context. See the individual commands for more information."
17307 (defun org-ctrl-c-star ()
17308 "Compute table, or change heading status of lines.
17309 Calls `org-table-recalculate' or `org-toggle-heading',
17310 depending on context."
17314 (call-interactively 'org-table-recalculate))
17316 ;; Convert all lines in region to list items
17317 (call-interactively 'org-toggle-heading))))
17319 (defun org-ctrl-c-minus ()
17320 "Insert separator line in table or modify bullet status of line.
17321 Also turns a plain line or a region of lines into list items.
17322 Calls `org-table-insert-hline', `org-toggle-item', or
17323 `org-cycle-list-bullet', depending on context."
17327 (call-interactively 'org-table-insert-hline))
17328 ((org-region-active-p)
17329 (call-interactively 'org-toggle-item))
17331 (call-interactively 'org-cycle-list-bullet))
17333 (call-interactively 'org-toggle-item))))
17335 (defun org-toggle-item ()
17336 "Convert headings or normal lines to items, items to normal lines.
17337 If there is no active region, only the current line is considered.
17339 If the first line in the region is a headline, convert all headlines to items.
17341 If the first line in the region is an item, convert all items to normal lines.
17343 If the first line is normal text, add an item bullet to each line."
17345 (let (l2 l beg end)
17346 (if (org-region-active-p)
17347 (setq beg (region-beginning) end (region-end))
17348 (setq beg (point-at-bol)
17349 end (min (1+ (point-at-eol)) (point-max))))
17352 (setq l2 (org-current-line))
17354 (beginning-of-line 1)
17355 (setq l (1- (org-current-line)))
17356 (if (org-at-item-p)
17357 ;; We already have items, de-itemize
17358 (while (< (setq l (1+ l)) l2)
17359 (when (org-at-item-p)
17360 (goto-char (match-beginning 2))
17361 (delete-region (match-beginning 2) (match-end 2))
17362 (and (looking-at "[ \t]+") (replace-match "")))
17363 (beginning-of-line 2))
17364 (if (org-on-heading-p)
17365 ;; Headings, convert to items
17366 (while (< (setq l (1+ l)) l2)
17367 (if (looking-at org-outline-regexp)
17368 (replace-match "- " t t))
17369 (beginning-of-line 2))
17370 ;; normal lines, turn them into items
17371 (while (< (setq l (1+ l)) l2)
17372 (unless (org-at-item-p)
17373 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17374 (replace-match "\\1- \\2")))
17375 (beginning-of-line 2)))))))
17377 (defun org-toggle-heading (&optional nstars)
17378 "Convert headings to normal text, or items or text to headings.
17379 If there is no active region, only the current line is considered.
17381 If the first line is a heading, remove the stars from all headlines
17384 If the first line is a plain list item, turn all plain list items
17387 If the first line is a normal line, turn each and every line in the
17388 region into a heading.
17390 When converting a line into a heading, the number of stars is chosen
17391 such that the lines become children of the current entry. However,
17392 when a prefix argument is given, its value determines the number of
17395 (let (l2 l itemp beg end)
17396 (if (org-region-active-p)
17397 (setq beg (region-beginning) end (region-end))
17398 (setq beg (point-at-bol)
17399 end (min (1+ (point-at-eol)) (point-max))))
17402 (setq l2 (org-current-line))
17404 (beginning-of-line 1)
17405 (setq l (1- (org-current-line)))
17406 (if (org-on-heading-p)
17407 ;; We already have headlines, de-star them
17408 (while (< (setq l (1+ l)) l2)
17409 (when (org-on-heading-p t)
17410 (and (looking-at outline-regexp) (replace-match "")))
17411 (beginning-of-line 2))
17412 (setq itemp (org-at-item-p))
17415 (make-string (prefix-numeric-value current-prefix-arg)
17418 (if (re-search-backward org-complex-heading-regexp nil t)
17419 (match-string 1) ""))))
17420 (add-stars (cond (nstars "")
17421 ((equal stars "") "*")
17422 (org-odd-levels-only "**")
17424 (rpl (concat stars add-stars " ")))
17425 (while (< (setq l (1+ l)) l2)
17427 (and (org-at-item-p) (replace-match rpl t t))
17428 (unless (org-on-heading-p)
17429 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17430 (replace-match (concat rpl (match-string 2))))))
17431 (beginning-of-line 2)))))))
17433 (defun org-meta-return (&optional arg)
17434 "Insert a new heading or wrap a region in a table.
17435 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
17436 See the individual commands for more information."
17439 ((run-hook-with-args-until-success 'org-metareturn-hook))
17441 (call-interactively 'org-table-wrap-region))
17442 (t (call-interactively 'org-insert-heading))))
17446 ;; Define the Org-mode menus
17447 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
17449 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
17450 ["Next Field" org-cycle (org-at-table-p)]
17451 ["Previous Field" org-shifttab (org-at-table-p)]
17452 ["Next Row" org-return (org-at-table-p)]
17454 ["Blank Field" org-table-blank-field (org-at-table-p)]
17455 ["Edit Field" org-table-edit-field (org-at-table-p)]
17456 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
17459 ["Move Column Left" org-metaleft (org-at-table-p)]
17460 ["Move Column Right" org-metaright (org-at-table-p)]
17461 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
17462 ["Insert Column" org-shiftmetaright (org-at-table-p)])
17464 ["Move Row Up" org-metaup (org-at-table-p)]
17465 ["Move Row Down" org-metadown (org-at-table-p)]
17466 ["Delete Row" org-shiftmetaup (org-at-table-p)]
17467 ["Insert Row" org-shiftmetadown (org-at-table-p)]
17468 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
17470 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
17472 ["Copy Rectangle" org-copy-special (org-at-table-p)]
17473 ["Cut Rectangle" org-cut-special (org-at-table-p)]
17474 ["Paste Rectangle" org-paste-special (org-at-table-p)]
17475 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
17478 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
17479 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
17480 ["Edit Formulas" org-edit-special (org-at-table-p)]
17482 ["Recalculate line" org-table-recalculate (org-at-table-p)]
17483 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
17484 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
17486 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
17488 ["Sum Column/Rectangle" org-table-sum
17489 (or (org-at-table-p) (org-region-active-p))]
17490 ["Which Column?" org-table-current-column (org-at-table-p)])
17492 org-table-toggle-formula-debugger
17493 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
17494 ["Show Col/Row Numbers"
17495 org-table-toggle-coordinate-overlays
17497 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
17499 ["Create" org-table-create (and (not (org-at-table-p))
17500 org-enable-table-editor)]
17501 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
17502 ["Import from File" org-table-import (not (org-at-table-p))]
17503 ["Export to File" org-table-export (org-at-table-p)]
17505 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
17507 (easy-menu-define org-org-menu org-mode-map "Org menu"
17510 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
17511 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
17512 ["Sparse Tree..." org-sparse-tree t]
17513 ["Reveal Context" org-reveal t]
17514 ["Show All" show-all t]
17516 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
17518 ["New Heading" org-insert-heading t]
17519 ("Navigate Headings"
17520 ["Up" outline-up-heading t]
17521 ["Next" outline-next-visible-heading t]
17522 ["Previous" outline-previous-visible-heading t]
17523 ["Next Same Level" outline-forward-same-level t]
17524 ["Previous Same Level" outline-backward-same-level t]
17526 ["Jump" org-goto t])
17528 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
17529 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
17531 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
17532 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
17533 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
17535 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
17537 ["Promote Heading" org-metaleft (not (org-at-table-p))]
17538 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
17539 ["Demote Heading" org-metaright (not (org-at-table-p))]
17540 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
17542 ["Sort Region/Children" org-sort (not (org-at-table-p))]
17544 ["Convert to odd levels" org-convert-to-odd-levels t]
17545 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
17547 ["Emphasis..." org-emphasize t]
17548 ["Edit Source Example" org-edit-special t]
17550 ["Footnote new/jump" org-footnote-action t]
17551 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
17553 ["Archive (default method)" org-archive-subtree-default t]
17555 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
17556 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
17557 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
17561 ["Store Link (Global)" org-store-link t]
17562 ["Find existing link to here" org-occur-link-in-agenda-files t]
17563 ["Insert Link" org-insert-link t]
17564 ["Follow Link" org-open-at-point t]
17566 ["Next link" org-next-link t]
17567 ["Previous link" org-previous-link t]
17569 ["Descriptive Links"
17570 (progn (add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
17572 :selected (member '(org-link) buffer-invisibility-spec)]
17575 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
17577 :selected (not (member '(org-link) buffer-invisibility-spec))])
17580 ["TODO/DONE/-" org-todo t]
17582 ["Next keyword" org-shiftright (org-on-heading-p)]
17583 ["Previous keyword" org-shiftleft (org-on-heading-p)]
17584 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
17585 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
17586 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
17587 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
17588 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
17590 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
17591 :selected org-enforce-todo-dependencies :style toggle :active t]
17592 "Settings for tree at point"
17593 ["Do Children sequentially" org-toggle-ordered-property :style radio
17594 :selected (ignore-errors (org-entry-get nil "ORDERED"))
17595 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
17596 ["Do Children parallel" org-toggle-ordered-property :style radio
17597 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
17598 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
17600 ["Set Priority" org-priority t]
17601 ["Priority Up" org-shiftup t]
17602 ["Priority Down" org-shiftdown t]
17604 ["Get news from all feeds" org-feed-update-all t]
17605 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
17606 ["Customize feeds" (customize-variable 'org-feed-alist) t])
17607 ("TAGS and Properties"
17608 ["Set Tags" org-set-tags-command t]
17609 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
17611 ["Set property" org-set-property t]
17612 ["Column view of properties" org-columns t]
17613 ["Insert Column View DBlock" org-insert-columns-dblock t])
17614 ("Dates and Scheduling"
17615 ["Timestamp" org-time-stamp t]
17616 ["Timestamp (inactive)" org-time-stamp-inactive t]
17618 ["1 Day Later" org-shiftright t]
17619 ["1 Day Earlier" org-shiftleft t]
17620 ["1 ... Later" org-shiftup t]
17621 ["1 ... Earlier" org-shiftdown t])
17622 ["Compute Time Range" org-evaluate-time-range t]
17623 ["Schedule Item" org-schedule t]
17624 ["Deadline" org-deadline t]
17626 ["Custom time format" org-toggle-time-stamp-overlays
17627 :style radio :selected org-display-custom-times]
17629 ["Goto Calendar" org-goto-calendar t]
17630 ["Date from Calendar" org-date-from-calendar t]
17632 ["Start/Restart Timer" org-timer-start t]
17633 ["Pause/Continue Timer" org-timer-pause-or-continue t]
17634 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
17635 ["Insert Timer String" org-timer t]
17636 ["Insert Timer Item" org-timer-item t])
17638 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
17639 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
17640 ["Clock out" org-clock-out t]
17641 ["Clock cancel" org-clock-cancel t]
17643 ["Mark as default task" org-clock-mark-default-task t]
17644 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
17645 ["Goto running clock" org-clock-goto t]
17647 ["Display times" org-clock-display t]
17648 ["Create clock table" org-clock-report t]
17650 ["Record DONE time"
17651 (progn (setq org-log-done (not org-log-done))
17652 (message "Switching to %s will %s record a timestamp"
17653 (car org-done-keywords)
17654 (if org-log-done "automatically" "not")))
17655 :style toggle :selected org-log-done])
17657 ["Agenda Command..." org-agenda t]
17658 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
17659 ("File List for Agenda")
17660 ("Special views current file"
17661 ["TODO Tree" org-show-todo-tree t]
17662 ["Check Deadlines" org-check-deadlines t]
17663 ["Timeline" org-timeline t]
17664 ["Tags/Property tree" org-match-sparse-tree t])
17666 ["Export/Publish..." org-export t]
17668 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
17669 :selected org-cdlatex-mode]
17670 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
17671 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
17672 ["Modify math symbol" org-cdlatex-math-modify
17673 (org-inside-LaTeX-fragment-p)]
17674 ["Insert citation" org-reftex-citation t]
17676 ["Template for BEAMER" org-insert-beamer-options-template t])
17679 ["Push Files and Views" org-mobile-push t]
17680 ["Get Captured and Flagged" org-mobile-pull t]
17681 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
17683 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
17686 ["Show Version" org-version t]
17687 ["Info Documentation" org-info t])
17689 ["Browse Org Group" org-customize t]
17691 ["Expand This Menu" org-create-customize-menu
17692 (fboundp 'customize-menu-create)])
17693 ["Send bug report" org-submit-bug-report t]
17696 ["Refresh setup current buffer" org-mode-restart t]
17697 ["Reload Org (after update)" org-reload t]
17698 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
17701 (defun org-info (&optional node)
17702 "Read documentation for Org-mode in the info system.
17703 With optional NODE, go directly to that node."
17705 (info (format "(org)%s" (or node ""))))
17708 (defun org-submit-bug-report ()
17709 "Submit a bug report on Org-mode via mail.
17711 Don't hesitate to report any problems or inaccurate documentation.
17713 If you don't have setup sending mail from (X)Emacs, please copy the
17714 output buffer into your mail program, as it gives us important
17715 information about your Org-mode version and configuration."
17717 (require 'reporter)
17718 (org-load-modules-maybe)
17719 (org-require-autoloaded-modules)
17720 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
17721 (reporter-submit-bug-report
17722 "emacs-orgmode@gnu.org"
17725 (save-window-excursion
17726 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
17727 (delete-other-windows)
17729 (insert "You are about to submit a bug report to the Org-mode mailing list.
17731 We would like to add your full Org-mode and Outline configuration to the
17732 bug report. This greatly simplifies the work of the maintainer and
17733 other experts on the mailing list.
17735 HOWEVER, some variables you have customized may contain private
17736 information. The names of customers, colleagues, or friends, might
17737 appear in the form of file names, tags, todo states, or search strings.
17738 If you answer yes to the prompt, you might want to check and remove
17739 such private information before sending the email.")
17740 (add-text-properties (point-min) (point-max) '(face org-warning))
17741 (when (yes-or-no-p "Include your Org-mode configuration ")
17745 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
17746 (or (and (symbol-value v)
17747 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
17749 (get v 'custom-type) (get v 'standard-value)
17750 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
17752 (kill-buffer (get-buffer "*Warn about privacy*"))
17755 "Remember to cover the basics, that is, what you expected to happen and
17756 what in fact did happen. You don't know how to make a good report? See
17758 http://orgmode.org/manual/Feedback.html#Feedback
17760 Your bug report will be posted to the Org-mode mailing list.
17761 ------------------------------------------------------------------------")
17763 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
17764 (replace-match "\\1Bug: \\3 [\\2]")))))
17767 (defun org-install-agenda-files-menu ()
17768 (let ((bl (buffer-list)))
17771 (set-buffer (pop bl))
17772 (if (org-mode-p) (setq bl nil)))
17775 '("Org") "File List for Agenda"
17778 ["Edit File List" (org-edit-agenda-file-list) t]
17779 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
17780 ["Remove Current File from List" org-remove-file t]
17781 ["Cycle through agenda files" org-cycle-agenda-files t]
17782 ["Occur in all agenda files" org-occur-in-agenda-files t]
17784 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
17789 (defun org-require-autoloaded-modules ()
17792 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
17793 org-docbook org-exp org-html org-icalendar
17795 org-publish org-remember org-table
17796 org-timer org-xoxo)))
17799 (defun org-reload (&optional uncompiled)
17800 "Reload all org lisp files.
17801 With prefix arg UNCOMPILED, load the uncompiled versions."
17803 (require 'find-func)
17804 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
17805 (dir-org (file-name-directory (org-find-library-name "org")))
17806 (dir-org-contrib (ignore-errors
17807 (file-name-directory
17808 (org-find-library-name "org-contribdir"))))
17810 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
17811 (append (list nil "comint" "eval" "exp" "keys"
17812 "lob" "ref" "table" "tangle")
17816 (when (cdr lang) (symbol-name (car lang))))
17817 org-babel-load-languages)))))
17819 (append (directory-files dir-org t file-re)
17821 (and dir-org-contrib
17822 (directory-files dir-org-contrib t file-re))))
17823 (remove-re (concat (if (featurep 'xemacs)
17824 "org-colview" "org-colview-xemacs")
17826 (setq files (mapcar 'file-name-sans-extension files))
17827 (setq files (mapcar
17828 (lambda (x) (if (string-match remove-re x) nil x))
17830 (setq files (delq nil files))
17833 (when (featurep (intern (file-name-nondirectory f)))
17834 (if (and (not uncompiled)
17835 (file-exists-p (concat f ".elc")))
17836 (load (concat f ".elc") nil nil t)
17837 (load (concat f ".el") nil nil t))))
17842 (defun org-customize ()
17843 "Call the customize function with org as argument."
17845 (org-load-modules-maybe)
17846 (org-require-autoloaded-modules)
17847 (customize-browse 'org))
17849 (defun org-create-customize-menu ()
17850 "Create a full customization menu for Org-mode, insert it into the menu."
17852 (org-load-modules-maybe)
17853 (org-require-autoloaded-modules)
17854 (if (fboundp 'customize-menu-create)
17857 '("Org") "Customize"
17858 `(["Browse Org group" org-customize t]
17860 ,(customize-menu-create 'org)
17861 ["Set" Custom-set t]
17862 ["Save" Custom-save t]
17863 ["Reset to Current" Custom-reset-current t]
17864 ["Reset to Saved" Custom-reset-saved t]
17865 ["Reset to Standard Settings" Custom-reset-standard t]))
17866 (message "\"Org\"-menu now contains full customization menu"))
17867 (error "Cannot expand menu (outdated version of cus-edit.el)")))
17869 ;;;; Miscellaneous stuff
17871 ;;; Generally useful functions
17873 (defun org-get-at-bol (property)
17874 "Get text property PROPERTY at beginning of line."
17875 (get-text-property (point-at-bol) property))
17877 (defun org-find-text-property-in-string (prop s)
17878 "Return the first non-nil value of property PROP in string S."
17879 (or (get-text-property 0 prop s)
17880 (get-text-property (or (next-single-property-change 0 prop s) 0)
17883 (defun org-display-warning (message) ;; Copied from Emacs-Muse
17884 "Display the given MESSAGE as a warning."
17885 (if (fboundp 'display-warning)
17886 (display-warning 'org message
17887 (if (featurep 'xemacs) 'warning :warning))
17888 (let ((buf (get-buffer-create "*Org warnings*")))
17889 (with-current-buffer buf
17890 (goto-char (point-max))
17891 (insert "Warning (Org): " message)
17894 (display-buffer buf)
17897 (defun org-in-commented-line ()
17898 "Is point in a line starting with `#'?"
17899 (equal (char-after (point-at-bol)) ?#))
17901 (defun org-in-indented-comment-line ()
17902 "Is point in a line starting with `#' after some white space?"
17905 (goto-char (point-at-bol))
17906 (looking-at "[ \t]*#"))))
17908 (defun org-in-verbatim-emphasis ()
17910 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
17912 (defun org-goto-marker-or-bmk (marker &optional bookmark)
17913 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
17914 (if (and marker (marker-buffer marker)
17915 (buffer-live-p (marker-buffer marker)))
17917 (switch-to-buffer (marker-buffer marker))
17918 (if (or (> marker (point-max)) (< marker (point-min)))
17921 (org-show-context 'org-goto))
17923 (bookmark-jump bookmark)
17924 (error "Cannot find location"))))
17926 (defun org-quote-csv-field (s)
17927 "Quote field for inclusion in CSV material."
17928 (if (string-match "[\",]" s)
17929 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
17932 (defun org-plist-delete (plist property)
17933 "Delete PROPERTY from PLIST.
17934 This is in contrast to merely setting it to 0."
17937 (if (not (eq property (car plist)))
17938 (setq p (plist-put p (car plist) (nth 1 plist))))
17939 (setq plist (cddr plist)))
17942 (defun org-force-self-insert (N)
17943 "Needed to enforce self-insert under remapping."
17945 (self-insert-command N))
17947 (defun org-string-width (s)
17948 "Compute width of string, ignoring invisible characters.
17949 This ignores character with invisibility property `org-link', and also
17950 characters with property `org-cwidth', because these will become invisible
17951 upon the next fontification round."
17953 (when (or (eq t buffer-invisibility-spec)
17954 (assq 'org-link buffer-invisibility-spec))
17955 (while (setq b (text-property-any 0 (length s)
17956 'invisible 'org-link s))
17957 (setq s (concat (substring s 0 b)
17958 (substring s (or (next-single-property-change
17959 b 'invisible s) (length s)))))))
17960 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
17961 (setq s (concat (substring s 0 b)
17962 (substring s (or (next-single-property-change
17963 b 'org-cwidth s) (length s))))))
17964 (setq l (string-width s) b -1)
17965 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
17966 (setq l (- l (get-text-property b 'org-dwidth-n s))))
17969 (defun org-get-indentation (&optional line)
17970 "Get the indentation of the current line, interpreting tabs.
17971 When LINE is given, assume it represents a line and compute its indentation."
17973 (if (string-match "^ *" (org-remove-tabs line))
17976 (beginning-of-line 1)
17977 (skip-chars-forward " \t")
17978 (current-column))))
17980 (defun org-remove-tabs (s &optional width)
17981 "Replace tabulators in S with spaces.
17982 Assumes that s is a single line, starting in column 0."
17983 (setq width (or width tab-width))
17984 (while (string-match "\t" s)
17985 (setq s (replace-match
17987 (- (* width (/ (+ (match-beginning 0) width) width))
17988 (match-beginning 0)) ?\ )
17992 (defun org-fix-indentation (line ind)
17993 "Fix indentation in LINE.
17994 IND is a cons cell with target and minimum indentation.
17995 If the current indentation in LINE is smaller than the minimum,
17996 leave it alone. If it is larger than ind, set it to the target."
17997 (let* ((l (org-remove-tabs line))
17998 (i (org-get-indentation l))
17999 (i1 (car ind)) (i2 (cdr ind)))
18000 (if (>= i i2) (setq l (substring line i2)))
18002 (concat (make-string i1 ?\ ) l)
18005 (defun org-remove-indentation (code &optional n)
18006 "Remove the maximum common indentation from the lines in CODE.
18007 N may optionally be the number of spaces to remove."
18010 (org-do-remove-indentation n)
18013 (defun org-do-remove-indentation (&optional n)
18014 "Remove the maximum common indentation from the buffer."
18015 (untabify (point-min) (point-max))
18016 (let ((min 10000) re)
18019 (goto-char (point-min))
18020 (while (re-search-forward "^ *[^ \n]" nil t)
18021 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
18022 (unless (or (= min 0) (= min 10000))
18023 (setq re (format "^ \\{%d\\}" min))
18024 (goto-char (point-min))
18025 (while (re-search-forward re nil t)
18030 (defun org-fill-template (template alist)
18031 "Find each %key of ALIST in TEMPLATE and replace it."
18032 (let ((case-fold-search nil)
18034 (setq alist (sort (copy-sequence alist)
18035 (lambda (a b) (< (length (car a)) (length (car b))))))
18036 (while (setq entry (pop alist))
18038 (replace-regexp-in-string
18039 (concat "%" (regexp-quote (car entry)))
18040 (cdr entry) template t t)))
18043 (defun org-base-buffer (buffer)
18044 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
18047 (or (buffer-base-buffer buffer)
18050 (defun org-trim (s)
18051 "Remove whitespace at beginning and end of string."
18052 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
18053 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
18056 (defun org-wrap (string &optional width lines)
18057 "Wrap string to either a number of lines, or a width in characters.
18058 If WIDTH is non-nil, the string is wrapped to that width, however many lines
18059 that costs. If there is a word longer than WIDTH, the text is actually
18060 wrapped to the length of that word.
18061 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
18062 many lines, whatever width that takes.
18063 The return value is a list of lines, without newlines at the end."
18064 (let* ((words (org-split-string string "[ \t\n]+"))
18065 (maxword (apply 'max (mapcar 'org-string-width words)))
18068 (org-do-wrap words (max maxword width)))
18071 (setq ll (org-do-wrap words maxword))
18072 (if (<= (length ll) lines)
18075 (while (> (length ll) lines)
18077 (setq ll (org-do-wrap words w)))
18079 (t (error "Cannot wrap this")))))
18081 (defun org-do-wrap (words width)
18082 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
18085 (setq line (pop words))
18086 (while (and words (< (+ (length line) (length (car words))) width))
18087 (setq line (concat line " " (pop words))))
18088 (setq lines (push line lines)))
18091 (defun org-split-string (string &optional separators)
18092 "Splits STRING into substrings at SEPARATORS.
18093 No empty strings are returned if there are matches at the beginning
18094 and end of string."
18095 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
18099 (while (and (string-match rexp string
18101 (= start (match-beginning 0))
18102 (< start (length string)))
18104 (< (match-beginning 0) (length string)))
18106 (or (eq (match-beginning 0) 0)
18107 (and (eq (match-beginning 0) (match-end 0))
18108 (eq (match-beginning 0) start))
18110 (cons (substring string start (match-beginning 0))
18112 (setq start (match-end 0)))
18113 (or (eq start (length string))
18115 (cons (substring string start)
18119 (defun org-quote-vert (s)
18120 "Replace \"|\" with \"\\vert\"."
18121 (while (string-match "|" s)
18122 (setq s (replace-match "\\vert" t t s)))
18125 (defun org-uuidgen-p (s)
18126 "Is S an ID created by UUIDGEN?"
18127 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
18129 (defun org-context ()
18130 "Return a list of contexts of the current cursor position.
18131 If several contexts apply, all are returned.
18132 Each context entry is a list with a symbol naming the context, and
18133 two positions indicating start and end of the context. Possible
18136 :headline anywhere in a headline
18137 :headline-stars on the leading stars in a headline
18138 :todo-keyword on a TODO keyword (including DONE) in a headline
18139 :tags on the TAGS in a headline
18140 :priority on the priority cookie in a headline
18141 :item on the first line of a plain list item
18142 :item-bullet on the bullet/number of a plain list item
18143 :checkbox on the checkbox in a plain list item
18144 :table in an org-mode table
18145 :table-special on a special filed in a table
18146 :table-table in a table.el table
18147 :link on a hyperlink
18148 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
18149 :target on a <<target>>
18150 :radio-target on a <<<radio-target>>>
18151 :latex-fragment on a LaTeX fragment
18152 :latex-preview on a LaTeX fragment with overlayed preview image
18154 This function expects the position to be visible because it uses font-lock
18155 faces as a help to recognize the following contexts: :table-special, :link,
18157 (let* ((f (get-text-property (point) 'face))
18158 (faces (if (listp f) f (list f)))
18159 (p (point)) clist o)
18160 ;; First the large context
18162 ((org-on-heading-p t)
18163 (push (list :headline (point-at-bol) (point-at-eol)) clist)
18165 (beginning-of-line 1)
18166 (looking-at org-todo-line-tags-regexp))
18167 (push (org-point-in-group p 1 :headline-stars) clist)
18168 (push (org-point-in-group p 2 :todo-keyword) clist)
18169 (push (org-point-in-group p 4 :tags) clist))
18171 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
18172 (if (looking-at "\\[#[A-Z0-9]\\]")
18173 (push (org-point-in-group p 0 :priority) clist)))
18176 (push (org-point-in-group p 2 :item-bullet) clist)
18177 (push (list :item (point-at-bol)
18178 (save-excursion (org-end-of-item) (point)))
18180 (and (org-at-item-checkbox-p)
18181 (push (org-point-in-group p 0 :checkbox) clist)))
18184 (push (list :table (org-table-begin) (org-table-end)) clist)
18185 (if (memq 'org-formula faces)
18186 (push (list :table-special
18187 (previous-single-property-change p 'face)
18188 (next-single-property-change p 'face)) clist)))
18189 ((org-at-table-p 'any)
18190 (push (list :table-table) clist)))
18193 ;; Now the small context
18195 ((org-at-timestamp-p)
18196 (push (org-point-in-group p 0 :timestamp) clist))
18197 ((memq 'org-link faces)
18199 (previous-single-property-change p 'face)
18200 (next-single-property-change p 'face)) clist))
18201 ((memq 'org-special-keyword faces)
18202 (push (list :keyword
18203 (previous-single-property-change p 'face)
18204 (next-single-property-change p 'face)) clist))
18206 (push (org-point-in-group p 0 :target) clist)
18207 (goto-char (1- (match-beginning 0)))
18208 (if (looking-at org-radio-target-regexp)
18209 (push (org-point-in-group p 0 :radio-target) clist))
18211 ((setq o (car (delq nil
18214 (if (memq x org-latex-fragment-image-overlays) x))
18215 (overlays-at (point))))))
18216 (push (list :latex-fragment
18217 (overlay-start o) (overlay-end o)) clist)
18218 (push (list :latex-preview
18219 (overlay-start o) (overlay-end o)) clist))
18220 ((org-inside-LaTeX-fragment-p)
18221 ;; FIXME: positions wrong.
18222 (push (list :latex-fragment (point) (point)) clist)))
18224 (setq clist (nreverse (delq nil clist)))
18227 ;; FIXME: Compare with at-regexp-p Do we need both?
18228 (defun org-in-regexp (re &optional nlines visually)
18229 "Check if point is inside a match of regexp.
18230 Normally only the current line is checked, but you can include NLINES extra
18231 lines both before and after point into the search.
18232 If VISUALLY is set, require that the cursor is not after the match but
18233 really on, so that the block visually is on the match."
18235 (let ((pos (point))
18236 (eol (point-at-eol (+ 1 (or nlines 0))))
18237 (inc (if visually 1 0)))
18239 (beginning-of-line (- 1 (or nlines 0)))
18240 (while (re-search-forward re eol t)
18241 (if (and (<= (match-beginning 0) pos)
18242 (>= (+ inc (match-end 0)) pos))
18243 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
18245 (defun org-at-regexp-p (regexp)
18246 "Is point inside a match of REGEXP in the current line?"
18249 (let ((pos (point)) (end (point-at-eol)))
18250 (beginning-of-line 1)
18251 (while (re-search-forward regexp end t)
18252 (if (and (<= (match-beginning 0) pos)
18253 (>= (match-end 0) pos))
18257 (defun org-in-regexps-block-p (start-re end-re)
18258 "Return t if the current point is between matches of START-RE and END-RE.
18259 This will also return to if point is on one of the two matches."
18263 (and (or (org-at-regexp-p start-re)
18264 (re-search-backward start-re nil t))
18265 (re-search-forward end-re nil t)
18268 (defun org-occur-in-agenda-files (regexp &optional nlines)
18269 "Call `multi-occur' with buffers for all agenda files."
18270 (interactive "sOrg-files matching: \np")
18271 (let* ((files (org-agenda-files))
18272 (tnames (mapcar 'file-truename files))
18273 (extra org-agenda-text-search-extra-files)
18275 (when (eq (car extra) 'agenda-archives)
18276 (setq extra (cdr extra))
18277 (setq files (org-add-archive-files files)))
18278 (while (setq f (pop extra))
18279 (unless (member (file-truename f) tnames)
18280 (add-to-list 'files f 'append)
18281 (add-to-list 'tnames (file-truename f) 'append)))
18283 (mapcar (lambda (x)
18284 (with-current-buffer
18285 (or (get-file-buffer x) (find-file-noselect x))
18291 (if (boundp 'occur-mode-find-occurrence-hook)
18293 (add-hook 'occur-mode-find-occurrence-hook
18298 (defadvice occur-mode-goto-occurrence
18299 (after org-occur-reveal activate)
18300 (and (org-mode-p) (org-reveal)))
18301 (defadvice occur-mode-goto-occurrence-other-window
18302 (after org-occur-reveal activate)
18303 (and (org-mode-p) (org-reveal)))
18304 (defadvice occur-mode-display-occurrence
18305 (after org-occur-reveal activate)
18307 (let ((pos (occur-mode-find-occurrence)))
18308 (with-current-buffer (marker-buffer pos)
18313 (defun org-occur-link-in-agenda-files ()
18314 "Create a link and search for it in the agendas.
18315 The link is not stored in `org-stored-links', it is just created
18316 for the search purpose."
18318 (let ((link (condition-case nil
18319 (org-store-link nil)
18320 (error "Unable to create a link to here"))))
18321 (org-occur-in-agenda-files (regexp-quote link))))
18323 (defun org-uniquify (list)
18324 "Remove duplicate elements from LIST."
18326 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
18329 (defun org-delete-all (elts list)
18330 "Remove all elements in ELTS from LIST."
18332 (setq list (delete (pop elts) list)))
18335 (defun org-count (cl-item cl-seq)
18336 "Count the number of occurrences of ITEM in SEQ.
18337 Taken from `count' in cl-seq.el with all keyword arguments removed."
18338 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
18339 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
18340 (while (< cl-start cl-end)
18341 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
18342 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
18343 (setq cl-start (1+ cl-start)))
18346 (defun org-remove-if (predicate seq)
18347 "Remove everything from SEQ that fulfills PREDICATE."
18351 (if (not (funcall predicate e)) (push e res)))
18354 (defun org-remove-if-not (predicate seq)
18355 "Remove everything from SEQ that does not fulfill PREDICATE."
18359 (if (funcall predicate e) (push e res)))
18362 (defun org-back-over-empty-lines ()
18363 "Move backwards over whitespace, to the beginning of the first empty line.
18364 Returns the number of empty lines passed."
18365 (let ((pos (point)))
18366 (skip-chars-backward " \t\n\r")
18367 (beginning-of-line 2)
18368 (goto-char (min (point) pos))
18369 (count-lines (point) pos)))
18371 (defun org-skip-whitespace ()
18372 (skip-chars-forward " \t\n\r"))
18374 (defun org-point-in-group (point group &optional context)
18375 "Check if POINT is in match-group GROUP.
18376 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
18377 match. If the match group does not exist or point is not inside it,
18379 (and (match-beginning group)
18380 (>= point (match-beginning group))
18381 (<= point (match-end group))
18383 (list context (match-beginning group) (match-end group))
18386 (defun org-switch-to-buffer-other-window (&rest args)
18387 "Switch to buffer in a second window on the current frame.
18388 In particular, do not allow pop-up frames.
18389 Returns the newly created buffer."
18390 (let (pop-up-frames special-display-buffer-names special-display-regexps
18391 special-display-function)
18392 (apply 'switch-to-buffer-other-window args)))
18394 (defun org-combine-plists (&rest plists)
18395 "Create a single property list from all plists in PLISTS.
18396 The process starts by copying the first list, and then setting properties
18397 from the other lists. Settings in the last list are the most significant
18398 ones and overrule settings in the other lists."
18399 (let ((rtn (copy-sequence (pop plists)))
18402 (setq ls (pop plists))
18404 (setq p (pop ls) v (pop ls))
18405 (setq rtn (plist-put rtn p v))))
18408 (defun org-move-line-down (arg)
18409 "Move the current line down. With prefix argument, move it past ARG lines."
18411 (let ((col (current-column))
18413 (beginning-of-line 1) (setq beg (point))
18414 (beginning-of-line 2) (setq end (point))
18415 (beginning-of-line (+ 1 arg))
18416 (setq pos (move-marker (make-marker) (point)))
18417 (insert (delete-and-extract-region beg end))
18419 (org-move-to-column col)))
18421 (defun org-move-line-up (arg)
18422 "Move the current line up. With prefix argument, move it past ARG lines."
18424 (let ((col (current-column))
18426 (beginning-of-line 1) (setq beg (point))
18427 (beginning-of-line 2) (setq end (point))
18428 (beginning-of-line (- arg))
18429 (setq pos (move-marker (make-marker) (point)))
18430 (insert (delete-and-extract-region beg end))
18432 (org-move-to-column col)))
18434 (defun org-replace-escapes (string table)
18435 "Replace %-escapes in STRING with values in TABLE.
18436 TABLE is an association list with keys like \"%a\" and string values.
18437 The sequences in STRING may contain normal field width and padding information,
18438 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
18439 so values can contain further %-escapes if they are define later in TABLE."
18440 (let ((tbl (copy-alist table))
18441 (case-fold-search nil)
18444 (while (setq e (pop tbl))
18445 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
18446 (when (and (cdr e) (string-match re (cdr e)))
18447 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
18449 (add-text-properties 0 3 (list 'sref sref) safe)
18450 (setcdr e (replace-match safe t t (cdr e)))))
18451 (while (string-match re string)
18452 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
18454 (setq string (replace-match rpl t t string))))
18455 (while (setq pchg (next-property-change pchg string))
18456 (let ((sref (get-text-property pchg 'sref string)))
18457 (when (and sref (string-match "SREF" string pchg))
18458 (setq string (replace-match sref t t string)))))
18461 (defun org-sublist (list start end)
18462 "Return a section of LIST, from START to END.
18463 Counting starts at 1."
18464 (let (rtn (c start))
18465 (setq list (nthcdr (1- start) list))
18466 (while (and list (<= c end))
18467 (push (pop list) rtn)
18471 (defun org-find-base-buffer-visiting (file)
18472 "Like `find-buffer-visiting' but always return the base buffer and
18473 not an indirect buffer."
18474 (let ((buf (or (get-file-buffer file)
18475 (find-buffer-visiting file))))
18477 (or (buffer-base-buffer buf) buf)
18480 (defun org-image-file-name-regexp (&optional extensions)
18481 "Return regexp matching the file names of images.
18482 If EXTENSIONS is given, only match these."
18483 (if (and (not extensions) (fboundp 'image-file-name-regexp))
18484 (image-file-name-regexp)
18485 (let ((image-file-name-extensions
18487 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
18488 "xbm" "xpm" "pbm" "pgm" "ppm"))))
18490 (regexp-opt (nconc (mapcar 'upcase
18491 image-file-name-extensions)
18492 image-file-name-extensions)
18496 (defun org-file-image-p (file &optional extensions)
18497 "Return non-nil if FILE is an image."
18499 (string-match (org-image-file-name-regexp extensions) file)))
18501 (defun org-get-cursor-date ()
18502 "Return the date at cursor in as a time.
18503 This works in the calendar and in the agenda, anywhere else it just
18504 returns the current time."
18505 (let (date day defd)
18507 ((eq major-mode 'calendar-mode)
18508 (setq date (calendar-cursor-to-date)
18509 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18510 ((eq major-mode 'org-agenda-mode)
18511 (setq day (get-text-property (point) 'day))
18513 (setq date (calendar-gregorian-from-absolute day)
18514 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
18516 (or defd (current-time))))
18518 (defvar org-agenda-action-marker (make-marker)
18519 "Marker pointing to the entry for the next agenda action.")
18521 (defun org-mark-entry-for-agenda-action ()
18522 "Mark the current entry as target of an agenda action.
18523 Agenda actions are actions executed from the agenda with the key `k',
18524 which make use of the date at the cursor."
18526 (move-marker org-agenda-action-marker
18527 (save-excursion (org-back-to-heading t) (point))
18530 "Entry marked for action; press `k' at desired date in agenda or calendar"))
18532 ;;; Paragraph filling stuff.
18533 ;; We want this to be just right, so use the full arsenal.
18535 (defun org-indent-line-function ()
18536 "Indent line like previous, but further if previous was headline or item."
18538 (let* ((pos (point))
18539 (itemp (org-at-item-p))
18540 (case-fold-search t)
18541 (org-drawer-regexp (or org-drawer-regexp "\000"))
18542 column bpos bcol tpos tcol bullet btype bullet-type)
18543 ;; Find the previous relevant line
18544 (beginning-of-line 1)
18546 ((looking-at "#") (setq column 0))
18547 ((looking-at "\\*+ ") (setq column 0))
18548 ((and (looking-at "[ \t]*:END:")
18549 (save-excursion (re-search-backward org-drawer-regexp nil t)))
18551 (goto-char (1- (match-beginning 1)))
18552 (setq column (current-column))))
18553 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
18555 (re-search-backward
18556 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
18557 (setq column (org-get-indentation (match-string 0))))
18559 (beginning-of-line 0)
18560 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
18561 (not (looking-at "[ \t]*:END:"))
18562 (not (looking-at org-drawer-regexp)))
18563 (beginning-of-line 0))
18565 ((looking-at "\\*+[ \t]+")
18566 (if (not org-adapt-indentation)
18568 (goto-char (match-end 0))
18569 (setq column (current-column))))
18570 ((looking-at org-drawer-regexp)
18571 (goto-char (1- (match-beginning 1)))
18572 (setq column (current-column)))
18573 ((looking-at "\\([ \t]*\\):END:")
18574 (goto-char (match-end 1))
18575 (setq column (current-column)))
18577 (org-beginning-of-item)
18578 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
18579 (setq bpos (match-beginning 1) tpos (match-end 0)
18580 bcol (progn (goto-char bpos) (current-column))
18581 tcol (progn (goto-char tpos) (current-column))
18582 bullet (match-string 1)
18583 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
18584 (if (> tcol (+ bcol org-description-max-indent))
18585 (setq tcol (+ bcol 5)))
18589 (beginning-of-line 1)
18590 (if (looking-at "\\S-")
18592 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
18593 (setq bullet (match-string 1)
18594 btype (if (string-match "[0-9]" bullet) "n" bullet))
18595 (setq column (if (equal btype bullet-type) bcol tcol)))
18596 (setq column (org-get-indentation)))))
18597 (t (setq column (org-get-indentation))))))
18599 (if (<= (current-column) (current-indentation))
18600 (org-indent-line-to column)
18601 (save-excursion (org-indent-line-to column)))
18602 (setq column (current-column))
18603 (beginning-of-line 1)
18605 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
18606 (replace-match (concat (match-string 1)
18607 (format org-property-format
18608 (match-string 2) (match-string 3)))
18610 (org-move-to-column column)))
18612 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
18613 "Variable to store copy of `adaptive-fill-regexp'.
18614 Since `adaptive-fill-regexp' is set to never match, we need to
18615 store a backup of its value before entering `org-mode' so that
18616 the functionality can be provided as a fall-back.")
18618 (defun org-set-autofill-regexps ()
18620 ;; In the paragraph separator we include headlines, because filling
18621 ;; text in a line directly attached to a headline would otherwise
18622 ;; fill the headline as well.
18623 (org-set-local 'comment-start-skip "^#+[ \t]*")
18624 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
18625 ;; The paragraph starter includes hand-formatted lists.
18633 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
18636 "\\\\\\(begin\\|end\\|[][]\\)"))
18637 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
18638 ;; But only if the user has not turned off tables or fixed-width regions
18640 'auto-fill-inhibit-regexp
18641 (concat "\\*+ \\|#\\+"
18642 "\\|[ \t]*" org-keyword-time-regexp
18643 (if (or org-enable-table-editor org-enable-fixed-width-editor)
18646 (if org-enable-table-editor "|" "")
18647 (if org-enable-fixed-width-editor ":" "")
18649 ;; We use our own fill-paragraph function, to make sure that tables
18650 ;; and fixed-width regions are not wrapped. That function will pass
18651 ;; through to `fill-paragraph' when appropriate.
18652 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
18653 ;; Adaptive filling: To get full control, first make sure that
18654 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
18655 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
18656 (org-set-local 'org-adaptive-fill-regexp-backup
18657 adaptive-fill-regexp))
18658 (org-set-local 'adaptive-fill-regexp "\000")
18659 (org-set-local 'adaptive-fill-function
18660 'org-adaptive-fill-function)
18662 'align-mode-rules-list
18663 '((org-in-buffer-settings
18664 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
18665 (modes . '(org-mode))))))
18667 (defun org-fill-paragraph (&optional justify)
18668 "Re-align a table, pass through to fill-paragraph if no table."
18669 (let ((table-p (org-at-table-p))
18670 (table.el-p (org-at-table.el-p)))
18671 (cond ((and (equal (char-after (point-at-bol)) ?*)
18672 (save-excursion (goto-char (point-at-bol))
18673 (looking-at outline-regexp)))
18674 t) ; skip headlines
18675 (table.el-p t) ; skip table.el tables
18676 (table-p (org-table-align) t) ; align org-mode tables
18677 (t nil)))) ; call paragraph-fill
18679 ;; For reference, this is the default value of adaptive-fill-regexp
18680 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
18682 (defun org-adaptive-fill-function ()
18683 "Return a fill prefix for org-mode files.
18684 In particular, this makes sure hanging paragraphs for hand-formatted lists
18688 ((looking-at "#[ \t]+")
18689 (match-string-no-properties 0))
18690 ;; Description list
18691 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
18693 (if (> (match-end 1) (+ (match-beginning 1)
18694 org-description-max-indent))
18695 (goto-char (+ (match-beginning 1) 5))
18696 (goto-char (match-end 0)))
18697 (make-string (current-column) ?\ )))
18698 ;; Ordered or unordered list
18699 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)")
18701 (goto-char (match-end 0))
18702 (make-string (current-column) ?\ )))
18704 ((looking-at org-adaptive-fill-regexp-backup)
18705 (match-string-no-properties 0))))
18709 (defun org-toggle-fixed-width-section (arg)
18710 "Toggle the fixed-width export.
18711 If there is no active region, the QUOTE keyword at the current headline is
18712 inserted or removed. When present, it causes the text between this headline
18713 and the next to be exported as fixed-width text, and unmodified.
18714 If there is an active region, this command adds or removes a colon as the
18715 first character of this line. If the first character of a line is a colon,
18716 this line is also exported in fixed-width font."
18719 (regionp (org-region-active-p))
18720 (beg (if regionp (region-beginning) (point)))
18721 (end (if regionp (region-end)))
18722 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
18723 (case-fold-search nil)
18724 (re "[ \t]*\\(: \\)")
18729 (setq cc (current-column))
18730 (beginning-of-line 1)
18731 (setq off (looking-at re))
18732 (while (> nlines 0)
18733 (setq nlines (1- nlines))
18734 (beginning-of-line 1)
18737 (org-move-to-column cc t)
18740 ((and off (looking-at re))
18741 (replace-match "" t t nil 1))
18742 ((not off) (org-move-to-column cc t) (insert ": ")))
18745 (org-back-to-heading)
18746 (if (looking-at (concat outline-regexp
18747 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
18748 (replace-match "" t t nil 1)
18749 (if (looking-at outline-regexp)
18751 (goto-char (match-end 0))
18752 (insert org-quote-string " "))))))))
18754 (defun org-reftex-citation ()
18755 "Use reftex-citation to insert a citation into the buffer.
18756 This looks for a line like
18758 #+BIBLIOGRAPHY: foo plain option:-d
18760 and derives from it that foo.bib is the bibliography file relevant
18761 for this document. It then installs the necessary environment for RefTeX
18762 to work in this buffer and calls `reftex-citation' to insert a citation
18765 Export of such citations to both LaTeX and HTML is handled by the contributed
18766 package org-exp-bibtex by Taru Karttunen."
18768 (let ((reftex-docstruct-symbol 'rds)
18769 (reftex-cite-format "\\cite{%l}")
18774 (let ((case-fold-search t)
18775 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
18776 (if (not (save-excursion
18777 (or (re-search-forward re nil t)
18778 (re-search-backward re nil t))))
18779 (error "No bibliography defined in file")
18780 (setq bib (concat (match-string 1) ".bib")
18781 rds (list (list 'bib bib)))))))
18782 (call-interactively 'reftex-citation)))
18784 ;;;; Functions extending outline functionality
18786 (defun org-beginning-of-line (&optional arg)
18787 "Go to the beginning of the current line. If that is invisible, continue
18788 to a visible line beginning. This makes the function of C-a more intuitive.
18789 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
18790 first attempt, and only move to after the tags when the cursor is already
18791 beyond the end of the headline."
18793 (let ((pos (point))
18794 (special (if (consp org-special-ctrl-a/e)
18795 (car org-special-ctrl-a/e)
18796 org-special-ctrl-a/e))
18798 (if (org-bound-and-true-p line-move-visual)
18799 (beginning-of-visual-line 1)
18800 (beginning-of-line 1))
18801 (if (and arg (fboundp 'move-beginning-of-line))
18802 (call-interactively 'move-beginning-of-line)
18806 (if (org-truely-invisible-p)
18807 (while (and (not (bobp)) (org-truely-invisible-p))
18809 (beginning-of-line 1))
18810 (forward-char 1))))
18813 ((and (looking-at org-complex-heading-regexp)
18814 (= (char-after (match-end 1)) ?\ ))
18815 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
18819 (cond ((> pos refpos) refpos)
18820 ((= pos (point)) refpos)
18822 (cond ((> pos (point)) (point))
18823 ((not (eq last-command this-command)) (point))
18828 (cond ((> pos (match-end 4)) (match-end 4))
18829 ((= pos (point)) (match-end 4))
18831 (cond ((> pos (point)) (point))
18832 ((not (eq last-command this-command)) (point))
18833 (t (match-end 4))))))))
18835 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
18837 (defun org-end-of-line (&optional arg)
18838 "Go to the end of the line.
18839 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
18840 first attempt, and only move to after the tags when the cursor is already
18841 beyond the end of the headline."
18843 (let ((special (if (consp org-special-ctrl-a/e)
18844 (cdr org-special-ctrl-a/e)
18845 org-special-ctrl-a/e)))
18846 (if (or (not special)
18847 (not (org-on-heading-p))
18849 (call-interactively
18850 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
18851 ((fboundp 'move-end-of-line) 'move-end-of-line)
18853 (let ((pos (point)))
18854 (beginning-of-line 1)
18855 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
18857 (if (or (< pos (match-beginning 1))
18858 (= pos (match-end 0)))
18859 (goto-char (match-beginning 1))
18860 (goto-char (match-end 0)))
18861 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
18862 (goto-char (match-end 0))
18863 (goto-char (match-beginning 1))))
18864 (call-interactively (if (fboundp 'move-end-of-line)
18868 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
18870 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
18871 (define-key org-mode-map "\C-e" 'org-end-of-line)
18872 (define-key org-mode-map [home] 'org-beginning-of-line)
18873 (define-key org-mode-map [end] 'org-end-of-line)
18875 (defun org-backward-sentence (&optional arg)
18876 "Go to beginning of sentence, or beginning of table field.
18877 This will call `backward-sentence' or `org-table-beginning-of-field',
18878 depending on context."
18881 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
18882 (t (call-interactively 'backward-sentence))))
18884 (defun org-forward-sentence (&optional arg)
18885 "Go to end of sentence, or end of table field.
18886 This will call `forward-sentence' or `org-table-end-of-field',
18887 depending on context."
18890 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
18891 (t (call-interactively 'forward-sentence))))
18893 (define-key org-mode-map "\M-a" 'org-backward-sentence)
18894 (define-key org-mode-map "\M-e" 'org-forward-sentence)
18896 (defun org-kill-line (&optional arg)
18897 "Kill line, to tags or end of line."
18900 ((or (not org-special-ctrl-k)
18902 (not (org-on-heading-p)))
18903 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
18904 org-ctrl-k-protect-subtree)
18905 (if (or (eq org-ctrl-k-protect-subtree 'error)
18906 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
18907 (error "C-k aborted - would kill hidden subtree")))
18908 (call-interactively 'kill-line))
18909 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
18910 (kill-region (point) (match-beginning 1))
18911 (org-set-tags nil t))
18912 (t (kill-region (point) (point-at-eol)))))
18914 (define-key org-mode-map "\C-k" 'org-kill-line)
18916 (defun org-yank (&optional arg)
18917 "Yank. If the kill is a subtree, treat it specially.
18918 This command will look at the current kill and check if is a single
18919 subtree, or a series of subtrees[1]. If it passes the test, and if the
18920 cursor is at the beginning of a line or after the stars of a currently
18921 empty headline, then the yank is handled specially. How exactly depends
18922 on the value of the following variables, both set by default.
18924 org-yank-folded-subtrees
18925 When set, the subtree(s) will be folded after insertion, but only
18926 if doing so would now swallow text after the yanked text.
18928 org-yank-adjusted-subtrees
18929 When set, the subtree will be promoted or demoted in order to
18930 fit into the local outline tree structure, which means that the level
18931 will be adjusted so that it becomes the smaller one of the two
18932 *visible* surrounding headings.
18934 Any prefix to this command will cause `yank' to be called directly with
18935 no special treatment. In particular, a simple \\[universal-argument] prefix \
18937 plainly yank the text as it is.
18939 \[1] The test checks if the first non-white line is a heading
18940 and if there are no other headings with fewer stars."
18942 (org-yank-generic 'yank arg))
18944 (defun org-yank-generic (command arg)
18945 "Perform some yank-like command.
18947 This function implements the behavior described in the `org-yank'
18948 documentation. However, it has been generalized to work for any
18949 interactive command with similar behavior."
18951 ;; pretend to be command COMMAND
18952 (setq this-command command)
18955 (call-interactively command)
18957 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
18958 (and (org-kill-is-subtree-p)
18960 (and (looking-at "[ \t]*$")
18963 (buffer-substring (point-at-bol) (point)))))))
18966 ((and subtreep org-yank-folded-subtrees)
18967 (let ((beg (point))
18969 (if (and subtreep org-yank-adjusted-subtrees)
18970 (org-paste-subtree nil nil 'for-yank)
18971 (call-interactively command))
18975 (when (and (bolp) subtreep
18976 (not (setq swallowp
18977 (org-yank-folding-would-swallow-text beg end))))
18978 (or (looking-at outline-regexp)
18979 (re-search-forward (concat "^" outline-regexp) end t))
18980 (while (and (< (point) end) (looking-at outline-regexp))
18982 (org-cycle-show-empty-lines 'folded)
18983 (condition-case nil
18984 (outline-forward-same-level 1)
18985 (error (goto-char end)))))
18988 "Inserted text not folded because that would swallow text"))
18991 (skip-chars-forward " \t\n\r")
18992 (beginning-of-line 1)
18993 (push-mark beg 'nomsg)))
18994 ((and subtreep org-yank-adjusted-subtrees)
18995 (let ((beg (point-at-bol)))
18996 (org-paste-subtree nil nil 'for-yank)
18997 (push-mark beg 'nomsg)))
18999 (call-interactively command))))))
19001 (defun org-yank-folding-would-swallow-text (beg end)
19002 "Would hide-subtree at BEG swallow any text after END?"
19006 (when (or (looking-at outline-regexp)
19007 (re-search-forward (concat "^" outline-regexp) end t))
19008 (setq level (org-outline-level)))
19010 (skip-chars-forward " \t\r\n\v\f")
19012 (and (bolp) (looking-at org-outline-regexp)
19013 (<= (org-outline-level) level)))
19014 nil ; Nothing would be swallowed
19015 t)))) ; something would swallow
19017 (define-key org-mode-map "\C-y" 'org-yank)
19019 (defun org-invisible-p ()
19020 "Check if point is at a character currently not visible."
19021 ;; Early versions of noutline don't have `outline-invisible-p'.
19022 (if (fboundp 'outline-invisible-p)
19023 (outline-invisible-p)
19024 (get-char-property (point) 'invisible)))
19026 (defun org-truely-invisible-p ()
19027 "Check if point is at a character currently not visible.
19028 This version does not only check the character property, but also
19030 ;; Early versions of noutline don't have `outline-invisible-p'.
19031 (if (org-bound-and-true-p visible-mode)
19033 (if (fboundp 'outline-invisible-p)
19034 (outline-invisible-p)
19035 (get-char-property (point) 'invisible))))
19037 (defun org-invisible-p2 ()
19038 "Check if point is at a character currently not visible."
19040 (if (and (eolp) (not (bobp))) (backward-char 1))
19041 ;; Early versions of noutline don't have `outline-invisible-p'.
19042 (if (fboundp 'outline-invisible-p)
19043 (outline-invisible-p)
19044 (get-char-property (point) 'invisible))))
19046 (defun org-back-to-heading (&optional invisible-ok)
19047 "Call `outline-back-to-heading', but provide a better error message."
19048 (condition-case nil
19049 (outline-back-to-heading invisible-ok)
19050 (error (error "Before first headline at position %d in buffer %s"
19051 (point) (current-buffer)))))
19053 (defun org-beginning-of-defun ()
19054 "Go to the beginning of the subtree, i.e. back to the heading."
19055 (org-back-to-heading))
19056 (defun org-end-of-defun ()
19057 "Go to the end of the subtree."
19058 (org-end-of-subtree nil t))
19060 (defun org-before-first-heading-p ()
19061 "Before first heading?"
19063 (null (re-search-backward "^\\*+ " nil t))))
19065 (defun org-on-heading-p (&optional ignored)
19066 (outline-on-heading-p t))
19067 (defun org-at-heading-p (&optional ignored)
19068 (outline-on-heading-p t))
19070 (defun org-point-at-end-of-empty-headline ()
19071 "If point is at the end of an empty headline, return t, else nil.
19072 If the heading only contains a TODO keyword, it is still still considered
19074 (and (looking-at "[ \t]*$")
19076 (beginning-of-line 1)
19077 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
19079 (defun org-at-heading-or-item-p ()
19080 (or (org-on-heading-p) (org-at-item-p)))
19082 (defun org-on-target-p ()
19083 (or (org-in-regexp org-radio-target-regexp)
19084 (org-in-regexp org-target-regexp)))
19086 (defun org-up-heading-all (arg)
19087 "Move to the heading line of which the present line is a subheading.
19088 This function considers both visible and invisible heading lines.
19089 With argument, move up ARG levels."
19090 (if (fboundp 'outline-up-heading-all)
19091 (outline-up-heading-all arg) ; emacs 21 version of outline.el
19092 (outline-up-heading arg t))) ; emacs 22 version of outline.el
19094 (defun org-up-heading-safe ()
19095 "Move to the heading line of which the present line is a subheading.
19096 This version will not throw an error. It will return the level of the
19097 headline found, or nil if no higher level is found.
19099 Also, this function will be a lot faster than `outline-up-heading',
19100 because it relies on stars being the outline starters. This can really
19101 make a significant difference in outlines with very many siblings."
19102 (let (start-level re)
19103 (org-back-to-heading t)
19104 (setq start-level (funcall outline-level))
19105 (if (equal start-level 1)
19107 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
19108 (if (re-search-backward re nil t)
19109 (funcall outline-level)))))
19111 (defun org-first-sibling-p ()
19112 "Is this heading the first child of its parents?"
19114 (let ((re (concat "^" outline-regexp))
19116 (unless (org-at-heading-p t)
19117 (error "Not at a heading"))
19118 (setq level (funcall outline-level))
19120 (if (not (re-search-backward re nil t))
19122 (setq l (funcall outline-level))
19125 (defun org-goto-sibling (&optional previous)
19126 "Goto the next sibling, even if it is invisible.
19127 When PREVIOUS is set, go to the previous sibling instead. Returns t
19128 when a sibling was found. When none is found, return nil and don't
19130 (let ((fun (if previous 're-search-backward 're-search-forward))
19132 (re (concat "^" outline-regexp))
19134 (when (condition-case nil (org-back-to-heading t) (error nil))
19135 (setq level (funcall outline-level))
19137 (or previous (forward-char 1))
19138 (while (funcall fun re nil t)
19139 (setq l (funcall outline-level))
19140 (when (< l level) (goto-char pos) (throw 'exit nil))
19141 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
19145 (defun org-show-siblings ()
19146 "Show all siblings of the current headline."
19148 (while (org-goto-sibling) (org-flag-heading nil)))
19150 (while (org-goto-sibling 'previous)
19151 (org-flag-heading nil))))
19153 (defun org-show-hidden-entry ()
19154 "Show an entry where even the heading is hidden."
19158 (defun org-flag-heading (flag &optional entry)
19159 "Flag the current heading. FLAG non-nil means make invisible.
19160 When ENTRY is non-nil, show the entire entry."
19162 (org-back-to-heading t)
19163 ;; Check if we should show the entire entry
19168 (and (outline-next-heading)
19169 (org-flag-heading nil))))
19170 (outline-flag-region (max (point-min) (1- (point)))
19171 (save-excursion (outline-end-of-heading) (point))
19174 (defun org-get-next-sibling ()
19175 "Move to next heading of the same level, and return point.
19176 If there is no such heading, return nil.
19177 This is like outline-next-sibling, but invisible headings are ok."
19178 (let ((level (funcall outline-level)))
19179 (outline-next-heading)
19180 (while (and (not (eobp)) (> (funcall outline-level) level))
19181 (outline-next-heading))
19182 (if (or (eobp) (< (funcall outline-level) level))
19186 (defun org-get-last-sibling ()
19187 "Move to previous heading of the same level, and return point.
19188 If there is no such heading, return nil."
19189 (let ((opoint (point))
19190 (level (funcall outline-level)))
19191 (outline-previous-heading)
19192 (when (and (/= (point) opoint) (outline-on-heading-p t))
19193 (while (and (> (funcall outline-level) level)
19195 (outline-previous-heading))
19196 (if (< (funcall outline-level) level)
19200 (defun org-end-of-subtree (&optional invisible-OK to-heading)
19201 ;; This contains an exact copy of the original function, but it uses
19202 ;; `org-back-to-heading', to make it work also in invisible
19203 ;; trees. And is uses an invisible-OK argument.
19204 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
19205 ;; Furthermore, when used inside Org, finding the end of a large subtree
19206 ;; with many children and grandchildren etc, this can be much faster
19207 ;; than the outline version.
19208 (org-back-to-heading invisible-OK)
19210 (level (funcall outline-level)))
19211 (if (and (org-mode-p) (< level 1000))
19212 ;; A true heading (not a plain list item), in Org-mode
19213 ;; This means we can easily find the end by looking
19214 ;; only for the right number of stars. Using a regexp to do
19215 ;; this is so much faster than using a Lisp loop.
19216 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
19218 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
19219 ;; something else, do it the slow way
19220 (while (and (not (eobp))
19221 (or first (> (funcall outline-level) level)))
19223 (outline-next-heading)))
19225 (if (memq (preceding-char) '(?\n ?\^M))
19227 ;; Go to end of line before heading
19229 (if (memq (preceding-char) '(?\n ?\^M))
19230 ;; leave blank line before heading
19231 (forward-char -1))))))
19234 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
19235 "Use Org version in org-mode, for dramatic speed-up."
19236 (if (eq major-mode 'org-mode)
19238 (org-end-of-subtree nil t)
19239 (unless (eobp) (backward-char 1)))
19242 (defun org-forward-same-level (arg &optional invisible-ok)
19243 "Move forward to the arg'th subheading at same level as this one.
19244 Stop at the first and last subheadings of a superior heading."
19246 (org-back-to-heading invisible-ok)
19248 (let* ((level (- (match-end 0) (match-beginning 0) 1))
19249 (re (format "^\\*\\{1,%d\\} " level))
19253 (while (and (re-search-forward re nil 'move)
19254 (setq l (- (match-end 0) (match-beginning 0) 1))
19257 (progn (backward-char 1) (org-invisible-p)))
19258 (if (< l level) (setq arg 1)))
19259 (setq arg (1- arg)))
19260 (beginning-of-line 1)))
19262 (defun org-backward-same-level (arg &optional invisible-ok)
19263 "Move backward to the arg'th subheading at same level as this one.
19264 Stop at the first and last subheadings of a superior heading."
19266 (org-back-to-heading)
19268 (let* ((level (- (match-end 0) (match-beginning 0) 1))
19269 (re (format "^\\*\\{1,%d\\} " level))
19272 (while (and (re-search-backward re nil 'move)
19273 (setq l (- (match-end 0) (match-beginning 0) 1))
19277 (if (< l level) (setq arg 1)))
19278 (setq arg (1- arg)))))
19280 (defun org-show-subtree ()
19281 "Show everything after this heading at deeper levels."
19282 (outline-flag-region
19285 (org-end-of-subtree t t))
19288 (defun org-show-entry ()
19289 "Show the body directly following this heading.
19290 Show the heading too, if it is currently invisible."
19293 (condition-case nil
19295 (org-back-to-heading t)
19296 (outline-flag-region
19297 (max (point-min) (1- (point)))
19299 (if (re-search-forward
19300 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
19301 (match-beginning 1)
19304 (org-cycle-hide-drawers 'children))
19307 (defun org-make-options-regexp (kwds &optional extra)
19308 "Make a regular expression for keyword lines."
19312 (mapconcat 'regexp-quote kwds "\\|")
19313 (if extra (concat "\\|" extra))
19317 ;; Make isearch reveal the necessary context
19318 (defun org-isearch-end ()
19319 "Reveal context after isearch exits."
19320 (when isearch-success ; only if search was successful
19321 (if (featurep 'xemacs)
19322 ;; Under XEmacs, the hook is run in the correct place,
19323 ;; we directly show the context.
19324 (org-show-context 'isearch)
19325 ;; In Emacs the hook runs *before* restoring the overlays.
19326 ;; So we have to use a one-time post-command-hook to do this.
19327 ;; (Emacs 22 has a special variable, see function `org-mode')
19328 (unless (and (boundp 'isearch-mode-end-hook-quit)
19329 isearch-mode-end-hook-quit)
19330 ;; Only when the isearch was not quitted.
19331 (org-add-hook 'post-command-hook 'org-isearch-post-command
19332 'append 'local)))))
19334 (defun org-isearch-post-command ()
19335 "Remove self from hook, and show context."
19336 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
19337 (org-show-context 'isearch))
19340 ;;;; Integration with and fixes for other packages
19344 (defvar org-imenu-markers nil
19345 "All markers currently used by Imenu.")
19346 (make-variable-buffer-local 'org-imenu-markers)
19348 (defun org-imenu-new-marker (&optional pos)
19349 "Return a new marker for use by Imenu, and remember the marker."
19350 (let ((m (make-marker)))
19351 (move-marker m (or pos (point)))
19352 (push m org-imenu-markers)
19355 (defun org-imenu-get-tree ()
19356 "Produce the index for Imenu."
19357 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
19358 (setq org-imenu-markers nil)
19359 (let* ((n org-imenu-depth)
19360 (re (concat "^" outline-regexp))
19361 (subs (make-vector (1+ n) nil))
19367 (goto-char (point-max))
19368 (while (re-search-backward re nil t)
19369 (setq level (org-reduced-level (funcall outline-level)))
19371 (looking-at org-complex-heading-regexp)
19372 (setq head (org-link-display-format
19373 (org-match-string-no-properties 4))
19374 m (org-imenu-new-marker))
19375 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
19376 (if (>= level last-level)
19377 (push (cons head m) (aref subs level))
19378 (push (cons head (aref subs (1+ level))) (aref subs level))
19379 (loop for i from (1+ level) to n do (aset subs i nil)))
19380 (setq last-level level)))))
19383 (eval-after-load "imenu"
19385 (add-hook 'imenu-after-jump-hook
19387 (if (eq major-mode 'org-mode)
19388 (org-show-context 'org-goto))))))
19390 (defun org-link-display-format (link)
19391 "Replace a link with either the description, or the link target
19392 if no description is present"
19394 (if (string-match org-bracket-link-analytic-regexp link)
19395 (replace-match (if (match-end 5)
19396 (match-string 5 link)
19397 (concat (match-string 1 link)
19398 (match-string 3 link)))
19402 ;; Speedbar support
19404 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
19405 "Overlay marking the agenda restriction line in speedbar.")
19406 (overlay-put org-speedbar-restriction-lock-overlay
19407 'face 'org-agenda-restriction-lock)
19408 (overlay-put org-speedbar-restriction-lock-overlay
19409 'help-echo "Agendas are currently limited to this item.")
19410 (org-detach-overlay org-speedbar-restriction-lock-overlay)
19412 (defun org-speedbar-set-agenda-restriction ()
19413 "Restrict future agenda commands to the location at point in speedbar.
19414 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
19416 (require 'org-agenda)
19417 (let (p m tp np dir txt)
19419 ((setq p (text-property-any (point-at-bol) (point-at-eol)
19421 (setq m (get-text-property p 'org-imenu-marker))
19422 (with-current-buffer (marker-buffer m)
19424 (org-agenda-set-restriction-lock 'subtree)))
19425 ((setq p (text-property-any (point-at-bol) (point-at-eol)
19426 'speedbar-function 'speedbar-find-file))
19427 (setq tp (previous-single-property-change
19428 (1+ p) 'speedbar-function)
19429 np (next-single-property-change
19430 tp 'speedbar-function)
19431 dir (speedbar-line-directory)
19432 txt (buffer-substring-no-properties (or tp (point-min))
19433 (or np (point-max))))
19434 (with-current-buffer (find-file-noselect
19435 (let ((default-directory dir))
19436 (expand-file-name txt)))
19437 (unless (org-mode-p)
19438 (error "Cannot restrict to non-Org-mode file"))
19439 (org-agenda-set-restriction-lock 'file)))
19440 (t (error "Don't know how to restrict Org-mode's agenda")))
19441 (move-overlay org-speedbar-restriction-lock-overlay
19442 (point-at-bol) (point-at-eol))
19443 (setq current-prefix-arg nil)
19444 (org-agenda-maybe-redo)))
19446 (eval-after-load "speedbar"
19448 (speedbar-add-supported-extension ".org")
19449 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
19450 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
19451 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
19452 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19453 (add-hook 'speedbar-visiting-tag-hook
19454 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
19456 ;;; Fixes and Hacks for problems with other packages
19458 ;; Make flyspell not check words in links, to not mess up our keymap
19459 (defun org-mode-flyspell-verify ()
19460 "Don't let flyspell put overlays at active buttons."
19461 (and (not (get-text-property (max (1- (point)) (point-min)) 'keymap))
19462 (not (get-text-property (max (1- (point)) (point-min)) 'org-no-flyspell))))
19464 (defun org-remove-flyspell-overlays-in (beg end)
19465 "Remove flyspell overlays in region."
19466 (and (org-bound-and-true-p flyspell-mode)
19467 (fboundp 'flyspell-delete-region-overlays)
19468 (flyspell-delete-region-overlays beg end))
19469 (add-text-properties beg end '(org-no-flyspell t)))
19471 ;; Make `bookmark-jump' shows the jump location if it was hidden.
19472 (eval-after-load "bookmark"
19473 '(if (boundp 'bookmark-after-jump-hook)
19474 ;; We can use the hook
19475 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
19476 ;; Hook not available, use advice
19477 (defadvice bookmark-jump (after org-make-visible activate)
19478 "Make the position visible."
19479 (org-bookmark-jump-unhide))))
19481 ;; Make sure saveplace shows the location if it was hidden
19482 (eval-after-load "saveplace"
19483 '(defadvice save-place-find-file-hook (after org-make-visible activate)
19484 "Make the position visible."
19485 (org-bookmark-jump-unhide)))
19487 ;; Make sure ecb shows the location if it was hidden
19488 (eval-after-load "ecb"
19489 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
19490 "Make hierarchy visible when jumping into location from ECB tree buffer."
19491 (if (eq major-mode 'org-mode)
19492 (org-show-context))))
19494 (defun org-bookmark-jump-unhide ()
19495 "Unhide the current position, to show the bookmark location."
19497 (or (org-invisible-p)
19498 (save-excursion (goto-char (max (point-min) (1- (point))))
19499 (org-invisible-p)))
19500 (org-show-context 'bookmark-jump)))
19502 ;; Make session.el ignore our circular variable
19503 (eval-after-load "session"
19504 '(add-to-list 'session-globals-exclude 'org-mark-ring))
19506 ;;;; Experimental code
19508 (defun org-closed-in-range ()
19509 "Sparse tree of items closed in a certain time range.
19510 Still experimental, may disappear in the future."
19512 ;; Get the time interval from the user.
19513 (let* ((time1 (org-float-time
19514 (org-read-date nil 'to-time nil "Starting date: ")))
19515 (time2 (org-float-time
19516 (org-read-date nil 'to-time nil "End date:")))
19517 ;; callback function
19518 (callback (lambda ()
19521 (apply 'encode-time
19522 (org-parse-time-string
19523 (match-string 1))))))
19524 ;; check if time in interval
19525 (and (>= time time1) (<= time time2))))))
19526 ;; make tree, check each match with the callback
19527 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
19533 (run-hooks 'org-load-hook)
19535 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
19537 ;;; org.el ends here