1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
66 (defvar org-inhibit-highlight-removal nil
) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local
)
71 ;;;; Require other packages
79 (require 'format-spec
)
81 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
82 ;; some places -- e.g. see the macro org-with-limited-levels.
84 ;; In Org buffers, the value of `outline-regexp' is that of
85 ;; `org-outline-regexp'. The only function still directly relying on
86 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
87 ;; job when `orgstruct-mode' is active.
88 (defvar org-outline-regexp
"\\*+ "
89 "Regexp to match Org headlines.")
91 (defvar org-outline-regexp-bol
"^\\*+ "
92 "Regexp to match Org headlines.
93 This is similar to `org-outline-regexp' but additionally makes
94 sure that we are at the beginning of the line.")
96 (defvar org-heading-regexp
"^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
97 "Matches an headline, putting stars and text into groups.
98 Stars are put in group 1 and the trimmed body in group 2.")
100 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
101 (when (fboundp 'defvaralias
)
102 (unless (boundp 'calendar-view-holidays-initially-flag
)
103 (defvaralias 'calendar-view-holidays-initially-flag
104 'view-calendar-holidays-initially
))
105 (unless (boundp 'calendar-view-diary-initially-flag
)
106 (defvaralias 'calendar-view-diary-initially-flag
107 'view-diary-entries-initially
))
108 (unless (boundp 'diary-fancy-buffer
)
109 (defvaralias 'diary-fancy-buffer
'fancy-diary-buffer
)))
111 (declare-function org-inlinetask-at-task-p
"org-inlinetask" ())
112 (declare-function org-inlinetask-outline-regexp
"org-inlinetask" ())
113 (declare-function org-inlinetask-toggle-visibility
"org-inlinetask" ())
114 (declare-function org-pop-to-buffer-same-window
"org-compat" (&optional buffer-or-name norecord label
))
115 (declare-function org-at-clock-log-p
"org-clock" ())
116 (declare-function org-clock-timestamps-up
"org-clock" ())
117 (declare-function org-clock-timestamps-down
"org-clock" ())
118 (declare-function org-clock-sum-current-item
"org-clock" (&optional tstart
))
120 ;; load languages based on value of `org-babel-load-languages'
121 (defvar org-babel-load-languages
)
123 (defun org-babel-do-load-languages (sym value
)
124 "Load the languages defined in `org-babel-load-languages'."
125 (set-default sym value
)
127 (let ((active (cdr pair
)) (lang (symbol-name (car pair
))))
130 (require (intern (concat "ob-" lang
))))
132 (funcall 'fmakunbound
133 (intern (concat "org-babel-execute:" lang
)))
134 (funcall 'fmakunbound
135 (intern (concat "org-babel-expand-body:" lang
)))))))
136 org-babel-load-languages
))
138 (defcustom org-babel-load-languages
'((emacs-lisp . t
))
139 "Languages which can be evaluated in Org-mode buffers.
140 This list can be used to load support for any of the languages
141 below, note that each language will depend on a different set of
142 system executables and/or Emacs modes. When a language is
143 \"loaded\", then code blocks in that language can be evaluated
144 with `org-babel-execute-src-block' bound by default to C-c
145 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
146 be set to remove code block evaluation from the C-c C-c
147 keybinding. By default only Emacs Lisp (which has no
148 requirements) is loaded."
150 :set
'org-babel-do-load-languages
152 :type
'(alist :tag
"Babel Languages"
155 (const :tag
"Awk" awk
)
158 (const :tag
"Asymptote" asymptote
)
159 (const :tag
"Calc" calc
)
160 (const :tag
"Clojure" clojure
)
161 (const :tag
"CSS" css
)
162 (const :tag
"Ditaa" ditaa
)
163 (const :tag
"Dot" dot
)
164 (const :tag
"Emacs Lisp" emacs-lisp
)
165 (const :tag
"Fortran" fortran
)
166 (const :tag
"Gnuplot" gnuplot
)
167 (const :tag
"Haskell" haskell
)
169 (const :tag
"Java" java
)
170 (const :tag
"Javascript" js
)
171 (const :tag
"LaTeX" latex
)
172 (const :tag
"Ledger" ledger
)
173 (const :tag
"Lilypond" lilypond
)
174 (const :tag
"Lisp" lisp
)
175 (const :tag
"Maxima" maxima
)
176 (const :tag
"Matlab" matlab
)
177 (const :tag
"Mscgen" mscgen
)
178 (const :tag
"Ocaml" ocaml
)
179 (const :tag
"Octave" octave
)
180 (const :tag
"Org" org
)
181 (const :tag
"Perl" perl
)
182 (const :tag
"Pico Lisp" picolisp
)
183 (const :tag
"PlantUML" plantuml
)
184 (const :tag
"Python" python
)
185 (const :tag
"Ruby" ruby
)
186 (const :tag
"Sass" sass
)
187 (const :tag
"Scala" scala
)
188 (const :tag
"Scheme" scheme
)
189 (const :tag
"Screen" screen
)
190 (const :tag
"Shell Script" sh
)
191 (const :tag
"Shen" shen
)
192 (const :tag
"Sql" sql
)
193 (const :tag
"Sqlite" sqlite
))
194 :value-type
(boolean :tag
"Activate" :value t
)))
196 ;;;; Customization variables
197 (defcustom org-clone-delete-id nil
198 "Remove ID property of clones of a subtree.
199 When non-nil, clones of a subtree don't inherit the ID property.
200 Otherwise they inherit the ID property with a new unique
207 (require 'org-compat
)
210 (defun org-version (&optional here full message
)
211 "Show the org-mode version in the echo area.
212 With prefix argument HERE, insert it at point.
213 When FULL is non-nil, use a verbose version string.
214 When MESSAGE is non-nil, display a message with the version."
216 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
217 (org-install-dir (ignore-errors (org-find-library-dir "org-install.el")))
219 (and (fboundp 'org-release
) (fboundp 'org-git-version
))
220 (load (concat org-dir
"org-version.el")
221 'noerror
'nomessage
'nosuffix
)))
222 (org-version (org-release))
223 (git-version (org-git-version))
224 (version (format "Org-mode version %s (%s @ %s)"
228 (if (string= org-dir org-install-dir
)
230 (concat "mixed installation! " org-install-dir
" and " org-dir
))
231 "org-install.el can not be found!")))
232 (_version (if full version org-version
)))
233 (if (org-called-interactively-p 'interactive
)
237 (if message
(message _version
))
240 (defconst org-version
(org-version))
242 ;;; Compatibility constants
244 ;;; The custom variables
247 "Outline-based notes management and organizer."
252 (defcustom org-mode-hook nil
253 "Mode hook for Org-mode, run after the mode was turned on."
257 (defcustom org-load-hook nil
258 "Hook that is run after org.el has been loaded."
262 (defcustom org-log-buffer-setup-hook nil
263 "Hook that is run after an Org log buffer is created."
268 (defvar org-modules
) ; defined below
269 (defvar org-modules-loaded nil
270 "Have the modules been loaded already?")
272 (defun org-load-modules-maybe (&optional force
)
273 "Load all extensions listed in `org-modules'."
274 (when (or force
(not org-modules-loaded
))
276 (condition-case nil
(require ext
)
277 (error (message "Problems while trying to load feature `%s'" ext
))))
279 (setq org-modules-loaded t
)))
281 (defun org-set-modules (var value
)
282 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
284 (when (featurep 'org
)
285 (org-load-modules-maybe 'force
)))
287 (when (org-bound-and-true-p org-modules
)
288 (let ((a (member 'org-infojs org-modules
)))
289 (and a
(setcar a
'org-jsinfo
))))
291 (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
)
292 "Modules that should always be loaded together with org.el.
293 If a description starts with <C>, the file is not part of Emacs
294 and loading it will require that you have downloaded and properly installed
295 the org-mode distribution.
297 You can also use this system to load external packages (i.e. neither Org
298 core modules, nor modules from the CONTRIB directory). Just add symbols
299 to the end of the list. If the package is called org-xyz.el, then you need
300 to add the symbol `xyz', and the package must have a call to
304 :set
'org-set-modules
307 (const :tag
" bbdb: Links to BBDB entries" org-bbdb
)
308 (const :tag
" bibtex: Links to BibTeX entries" org-bibtex
)
309 (const :tag
" crypt: Encryption of subtrees" org-crypt
)
310 (const :tag
" ctags: Access to Emacs tags with links" org-ctags
)
311 (const :tag
" docview: Links to doc-view buffers" org-docview
)
312 (const :tag
" gnus: Links to GNUS folders/messages" org-gnus
)
313 (const :tag
" id: Global IDs for identifying entries" org-id
)
314 (const :tag
" info: Links to Info nodes" org-info
)
315 (const :tag
" jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo
)
316 (const :tag
" habit: Track your consistency with habits" org-habit
)
317 (const :tag
" inlinetask: Tasks independent of outline hierarchy" org-inlinetask
)
318 (const :tag
" irc: Links to IRC/ERC chat sessions" org-irc
)
319 (const :tag
" mac-message: Links to messages in Apple Mail" org-mac-message
)
320 (const :tag
" mew Links to Mew folders/messages" org-mew
)
321 (const :tag
" mhe: Links to MHE folders/messages" org-mhe
)
322 (const :tag
" protocol: Intercept calls from emacsclient" org-protocol
)
323 (const :tag
" rmail: Links to RMAIL folders/messages" org-rmail
)
324 (const :tag
" special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks
)
325 (const :tag
" vm: Links to VM folders/messages" org-vm
)
326 (const :tag
" wl: Links to Wanderlust folders/messages" org-wl
)
327 (const :tag
" w3m: Special cut/paste from w3m to Org-mode." org-w3m
)
328 (const :tag
" mouse: Additional mouse support" org-mouse
)
329 (const :tag
" TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler
)
331 (const :tag
"C annotate-file: Annotate a file with org syntax" org-annotate-file
)
332 (const :tag
"C bookmark: Org-mode links to bookmarks" org-bookmark
)
333 (const :tag
"C checklist: Extra functions for checklists in repeated tasks" org-checklist
)
334 (const :tag
"C choose: Use TODO keywords to mark decisions states" org-choose
)
335 (const :tag
"C collector: Collect properties into tables" org-collector
)
336 (const :tag
"C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend
)
337 (const :tag
"C drill: Flashcards and spaced repetition for Org-mode" org-drill
)
338 (const :tag
"C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol
)
339 (const :tag
"C eshell Support for links to working directories in eshell" org-eshell
)
340 (const :tag
"C eval: Include command output as text" org-eval
)
341 (const :tag
"C eval-light: Evaluate inbuffer-code on demand" org-eval-light
)
342 (const :tag
"C expiry: Expiry mechanism for Org-mode entries" org-expiry
)
343 (const :tag
"C exp-bibtex: Export citations using BibTeX" org-exp-bibtex
)
344 (const :tag
"C git-link: Provide org links to specific file version" org-git-link
)
345 (const :tag
"C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query
)
347 (const :tag
"C invoice: Help manage client invoices in Org-mode" org-invoice
)
349 (const :tag
"C jira: Add a jira:ticket protocol to Org-mode" org-jira
)
350 (const :tag
"C learn: SuperMemo's incremental learning algorithm" org-learn
)
351 (const :tag
"C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix
)
352 (const :tag
"C notmuch: Provide org links to notmuch searches or messages" org-notmuch
)
353 (const :tag
"C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal
)
354 (const :tag
"C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber
)
355 (const :tag
"C man: Support for links to manpages in Org-mode" org-man
)
356 (const :tag
"C mtags: Support for muse-like tags" org-mtags
)
357 (const :tag
"C panel: Simple routines for us with bad memory" org-panel
)
358 (const :tag
"C registry: A registry for Org-mode links" org-registry
)
359 (const :tag
"C org2rem: Convert org appointments into reminders" org2rem
)
360 (const :tag
"C screen: Visit screen sessions through Org-mode links" org-screen
)
361 (const :tag
"C secretary: Team management with org-mode" org-secretary
)
362 (const :tag
"C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert
)
363 (const :tag
"C toc: Table of contents for Org-mode buffer" org-toc
)
364 (const :tag
"C track: Keep up with Org-mode development" org-track
)
365 (const :tag
"C velocity Something like Notational Velocity for Org" org-velocity
)
366 (const :tag
"C wikinodes: CamelCase wiki-like links" org-wikinodes
)
367 (repeat :tag
"External packages" :inline t
(symbol :tag
"Package"))))
369 (defcustom org-support-shift-select nil
370 "Non-nil means make shift-cursor commands select text when possible.
372 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
373 start selecting a region, or enlarge regions started in this way.
374 In Org-mode, in special contexts, these same keys are used for
375 other purposes, important enough to compete with shift selection.
376 Org tries to balance these needs by supporting `shift-select-mode'
377 outside these special contexts, under control of this variable.
379 The default of this variable is nil, to avoid confusing behavior. Shifted
380 cursor keys will then execute Org commands in the following contexts:
381 - on a headline, changing TODO state (left/right) and priority (up/down)
382 - on a time stamp, changing the time
383 - in a plain list item, changing the bullet type
384 - in a property definition line, switching between allowed values
385 - in the BEGIN line of a clock table (changing the time block).
386 Outside these contexts, the commands will throw an error.
388 When this variable is t and the cursor is not in a special
389 context, Org-mode will support shift-selection for making and
390 enlarging regions. To make this more effective, the bullet
391 cycling will no longer happen anywhere in an item line, but only
392 if the cursor is exactly on the bullet.
394 If you set this variable to the symbol `always', then the keys
395 will not be special in headlines, property lines, and item lines,
396 to make shift selection work there as well. If this is what you
397 want, you can use the following alternative commands: `C-c C-t'
398 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
399 can be used to switch TODO sets, `C-c -' to cycle item bullet
400 types, and properties can be edited by hand or in column view.
402 However, when the cursor is on a timestamp, shift-cursor commands
403 will still edit the time stamp - this is just too good to give up.
405 XEmacs user should have this variable set to nil, because
406 `shift-select-mode' is in Emacs 23 or later only."
409 (const :tag
"Never" nil
)
410 (const :tag
"When outside special context" t
)
411 (const :tag
"Everywhere except timestamps" always
)))
413 (defcustom org-loop-over-headlines-in-active-region nil
414 "Shall some commands act upon headlines in the active region?
416 When set to `t', some commands will be performed in all headlines
417 within the active region.
419 When set to `start-level', some commands will be performed in all
420 headlines within the active region, provided that these headlines
421 are of the same level than the first one.
423 When set to a string, those commands will be performed on the
424 matching headlines within the active region. Such string must be
425 a tags/property/todo match as it is used in the agenda tags view.
427 The list of commands is: `org-schedule', `org-deadline',
428 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
429 `org-archive-to-archive-sibling'. The archiving commands skip
430 already archived entries."
431 :type
'(choice (const :tag
"Don't loop" nil
)
432 (const :tag
"All headlines in active region" t
)
433 (const :tag
"In active region, headlines at the same level than the first one" 'start-level
)
434 (string :tag
"Tags/Property/Todo matcher"))
439 (defgroup org-startup nil
440 "Options concerning startup of Org-mode."
444 (defcustom org-startup-folded t
445 "Non-nil means entering Org-mode will switch to OVERVIEW.
446 This can also be configured on a per-file basis by adding one of
447 the following lines anywhere in the buffer:
449 #+STARTUP: fold (or `overview', this is equivalent)
450 #+STARTUP: nofold (or `showall', this is equivalent)
452 #+STARTUP: showeverything"
455 (const :tag
"nofold: show all" nil
)
456 (const :tag
"fold: overview" t
)
457 (const :tag
"content: all headlines" content
)
458 (const :tag
"show everything, even drawers" showeverything
)))
460 (defcustom org-startup-truncated t
461 "Non-nil means entering Org-mode will set `truncate-lines'.
462 This is useful since some lines containing links can be very long and
463 uninteresting. Also tables look terrible when wrapped."
467 (defcustom org-startup-indented nil
468 "Non-nil means turn on `org-indent-mode' on startup.
469 This can also be configured on a per-file basis by adding one of
470 the following lines anywhere in the buffer:
474 :group
'org-structure
476 (const :tag
"Not" nil
)
477 (const :tag
"Globally (slow on startup in large files)" t
)))
479 (defcustom org-use-sub-superscripts t
480 "Non-nil means interpret \"_\" and \"^\" for export.
481 When this option is turned on, you can use TeX-like syntax for sub- and
482 superscripts. Several characters after \"_\" or \"^\" will be
483 considered as a single item - so grouping with {} is normally not
484 needed. For example, the following things will be parsed as single
485 sub- or superscripts.
487 10^24 or 10^tau several digits will be considered 1 item.
488 10^-12 or 10^-tau a leading sign with digits or a word
489 x^2-y^3 will be read as x^2 - y^3, because items are
490 terminated by almost any nonword/nondigit char.
491 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
493 Still, ambiguity is possible - so when in doubt use {} to enclose the
494 sub/superscript. If you set this variable to the symbol `{}',
495 the braces are *required* in order to trigger interpretations as
496 sub/superscript. This can be helpful in documents that need \"_\"
497 frequently in plain text.
499 Not all export backends support this, but HTML does.
501 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
503 :group
'org-export-translation
506 (const :tag
"Always interpret" t
)
507 (const :tag
"Only with braces" {})
508 (const :tag
"Never interpret" nil
)))
510 (if (fboundp 'defvaralias
)
511 (defvaralias 'org-export-with-sub-superscripts
'org-use-sub-superscripts
))
514 (defcustom org-startup-with-beamer-mode nil
515 "Non-nil means turn on `org-beamer-mode' on startup.
516 This can also be configured on a per-file basis by adding one of
517 the following lines anywhere in the buffer:
524 (defcustom org-startup-align-all-tables nil
525 "Non-nil means align all tables when visiting a file.
526 This is useful when the column width in tables is forced with <N> cookies
527 in table fields. Such tables will look correct only after the first re-align.
528 This can also be configured on a per-file basis by adding one of
529 the following lines anywhere in the buffer:
535 (defcustom org-startup-with-inline-images nil
536 "Non-nil means show inline images when loading a new Org file.
537 This can also be configured on a per-file basis by adding one of
538 the following lines anywhere in the buffer:
539 #+STARTUP: inlineimages
540 #+STARTUP: noinlineimages"
545 (defcustom org-insert-mode-line-in-empty-file nil
546 "Non-nil means insert the first line setting Org-mode in empty files.
547 When the function `org-mode' is called interactively in an empty file, this
548 normally means that the file name does not automatically trigger Org-mode.
549 To ensure that the file will always be in Org-mode in the future, a
550 line enforcing Org-mode will be inserted into the buffer, if this option
555 (defcustom org-replace-disputed-keys nil
556 "Non-nil means use alternative key bindings for some keys.
557 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
558 These keys are also used by other packages like shift-selection-mode'
559 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
560 If you want to use Org-mode together with one of these other modes,
561 or more generally if you would like to move some Org-mode commands to
562 other keys, set this variable and configure the keys with the variable
565 This option is only relevant at load-time of Org-mode, and must be set
566 *before* org.el is loaded. Changing it requires a restart of Emacs to
571 (defcustom org-use-extra-keys nil
572 "Non-nil means use extra key sequence definitions for certain commands.
573 This happens automatically if you run XEmacs or if `window-system'
574 is nil. This variable lets you do the same manually. You must
575 set it before loading org.
577 Example: on Carbon Emacs 22 running graphically, with an external
578 keyboard on a Powerbook, the default way of setting M-left might
579 not work for either Alt or ESC. Setting this variable will make
584 (if (fboundp 'defvaralias
)
585 (defvaralias 'org-CUA-compatible
'org-replace-disputed-keys
))
587 (defcustom org-disputed-keys
588 '(([(shift up
)] .
[(meta p
)])
589 ([(shift down
)] .
[(meta n
)])
590 ([(shift left
)] .
[(meta -
)])
591 ([(shift right
)] .
[(meta +)])
592 ([(control shift right
)] .
[(meta shift
+)])
593 ([(control shift left
)] .
[(meta shift -
)]))
594 "Keys for which Org-mode and other modes compete.
595 This is an alist, cars are the default keys, second element specifies
596 the alternative to use when `org-replace-disputed-keys' is t.
598 Keys can be specified in any syntax supported by `define-key'.
599 The value of this option takes effect only at Org-mode's startup,
600 therefore you'll have to restart Emacs to apply it after changing."
605 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
606 Or return the original if not disputed.
607 Also apply the translations defined in `org-xemacs-key-equivalents'."
608 (when org-replace-disputed-keys
609 (let* ((nkey (key-description key
))
610 (x (org-find-if (lambda (x)
611 (equal (key-description (car x
)) nkey
))
613 (setq key
(if x
(cdr x
) key
))))
614 (when (featurep 'xemacs
)
615 (setq key
(or (cdr (assoc key org-xemacs-key-equivalents
)) key
)))
618 (defun org-find-if (predicate seq
)
621 (if (funcall predicate
(car seq
))
622 (throw 'exit
(car seq
))
625 (defun org-defkey (keymap key def
)
626 "Define a key, possibly translated, as returned by `org-key'."
627 (define-key keymap
(org-key key
) def
))
629 (defcustom org-ellipsis nil
630 "The ellipsis to use in the Org-mode outline.
631 When nil, just use the standard three dots. When a string, use that instead,
632 When a face, use the standard 3 dots, but with the specified face.
633 The change affects only Org-mode (which will then use its own display table).
634 Changing this requires executing `M-x org-mode' in a buffer to become
637 :type
'(choice (const :tag
"Default" nil
)
638 (face :tag
"Face" :value org-warning
)
639 (string :tag
"String" :value
"...#")))
641 (defvar org-display-table nil
642 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
644 (defgroup org-keywords nil
645 "Keywords in Org-mode."
649 (defcustom org-deadline-string
"DEADLINE:"
650 "String to mark deadline entries.
651 A deadline is this string, followed by a time stamp. Should be a word,
652 terminated by a colon. You can insert a schedule keyword and
653 a timestamp with \\[org-deadline].
654 Changes become only effective after restarting Emacs."
658 (defcustom org-scheduled-string
"SCHEDULED:"
659 "String to mark scheduled TODO entries.
660 A schedule is this string, followed by a time stamp. Should be a word,
661 terminated by a colon. You can insert a schedule keyword and
662 a timestamp with \\[org-schedule].
663 Changes become only effective after restarting Emacs."
667 (defcustom org-closed-string
"CLOSED:"
668 "String used as the prefix for timestamps logging closing a TODO entry."
672 (defcustom org-clock-string
"CLOCK:"
673 "String used as prefix for timestamps clocking work hours on an item."
677 (defconst org-planning-or-clock-line-re
(concat "^[ \t]*\\("
678 org-scheduled-string
"\\|"
679 org-deadline-string
"\\|"
680 org-closed-string
"\\|"
681 org-clock-string
"\\)")
682 "Matches a line with planning or clock info.")
684 (defcustom org-comment-string
"COMMENT"
685 "Entries starting with this keyword will never be exported.
686 An entry can be toggled between COMMENT and normal with
687 \\[org-toggle-comment].
688 Changes become only effective after restarting Emacs."
692 (defcustom org-quote-string
"QUOTE"
693 "Entries starting with this keyword will be exported in fixed-width font.
694 Quoting applies only to the text in the entry following the headline, and does
695 not extend beyond the next headline, even if that is lower level.
696 An entry can be toggled between QUOTE and normal with
697 \\[org-toggle-fixed-width-section]."
701 (defconst org-repeat-re
702 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
703 "Regular expression for specifying repeated events.
704 After a match, group 1 contains the repeat expression.")
706 (defgroup org-structure nil
707 "Options concerning the general structure of Org-mode files."
711 (defgroup org-reveal-location nil
712 "Options about how to make context of a location visible."
713 :tag
"Org Reveal Location"
714 :group
'org-structure
)
716 (defconst org-context-choice
718 (const :tag
"Always" t
)
719 (const :tag
"Never" nil
)
720 (repeat :greedy t
:tag
"Individual contexts"
722 (choice :tag
"Context"
729 (const bookmark-jump
)
733 "Contexts for the reveal options.")
735 (defcustom org-show-hierarchy-above
'((default . t
))
736 "Non-nil means show full hierarchy when revealing a location.
737 Org-mode often shows locations in an org-mode file which might have
738 been invisible before. When this is set, the hierarchy of headings
739 above the exposed location is shown.
740 Turning this off for example for sparse trees makes them very compact.
741 Instead of t, this can also be an alist specifying this option for different
742 contexts. Valid contexts are
743 agenda when exposing an entry from the agenda
744 org-goto when using the command `org-goto' on key C-c C-j
745 occur-tree when using the command `org-occur' on key C-c /
746 tags-tree when constructing a sparse tree based on tags matches
747 link-search when exposing search matches associated with a link
748 mark-goto when exposing the jump goal of a mark
749 bookmark-jump when exposing a bookmark location
750 isearch when exiting from an incremental search
751 default default for all contexts not set explicitly"
752 :group
'org-reveal-location
753 :type org-context-choice
)
755 (defcustom org-show-following-heading
'((default . nil
))
756 "Non-nil means show following heading when revealing a location.
757 Org-mode often shows locations in an org-mode file which might have
758 been invisible before. When this is set, the heading following the
760 Turning this off for example for sparse trees makes them very compact,
761 but makes it harder to edit the location of the match. In such a case,
762 use the command \\[org-reveal] to show more context.
763 Instead of t, this can also be an alist specifying this option for different
764 contexts. See `org-show-hierarchy-above' for valid contexts."
765 :group
'org-reveal-location
766 :type org-context-choice
)
768 (defcustom org-show-siblings
'((default . nil
) (isearch t
))
769 "Non-nil means show all sibling heading when revealing a location.
770 Org-mode often shows locations in an org-mode file which might have
771 been invisible before. When this is set, the sibling of the current entry
772 heading are all made visible. If `org-show-hierarchy-above' is t,
773 the same happens on each level of the hierarchy above the current entry.
775 By default this is on for the isearch context, off for all other contexts.
776 Turning this off for example for sparse trees makes them very compact,
777 but makes it harder to edit the location of the match. In such a case,
778 use the command \\[org-reveal] to show more context.
779 Instead of t, this can also be an alist specifying this option for different
780 contexts. See `org-show-hierarchy-above' for valid contexts."
781 :group
'org-reveal-location
782 :type org-context-choice
)
784 (defcustom org-show-entry-below
'((default . nil
))
785 "Non-nil means show the entry below a headline when revealing a location.
786 Org-mode often shows locations in an org-mode file which might have
787 been invisible before. When this is set, the text below the headline that is
788 exposed is also shown.
790 By default this is off for all contexts.
791 Instead of t, this can also be an alist specifying this option for different
792 contexts. See `org-show-hierarchy-above' for valid contexts."
793 :group
'org-reveal-location
794 :type org-context-choice
)
796 (defcustom org-indirect-buffer-display
'other-window
797 "How should indirect tree buffers be displayed?
798 This applies to indirect buffers created with the commands
799 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
801 current-window Display in the current window
802 other-window Just display in another window.
803 dedicated-frame Create one new frame, and re-use it each time.
804 new-frame Make a new frame each time. Note that in this case
805 previously-made indirect buffers are kept, and you need to
806 kill these buffers yourself."
807 :group
'org-structure
808 :group
'org-agenda-windows
810 (const :tag
"In current window" current-window
)
811 (const :tag
"In current frame, other window" other-window
)
812 (const :tag
"Each time a new frame" new-frame
)
813 (const :tag
"One dedicated frame" dedicated-frame
)))
815 (defcustom org-use-speed-commands nil
816 "Non-nil means activate single letter commands at beginning of a headline.
817 This may also be a function to test for appropriate locations where speed
818 commands should be active."
819 :group
'org-structure
821 (const :tag
"Never" nil
)
822 (const :tag
"At beginning of headline stars" t
)
825 (defcustom org-speed-commands-user nil
826 "Alist of additional speed commands.
827 This list will be checked before `org-speed-commands-default'
828 when the variable `org-use-speed-commands' is non-nil
829 and when the cursor is at the beginning of a headline.
830 The car if each entry is a string with a single letter, which must
831 be assigned to `self-insert-command' in the global map.
832 The cdr is either a command to be called interactively, a function
833 to be called, or a form to be evaluated.
834 An entry that is just a list with a single string will be interpreted
835 as a descriptive headline that will be added when listing the speed
836 commands in the Help buffer using the `?' speed command."
837 :group
'org-structure
838 :type
'(repeat :value
("k" . ignore
)
839 (choice :value
("k" . ignore
)
840 (list :tag
"Descriptive Headline" (string :tag
"Headline"))
841 (cons :tag
"Letter and Command"
842 (string :tag
"Command letter")
847 (defgroup org-cycle nil
848 "Options concerning visibility cycling in Org-mode."
850 :group
'org-structure
)
852 (defcustom org-cycle-skip-children-state-if-no-children t
853 "Non-nil means skip CHILDREN state in entries that don't have any."
857 (defcustom org-cycle-max-level nil
858 "Maximum level which should still be subject to visibility cycling.
859 Levels higher than this will, for cycling, be treated as text, not a headline.
860 When `org-odd-levels-only' is set, a value of N in this variable actually
861 means 2N-1 stars as the limiting headline.
862 When nil, cycle all levels.
863 Note that the limiting level of cycling is also influenced by
864 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
865 `org-inlinetask-min-level' is, cycling will be limited to levels one less
869 (const :tag
"No limit" nil
)
870 (integer :tag
"Maximum level")))
872 (defcustom org-drawers
'("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
873 "Names of drawers. Drawers are not opened by cycling on the headline above.
874 Drawers only open with a TAB on the drawer line itself. A drawer looks like
879 The drawer \"PROPERTIES\" is special for capturing properties through
882 Drawers can be defined on the per-file basis with a line like:
884 #+DRAWERS: HIDDEN STATE PROPERTIES"
885 :group
'org-structure
887 :type
'(repeat (string :tag
"Drawer Name")))
889 (defcustom org-hide-block-startup nil
890 "Non-nil means entering Org-mode will fold all blocks.
891 This can also be set in on a per-file basis with
893 #+STARTUP: hideblocks
894 #+STARTUP: showblocks"
899 (defcustom org-cycle-global-at-bob nil
900 "Cycle globally if cursor is at beginning of buffer and not at a headline.
901 This makes it possible to do global cycling without having to use S-TAB or
902 \\[universal-argument] TAB. For this special case to work, the first line
903 of the buffer must not be a headline -- it may be empty or some other text.
904 When used in this way, `org-cycle-hook' is disabled temporarily to make
905 sure the cursor stays at the beginning of the buffer. When this option is
906 nil, don't do anything special at the beginning of the buffer."
910 (defcustom org-cycle-level-after-item
/entry-creation t
911 "Non-nil means cycle entry level or item indentation in new empty entries.
913 When the cursor is at the end of an empty headline, i.e with only stars
914 and maybe a TODO keyword, TAB will then switch the entry to become a child,
915 and then all possible ancestor states, before returning to the original state.
916 This makes data entry extremely fast: M-RET to create a new headline,
917 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
919 When the cursor is at the end of an empty plain list item, one TAB will
920 make it a subitem, two or more tabs will back up to make this an item
921 higher up in the item hierarchy."
925 (defcustom org-cycle-emulate-tab t
926 "Where should `org-cycle' emulate TAB.
928 white Only in completely white lines
929 whitestart Only at the beginning of lines, before the first non-white char
930 t Everywhere except in headlines
931 exc-hl-bol Everywhere except at the start of a headline
932 If TAB is used in a place where it does not emulate TAB, the current subtree
933 visibility is cycled."
935 :type
'(choice (const :tag
"Never" nil
)
936 (const :tag
"Only in completely white lines" white
)
937 (const :tag
"Before first char in a line" whitestart
)
938 (const :tag
"Everywhere except in headlines" t
)
939 (const :tag
"Everywhere except at bol in headlines" exc-hl-bol
)
942 (defcustom org-cycle-separator-lines
2
943 "Number of empty lines needed to keep an empty line between collapsed trees.
944 If you leave an empty line between the end of a subtree and the following
945 headline, this empty line is hidden when the subtree is folded.
946 Org-mode will leave (exactly) one empty line visible if the number of
947 empty lines is equal or larger to the number given in this variable.
948 So the default 2 means at least 2 empty lines after the end of a subtree
949 are needed to produce free space between a collapsed subtree and the
952 If the number is negative, and the number of empty lines is at least -N,
953 all empty lines are shown.
955 Special case: when 0, never leave empty lines in collapsed view."
958 (put 'org-cycle-separator-lines
'safe-local-variable
'integerp
)
960 (defcustom org-pre-cycle-hook nil
961 "Hook that is run before visibility cycling is happening.
962 The function(s) in this hook must accept a single argument which indicates
963 the new state that will be set right after running this hook. The
964 argument is a symbol. Before a global state change, it can have the values
965 `overview', `content', or `all'. Before a local state change, it can have
966 the values `folded', `children', or `subtree'."
970 (defcustom org-cycle-hook
'(org-cycle-hide-archived-subtrees
971 org-cycle-hide-drawers
972 org-cycle-show-empty-lines
973 org-optimize-window-after-visibility-change
)
974 "Hook that is run after `org-cycle' has changed the buffer visibility.
975 The function(s) in this hook must accept a single argument which indicates
976 the new state that was set by the most recent `org-cycle' command. The
977 argument is a symbol. After a global state change, it can have the values
978 `overview', `contents', or `all'. After a local state change, it can have
979 the values `folded', `children', or `subtree'."
983 (defgroup org-edit-structure nil
984 "Options concerning structure editing in Org-mode."
985 :tag
"Org Edit Structure"
986 :group
'org-structure
)
988 (defcustom org-odd-levels-only nil
989 "Non-nil means skip even levels and only use odd levels for the outline.
990 This has the effect that two stars are being added/taken away in
991 promotion/demotion commands. It also influences how levels are
992 handled by the exporters.
993 Changing it requires restart of `font-lock-mode' to become effective
994 for fontification also in regions already fontified.
995 You may also set this on a per-file basis by adding one of the following
1000 :group
'org-edit-structure
1001 :group
'org-appearance
1004 (defcustom org-adapt-indentation t
1005 "Non-nil means adapt indentation to outline node level.
1007 When this variable is set, Org assumes that you write outlines by
1008 indenting text in each node to align with the headline (after the stars).
1009 The following issues are influenced by this variable:
1011 - When this is set and the *entire* text in an entry is indented, the
1012 indentation is increased by one space in a demotion command, and
1013 decreased by one in a promotion command. If any line in the entry
1014 body starts with text at column 0, indentation is not changed at all.
1016 - Property drawers and planning information is inserted indented when
1017 this variable s set. When nil, they will not be indented.
1019 - TAB indents a line relative to context. The lines below a headline
1020 will be indented when this variable is set.
1022 Note that this is all about true indentation, by adding and removing
1023 space characters. See also `org-indent.el' which does level-dependent
1024 indentation in a virtual way, i.e. at display time in Emacs."
1025 :group
'org-edit-structure
1028 (defcustom org-special-ctrl-a
/e nil
1029 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1031 When t, `C-a' will bring back the cursor to the beginning of the
1032 headline text, i.e. after the stars and after a possible TODO
1033 keyword. In an item, this will be the position after bullet and
1034 check-box, if any. When the cursor is already at that position,
1035 another `C-a' will bring it to the beginning of the line.
1037 `C-e' will jump to the end of the headline, ignoring the presence
1038 of tags in the headline. A second `C-e' will then jump to the
1039 true end of the line, after any tags. This also means that, when
1040 this variable is non-nil, `C-e' also will never jump beyond the
1041 end of the heading of a folded section, i.e. not after the
1044 When set to the symbol `reversed', the first `C-a' or `C-e' works
1045 normally, going to the true line boundary first. Only a directly
1046 following, identical keypress will bring the cursor to the
1049 This may also be a cons cell where the behavior for `C-a' and
1050 `C-e' is set separately."
1051 :group
'org-edit-structure
1053 (const :tag
"off" nil
)
1054 (const :tag
"on: after stars/bullet and before tags first" t
)
1055 (const :tag
"reversed: true line boundary first" reversed
)
1056 (cons :tag
"Set C-a and C-e separately"
1057 (choice :tag
"Special C-a"
1058 (const :tag
"off" nil
)
1059 (const :tag
"on: after stars/bullet first" t
)
1060 (const :tag
"reversed: before stars/bullet first" reversed
))
1061 (choice :tag
"Special C-e"
1062 (const :tag
"off" nil
)
1063 (const :tag
"on: before tags first" t
)
1064 (const :tag
"reversed: after tags first" reversed
)))))
1065 (if (fboundp 'defvaralias
)
1066 (defvaralias 'org-special-ctrl-a
'org-special-ctrl-a
/e
))
1068 (defcustom org-special-ctrl-k nil
1069 "Non-nil means `C-k' will behave specially in headlines.
1070 When nil, `C-k' will call the default `kill-line' command.
1071 When t, the following will happen while the cursor is in the headline:
1073 - When the cursor is at the beginning of a headline, kill the entire
1074 line and possible the folded subtree below the line.
1075 - When in the middle of the headline text, kill the headline up to the tags.
1076 - When after the headline text, kill the tags."
1077 :group
'org-edit-structure
1080 (defcustom org-ctrl-k-protect-subtree nil
1081 "Non-nil means, do not delete a hidden subtree with C-k.
1082 When set to the symbol `error', simply throw an error when C-k is
1083 used to kill (part-of) a headline that has hidden text behind it.
1084 Any other non-nil value will result in a query to the user, if it is
1085 OK to kill that hidden subtree. When nil, kill without remorse."
1086 :group
'org-edit-structure
1089 (const :tag
"Do not protect hidden subtrees" nil
)
1090 (const :tag
"Protect hidden subtrees with a security query" t
)
1091 (const :tag
"Never kill a hidden subtree with C-k" error
)))
1093 (defcustom org-catch-invisible-edits nil
1094 "Check if in invisible region before inserting or deleting a character.
1097 nil Do not check, so just do invisible edits.
1098 error Throw an error and do nothing.
1099 show Make point visible, and do the requested edit.
1100 show-and-error Make point visible, then throw an error and abort the edit.
1101 smart Make point visible, and do insertion/deletion if it is
1102 adjacent to visible text and the change feels predictable.
1103 Never delete a previously invisible character or add in the
1104 middle or right after an invisible region. Basically, this
1105 allows insertion and backward-delete right before ellipses.
1106 FIXME: maybe in this case we should not even show?"
1107 :group
'org-edit-structure
1110 (const :tag
"Do not check" nil
)
1111 (const :tag
"Throw error when trying to edit" error
)
1112 (const :tag
"Unhide, but do not do the edit" show-and-error
)
1113 (const :tag
"Show invisible part and do the edit" show
)
1114 (const :tag
"Be smart and do the right thing" smart
)))
1116 (defcustom org-yank-folded-subtrees t
1117 "Non-nil means when yanking subtrees, fold them.
1118 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1119 it starts with a heading and all other headings in it are either children
1120 or siblings, then fold all the subtrees. However, do this only if no
1121 text after the yank would be swallowed into a folded tree by this action."
1122 :group
'org-edit-structure
1125 (defcustom org-yank-adjusted-subtrees nil
1126 "Non-nil means when yanking subtrees, adjust the level.
1127 With this setting, `org-paste-subtree' is used to insert the subtree, see
1128 this function for details."
1129 :group
'org-edit-structure
1132 (defcustom org-M-RET-may-split-line
'((default . t
))
1133 "Non-nil means M-RET will split the line at the cursor position.
1134 When nil, it will go to the end of the line before making a
1136 You may also set this option in a different way for different
1137 contexts. Valid contexts are:
1139 headline when creating a new headline
1140 item when creating a new item
1141 table in a table field
1142 default the value to be used for all contexts not explicitly
1144 :group
'org-structure
1147 (const :tag
"Always" t
)
1148 (const :tag
"Never" nil
)
1149 (repeat :greedy t
:tag
"Individual contexts"
1151 (choice :tag
"Context"
1159 (defcustom org-insert-heading-respect-content nil
1160 "Non-nil means insert new headings after the current subtree.
1161 When nil, the new heading is created directly after the current line.
1162 The commands \\[org-insert-heading-respect-content] and
1163 \\[org-insert-todo-heading-respect-content] turn this variable on
1164 for the duration of the command."
1165 :group
'org-structure
1168 (defcustom org-blank-before-new-entry
'((heading . auto
)
1169 (plain-list-item . auto
))
1170 "Should `org-insert-heading' leave a blank line before new heading/item?
1171 The value is an alist, with `heading' and `plain-list-item' as CAR,
1172 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1173 which case Org will look at the surrounding headings/items and try to
1174 make an intelligent decision whether to insert a blank line or not.
1176 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1177 set, the setting here is ignored and no empty line is inserted, to avoid
1178 breaking the list structure."
1179 :group
'org-edit-structure
1181 (cons (const heading
)
1182 (choice (const :tag
"Never" nil
)
1183 (const :tag
"Always" t
)
1184 (const :tag
"Auto" auto
)))
1185 (cons (const plain-list-item
)
1186 (choice (const :tag
"Never" nil
)
1187 (const :tag
"Always" t
)
1188 (const :tag
"Auto" auto
)))))
1190 (defcustom org-insert-heading-hook nil
1191 "Hook being run after inserting a new heading."
1192 :group
'org-edit-structure
1195 (defcustom org-enable-fixed-width-editor t
1196 "Non-nil means lines starting with \":\" are treated as fixed-width.
1197 This currently only means they are never auto-wrapped.
1198 When nil, such lines will be treated like ordinary lines.
1199 See also the QUOTE keyword."
1200 :group
'org-edit-structure
1203 (defcustom org-goto-auto-isearch t
1204 "Non-nil means typing characters in `org-goto' starts incremental search."
1205 :group
'org-edit-structure
1208 (defgroup org-sparse-trees nil
1209 "Options concerning sparse trees in Org-mode."
1210 :tag
"Org Sparse Trees"
1211 :group
'org-structure
)
1213 (defcustom org-highlight-sparse-tree-matches t
1214 "Non-nil means highlight all matches that define a sparse tree.
1215 The highlights will automatically disappear the next time the buffer is
1216 changed by an edit command."
1217 :group
'org-sparse-trees
1220 (defcustom org-remove-highlights-with-change t
1221 "Non-nil means any change to the buffer will remove temporary highlights.
1222 Such highlights are created by `org-occur' and `org-clock-display'.
1223 When nil, `C-c C-c needs to be used to get rid of the highlights.
1224 The highlights created by `org-preview-latex-fragment' always need
1225 `C-c C-c' to be removed."
1226 :group
'org-sparse-trees
1231 (defcustom org-occur-hook
'(org-first-headline-recenter)
1232 "Hook that is run after `org-occur' has constructed a sparse tree.
1233 This can be used to recenter the window to show as much of the structure
1235 :group
'org-sparse-trees
1238 (defgroup org-imenu-and-speedbar nil
1239 "Options concerning imenu and speedbar in Org-mode."
1240 :tag
"Org Imenu and Speedbar"
1241 :group
'org-structure
)
1243 (defcustom org-imenu-depth
2
1244 "The maximum level for Imenu access to Org-mode headlines.
1245 This also applied for speedbar access."
1246 :group
'org-imenu-and-speedbar
1249 (defgroup org-table nil
1250 "Options concerning tables in Org-mode."
1254 (defcustom org-enable-table-editor
'optimized
1255 "Non-nil means lines starting with \"|\" are handled by the table editor.
1256 When nil, such lines will be treated like ordinary lines.
1258 When equal to the symbol `optimized', the table editor will be optimized to
1260 - Automatic overwrite mode in front of whitespace in table fields.
1261 This makes the structure of the table stay in tact as long as the edited
1262 field does not exceed the column width.
1263 - Minimize the number of realigns. Normally, the table is aligned each time
1264 TAB or RET are pressed to move to another field. With optimization this
1265 happens only if changes to a field might have changed the column width.
1266 Optimization requires replacing the functions `self-insert-command',
1267 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1268 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1269 very good at guessing when a re-align will be necessary, but you can always
1270 force one with \\[org-ctrl-c-ctrl-c].
1272 If you would like to use the optimized version in Org-mode, but the
1273 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1275 This variable can be used to turn on and off the table editor during a session,
1276 but in order to toggle optimization, a restart is required.
1278 See also the variable `org-table-auto-blank-field'."
1281 (const :tag
"off" nil
)
1283 (const :tag
"on, optimized" optimized
)))
1285 (defcustom org-self-insert-cluster-for-undo
(or (featurep 'xemacs
)
1286 (version<= emacs-version
"24.1"))
1287 "Non-nil means cluster self-insert commands for undo when possible.
1288 If this is set, then, like in the Emacs command loop, 20 consecutive
1289 characters will be undone together.
1290 This is configurable, because there is some impact on typing performance."
1294 (defcustom org-table-tab-recognizes-table.el t
1295 "Non-nil means TAB will automatically notice a table.el table.
1296 When it sees such a table, it moves point into it and - if necessary -
1297 calls `table-recognize-table'."
1298 :group
'org-table-editing
1301 (defgroup org-link nil
1302 "Options concerning links in Org-mode."
1306 (defvar org-link-abbrev-alist-local nil
1307 "Buffer-local version of `org-link-abbrev-alist', which see.
1308 The value of this is taken from the #+LINK lines.")
1309 (make-variable-buffer-local 'org-link-abbrev-alist-local
)
1311 (defcustom org-link-abbrev-alist nil
1312 "Alist of link abbreviations.
1313 The car of each element is a string, to be replaced at the start of a link.
1314 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1315 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1317 [[linkkey:tag][description]]
1319 The 'linkkey' must be a word word, starting with a letter, followed
1320 by letters, numbers, '-' or '_'.
1322 If REPLACE is a string, the tag will simply be appended to create the link.
1323 If the string contains \"%s\", the tag will be inserted there. If the string
1324 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1325 at that point (see the function `url-hexify-string'). If the string contains
1326 the specifier \"%(my-function)\", then the custom function `my-function' will
1327 be invoked: this function takes the tag as its only argument and must return
1330 REPLACE may also be a function that will be called with the tag as the
1331 only argument to create the link, which should be returned as a string.
1333 See the manual for examples."
1337 (string :tag
"Protocol")
1339 (string :tag
"Format")
1342 (defcustom org-descriptive-links t
1343 "Non-nil means Org will display descriptive links.
1344 E.g. [[http://orgmode.org][Org website]] will be displayed as
1345 \"Org Website\", hiding the link itself and just displaying its
1346 description. When set to `nil', Org will display the full links
1349 You can interactively set the value of this variable by calling
1350 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1354 (defcustom org-link-file-path-type
'adaptive
1355 "How the path name in file links should be stored.
1358 relative Relative to the current directory, i.e. the directory of the file
1359 into which the link is being inserted.
1360 absolute Absolute path, if possible with ~ for home directory.
1361 noabbrev Absolute path, no abbreviation of home directory.
1362 adaptive Use relative path for files in the current directory and sub-
1363 directories of it. For other files, use an absolute path."
1371 (defcustom org-activate-links
'(bracket angle plain radio tag date footnote
)
1372 "Types of links that should be activated in Org-mode files.
1373 This is a list of symbols, each leading to the activation of a certain link
1374 type. In principle, it does not hurt to turn on most link types - there may
1375 be a small gain when turning off unused link types. The types are:
1377 bracket The recommended [[link][description]] or [[link]] links with hiding.
1378 angle Links in angular brackets that may contain whitespace like
1379 <bbdb:Carsten Dominik>.
1380 plain Plain links in normal text, no whitespace, like http://google.com.
1381 radio Text that is matched by a radio target, see manual for details.
1382 tag Tag settings in a headline (link to tag search).
1383 date Time stamps (link to calendar).
1384 footnote Footnote labels.
1386 Changing this variable requires a restart of Emacs to become effective."
1388 :type
'(set :greedy t
1389 (const :tag
"Double bracket links" bracket
)
1390 (const :tag
"Angular bracket links" angle
)
1391 (const :tag
"Plain text links" plain
)
1392 (const :tag
"Radio target matches" radio
)
1393 (const :tag
"Tags" tag
)
1394 (const :tag
"Timestamps" date
)
1395 (const :tag
"Footnotes" footnote
)))
1397 (defcustom org-make-link-description-function nil
1398 "Function to use for generating link descriptions from links.
1399 When nil, the link location will be used. This function must take
1400 two parameters: the first one is the link, the second one is the
1401 description generated by `org-insert-link'. The function should
1402 return the description to use."
1406 (defgroup org-link-store nil
1407 "Options concerning storing links in Org-mode."
1408 :tag
"Org Store Link"
1411 (defcustom org-url-hexify-p t
1412 "When non-nil, hexify URL when creating a link."
1415 :group
'org-link-store
)
1417 (defcustom org-email-link-description-format
"Email %c: %.30s"
1418 "Format of the description part of a link to an email or usenet message.
1419 The following %-escapes will be replaced by corresponding information:
1421 %F full \"From\" field
1422 %f name, taken from \"From\" field, address if no name
1423 %T full \"To\" field
1424 %t first name in \"To\" field, address if no name
1425 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1426 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1431 You may use normal field width specification between the % and the letter.
1432 This is for example useful to limit the length of the subject.
1434 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1435 :group
'org-link-store
1438 (defcustom org-from-is-user-regexp
1440 (when (and user-mail-address
(not (string= user-mail-address
"")))
1441 (setq r1
(concat "\\<" (regexp-quote user-mail-address
) "\\>")))
1442 (when (and user-full-name
(not (string= user-full-name
"")))
1443 (setq r2
(concat "\\<" (regexp-quote user-full-name
) "\\>")))
1444 (if (and r1 r2
) (concat r1
"\\|" r2
) (or r1 r2
)))
1445 "Regexp matched against the \"From:\" header of an email or usenet message.
1446 It should match if the message is from the user him/herself."
1447 :group
'org-link-store
1450 (defcustom org-context-in-file-links t
1451 "Non-nil means file links from `org-store-link' contain context.
1452 A search string will be added to the file name with :: as separator and
1453 used to find the context when the link is activated by the command
1454 `org-open-at-point'. When this option is t, the entire active region
1455 will be placed in the search string of the file link. If set to a
1456 positive integer, only the first n lines of context will be stored.
1458 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1459 negates this setting for the duration of the command."
1460 :group
'org-link-store
1461 :type
'(choice boolean integer
))
1463 (defcustom org-keep-stored-link-after-insertion nil
1464 "Non-nil means keep link in list for entire session.
1466 The command `org-store-link' adds a link pointing to the current
1467 location to an internal list. These links accumulate during a session.
1468 The command `org-insert-link' can be used to insert links into any
1469 Org-mode file (offering completion for all stored links). When this
1470 option is nil, every link which has been inserted once using \\[org-insert-link]
1471 will be removed from the list, to make completing the unused links
1473 :group
'org-link-store
1476 (defgroup org-link-follow nil
1477 "Options concerning following links in Org-mode."
1478 :tag
"Org Follow Link"
1481 (defcustom org-link-translation-function nil
1482 "Function to translate links with different syntax to Org syntax.
1483 This can be used to translate links created for example by the Planner
1484 or emacs-wiki packages to Org syntax.
1485 The function must accept two parameters, a TYPE containing the link
1486 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1487 which is everything after the link protocol. It should return a cons
1488 with possibly modified values of type and path.
1489 Org contains a function for this, so if you set this variable to
1490 `org-translate-link-from-planner', you should be able follow many
1491 links created by planner."
1492 :group
'org-link-follow
1495 (defcustom org-follow-link-hook nil
1496 "Hook that is run after a link has been followed."
1497 :group
'org-link-follow
1500 (defcustom org-tab-follows-link nil
1501 "Non-nil means on links TAB will follow the link.
1502 Needs to be set before org.el is loaded.
1503 This really should not be used, it does not make sense, and the
1504 implementation is bad."
1505 :group
'org-link-follow
1508 (defcustom org-return-follows-link nil
1509 "Non-nil means on links RET will follow the link."
1510 :group
'org-link-follow
1513 (defcustom org-mouse-1-follows-link
1514 (if (boundp 'mouse-1-click-follows-link
) mouse-1-click-follows-link t
)
1515 "Non-nil means mouse-1 on a link will follow the link.
1516 A longer mouse click will still set point. Does not work on XEmacs.
1517 Needs to be set before org.el is loaded."
1518 :group
'org-link-follow
1521 (defcustom org-mark-ring-length
4
1522 "Number of different positions to be recorded in the ring.
1523 Changing this requires a restart of Emacs to work correctly."
1524 :group
'org-link-follow
1527 (defcustom org-link-search-must-match-exact-headline
'query-to-create
1528 "Non-nil means internal links in Org files must exactly match a headline.
1529 When nil, the link search tries to match a phrase with all words
1530 in the search text."
1531 :group
'org-link-follow
1534 (const :tag
"Use fuzzy text search" nil
)
1535 (const :tag
"Match only exact headline" t
)
1536 (const :tag
"Match exact headline or query to create it"
1539 (defcustom org-link-frame-setup
1540 '((vm . vm-visit-folder-other-frame
)
1541 (vm-imap . vm-visit-imap-folder-other-frame
)
1542 (gnus . org-gnus-no-new-news
)
1543 (file . find-file-other-window
)
1544 (wl . wl-other-frame
))
1545 "Setup the frame configuration for following links.
1546 When following a link with Emacs, it may often be useful to display
1547 this link in another window or frame. This variable can be used to
1548 set this up for the different types of links.
1551 `vm-visit-folder-other-window'
1552 `vm-visit-folder-other-frame'
1553 For Gnus, use any of
1556 `org-gnus-no-new-news'
1557 For FILE, use any of
1559 `find-file-other-window'
1560 `find-file-other-frame'
1561 For Wanderlust use any of
1564 For the calendar, use the variable `calendar-setup'.
1565 For BBDB, it is currently only possible to display the matches in
1567 :group
'org-link-follow
1571 (const vm-visit-folder
)
1572 (const vm-visit-folder-other-window
)
1573 (const vm-visit-folder-other-frame
)))
1577 (const gnus-other-frame
)
1578 (const org-gnus-no-new-news
)))
1582 (const find-file-other-window
)
1583 (const find-file-other-frame
)))
1587 (const wl-other-frame
)))))
1589 (defcustom org-display-internal-link-with-indirect-buffer nil
1590 "Non-nil means use indirect buffer to display infile links.
1591 Activating internal links (from one location in a file to another location
1592 in the same file) normally just jumps to the location. When the link is
1593 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1595 another window. When this option is set, the other window actually displays
1596 an indirect buffer clone of the current buffer, to avoid any visibility
1597 changes to the current buffer."
1598 :group
'org-link-follow
1601 (defcustom org-open-non-existing-files nil
1602 "Non-nil means `org-open-file' will open non-existing files.
1603 When nil, an error will be generated.
1604 This variable applies only to external applications because they
1605 might choke on non-existing files. If the link is to a file that
1606 will be opened in Emacs, the variable is ignored."
1607 :group
'org-link-follow
1610 (defcustom org-open-directory-means-index-dot-org nil
1611 "Non-nil means a link to a directory really means to index.org.
1612 When nil, following a directory link will run dired or open a finder/explorer
1613 window on that directory."
1614 :group
'org-link-follow
1617 (defcustom org-link-mailto-program
'(browse-url "mailto:%a?subject=%s")
1618 "Function and arguments to call for following mailto links.
1619 This is a list with the first element being a Lisp function, and the
1620 remaining elements being arguments to the function. In string arguments,
1621 %a will be replaced by the address, and %s will be replaced by the subject
1622 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1623 :group
'org-link-follow
1625 (const :tag
"browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1626 (const :tag
"compose-mail" (compose-mail "%a" "%s"))
1627 (const :tag
"message-mail" (message-mail "%a" "%s"))
1628 (cons :tag
"other" (function) (repeat :tag
"argument" sexp
))))
1630 (defcustom org-confirm-shell-link-function
'yes-or-no-p
1631 "Non-nil means ask for confirmation before executing shell links.
1632 Shell links can be dangerous: just think about a link
1634 [[shell:rm -rf ~/*][Google Search]]
1636 This link would show up in your Org-mode document as \"Google Search\",
1637 but really it would remove your entire home directory.
1638 Therefore we advise against setting this variable to nil.
1639 Just change it to `y-or-n-p' if you want to confirm with a
1640 single keystroke rather than having to type \"yes\"."
1641 :group
'org-link-follow
1643 (const :tag
"with yes-or-no (safer)" yes-or-no-p
)
1644 (const :tag
"with y-or-n (faster)" y-or-n-p
)
1645 (const :tag
"no confirmation (dangerous)" nil
)))
1646 (put 'org-confirm-shell-link-function
1647 'safe-local-variable
1648 #'(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
1650 (defcustom org-confirm-shell-link-not-regexp
""
1651 "A regexp to skip confirmation for shell links."
1652 :group
'org-link-follow
1656 (defcustom org-confirm-elisp-link-function
'yes-or-no-p
1657 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1658 Elisp links can be dangerous: just think about a link
1660 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1662 This link would show up in your Org-mode document as \"Google Search\",
1663 but really it would remove your entire home directory.
1664 Therefore we advise against setting this variable to nil.
1665 Just change it to `y-or-n-p' if you want to confirm with a
1666 single keystroke rather than having to type \"yes\"."
1667 :group
'org-link-follow
1669 (const :tag
"with yes-or-no (safer)" yes-or-no-p
)
1670 (const :tag
"with y-or-n (faster)" y-or-n-p
)
1671 (const :tag
"no confirmation (dangerous)" nil
)))
1672 (put 'org-confirm-shell-link-function
1673 'safe-local-variable
1674 #'(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
1676 (defcustom org-confirm-elisp-link-not-regexp
""
1677 "A regexp to skip confirmation for Elisp links."
1678 :group
'org-link-follow
1682 (defconst org-file-apps-defaults-gnu
1686 "Default file applications on a UNIX or GNU/Linux system.
1687 See `org-file-apps'.")
1689 (defconst org-file-apps-defaults-macosx
1692 (system .
"open %s")
1694 ("eps.gz" .
"gv %s")
1696 ("fig" .
"xfig %s"))
1697 "Default file applications on a MacOS X system.
1698 The system \"open\" is known as a default, but we use X11 applications
1699 for some files for which the OS does not have a good default.
1700 See `org-file-apps'.")
1702 (defconst org-file-apps-defaults-windowsnt
1706 (list (if (featurep 'xemacs
)
1707 'mswindows-shell-execute
1711 (list (if (featurep 'xemacs
)
1712 'mswindows-shell-execute
1715 "Default file applications on a Windows NT system.
1716 The system \"open\" is used for most files.
1717 See `org-file-apps'.")
1719 (defcustom org-file-apps
1722 ("\\.mm\\'" . default
)
1723 ("\\.x?html?\\'" . default
)
1724 ("\\.pdf\\'" . default
)
1726 "External applications for opening `file:path' items in a document.
1727 Org-mode uses system defaults for different file types, but
1728 you can use this variable to set the application for a given file
1729 extension. The entries in this list are cons cells where the car identifies
1730 files and the cdr the corresponding command. Possible values for the
1732 \"string\" A string as a file identifier can be interpreted in different
1733 ways, depending on its contents:
1735 - Alphanumeric characters only:
1736 Match links with this file extension.
1737 Example: (\"pdf\" . \"evince %s\")
1738 to open PDFs with evince.
1740 - Regular expression: Match links where the
1741 filename matches the regexp. If you want to
1742 use groups here, use shy groups.
1744 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1745 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1746 to open *.html and *.xhtml with firefox.
1748 - Regular expression which contains (non-shy) groups:
1749 Match links where the whole link, including \"::\", and
1750 anything after that, matches the regexp.
1751 In a custom command string, %1, %2, etc. are replaced with
1752 the parts of the link that were matched by the groups.
1753 For backwards compatibility, if a command string is given
1754 that does not use any of the group matches, this case is
1755 handled identically to the second one (i.e. match against
1757 In a custom lisp form, you can access the group matches with
1758 (match-string n link).
1760 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1761 to open [[file:document.pdf::5]] with evince at page 5.
1763 `directory' Matches a directory
1764 `remote' Matches a remote file, accessible through tramp or efs.
1765 Remote files most likely should be visited through Emacs
1766 because external applications cannot handle such paths.
1767 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1768 so all files Emacs knows how to handle. Using this with
1769 command `emacs' will open most files in Emacs. Beware that this
1770 will also open html files inside Emacs, unless you add
1771 (\"html\" . default) to the list as well.
1772 t Default for files not matched by any of the other options.
1773 `system' The system command to open files, like `open' on Windows
1774 and Mac OS X, and mailcap under GNU/Linux. This is the command
1775 that will be selected if you call `C-c C-o' with a double
1776 \\[universal-argument] \\[universal-argument] prefix.
1778 Possible values for the command are:
1779 `emacs' The file will be visited by the current Emacs process.
1780 `default' Use the default application for this file type, which is the
1781 association for t in the list, most likely in the system-specific
1783 This can be used to overrule an unwanted setting in the
1784 system-specific variable.
1785 `system' Use the system command for opening files, like \"open\".
1786 This command is specified by the entry whose car is `system'.
1787 Most likely, the system-specific version of this variable
1788 does define this command, but you can overrule/replace it
1790 string A command to be executed by a shell; %s will be replaced
1791 by the path to the file.
1792 sexp A Lisp form which will be evaluated. The file path will
1793 be available in the Lisp variable `file'.
1794 For more examples, see the system specific constants
1795 `org-file-apps-defaults-macosx'
1796 `org-file-apps-defaults-windowsnt'
1797 `org-file-apps-defaults-gnu'."
1798 :group
'org-link-follow
1800 (cons (choice :value
""
1801 (string :tag
"Extension")
1802 (const :tag
"System command to open files" system
)
1803 (const :tag
"Default for unrecognized files" t
)
1804 (const :tag
"Remote file" remote
)
1805 (const :tag
"Links to a directory" directory
)
1806 (const :tag
"Any files that have Emacs modes"
1809 (const :tag
"Visit with Emacs" emacs
)
1810 (const :tag
"Use default" default
)
1811 (const :tag
"Use the system command" system
)
1812 (string :tag
"Command")
1813 (sexp :tag
"Lisp form")))))
1815 (defcustom org-doi-server-url
"http://dx.doi.org/"
1816 "The URL of the DOI server."
1819 :group
'org-link-follow
)
1821 (defgroup org-refile nil
1822 "Options concerning refiling entries in Org-mode."
1826 (defcustom org-directory
"~/org"
1827 "Directory with org files.
1828 This is just a default location to look for Org files. There is no need
1829 at all to put your files into this directory. It is only used in the
1830 following situations:
1832 1. When a capture template specifies a target file that is not an
1833 absolute path. The path will then be interpreted relative to
1835 2. When a capture note is filed away in an interactive way (when exiting the
1836 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1837 with `org-directory' as the default path."
1839 :group
'org-remember
1843 (defcustom org-default-notes-file
(convert-standard-filename "~/.notes")
1844 "Default target for storing notes.
1845 Used as a fall back file for org-remember.el and org-capture.el, for
1846 templates that do not specify a target file."
1848 :group
'org-remember
1851 (const :tag
"Default from remember-data-file" nil
)
1854 (defcustom org-goto-interface
'outline
1855 "The default interface to be used for `org-goto'.
1857 outline The interface shows an outline of the relevant file
1858 and the correct heading is found by moving through
1859 the outline or by searching with incremental search.
1860 outline-path-completion Headlines in the current buffer are offered via
1861 completion. This is the interface also used by
1862 the refile command."
1865 (const :tag
"Outline" outline
)
1866 (const :tag
"Outline-path-completion" outline-path-completion
)))
1868 (defcustom org-goto-max-level
5
1869 "Maximum target level when running `org-goto' with refile interface."
1873 (defcustom org-reverse-note-order nil
1874 "Non-nil means store new notes at the beginning of a file or entry.
1875 When nil, new notes will be filed to the end of a file or entry.
1876 This can also be a list with cons cells of regular expressions that
1877 are matched against file names, and values."
1878 :group
'org-remember
1882 (const :tag
"Reverse always" t
)
1883 (const :tag
"Reverse never" nil
)
1884 (repeat :tag
"By file name regexp"
1885 (cons regexp boolean
))))
1887 (defcustom org-log-refile nil
1888 "Information to record when a task is refiled.
1890 Possible values are:
1892 nil Don't add anything
1893 time Add a time stamp to the task
1894 note Prompt for a note and add it with template `org-log-note-headings'
1896 This option can also be set with on a per-file-basis with
1898 #+STARTUP: nologrefile
1899 #+STARTUP: logrefile
1900 #+STARTUP: lognoterefile
1902 You can have local logging settings for a subtree by setting the LOGGING
1903 property to one or more of these keywords.
1905 When bulk-refiling from the agenda, the value `note' is forbidden and
1906 will temporarily be changed to `time'."
1908 :group
'org-progress
1911 (const :tag
"No logging" nil
)
1912 (const :tag
"Record timestamp" time
)
1913 (const :tag
"Record timestamp with note." note
)))
1915 (defcustom org-refile-targets nil
1916 "Targets for refiling entries with \\[org-refile].
1917 This is a list of cons cells. Each cell contains:
1918 - a specification of the files to be considered, either a list of files,
1919 or a symbol whose function or variable value will be used to retrieve
1920 a file name or a list of file names. If you use `org-agenda-files' for
1921 that, all agenda files will be scanned for targets. Nil means consider
1922 headings in the current buffer.
1923 - A specification of how to find candidate refile targets. This may be
1925 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1926 This tag has to be present in all target headlines, inheritance will
1928 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1930 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1931 headlines that are refiling targets.
1932 - a cons cell (:level . N). Any headline of level N is considered a target.
1933 Note that, when `org-odd-levels-only' is set, level corresponds to
1934 order in hierarchy, not to the number of stars.
1935 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1936 Note that, when `org-odd-levels-only' is set, level corresponds to
1937 order in hierarchy, not to the number of stars.
1939 Each element of this list generates a set of possible targets.
1940 The union of these sets is presented (with completion) to
1941 the user by `org-refile'.
1943 You can set the variable `org-refile-target-verify-function' to a function
1944 to verify each headline found by the simple criteria above.
1946 When this variable is nil, all top-level headlines in the current buffer
1947 are used, equivalent to the value `((nil . (:level . 1))'."
1951 (choice :value org-agenda-files
1952 (const :tag
"All agenda files" org-agenda-files
)
1953 (const :tag
"Current buffer" nil
)
1954 (function) (variable) (file))
1955 (choice :tag
"Identify target headline by"
1956 (cons :tag
"Specific tag" (const :value
:tag
) (string))
1957 (cons :tag
"TODO keyword" (const :value
:todo
) (string))
1958 (cons :tag
"Regular expression" (const :value
:regexp
) (regexp))
1959 (cons :tag
"Level number" (const :value
:level
) (integer))
1960 (cons :tag
"Max Level number" (const :value
:maxlevel
) (integer))))))
1962 (defcustom org-refile-target-verify-function nil
1963 "Function to verify if the headline at point should be a refile target.
1964 The function will be called without arguments, with point at the
1965 beginning of the headline. It should return t and leave point
1966 where it is if the headline is a valid target for refiling.
1968 If the target should not be selected, the function must return nil.
1969 In addition to this, it may move point to a place from where the search
1970 should be continued. For example, the function may decide that the entire
1971 subtree of the current entry should be excluded and move point to the end
1976 (defcustom org-refile-use-cache nil
1977 "Non-nil means cache refile targets to speed up the process.
1978 The cache for a particular file will be updated automatically when
1979 the buffer has been killed, or when any of the marker used for flagging
1980 refile targets no longer points at a live buffer.
1981 If you have added new entries to a buffer that might themselves be targets,
1982 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1983 find that easier, `C-u C-u C-u C-c C-w'."
1988 (defcustom org-refile-use-outline-path nil
1989 "Non-nil means provide refile targets as paths.
1990 So a level 3 headline will be available as level1/level2/level3.
1992 When the value is `file', also include the file name (without directory)
1993 into the path. In this case, you can also stop the completion after
1994 the file name, to get entries inserted as top level in the file.
1996 When `full-file-path', include the full file path."
1999 (const :tag
"Not" nil
)
2000 (const :tag
"Yes" t
)
2001 (const :tag
"Start with file name" file
)
2002 (const :tag
"Start with full file path" full-file-path
)))
2004 (defcustom org-outline-path-complete-in-steps t
2005 "Non-nil means complete the outline path in hierarchical steps.
2006 When Org-mode uses the refile interface to select an outline path
2007 \(see variable `org-refile-use-outline-path'), the completion of
2008 the path can be done is a single go, or if can be done in steps down
2009 the headline hierarchy. Going in steps is probably the best if you
2010 do not use a special completion package like `ido' or `icicles'.
2011 However, when using these packages, going in one step can be very
2012 fast, while still showing the whole path to the entry."
2016 (defcustom org-refile-allow-creating-parent-nodes nil
2017 "Non-nil means allow to create new nodes as refile targets.
2018 New nodes are then created by adding \"/new node name\" to the completion
2019 of an existing node. When the value of this variable is `confirm',
2020 new node creation must be confirmed by the user (recommended)
2021 When nil, the completion must match an existing entry.
2023 Note that, if the new heading is not seen by the criteria
2024 listed in `org-refile-targets', multiple instances of the same
2025 heading would be created by trying again to file under the new
2029 (const :tag
"Never" nil
)
2030 (const :tag
"Always" t
)
2031 (const :tag
"Prompt for confirmation" confirm
)))
2033 (defcustom org-refile-active-region-within-subtree nil
2034 "Non-nil means also refile active region within a subtree.
2036 By default `org-refile' doesn't allow refiling regions if they
2037 don't contain a set of subtrees, but it might be convenient to
2038 do so sometimes: in that case, the first line of the region is
2039 converted to a headline before refiling."
2044 (defgroup org-todo nil
2045 "Options concerning TODO items in Org-mode."
2049 (defgroup org-progress nil
2050 "Options concerning Progress logging in Org-mode."
2054 (defvar org-todo-interpretation-widgets
2055 '((:tag
"Sequence (cycling hits every state)" sequence
)
2056 (:tag
"Type (cycling directly to DONE)" type
))
2057 "The available interpretation symbols for customizing `org-todo-keywords'.
2058 Interested libraries should add to this list.")
2060 (defcustom org-todo-keywords
'((sequence "TODO" "DONE"))
2061 "List of TODO entry keyword sequences and their interpretation.
2062 \\<org-mode-map>This is a list of sequences.
2064 Each sequence starts with a symbol, either `sequence' or `type',
2065 indicating if the keywords should be interpreted as a sequence of
2066 action steps, or as different types of TODO items. The first
2067 keywords are states requiring action - these states will select a headline
2068 for inclusion into the global TODO list Org-mode produces. If one of
2069 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2070 signify that no further action is necessary. If \"|\" is not found,
2071 the last keyword is treated as the only DONE state of the sequence.
2073 The command \\[org-todo] cycles an entry through these states, and one
2074 additional state where no keyword is present. For details about this
2075 cycling, see the manual.
2077 TODO keywords and interpretation can also be set on a per-file basis with
2078 the special #+SEQ_TODO and #+TYP_TODO lines.
2080 Each keyword can optionally specify a character for fast state selection
2081 \(in combination with the variable `org-use-fast-todo-selection')
2082 and specifiers for state change logging, using the same syntax that
2083 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2084 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2085 indicates to record a time stamp each time this state is selected.
2087 Each keyword may also specify if a timestamp or a note should be
2088 recorded when entering or leaving the state, by adding additional
2089 characters in the parenthesis after the keyword. This looks like this:
2090 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2091 record only the time of the state change. With X and Y being either
2092 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2093 Y when leaving the state if and only if the *target* state does not
2094 define X. You may omit any of the fast-selection key or X or /Y,
2095 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2097 For backward compatibility, this variable may also be just a list
2098 of keywords. In this case the interpretation (sequence or type) will be
2099 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2101 :group
'org-keywords
2103 (repeat :tag
"Old syntax, just keywords"
2104 (string :tag
"Keyword"))
2105 (repeat :tag
"New syntax"
2108 :tag
"Interpretation"
2109 ;;Quick and dirty way to see
2110 ;;`org-todo-interpretations'. This takes the
2111 ;;place of item arguments
2119 org-todo-interpretation-widgets
))
2122 (string :tag
"Keyword"))))))
2124 (defvar org-todo-keywords-1 nil
2125 "All TODO and DONE keywords active in a buffer.")
2126 (make-variable-buffer-local 'org-todo-keywords-1
)
2127 (defvar org-todo-keywords-for-agenda nil
)
2128 (defvar org-done-keywords-for-agenda nil
)
2129 (defvar org-drawers-for-agenda nil
)
2130 (defvar org-todo-keyword-alist-for-agenda nil
)
2131 (defvar org-tag-alist-for-agenda nil
)
2132 (defvar org-agenda-contributing-files nil
)
2133 (defvar org-not-done-keywords nil
)
2134 (make-variable-buffer-local 'org-not-done-keywords
)
2135 (defvar org-done-keywords nil
)
2136 (make-variable-buffer-local 'org-done-keywords
)
2137 (defvar org-todo-heads nil
)
2138 (make-variable-buffer-local 'org-todo-heads
)
2139 (defvar org-todo-sets nil
)
2140 (make-variable-buffer-local 'org-todo-sets
)
2141 (defvar org-todo-log-states nil
)
2142 (make-variable-buffer-local 'org-todo-log-states
)
2143 (defvar org-todo-kwd-alist nil
)
2144 (make-variable-buffer-local 'org-todo-kwd-alist
)
2145 (defvar org-todo-key-alist nil
)
2146 (make-variable-buffer-local 'org-todo-key-alist
)
2147 (defvar org-todo-key-trigger nil
)
2148 (make-variable-buffer-local 'org-todo-key-trigger
)
2150 (defcustom org-todo-interpretation
'sequence
2151 "Controls how TODO keywords are interpreted.
2152 This variable is in principle obsolete and is only used for
2153 backward compatibility, if the interpretation of todo keywords is
2154 not given already in `org-todo-keywords'. See that variable for
2157 :group
'org-keywords
2158 :type
'(choice (const sequence
)
2161 (defcustom org-use-fast-todo-selection t
2162 "Non-nil means use the fast todo selection scheme with C-c C-t.
2163 This variable describes if and under what circumstances the cycling
2164 mechanism for TODO keywords will be replaced by a single-key, direct
2167 When nil, fast selection is never used.
2169 When the symbol `prefix', it will be used when `org-todo' is called
2170 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2171 `C-u t' in an agenda buffer.
2173 When t, fast selection is used by default. In this case, the prefix
2174 argument forces cycling instead.
2176 In all cases, the special interface is only used if access keys have
2177 actually been assigned by the user, i.e. if keywords in the configuration
2178 are followed by a letter in parenthesis, like TODO(t)."
2181 (const :tag
"Never" nil
)
2182 (const :tag
"By default" t
)
2183 (const :tag
"Only with C-u C-c C-t" prefix
)))
2185 (defcustom org-provide-todo-statistics t
2186 "Non-nil means update todo statistics after insert and toggle.
2187 ALL-HEADLINES means update todo statistics by including headlines
2188 with no TODO keyword as well, counting them as not done.
2189 A list of TODO keywords means the same, but skip keywords that are
2192 When this is set, todo statistics is updated in the parent of the
2193 current entry each time a todo state is changed."
2196 (const :tag
"Yes, only for TODO entries" t
)
2197 (const :tag
"Yes, including all entries" 'all-headlines
)
2198 (repeat :tag
"Yes, for TODOs in this list"
2199 (string :tag
"TODO keyword"))
2200 (other :tag
"No TODO statistics" nil
)))
2202 (defcustom org-hierarchical-todo-statistics t
2203 "Non-nil means TODO statistics covers just direct children.
2204 When nil, all entries in the subtree are considered.
2205 This has only an effect if `org-provide-todo-statistics' is set.
2206 To set this to nil for only a single subtree, use a COOKIE_DATA
2207 property and include the word \"recursive\" into the value."
2211 (defcustom org-after-todo-state-change-hook nil
2212 "Hook which is run after the state of a TODO item was changed.
2213 The new state (a string with a TODO keyword, or nil) is available in the
2214 Lisp variable `org-state'."
2218 (defvar org-blocker-hook nil
2219 "Hook for functions that are allowed to block a state change.
2221 Each function gets as its single argument a property list, see
2222 `org-trigger-hook' for more information about this list.
2224 If any of the functions in this hook returns nil, the state change
2227 (defvar org-trigger-hook nil
2228 "Hook for functions that are triggered by a state change.
2230 Each function gets as its single argument a property list with at least
2231 the following elements:
2233 (:type type-of-change :position pos-at-entry-start
2234 :from old-state :to new-state)
2236 Depending on the type, more properties may be present.
2238 This mechanism is currently implemented for:
2242 :type todo-state-change
2243 :from previous state (keyword as a string), or nil, or a symbol
2244 'todo' or 'done', to indicate the general type of state.
2245 :to new state, like in :from")
2247 (defcustom org-enforce-todo-dependencies nil
2248 "Non-nil means undone TODO entries will block switching the parent to DONE.
2249 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2250 be blocked if any prior sibling is not yet done.
2251 Finally, if the parent is blocked because of ordered siblings of its own,
2252 the child will also be blocked."
2253 :set
(lambda (var val
)
2256 (add-hook 'org-blocker-hook
2257 'org-block-todo-from-children-or-siblings-or-parent
)
2258 (remove-hook 'org-blocker-hook
2259 'org-block-todo-from-children-or-siblings-or-parent
)))
2263 (defcustom org-enforce-todo-checkbox-dependencies nil
2264 "Non-nil means unchecked boxes will block switching the parent to DONE.
2265 When this is nil, checkboxes have no influence on switching TODO states.
2266 When non-nil, you first need to check off all check boxes before the TODO
2267 entry can be switched to DONE.
2268 This variable needs to be set before org.el is loaded, and you need to
2269 restart Emacs after a change to make the change effective. The only way
2270 to change is while Emacs is running is through the customize interface."
2271 :set
(lambda (var val
)
2274 (add-hook 'org-blocker-hook
2275 'org-block-todo-from-checkboxes
)
2276 (remove-hook 'org-blocker-hook
2277 'org-block-todo-from-checkboxes
)))
2281 (defcustom org-treat-insert-todo-heading-as-state-change nil
2282 "Non-nil means inserting a TODO heading is treated as state change.
2283 So when the command \\[org-insert-todo-heading] is used, state change
2284 logging will apply if appropriate. When nil, the new TODO item will
2285 be inserted directly, and no logging will take place."
2289 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2290 "Non-nil means switching TODO states with S-cursor counts as state change.
2291 This is the default behavior. However, setting this to nil allows a
2292 convenient way to select a TODO state and bypass any logging associated
2297 (defcustom org-todo-state-tags-triggers nil
2298 "Tag changes that should be triggered by TODO state changes.
2299 This is a list. Each entry is
2301 (state-change (tag . flag) .......)
2303 State-change can be a string with a state, and empty string to indicate the
2304 state that has no TODO keyword, or it can be one of the symbols `todo'
2305 or `done', meaning any not-done or done state, respectively."
2309 (cons (choice :tag
"When changing to"
2310 (const :tag
"Not-done state" todo
)
2311 (const :tag
"Done state" done
)
2312 (string :tag
"State"))
2314 (cons :tag
"Tag action"
2316 (choice (const :tag
"Add" t
) (const :tag
"Remove" nil
)))))))
2318 (defcustom org-log-done nil
2319 "Information to record when a task moves to the DONE state.
2321 Possible values are:
2323 nil Don't add anything, just change the keyword
2324 time Add a time stamp to the task
2325 note Prompt for a note and add it with template `org-log-note-headings'
2327 This option can also be set with on a per-file-basis with
2329 #+STARTUP: nologdone
2331 #+STARTUP: lognotedone
2333 You can have local logging settings for a subtree by setting the LOGGING
2334 property to one or more of these keywords."
2336 :group
'org-progress
2338 (const :tag
"No logging" nil
)
2339 (const :tag
"Record CLOSED timestamp" time
)
2340 (const :tag
"Record CLOSED timestamp with note." note
)))
2342 ;; Normalize old uses of org-log-done.
2344 ((eq org-log-done t
) (setq org-log-done
'time
))
2345 ((and (listp org-log-done
) (memq 'done org-log-done
))
2346 (setq org-log-done
'note
)))
2348 (defcustom org-log-reschedule nil
2349 "Information to record when the scheduling date of a tasks is modified.
2351 Possible values are:
2353 nil Don't add anything, just change the date
2354 time Add a time stamp to the task
2355 note Prompt for a note and add it with template `org-log-note-headings'
2357 This option can also be set with on a per-file-basis with
2359 #+STARTUP: nologreschedule
2360 #+STARTUP: logreschedule
2361 #+STARTUP: lognotereschedule"
2363 :group
'org-progress
2365 (const :tag
"No logging" nil
)
2366 (const :tag
"Record timestamp" time
)
2367 (const :tag
"Record timestamp with note." note
)))
2369 (defcustom org-log-redeadline nil
2370 "Information to record when the deadline date of a tasks is modified.
2372 Possible values are:
2374 nil Don't add anything, just change the date
2375 time Add a time stamp to the task
2376 note Prompt for a note and add it with template `org-log-note-headings'
2378 This option can also be set with on a per-file-basis with
2380 #+STARTUP: nologredeadline
2381 #+STARTUP: logredeadline
2382 #+STARTUP: lognoteredeadline
2384 You can have local logging settings for a subtree by setting the LOGGING
2385 property to one or more of these keywords."
2387 :group
'org-progress
2389 (const :tag
"No logging" nil
)
2390 (const :tag
"Record timestamp" time
)
2391 (const :tag
"Record timestamp with note." note
)))
2393 (defcustom org-log-note-clock-out nil
2394 "Non-nil means record a note when clocking out of an item.
2395 This can also be configured on a per-file basis by adding one of
2396 the following lines anywhere in the buffer:
2398 #+STARTUP: lognoteclock-out
2399 #+STARTUP: nolognoteclock-out"
2401 :group
'org-progress
2404 (defcustom org-log-done-with-time t
2405 "Non-nil means the CLOSED time stamp will contain date and time.
2406 When nil, only the date will be recorded."
2407 :group
'org-progress
2410 (defcustom org-log-note-headings
2411 '((done .
"CLOSING NOTE %t")
2412 (state .
"State %-12s from %-12S %t")
2413 (note .
"Note taken on %t")
2414 (reschedule .
"Rescheduled from %S on %t")
2415 (delschedule .
"Not scheduled, was %S on %t")
2416 (redeadline .
"New deadline from %S on %t")
2417 (deldeadline .
"Removed deadline, was %S on %t")
2418 (refile .
"Refiled on %t")
2420 "Headings for notes added to entries.
2421 The value is an alist, with the car being a symbol indicating the note
2422 context, and the cdr is the heading to be used. The heading may also be the
2424 %t in the heading will be replaced by a time stamp.
2425 %T will be an active time stamp instead the default inactive one
2426 %d will be replaced by a short-format time stamp.
2427 %D will be replaced by an active short-format time stamp.
2428 %s will be replaced by the new TODO state, in double quotes.
2429 %S will be replaced by the old TODO state, in double quotes.
2430 %u will be replaced by the user name.
2431 %U will be replaced by the full user name.
2433 In fact, it is not a good idea to change the `state' entry, because
2434 agenda log mode depends on the format of these entries."
2436 :group
'org-progress
2437 :type
'(list :greedy t
2438 (cons (const :tag
"Heading when closing an item" done
) string
)
2440 "Heading when changing todo state (todo sequence only)"
2442 (cons (const :tag
"Heading when just taking a note" note
) string
)
2443 (cons (const :tag
"Heading when clocking out" clock-out
) string
)
2444 (cons (const :tag
"Heading when an item is no longer scheduled" delschedule
) string
)
2445 (cons (const :tag
"Heading when rescheduling" reschedule
) string
)
2446 (cons (const :tag
"Heading when changing deadline" redeadline
) string
)
2447 (cons (const :tag
"Heading when deleting a deadline" deldeadline
) string
)
2448 (cons (const :tag
"Heading when refiling" refile
) string
)))
2450 (unless (assq 'note org-log-note-headings
)
2451 (push '(note .
"%t") org-log-note-headings
))
2453 (defcustom org-log-into-drawer nil
2454 "Non-nil means insert state change notes and time stamps into a drawer.
2455 When nil, state changes notes will be inserted after the headline and
2456 any scheduling and clock lines, but not inside a drawer.
2458 The value of this variable should be the name of the drawer to use.
2459 LOGBOOK is proposed as the default drawer for this purpose, you can
2460 also set this to a string to define the drawer of your choice.
2462 A value of t is also allowed, representing \"LOGBOOK\".
2464 If this variable is set, `org-log-state-notes-insert-after-drawers'
2467 You can set the property LOG_INTO_DRAWER to overrule this setting for
2470 :group
'org-progress
2472 (const :tag
"Not into a drawer" nil
)
2473 (const :tag
"LOGBOOK" t
)
2474 (string :tag
"Other")))
2476 (if (fboundp 'defvaralias
)
2477 (defvaralias 'org-log-state-notes-into-drawer
'org-log-into-drawer
))
2479 (defun org-log-into-drawer ()
2480 "Return the value of `org-log-into-drawer', but let properties overrule.
2481 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2482 used instead of the default value."
2483 (let ((p (org-entry-get nil
"LOG_INTO_DRAWER" 'inherit
)))
2485 ((or (not p
) (equal p
"nil")) org-log-into-drawer
)
2486 ((equal p
"t") "LOGBOOK")
2489 (defcustom org-log-state-notes-insert-after-drawers nil
2490 "Non-nil means insert state change notes after any drawers in entry.
2491 Only the drawers that *immediately* follow the headline and the
2492 deadline/scheduled line are skipped.
2493 When nil, insert notes right after the heading and perhaps the line
2494 with deadline/scheduling if present.
2496 This variable will have no effect if `org-log-into-drawer' is
2499 :group
'org-progress
2502 (defcustom org-log-states-order-reversed t
2503 "Non-nil means the latest state note will be directly after heading.
2504 When nil, the state change notes will be ordered according to time."
2506 :group
'org-progress
2509 (defcustom org-todo-repeat-to-state nil
2510 "The TODO state to which a repeater should return the repeating task.
2511 By default this is the first task in a TODO sequence, or the previous state
2512 in a TODO_TYP set. But you can specify another task here.
2513 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2516 :type
'(choice (const :tag
"Head of sequence" nil
)
2517 (string :tag
"Specific state")))
2519 (defcustom org-log-repeat
'time
2520 "Non-nil means record moving through the DONE state when triggering repeat.
2521 An auto-repeating task is immediately switched back to TODO when
2522 marked DONE. If you are not logging state changes (by adding \"@\"
2523 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2524 record a closing note, there will be no record of the task moving
2525 through DONE. This variable forces taking a note anyway.
2527 nil Don't force a record
2528 time Record a time stamp
2529 note Prompt for a note and add it with template `org-log-note-headings'
2531 This option can also be set with on a per-file-basis with
2533 #+STARTUP: nologrepeat
2534 #+STARTUP: logrepeat
2535 #+STARTUP: lognoterepeat
2537 You can have local logging settings for a subtree by setting the LOGGING
2538 property to one or more of these keywords."
2540 :group
'org-progress
2542 (const :tag
"Don't force a record" nil
)
2543 (const :tag
"Force recording the DONE state" time
)
2544 (const :tag
"Force recording a note with the DONE state" note
)))
2547 (defgroup org-priorities nil
2548 "Priorities in Org-mode."
2549 :tag
"Org Priorities"
2552 (defcustom org-enable-priority-commands t
2553 "Non-nil means priority commands are active.
2554 When nil, these commands will be disabled, so that you never accidentally
2556 :group
'org-priorities
2559 (defcustom org-highest-priority ?A
2560 "The highest priority of TODO items. A character like ?A, ?B etc.
2561 Must have a smaller ASCII number than `org-lowest-priority'."
2562 :group
'org-priorities
2565 (defcustom org-lowest-priority ?C
2566 "The lowest priority of TODO items. A character like ?A, ?B etc.
2567 Must have a larger ASCII number than `org-highest-priority'."
2568 :group
'org-priorities
2571 (defcustom org-default-priority ?B
2572 "The default priority of TODO items.
2573 This is the priority an item gets if no explicit priority is given.
2574 When starting to cycle on an empty priority the first step in the cycle
2575 depends on `org-priority-start-cycle-with-default'. The resulting first
2576 step priority must not exceed the range from `org-highest-priority' to
2577 `org-lowest-priority' which means that `org-default-priority' has to be
2578 in this range exclusive or inclusive the range boundaries. Else the
2579 first step refuses to set the default and the second will fall back
2580 to (depending on the command used) the highest or lowest priority."
2581 :group
'org-priorities
2584 (defcustom org-priority-start-cycle-with-default t
2585 "Non-nil means start with default priority when starting to cycle.
2586 When this is nil, the first step in the cycle will be (depending on the
2587 command used) one higher or lower than the default priority.
2588 See also `org-default-priority'."
2589 :group
'org-priorities
2592 (defcustom org-get-priority-function nil
2593 "Function to extract the priority from a string.
2594 The string is normally the headline. If this is nil Org computes the
2595 priority from the priority cookie like [#A] in the headline. It returns
2596 an integer, increasing by 1000 for each priority level.
2597 The user can set a different function here, which should take a string
2598 as an argument and return the numeric priority."
2599 :group
'org-priorities
2603 (defgroup org-time nil
2604 "Options concerning time stamps and deadlines in Org-mode."
2608 (defcustom org-insert-labeled-timestamps-at-point nil
2609 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2610 When nil, these labeled time stamps are forces into the second line of an
2611 entry, just after the headline. When scheduling from the global TODO list,
2612 the time stamp will always be forced into the second line."
2616 (defconst org-time-stamp-formats
'("<%Y-%m-%d %a>" .
"<%Y-%m-%d %a %H:%M>")
2617 "Formats for `format-time-string' which are used for time stamps.
2618 It is not recommended to change this constant.")
2620 (defcustom org-time-stamp-rounding-minutes
'(0 5)
2621 "Number of minutes to round time stamps to.
2622 These are two values, the first applies when first creating a time stamp.
2623 The second applies when changing it with the commands `S-up' and `S-down'.
2624 When changing the time stamp, this means that it will change in steps
2625 of N minutes, as given by the second value.
2627 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2628 numbers should be factors of 60, so for example 5, 10, 15.
2630 When this is larger than 1, you can still force an exact time stamp by using
2631 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2632 and by using a prefix arg to `S-up/down' to specify the exact number
2633 of minutes to shift."
2635 :get
#'(lambda (var) ; Make sure both elements are there
2636 (if (integerp (default-value var
))
2637 (list (default-value var
) 5)
2638 (default-value var
)))
2640 (integer :tag
"when inserting times")
2641 (integer :tag
"when modifying times")))
2643 ;; Normalize old customizations of this variable.
2644 (when (integerp org-time-stamp-rounding-minutes
)
2645 (setq org-time-stamp-rounding-minutes
2646 (list org-time-stamp-rounding-minutes
2647 org-time-stamp-rounding-minutes
)))
2649 (defcustom org-display-custom-times nil
2650 "Non-nil means overlay custom formats over all time stamps.
2651 The formats are defined through the variable `org-time-stamp-custom-formats'.
2652 To turn this on on a per-file basis, insert anywhere in the file:
2653 #+STARTUP: customtime"
2657 (make-variable-buffer-local 'org-display-custom-times
)
2659 (defcustom org-time-stamp-custom-formats
2660 '("<%m/%d/%y %a>" .
"<%m/%d/%y %a %H:%M>") ; american
2661 "Custom formats for time stamps. See `format-time-string' for the syntax.
2662 These are overlaid over the default ISO format if the variable
2663 `org-display-custom-times' is set. Time like %H:%M should be at the
2664 end of the second format. The custom formats are also honored by export
2665 commands, if custom time display is turned on at the time of export."
2669 (defun org-time-stamp-format (&optional long inactive
)
2670 "Get the right format for a time string."
2671 (let ((f (if long
(cdr org-time-stamp-formats
)
2672 (car org-time-stamp-formats
))))
2674 (concat "[" (substring f
1 -
1) "]")
2677 (defcustom org-time-clocksum-format
"%d:%02d"
2678 "The format string used when creating CLOCKSUM lines.
2679 This is also used when org-mode generates a time duration."
2683 (defcustom org-time-clocksum-use-fractional nil
2684 "If non-nil, \\[org-clock-display] uses fractional times.
2685 org-mode generates a time duration."
2689 (defcustom org-time-clocksum-fractional-format
"%.2f"
2690 "The format string used when creating CLOCKSUM lines, or when
2691 org-mode generates a time duration."
2695 (defcustom org-deadline-warning-days
14
2696 "No. of days before expiration during which a deadline becomes active.
2697 This variable governs the display in sparse trees and in the agenda.
2698 When 0 or negative, it means use this number (the absolute value of it)
2699 even if a deadline has a different individual lead time specified.
2701 Custom commands can set this variable in the options section."
2703 :group
'org-agenda-daily
/weekly
2706 (defcustom org-read-date-prefer-future t
2707 "Non-nil means assume future for incomplete date input from user.
2708 This affects the following situations:
2709 1. The user gives a month but not a year.
2710 For example, if it is April and you enter \"feb 2\", this will be read
2711 as Feb 2, *next* year. \"May 5\", however, will be this year.
2712 2. The user gives a day, but no month.
2713 For example, if today is the 15th, and you enter \"3\", Org-mode will
2714 read this as the third of *next* month. However, if you enter \"17\",
2715 it will be considered as *this* month.
2717 If you set this variable to the symbol `time', then also the following
2720 3. If the user gives a time.
2721 If the time is before now, it will be interpreted as tomorrow.
2723 Currently none of this works for ISO week specifications.
2725 When this option is nil, the current day, month and year will always be
2728 See also `org-agenda-jump-prefer-future'."
2731 (const :tag
"Never" nil
)
2732 (const :tag
"Check month and day" t
)
2733 (const :tag
"Check month, day, and time" time
)))
2735 (defcustom org-agenda-jump-prefer-future
'org-read-date-prefer-future
2736 "Should the agenda jump command prefer the future for incomplete dates?
2737 The default is to do the same as configured in `org-read-date-prefer-future'.
2738 But you can also set a deviating value here.
2739 This may t or nil, or the symbol `org-read-date-prefer-future'."
2744 (const :tag
"Use org-read-date-prefer-future"
2745 org-read-date-prefer-future
)
2746 (const :tag
"Never" nil
)
2747 (const :tag
"Always" t
)))
2749 (defcustom org-read-date-force-compatible-dates t
2750 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2752 Depending on the system Emacs is running on, certain dates cannot
2753 be represented with the type used internally to represent time.
2754 Dates between 1970-1-1 and 2038-1-1 can always be represented
2755 correctly. Some systems allow for earlier dates, some for later,
2756 some for both. One way to find out it to insert any date into an
2757 Org buffer, putting the cursor on the year and hitting S-up and
2758 S-down to test the range.
2760 When this variable is set to t, the date/time prompt will not let
2761 you specify dates outside the 1970-2037 range, so it is certain that
2762 these dates will work in whatever version of Emacs you are
2763 running, and also that you can move a file from one Emacs implementation
2764 to another. WHenever Org is forcing the year for you, it will display
2767 When this variable is nil, Org will check if the date is
2768 representable in the specific Emacs implementation you are using.
2769 If not, it will force a year, usually the current year, and beep
2770 to remind you. Currently this setting is not recommended because
2771 the likelihood that you will open your Org files in an Emacs that
2772 has limited date range is not negligible.
2774 A workaround for this problem is to use diary sexp dates for time
2775 stamps outside of this range."
2780 (defcustom org-read-date-display-live t
2781 "Non-nil means display current interpretation of date prompt live.
2782 This display will be in an overlay, in the minibuffer."
2786 (defcustom org-read-date-popup-calendar t
2787 "Non-nil means pop up a calendar when prompting for a date.
2788 In the calendar, the date can be selected with mouse-1. However, the
2789 minibuffer will also be active, and you can simply enter the date as well.
2790 When nil, only the minibuffer will be available."
2793 (if (fboundp 'defvaralias
)
2794 (defvaralias 'org-popup-calendar-for-date-prompt
2795 'org-read-date-popup-calendar
))
2797 (defcustom org-read-date-minibuffer-setup-hook nil
2798 "Hook to be used to set up keys for the date/time interface.
2799 Add key definitions to `minibuffer-local-map', which will be a temporary
2804 (defcustom org-extend-today-until
0
2805 "The hour when your day really ends. Must be an integer.
2806 This has influence for the following applications:
2807 - When switching the agenda to \"today\". It it is still earlier than
2808 the time given here, the day recognized as TODAY is actually yesterday.
2809 - When a date is read from the user and it is still before the time given
2810 here, the current date and time will be assumed to be yesterday, 23:59.
2811 Also, timestamps inserted in capture templates follow this rule.
2813 IMPORTANT: This is a feature whose implementation is and likely will
2814 remain incomplete. Really, it is only here because past midnight seems to
2815 be the favorite working time of John Wiegley :-)"
2819 (defcustom org-use-effective-time nil
2820 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2821 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2822 \"effective time\" of any timestamps between midnight and 8am will be
2823 23:59 of the previous day."
2828 (defcustom org-edit-timestamp-down-means-later nil
2829 "Non-nil means S-down will increase the time in a time stamp.
2830 When nil, S-up will increase."
2834 (defcustom org-calendar-follow-timestamp-change t
2835 "Non-nil means make the calendar window follow timestamp changes.
2836 When a timestamp is modified and the calendar window is visible, it will be
2837 moved to the new date."
2841 (defgroup org-tags nil
2842 "Options concerning tags in Org-mode."
2846 (defcustom org-tag-alist nil
2847 "List of tags allowed in Org-mode files.
2848 When this list is nil, Org-mode will base TAG input on what is already in the
2850 The value of this variable is an alist, the car of each entry must be a
2851 keyword as a string, the cdr may be a character that is used to select
2852 that tag through the fast-tag-selection interface.
2853 See the manual for details."
2857 (cons (string :tag
"Tag name")
2858 (character :tag
"Access char"))
2859 (list :tag
"Start radio group"
2861 (option (string :tag
"Group description")))
2862 (list :tag
"End radio group"
2864 (option (string :tag
"Group description")))
2865 (const :tag
"New line" (:newline
)))))
2867 (defcustom org-tag-persistent-alist nil
2868 "List of tags that will always appear in all Org-mode files.
2869 This is in addition to any in buffer settings or customizations
2871 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2872 The value of this variable is an alist, the car of each entry must be a
2873 keyword as a string, the cdr may be a character that is used to select
2874 that tag through the fast-tag-selection interface.
2875 See the manual for details.
2876 To disable these tags on a per-file basis, insert anywhere in the file:
2881 (cons (string :tag
"Tag name")
2882 (character :tag
"Access char"))
2883 (const :tag
"Start radio group" (:startgroup
))
2884 (const :tag
"End radio group" (:endgroup
))
2885 (const :tag
"New line" (:newline
)))))
2887 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2888 "If non-nil, always offer completion for all tags of all agenda files.
2889 Instead of customizing this variable directly, you might want to
2890 set it locally for capture buffers, because there no list of
2891 tags in that file can be created dynamically (there are none).
2893 (add-hook 'org-capture-mode-hook
2895 (set (make-local-variable
2896 'org-complete-tags-always-offer-all-agenda-tags)
2902 (defvar org-file-tags nil
2903 "List of tags that can be inherited by all entries in the file.
2904 The tags will be inherited if the variable `org-use-tag-inheritance'
2905 says they should be.
2906 This variable is populated from #+FILETAGS lines.")
2908 (defcustom org-use-fast-tag-selection
'auto
2909 "Non-nil means use fast tag selection scheme.
2910 This is a special interface to select and deselect tags with single keys.
2911 When nil, fast selection is never used.
2912 When the symbol `auto', fast selection is used if and only if selection
2913 characters for tags have been configured, either through the variable
2914 `org-tag-alist' or through a #+TAGS line in the buffer.
2915 When t, fast selection is always used and selection keys are assigned
2916 automatically if necessary."
2919 (const :tag
"Always" t
)
2920 (const :tag
"Never" nil
)
2921 (const :tag
"When selection characters are configured" 'auto
)))
2923 (defcustom org-fast-tag-selection-single-key nil
2924 "Non-nil means fast tag selection exits after first change.
2925 When nil, you have to press RET to exit it.
2926 During fast tag selection, you can toggle this flag with `C-c'.
2927 This variable can also have the value `expert'. In this case, the window
2928 displaying the tags menu is not even shown, until you press C-c again."
2931 (const :tag
"No" nil
)
2932 (const :tag
"Yes" t
)
2933 (const :tag
"Expert" expert
)))
2935 (defvar org-fast-tag-selection-include-todo nil
2936 "Non-nil means fast tags selection interface will also offer TODO states.
2937 This is an undocumented feature, you should not rely on it.")
2939 (defcustom org-tags-column
(if (featurep 'xemacs
) -
76 -
77)
2940 "The column to which tags should be indented in a headline.
2941 If this number is positive, it specifies the column. If it is negative,
2942 it means that the tags should be flushright to that column. For example,
2943 -80 works well for a normal 80 character screen.
2944 When 0, place tags directly after headline text, with only one space in
2949 (defcustom org-auto-align-tags t
2950 "Non-nil keeps tags aligned when modifying headlines.
2951 Some operations (i.e. demoting) change the length of a headline and
2952 therefore shift the tags around. With this option turned on, after
2953 each such operation the tags are again aligned to `org-tags-column'."
2957 (defcustom org-use-tag-inheritance t
2958 "Non-nil means tags in levels apply also for sublevels.
2959 When nil, only the tags directly given in a specific line apply there.
2960 This may also be a list of tags that should be inherited, or a regexp that
2961 matches tags that should be inherited. Additional control is possible
2962 with the variable `org-tags-exclude-from-inheritance' which gives an
2963 explicit list of tags to be excluded from inheritance., even if the value of
2964 `org-use-tag-inheritance' would select it for inheritance.
2966 If this option is t, a match early-on in a tree can lead to a large
2967 number of matches in the subtree when constructing the agenda or creating
2968 a sparse tree. If you only want to see the first match in a tree during
2969 a search, check out the variable `org-tags-match-list-sublevels'."
2972 (const :tag
"Not" nil
)
2973 (const :tag
"Always" t
)
2974 (repeat :tag
"Specific tags" (string :tag
"Tag"))
2975 (regexp :tag
"Tags matched by regexp")))
2977 (defcustom org-tags-exclude-from-inheritance nil
2978 "List of tags that should never be inherited.
2979 This is a way to exclude a few tags from inheritance. For way to do
2980 the opposite, to actively allow inheritance for selected tags,
2981 see the variable `org-use-tag-inheritance'."
2983 :type
'(repeat (string :tag
"Tag")))
2985 (defun org-tag-inherit-p (tag)
2986 "Check if TAG is one that should be inherited."
2988 ((member tag org-tags-exclude-from-inheritance
) nil
)
2989 ((eq org-use-tag-inheritance t
) t
)
2990 ((not org-use-tag-inheritance
) nil
)
2991 ((stringp org-use-tag-inheritance
)
2992 (string-match org-use-tag-inheritance tag
))
2993 ((listp org-use-tag-inheritance
)
2994 (member tag org-use-tag-inheritance
))
2995 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2997 (defcustom org-tags-match-list-sublevels t
2998 "Non-nil means list also sublevels of headlines matching a search.
2999 This variable applies to tags/property searches, and also to stuck
3000 projects because this search is based on a tags match as well.
3002 When set to the symbol `indented', sublevels are indented with
3005 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3006 the sublevels of a headline matching a tag search often also match
3007 the same search. Listing all of them can create very long lists.
3008 Setting this variable to nil causes subtrees of a match to be skipped.
3010 This variable is semi-obsolete and probably should always be true. It
3011 is better to limit inheritance to certain tags using the variables
3012 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3015 (const :tag
"No, don't list them" nil
)
3016 (const :tag
"Yes, do list them" t
)
3017 (const :tag
"List them, indented with leading dots" indented
)))
3019 (defcustom org-tags-sort-function nil
3020 "When set, tags are sorted using this function as a comparator."
3023 (const :tag
"No sorting" nil
)
3024 (const :tag
"Alphabetical" string
<)
3025 (const :tag
"Reverse alphabetical" string
>)
3026 (function :tag
"Custom function" nil
)))
3028 (defvar org-tags-history nil
3029 "History of minibuffer reads for tags.")
3030 (defvar org-last-tags-completion-table nil
3031 "The last used completion table for tags.")
3032 (defvar org-after-tags-change-hook nil
3033 "Hook that is run after the tags in a line have changed.")
3035 (defgroup org-properties nil
3036 "Options concerning properties in Org-mode."
3037 :tag
"Org Properties"
3040 (defcustom org-property-format
"%-10s %s"
3041 "How property key/value pairs should be formatted by `indent-line'.
3042 When `indent-line' hits a property definition, it will format the line
3043 according to this format, mainly to make sure that the values are
3044 lined-up with respect to each other."
3045 :group
'org-properties
3048 (defcustom org-properties-postprocess-alist nil
3049 "Alist of properties and functions to adjust inserted values.
3050 Elements of this alist must be of the form
3052 ([string] [function])
3054 where [string] must be a property name and [function] must be a
3055 lambda expression: this lambda expression must take one argument,
3056 the value to adjust, and return the new value as a string.
3058 For example, this element will allow the property \"Remaining\"
3059 to be updated wrt the relation between the \"Effort\" property
3060 and the clock summary:
3062 ((\"Remaining\" (lambda(value)
3063 (let ((clocksum (org-clock-sum-current-item))
3064 (effort (org-duration-string-to-minutes
3065 (org-entry-get (point) \"Effort\"))))
3066 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3067 :group
'org-properties
3069 :type
'(alist :key-type
(string :tag
"Property")
3070 :value-type
(function :tag
"Function")))
3072 (defcustom org-use-property-inheritance nil
3073 "Non-nil means properties apply also for sublevels.
3075 This setting is chiefly used during property searches. Turning it on can
3076 cause significant overhead when doing a search, which is why it is not
3079 When nil, only the properties directly given in the current entry count.
3080 When t, every property is inherited. The value may also be a list of
3081 properties that should have inheritance, or a regular expression matching
3082 properties that should be inherited.
3084 However, note that some special properties use inheritance under special
3085 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3086 and the properties ending in \"_ALL\" when they are used as descriptor
3087 for valid values of a property.
3089 Note for programmers:
3090 When querying an entry with `org-entry-get', you can control if inheritance
3091 should be used. By default, `org-entry-get' looks only at the local
3092 properties. You can request inheritance by setting the inherit argument
3093 to t (to force inheritance) or to `selective' (to respect the setting
3095 :group
'org-properties
3097 (const :tag
"Not" nil
)
3098 (const :tag
"Always" t
)
3099 (repeat :tag
"Specific properties" (string :tag
"Property"))
3100 (regexp :tag
"Properties matched by regexp")))
3102 (defun org-property-inherit-p (property)
3103 "Check if PROPERTY is one that should be inherited."
3105 ((eq org-use-property-inheritance t
) t
)
3106 ((not org-use-property-inheritance
) nil
)
3107 ((stringp org-use-property-inheritance
)
3108 (string-match org-use-property-inheritance property
))
3109 ((listp org-use-property-inheritance
)
3110 (member property org-use-property-inheritance
))
3111 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3113 (defcustom org-columns-default-format
"%25ITEM %TODO %3PRIORITY %TAGS"
3114 "The default column format, if no other format has been defined.
3115 This variable can be set on the per-file basis by inserting a line
3117 #+COLUMNS: %25ITEM ....."
3118 :group
'org-properties
3121 (defcustom org-columns-ellipses
".."
3122 "The ellipses to be used when a field in column view is truncated.
3123 When this is the empty string, as many characters as possible are shown,
3124 but then there will be no visual indication that the field has been truncated.
3125 When this is a string of length N, the last N characters of a truncated
3126 field are replaced by this string. If the column is narrower than the
3127 ellipses string, only part of the ellipses string will be shown."
3128 :group
'org-properties
3131 (defcustom org-columns-modify-value-for-display-function nil
3132 "Function that modifies values for display in column view.
3133 For example, it can be used to cut out a certain part from a time stamp.
3134 The function must take 2 arguments:
3136 column-title The title of the column (*not* the property name)
3137 value The value that should be modified.
3139 The function should return the value that should be displayed,
3140 or nil if the normal value should be used."
3141 :group
'org-properties
3144 (defcustom org-effort-property
"Effort"
3145 "The property that is being used to keep track of effort estimates.
3146 Effort estimates given in this property need to have the format H:MM."
3147 :group
'org-properties
3148 :group
'org-progress
3149 :type
'(string :tag
"Property"))
3151 (defconst org-global-properties-fixed
3152 '(("VISIBILITY_ALL" .
"folded children content all")
3153 ("CLOCK_MODELINE_TOTAL_ALL" .
"current today repeat all auto"))
3154 "List of property/value pairs that can be inherited by any entry.
3156 These are fixed values, for the preset properties. The user variable
3157 that can be used to add to this list is `org-global-properties'.
3159 The entries in this list are cons cells where the car is a property
3160 name and cdr is a string with the value. If the value represents
3161 multiple items like an \"_ALL\" property, separate the items by
3164 (defcustom org-global-properties nil
3165 "List of property/value pairs that can be inherited by any entry.
3167 This list will be combined with the constant `org-global-properties-fixed'.
3169 The entries in this list are cons cells where the car is a property
3170 name and cdr is a string with the value.
3172 You can set buffer-local values for the same purpose in the variable
3173 `org-file-properties' this by adding lines like
3175 #+PROPERTY: NAME VALUE"
3176 :group
'org-properties
3178 (cons (string :tag
"Property")
3179 (string :tag
"Value"))))
3181 (defvar org-file-properties nil
3182 "List of property/value pairs that can be inherited by any entry.
3183 Valid for the current buffer.
3184 This variable is populated from #+PROPERTY lines.")
3185 (make-variable-buffer-local 'org-file-properties
)
3187 (defgroup org-agenda nil
3188 "Options concerning agenda views in Org-mode."
3192 (defvar org-category nil
3193 "Variable used by org files to set a category for agenda display.
3194 Such files should use a file variable to set it, for example
3196 # -*- mode: org; org-category: \"ELisp\"
3198 or contain a special line
3202 If the file does not specify a category, then file's base name
3204 (make-variable-buffer-local 'org-category
)
3205 (put 'org-category
'safe-local-variable
#'(lambda (x) (or (symbolp x
) (stringp x
))))
3207 (defcustom org-agenda-files nil
3208 "The files to be used for agenda display.
3209 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3210 \\[org-remove-file]. You can also use customize to edit the list.
3212 If an entry is a directory, all files in that directory that are matched by
3213 `org-agenda-file-regexp' will be part of the file list.
3215 If the value of the variable is not a list but a single file name, then
3216 the list of agenda files is actually stored and maintained in that file, one
3217 agenda file per line. In this file paths can be given relative to
3218 `org-directory'. Tilde expansion and environment variable substitution
3222 (repeat :tag
"List of files and directories" file
)
3223 (file :tag
"Store list in a file\n" :value
"~/.agenda_files")))
3225 (defcustom org-agenda-file-regexp
"\\`[^.].*\\.org\\'"
3226 "Regular expression to match files for `org-agenda-files'.
3227 If any element in the list in that variable contains a directory instead
3228 of a normal file, all files in that directory that are matched by this
3229 regular expression will be included."
3233 (defcustom org-agenda-text-search-extra-files nil
3234 "List of extra files to be searched by text search commands.
3235 These files will be search in addition to the agenda files by the
3236 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3237 Note that these files will only be searched for text search commands,
3238 not for the other agenda views like todo lists, tag searches or the weekly
3239 agenda. This variable is intended to list notes and possibly archive files
3240 that should also be searched by these two commands.
3241 In fact, if the first element in the list is the symbol `agenda-archives',
3242 than all archive files of all agenda files will be added to the search
3245 :type
'(set :greedy t
3246 (const :tag
"Agenda Archives" agenda-archives
)
3247 (repeat :inline t
(file))))
3249 (if (fboundp 'defvaralias
)
3250 (defvaralias 'org-agenda-multi-occur-extra-files
3251 'org-agenda-text-search-extra-files
))
3253 (defcustom org-agenda-skip-unavailable-files nil
3254 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3255 A nil value means to remove them, after a query, from the list."
3259 (defcustom org-calendar-to-agenda-key
[?c
]
3260 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3261 The command `org-calendar-goto-agenda' will be bound to this key. The
3262 default is the character `c' because then `c' can be used to switch back and
3263 forth between agenda and calendar."
3267 (defcustom org-calendar-agenda-action-key
[?k
]
3268 "The key to be installed in `calendar-mode-map' for agenda-action.
3269 The command `org-agenda-action' will be bound to this key. The
3270 default is the character `k' because we use the same key in the agenda."
3274 (defcustom org-calendar-insert-diary-entry-key
[?i
]
3275 "The key to be installed in `calendar-mode-map' for adding diary entries.
3276 This option is irrelevant until `org-agenda-diary-file' has been configured
3277 to point to an Org-mode file. When that is the case, the command
3278 `org-agenda-diary-entry' will be bound to the key given here, by default
3279 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3280 if you want to continue doing this, you need to change this to a different
3285 (defcustom org-agenda-diary-file
'diary-file
3286 "File to which to add new entries with the `i' key in agenda and calendar.
3287 When this is the symbol `diary-file', the functionality in the Emacs
3288 calendar will be used to add entries to the `diary-file'. But when this
3289 points to a file, `org-agenda-diary-entry' will be used instead."
3292 (const :tag
"The standard Emacs diary file" diary-file
)
3293 (file :tag
"Special Org file diary entries")))
3295 (eval-after-load "calendar"
3297 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3298 'org-calendar-goto-agenda
)
3299 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3301 (add-hook 'calendar-mode-hook
3303 (unless (eq org-agenda-diary-file
'diary-file
)
3304 (define-key calendar-mode-map
3305 org-calendar-insert-diary-entry-key
3306 'org-agenda-diary-entry
))))))
3308 (defgroup org-latex nil
3309 "Options for embedding LaTeX code into Org-mode."
3313 (defcustom org-format-latex-options
3314 '(:foreground default
:background default
:scale
1.0
3315 :html-foreground
"Black" :html-background
"Transparent"
3316 :html-scale
1.0 :matchers
("begin" "$1" "$" "$$" "\\(" "\\["))
3317 "Options for creating images from LaTeX fragments.
3318 This is a property list with the following properties:
3319 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3320 `default' means use the foreground of the default face.
3321 :background the background color, or \"Transparent\".
3322 `default' means use the background of the default face.
3323 :scale a scaling factor for the size of the images, to get more pixels
3324 :html-foreground, :html-background, :html-scale
3325 the same numbers for HTML export.
3326 :matchers a list indicating which matchers should be used to
3327 find LaTeX fragments. Valid members of this list are:
3328 \"begin\" find environments
3329 \"$1\" find single characters surrounded by $.$
3330 \"$\" find math expressions surrounded by $...$
3331 \"$$\" find math expressions surrounded by $$....$$
3332 \"\\(\" find math expressions surrounded by \\(...\\)
3333 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3337 (defcustom org-format-latex-signal-error t
3338 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3339 When nil, just push out a message."
3344 (defcustom org-latex-to-mathml-jar-file nil
3345 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3346 Use this to specify additional executable file say a jar file.
3348 When using MathToWeb as the converter, specify the full-path to
3349 your mathtoweb.jar file."
3353 (const :tag
"None" nil
)
3354 (file :tag
"JAR file" :must-match t
)))
3356 (defcustom org-latex-to-mathml-convert-command nil
3357 "Command to convert LaTeX fragments to MathML.
3358 Replace format-specifiers in the command as noted below and use
3359 `shell-command' to convert LaTeX to MathML.
3360 %j: Executable file in fully expanded form as specified by
3361 `org-latex-to-mathml-jar-file'.
3362 %I: Input LaTeX file in fully expanded form
3363 %o: Output MathML file
3364 This command is used by `org-create-math-formula'.
3366 When using MathToWeb as the converter, set this to
3367 \"java -jar %j -unicode -force -df %o %I\"."
3371 (const :tag
"None" nil
)
3372 (string :tag
"\nShell command")))
3374 (defcustom org-latex-create-formula-image-program
'dvipng
3375 "Program to convert LaTeX fragments with.
3377 dvipng Process the LaTeX fragments to dvi file, then convert
3378 dvi files to png files using dvipng.
3379 This will also include processing of non-math environments.
3380 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3381 to convert pdf files to png files"
3385 (const :tag
"dvipng" dvipng
)
3386 (const :tag
"imagemagick" imagemagick
)))
3388 (defcustom org-latex-preview-ltxpng-directory
"ltxpng/"
3389 "Path to store latex preview images. A relative path here creates many
3390 directories relative to the processed org files paths. An absolute path
3391 puts all preview images at the same place."
3396 (defun org-format-latex-mathml-available-p ()
3397 "Return t if `org-latex-to-mathml-convert-command' is usable."
3399 (when (and (boundp 'org-latex-to-mathml-convert-command
)
3400 org-latex-to-mathml-convert-command
)
3401 (let ((executable (car (split-string
3402 org-latex-to-mathml-convert-command
))))
3403 (when (executable-find executable
)
3405 "%j" org-latex-to-mathml-convert-command
)
3406 (file-readable-p org-latex-to-mathml-jar-file
)
3409 (defcustom org-format-latex-header
"\\documentclass{article}
3410 \\usepackage[usenames]{color}
3411 \\usepackage{amsmath}
3412 \\usepackage[mathscr]{eucal}
3413 \\pagestyle{empty} % do not remove
3416 % The settings below are copied from fullpage.sty
3417 \\setlength{\\textwidth}{\\paperwidth}
3418 \\addtolength{\\textwidth}{-3cm}
3419 \\setlength{\\oddsidemargin}{1.5cm}
3420 \\addtolength{\\oddsidemargin}{-2.54cm}
3421 \\setlength{\\evensidemargin}{\\oddsidemargin}
3422 \\setlength{\\textheight}{\\paperheight}
3423 \\addtolength{\\textheight}{-\\headheight}
3424 \\addtolength{\\textheight}{-\\headsep}
3425 \\addtolength{\\textheight}{-\\footskip}
3426 \\addtolength{\\textheight}{-3cm}
3427 \\setlength{\\topmargin}{1.5cm}
3428 \\addtolength{\\topmargin}{-2.54cm}"
3429 "The document header used for processing LaTeX fragments.
3430 It is imperative that this header make sure that no page number
3431 appears on the page. The package defined in the variables
3432 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3433 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3438 (defvar org-format-latex-header-extra nil
)
3440 (defun org-set-packages-alist (var val
)
3441 "Set the packages alist and make sure it has 3 elements per entry."
3442 (set var
(mapcar (lambda (x)
3443 (if (and (consp x
) (= (length x
) 2))
3444 (list (car x
) (nth 1 x
) t
)
3448 (defun org-get-packages-alist (var)
3450 "Get the packages alist and make sure it has 3 elements per entry."
3452 (if (and (consp x
) (= (length x
) 2))
3453 (list (car x
) (nth 1 x
) t
)
3455 (default-value var
)))
3457 ;; The following variables are defined here because is it also used
3458 ;; when formatting latex fragments. Originally it was part of the
3459 ;; LaTeX exporter, which is why the name includes "export".
3460 (defcustom org-export-latex-default-packages-alist
3461 '(("AUTO" "inputenc" t
)
3465 ("" "longtable" nil
)
3477 "Alist of default packages to be inserted in the header.
3478 Change this only if one of the packages here causes an incompatibility
3479 with another package you are using.
3480 The packages in this list are needed by one part or another of Org-mode
3481 to function properly.
3483 - inputenc, fontenc: for basic font and character selection
3484 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3485 for interpreting the entities in `org-entities'. You can skip some of these
3486 packages if you don't use any of the symbols in it.
3487 - graphicx: for including images
3488 - float, wrapfig: for figure placement
3489 - longtable: for long tables
3490 - hyperref: for cross references
3492 Therefore you should not modify this variable unless you know what you
3493 are doing. The one reason to change it anyway is that you might be loading
3494 some other package that conflicts with one of the default packages.
3495 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3496 If SNIPPET-FLAG is t, the package also needs to be included when
3497 compiling LaTeX snippets into images for inclusion into HTML."
3498 :group
'org-export-latex
3499 :set
'org-set-packages-alist
3500 :get
'org-get-packages-alist
3504 (list :tag
"options/package pair"
3505 (string :tag
"options")
3506 (string :tag
"package")
3507 (boolean :tag
"Snippet"))
3508 (string :tag
"A line of LaTeX"))))
3510 (defcustom org-export-latex-packages-alist nil
3511 "Alist of packages to be inserted in every LaTeX header.
3512 These will be inserted after `org-export-latex-default-packages-alist'.
3513 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3514 SNIPPET-FLAG, when t, indicates that this package is also needed when
3515 turning LaTeX snippets into images for inclusion into HTML.
3516 Make sure that you only list packages here which:
3517 - you want in every file
3518 - do not conflict with the default packages in
3519 `org-export-latex-default-packages-alist'
3520 - do not conflict with the setup in `org-format-latex-header'."
3521 :group
'org-export-latex
3522 :set
'org-set-packages-alist
3523 :get
'org-get-packages-alist
3526 (list :tag
"options/package pair"
3527 (string :tag
"options")
3528 (string :tag
"package")
3529 (boolean :tag
"Snippet"))
3530 (string :tag
"A line of LaTeX"))))
3533 (defgroup org-appearance nil
3534 "Settings for Org-mode appearance."
3535 :tag
"Org Appearance"
3538 (defcustom org-level-color-stars-only nil
3539 "Non-nil means fontify only the stars in each headline.
3540 When nil, the entire headline is fontified.
3541 Changing it requires restart of `font-lock-mode' to become effective
3542 also in regions already fontified."
3543 :group
'org-appearance
3546 (defcustom org-hide-leading-stars nil
3547 "Non-nil means hide the first N-1 stars in a headline.
3548 This works by using the face `org-hide' for these stars. This
3549 face is white for a light background, and black for a dark
3550 background. You may have to customize the face `org-hide' to
3552 Changing it requires restart of `font-lock-mode' to become effective
3553 also in regions already fontified.
3554 You may also set this on a per-file basis by adding one of the following
3555 lines to the buffer:
3557 #+STARTUP: hidestars
3558 #+STARTUP: showstars"
3559 :group
'org-appearance
3562 (defcustom org-hidden-keywords nil
3563 "List of symbols corresponding to keywords to be hidden the org buffer.
3564 For example, a value '(title) for this list will make the document's title
3565 appear in the buffer without the initial #+TITLE: keyword."
3566 :group
'org-appearance
3568 :type
'(set (const :tag
"#+AUTHOR" author
)
3569 (const :tag
"#+DATE" date
)
3570 (const :tag
"#+EMAIL" email
)
3571 (const :tag
"#+TITLE" title
)))
3573 (defcustom org-custom-properties nil
3574 "List of properties (as strings) with a special meaning.
3575 The default use of these custom properties is to let the user
3576 hide them with `org-toggle-custom-properties-visibility'."
3577 :group
'org-properties
3578 :group
'org-appearance
3580 :type
'(repeat (string :tag
"Property Name")))
3582 (defcustom org-fontify-done-headline nil
3583 "Non-nil means change the face of a headline if it is marked DONE.
3584 Normally, only the TODO/DONE keyword indicates the state of a headline.
3585 When this is non-nil, the headline after the keyword is set to the
3586 `org-headline-done' as an additional indication."
3587 :group
'org-appearance
3590 (defcustom org-fontify-emphasized-text t
3591 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3592 Changing this variable requires a restart of Emacs to take effect."
3593 :group
'org-appearance
3596 (defcustom org-fontify-whole-heading-line nil
3597 "Non-nil means fontify the whole line for headings.
3598 This is useful when setting a background color for the
3600 :group
'org-appearance
3603 (defcustom org-highlight-latex-fragments-and-specials nil
3604 "Non-nil means fontify what is treated specially by the exporters."
3605 :group
'org-appearance
3608 (defcustom org-hide-emphasis-markers nil
3609 "Non-nil mean font-lock should hide the emphasis marker characters."
3610 :group
'org-appearance
3613 (defcustom org-pretty-entities nil
3614 "Non-nil means show entities as UTF8 characters.
3615 When nil, the \\name form remains in the buffer."
3616 :group
'org-appearance
3620 (defcustom org-pretty-entities-include-sub-superscripts t
3621 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3622 :group
'org-appearance
3626 (defvar org-emph-re nil
3627 "Regular expression for matching emphasis.
3628 After a match, the match groups contain these elements:
3629 0 The match of the full regular expression, including the characters
3630 before and after the proper match
3631 1 The character before the proper match, or empty at beginning of line
3632 2 The proper match, including the leading and trailing markers
3633 3 The leading marker like * or /, indicating the type of highlighting
3634 4 The text between the emphasis markers, not including the markers
3635 5 The character after the match, empty at the end of a line")
3636 (defvar org-verbatim-re nil
3637 "Regular expression for matching verbatim text.")
3638 (defvar org-emphasis-regexp-components
) ; defined just below
3639 (defvar org-emphasis-alist
) ; defined just below
3640 (defun org-set-emph-re (var val
)
3641 "Set variable and compute the emphasis regular expression."
3643 (when (and (boundp 'org-emphasis-alist
)
3644 (boundp 'org-emphasis-regexp-components
)
3645 org-emphasis-alist org-emphasis-regexp-components
)
3646 (let* ((e org-emphasis-regexp-components
)
3652 (body1 (concat body
"*?"))
3653 (markers (mapconcat 'car org-emphasis-alist
""))
3654 (vmarkers (mapconcat
3655 (lambda (x) (if (eq (nth 4 x
) 'verbatim
) (car x
) ""))
3656 org-emphasis-alist
"")))
3657 ;; make sure special characters appear at the right position in the class
3658 (if (string-match "\\^" markers
)
3659 (setq markers
(concat (replace-match "" t t markers
) "^")))
3660 (if (string-match "-" markers
)
3661 (setq markers
(concat (replace-match "" t t markers
) "-")))
3662 (if (string-match "\\^" vmarkers
)
3663 (setq vmarkers
(concat (replace-match "" t t vmarkers
) "^")))
3664 (if (string-match "-" vmarkers
)
3665 (setq vmarkers
(concat (replace-match "" t t vmarkers
) "-")))
3667 (setq body1
(concat body1
"\\(?:\n" body
"*?\\)\\{0,"
3668 (int-to-string nl
) "\\}")))
3671 (concat "\\([" pre
"]\\|^\\)"
3673 "\\([" markers
"]\\)"
3681 "\\([" post
"]\\|$\\)"))
3682 (setq org-verbatim-re
3683 (concat "\\([" pre
"]\\|^\\)"
3685 "\\([" vmarkers
"]\\)"
3693 "\\([" post
"]\\|$\\)")))))
3695 (defcustom org-emphasis-regexp-components
3696 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3697 "Components used to build the regular expression for emphasis.
3698 This is a list with five entries. Terminology: In an emphasis string
3699 like \" *strong word* \", we call the initial space PREMATCH, the final
3700 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3701 and \"trong wor\" is the body. The different components in this variable
3702 specify what is allowed/forbidden in each part:
3704 pre Chars allowed as prematch. Beginning of line will be allowed too.
3705 post Chars allowed as postmatch. End of line will be allowed too.
3706 border The chars *forbidden* as border characters.
3707 body-regexp A regexp like \".\" to match a body character. Don't use
3708 non-shy groups here, and don't allow newline here.
3709 newline The maximum number of newlines allowed in an emphasis exp.
3711 Use customize to modify this, or restart Emacs after changing it."
3712 :group
'org-appearance
3713 :set
'org-set-emph-re
3715 (sexp :tag
"Allowed chars in pre ")
3716 (sexp :tag
"Allowed chars in post ")
3717 (sexp :tag
"Forbidden chars in border ")
3718 (sexp :tag
"Regexp for body ")
3719 (integer :tag
"number of newlines allowed")
3720 (option (boolean :tag
"Please ignore this button"))))
3722 (defcustom org-emphasis-alist
3723 `(("*" bold
"<b>" "</b>")
3724 ("/" italic
"<i>" "</i>")
3725 ("_" underline
"<span style=\"text-decoration:underline;\">" "</span>")
3726 ("=" org-code
"<code>" "</code>" verbatim
)
3727 ("~" org-verbatim
"<code>" "</code>" verbatim
)
3728 ("+" ,(if (featurep 'xemacs
) 'org-table
'(:strike-through t
))
3731 "Special syntax for emphasized text.
3732 Text starting and ending with a special character will be emphasized, for
3733 example *bold*, _underlined_ and /italic/. This variable sets the marker
3734 characters, the face to be used by font-lock for highlighting in Org-mode
3735 Emacs buffers, and the HTML tags to be used for this.
3736 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3737 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3738 Use customize to modify this, or restart Emacs after changing it."
3739 :group
'org-appearance
3740 :set
'org-set-emph-re
3743 (string :tag
"Marker character")
3745 (face :tag
"Font-lock-face")
3746 (plist :tag
"Face property list"))
3747 (string :tag
"HTML start tag")
3748 (string :tag
"HTML end tag")
3749 (option (const verbatim
)))))
3751 (defvar org-protecting-blocks
3752 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3753 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3754 This is needed for font-lock setup.")
3756 ;;; Miscellaneous options
3758 (defgroup org-completion nil
3759 "Completion in Org-mode."
3760 :tag
"Org Completion"
3763 (defcustom org-completion-use-ido nil
3764 "Non-nil means use ido completion wherever possible.
3765 Note that `ido-mode' must be active for this variable to be relevant.
3766 If you decide to turn this variable on, you might well want to turn off
3767 `org-outline-path-complete-in-steps'.
3768 See also `org-completion-use-iswitchb'."
3769 :group
'org-completion
3772 (defcustom org-completion-use-iswitchb nil
3773 "Non-nil means use iswitchb completion wherever possible.
3774 Note that `iswitchb-mode' must be active for this variable to be relevant.
3775 If you decide to turn this variable on, you might well want to turn off
3776 `org-outline-path-complete-in-steps'.
3777 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3778 :group
'org-completion
3781 (defcustom org-completion-fallback-command
'hippie-expand
3782 "The expansion command called by \\[pcomplete] in normal context.
3783 Normal means, no org-mode-specific context."
3784 :group
'org-completion
3787 ;;; Functions and variables from their packages
3788 ;; Declared here to avoid compiler warnings
3791 (defvar outline-mode-menu-heading
)
3792 (defvar outline-mode-menu-show
)
3793 (defvar outline-mode-menu-hide
)
3794 (defvar zmacs-regions
) ; XEmacs regions
3797 (defvar mark-active
)
3800 (declare-function calendar-absolute-from-iso
"cal-iso" (date))
3801 (declare-function calendar-forward-day
"cal-move" (arg))
3802 (declare-function calendar-goto-date
"cal-move" (date))
3803 (declare-function calendar-goto-today
"cal-move" ())
3804 (declare-function calendar-iso-from-absolute
"cal-iso" (date))
3805 (defvar calc-embedded-close-formula
)
3806 (defvar calc-embedded-open-formula
)
3807 (declare-function cdlatex-tab
"ext:cdlatex" ())
3808 (declare-function cdlatex-compute-tables
"ext:cdlatex" ())
3809 (declare-function dired-get-filename
"dired" (&optional localp no-error-if-not-filep
))
3810 (defvar font-lock-unfontify-region-function
)
3811 (declare-function iswitchb-read-buffer
"iswitchb"
3812 (prompt &optional default require-match start matches-set
))
3813 (defvar iswitchb-temp-buflist
)
3814 (declare-function org-gnus-follow-link
"org-gnus" (&optional group article
))
3815 (defvar org-agenda-tags-todo-honor-ignore-options
)
3816 (declare-function org-agenda-skip
"org-agenda" ())
3818 org-agenda-format-item
"org-agenda"
3819 (extra txt
&optional category tags dotime noprefix remove-re habitp
))
3820 (declare-function org-agenda-new-marker
"org-agenda" (&optional pos
))
3821 (declare-function org-agenda-change-all-lines
"org-agenda"
3822 (newhead hdmarker
&optional fixface just-this
))
3823 (declare-function org-agenda-set-restriction-lock
"org-agenda" (&optional type
))
3824 (declare-function org-agenda-maybe-redo
"org-agenda" ())
3825 (declare-function org-agenda-save-markers-for-cut-and-paste
"org-agenda"
3827 (declare-function org-agenda-copy-local-variable
"org-agenda" (var))
3828 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3829 "org-agenda" (&optional end
))
3830 (declare-function org-inlinetask-remove-END-maybe
"org-inlinetask" ())
3831 (declare-function org-inlinetask-in-task-p
"org-inlinetask" ())
3832 (declare-function org-inlinetask-goto-beginning
"org-inlinetask" ())
3833 (declare-function org-inlinetask-goto-end
"org-inlinetask" ())
3834 (declare-function org-indent-mode
"org-indent" (&optional arg
))
3835 (declare-function parse-time-string
"parse-time" (string))
3836 (declare-function org-attach-reveal
"org-attach" (&optional if-exists
))
3837 (declare-function org-export-latex-fix-inputenc
"org-latex" ())
3838 (declare-function orgtbl-send-table
"org-table" (&optional maybe
))
3839 (defvar remember-data-file
)
3840 (defvar texmathp-why
)
3841 (declare-function speedbar-line-directory
"speedbar" (&optional depth
))
3842 (declare-function table--at-cell-p
"table" (position &optional object at-column
))
3844 (defvar w3m-current-url
)
3845 (defvar w3m-current-title
)
3847 (defvar org-latex-regexps
)
3849 ;;; Autoload and prepare some org modules
3851 ;; Some table stuff that needs to be defined here, because it is used
3852 ;; by the functions setting up org-mode or checking for table context.
3854 (defconst org-table-any-line-regexp
"^[ \t]*\\(|\\|\\+-[-+]\\)"
3855 "Detect an org-type or table-type table.")
3856 (defconst org-table-line-regexp
"^[ \t]*|"
3857 "Detect an org-type table line.")
3858 (defconst org-table-dataline-regexp
"^[ \t]*|[^-]"
3859 "Detect an org-type table line.")
3860 (defconst org-table-hline-regexp
"^[ \t]*|-"
3861 "Detect an org-type table hline.")
3862 (defconst org-table1-hline-regexp
"^[ \t]*\\+-[-+]"
3863 "Detect a table-type table hline.")
3864 (defconst org-table-any-border-regexp
"^[ \t]*[^|+ \t]"
3865 "Detect the first line outside a table when searching from within it.
3866 This works for both table types.")
3868 ;; Autoload the functions in org-table.el that are needed by functions here.
3871 (org-autoload "org-table"
3872 '(org-table-align org-table-begin org-table-blank-field
3873 org-table-convert org-table-convert-region org-table-copy-down
3874 org-table-copy-region org-table-create
3875 org-table-create-or-convert-from-region
3876 org-table-create-with-table.el org-table-current-dline
3877 org-table-cut-region org-table-delete-column org-table-edit-field
3878 org-table-edit-formulas org-table-end org-table-eval-formula
3879 org-table-export org-table-field-info
3880 org-table-get-stored-formulas org-table-goto-column
3881 org-table-hline-and-move org-table-import org-table-insert-column
3882 org-table-insert-hline org-table-insert-row org-table-iterate
3883 org-table-justify-field-maybe org-table-kill-row
3884 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3885 org-table-move-column org-table-move-column-left
3886 org-table-move-column-right org-table-move-row
3887 org-table-move-row-down org-table-move-row-up
3888 org-table-next-field org-table-next-row org-table-paste-rectangle
3889 org-table-previous-field org-table-recalculate
3890 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3891 org-table-toggle-coordinate-overlays
3892 org-table-toggle-formula-debugger org-table-wrap-region
3893 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3894 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3895 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo
)))
3897 (defun org-at-table-p (&optional table-type
)
3898 "Return t if the cursor is inside an org-type table.
3899 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3900 (if org-enable-table-editor
3902 (beginning-of-line 1)
3903 (looking-at (if table-type org-table-any-line-regexp
3904 org-table-line-regexp
)))
3906 (defsubst org-table-p
() (org-at-table-p))
3908 (defun org-at-table.el-p
()
3909 "Return t if and only if we are at a table.el table."
3910 (and (org-at-table-p 'any
)
3912 (goto-char (org-table-begin 'any
))
3913 (looking-at org-table1-hline-regexp
))))
3914 (defun org-table-recognize-table.el
()
3915 "If there is a table.el table nearby, recognize it and move into it."
3916 (if org-table-tab-recognizes-table.el
3917 (if (org-at-table.el-p
)
3919 (beginning-of-line 1)
3920 (if (looking-at org-table-dataline-regexp
)
3922 (if (looking-at org-table1-hline-regexp
)
3924 (beginning-of-line 2)
3925 (if (looking-at org-table-any-border-regexp
)
3926 (beginning-of-line -
1)))))
3927 (if (re-search-forward "|" (org-table-end t
) t
)
3930 (if (table--at-cell-p (point))
3932 (message "recognizing table.el table...")
3933 (table-recognize-table)
3934 (message "recognizing table.el table...done")))
3935 (error "This should not happen"))
3940 (defun org-at-table-hline-p ()
3941 "Return t if the cursor is inside a hline in a table."
3942 (if org-enable-table-editor
3944 (beginning-of-line 1)
3945 (looking-at org-table-hline-regexp
))
3948 (defvar org-table-clean-did-remove-column nil
)
3950 (defun org-table-map-tables (function &optional quietly
)
3951 "Apply FUNCTION to the start of all tables in the buffer."
3955 (goto-char (point-min))
3956 (while (re-search-forward org-table-any-line-regexp nil t
)
3958 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3959 (beginning-of-line 1)
3960 (when (and (looking-at org-table-line-regexp
)
3961 ;; Exclude tables in src/example/verbatim/clocktable blocks
3962 (not (org-in-block-p '("src" "example"))))
3963 (save-excursion (funcall function
))
3964 (or (looking-at org-table-line-regexp
)
3966 (re-search-forward org-table-any-border-regexp nil
1))))
3967 (unless quietly
(message "Mapping tables: done")))
3969 ;; Declare and autoload functions from org-exp.el & Co
3971 (declare-function org-default-export-plist
"org-exp")
3972 (declare-function org-infile-export-plist
"org-exp")
3973 (declare-function org-get-current-options
"org-exp")
3975 (org-autoload "org-exp"
3976 '(org-export org-export-visible
3977 org-insert-export-options-template
3978 org-table-clean-before-export
))
3979 (org-autoload "org-ascii"
3980 '(org-export-as-ascii org-export-ascii-preprocess
3981 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3982 org-export-region-as-ascii
))
3983 (org-autoload "org-latex"
3984 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3985 org-replace-region-by-latex org-export-region-as-latex
3986 org-export-as-latex org-export-as-pdf
3987 org-export-as-pdf-and-open
))
3988 (org-autoload "org-html"
3989 '(org-export-as-html-and-open
3990 org-export-as-html-batch org-export-as-html-to-buffer
3991 org-replace-region-by-html org-export-region-as-html
3992 org-export-as-html
))
3993 (org-autoload "org-docbook"
3994 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3995 org-replace-region-by-docbook org-export-region-as-docbook
3996 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3997 org-export-as-docbook
))
3998 (org-autoload "org-icalendar"
3999 '(org-export-icalendar-this-file
4000 org-export-icalendar-all-agenda-files
4001 org-export-icalendar-combine-agenda-files
))
4002 (org-autoload "org-xoxo" '(org-export-as-xoxo))
4003 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning
)))
4005 ;; Declare and autoload functions from org-agenda.el
4008 (org-autoload "org-agenda"
4009 '(org-agenda org-agenda-list org-search-view
4010 org-todo-list org-tags-view org-agenda-list-stuck-projects
4011 org-diary org-agenda-to-appt
4012 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
)))
4014 ;; Autoload org-remember
4017 (org-autoload "org-remember"
4018 '(org-remember-insinuate org-remember-annotation
4019 org-remember-apply-template org-remember org-remember-handler
)))
4022 (org-autoload "org-capture"
4023 '(org-capture org-capture-insert-template-here
4024 org-capture-import-remember-templates
)))
4026 ;; Autoload org-clock.el
4028 (declare-function org-clock-save-markers-for-cut-and-paste
"org-clock"
4030 (declare-function org-clock-update-mode-line
"org-clock" ())
4031 (declare-function org-resolve-clocks
"org-clock"
4032 (&optional also-non-dangling-p prompt last-valid
))
4033 (defvar org-clock-start-time
)
4034 (defvar org-clock-marker
(make-marker)
4035 "Marker recording the last clock-in.")
4036 (defvar org-clock-hd-marker
(make-marker)
4037 "Marker recording the last clock-in, but the headline position.")
4038 (defvar org-clock-heading
""
4039 "The heading of the current clock entry.")
4040 (defun org-clock-is-active ()
4041 "Return non-nil if clock is currently running.
4042 The return value is actually the clock marker."
4043 (marker-buffer org-clock-marker
))
4048 '(org-clock-in org-clock-out org-clock-cancel
4049 org-clock-goto org-clock-sum org-clock-display
4050 org-clock-remove-overlays org-clock-report
4051 org-clocktable-shift org-dblock-write
:clocktable
4052 org-get-clocktable org-resolve-clocks
)))
4054 (defun org-clock-update-time-maybe ()
4055 "If this is a CLOCK line, update it and return t.
4056 Otherwise, return nil."
4059 (beginning-of-line 1)
4060 (skip-chars-forward " \t")
4061 (when (looking-at org-clock-string
)
4062 (let ((re (concat "[ \t]*" org-clock-string
4063 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4064 "\\([ \t]*=>.*\\)?\\)?"))
4067 ((not (looking-at re
))
4069 ((not (match-end 2))
4070 (when (and (equal (marker-buffer org-clock-marker
) (current-buffer))
4071 (> org-clock-marker
(point))
4072 (<= org-clock-marker
(point-at-eol)))
4073 ;; The clock is running here
4074 (setq org-clock-start-time
4076 (org-parse-time-string (match-string 1))))
4077 (org-clock-update-mode-line)))
4079 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4081 (setq ts
(match-string 1)
4082 te
(match-string 3))
4083 (setq s
(- (org-float-time
4084 (apply 'encode-time
(org-parse-time-string te
)))
4086 (apply 'encode-time
(org-parse-time-string ts
))))
4089 h
(floor (/ s
3600))
4093 (insert " => " (format (if neg
"-%d:%02d" "%2d:%02d") h m
))
4096 (defun org-check-running-clock ()
4097 "Check if the current buffer contains the running clock.
4098 If yes, offer to stop it and to save the buffer with the changes."
4099 (when (and (equal (marker-buffer org-clock-marker
) (current-buffer))
4100 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4103 (when (y-or-n-p "Save changed buffer?")
4106 (defun org-clocktable-try-shift (dir n
)
4107 "Check if this line starts a clock table, if yes, shift the time block."
4108 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4109 (org-clocktable-shift dir n
)))
4111 ;; Autoload org-timer.el
4116 '(org-timer-start org-timer org-timer-item
4117 org-timer-change-times-in-region
4119 org-timer-reset-timers
4120 org-timer-show-remaining-time
)))
4122 ;; Autoload org-feed.el
4127 '(org-feed-update org-feed-update-all org-feed-goto-inbox
)))
4130 ;; Autoload org-indent.el
4132 ;; Define the variable already here, to make sure we have it.
4133 (defvar org-indent-mode nil
4134 "Non-nil if Org-Indent mode is enabled.
4135 Use the command `org-indent-mode' to change this variable.")
4140 '(org-indent-mode)))
4142 ;; Autoload org-mobile.el
4147 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda
)))
4149 ;; Autoload archiving code
4150 ;; The stuff that is needed for cycling and tags has to be defined here.
4152 (defgroup org-archive nil
4153 "Options concerning archiving in Org-mode."
4155 :group
'org-structure
)
4157 (defcustom org-archive-location
"%s_archive::"
4158 "The location where subtrees should be archived.
4160 The value of this variable is a string, consisting of two parts,
4161 separated by a double-colon. The first part is a filename and
4162 the second part is a headline.
4164 When the filename is omitted, archiving happens in the same file.
4165 %s in the filename will be replaced by the current file
4166 name (without the directory part). Archiving to a different file
4167 is useful to keep archived entries from contributing to the
4170 The archived entries will be filed as subtrees of the specified
4171 headline. When the headline is omitted, the subtrees are simply
4172 filed away at the end of the file, as top-level entries. Also in
4173 the heading you can use %s to represent the file name, this can be
4174 useful when using the same archive for a number of different files.
4176 Here are a few examples:
4178 If the current file is Projects.org, archive in file
4179 Projects.org_archive, as top-level trees. This is the default.
4181 \"::* Archived Tasks\"
4182 Archive in the current file, under the top-level headline
4183 \"* Archived Tasks\".
4185 \"~/org/archive.org::\"
4186 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4188 \"~/org/archive.org::* From %s\"
4189 Archive in file ~/org/archive.org (absolute path), under headlines
4190 \"From FILENAME\" where file name is the current file name.
4192 \"~/org/datetree.org::datetree/* Finished Tasks\"
4193 The \"datetree/\" string is special, signifying to archive
4194 items to the datetree. Items are placed in either the CLOSED
4195 date of the item, or the current date if there is no CLOSED date.
4196 The heading will be a subentry to the current date. There doesn't
4197 need to be a heading, but there always needs to be a slash after
4198 datetree. For example, to store archived items directly in the
4199 datetree, use \"~/org/datetree.org::datetree/\".
4201 \"basement::** Finished Tasks\"
4202 Archive in file ./basement (relative path), as level 3 trees
4203 below the level 2 heading \"** Finished Tasks\".
4205 You may set this option on a per-file basis by adding to the buffer a
4208 #+ARCHIVE: basement::** Finished Tasks
4210 You may also define it locally for a subtree by setting an ARCHIVE property
4211 in the entry. If such a property is found in an entry, or anywhere up
4212 the hierarchy, it will be used."
4216 (defcustom org-archive-tag
"ARCHIVE"
4217 "The tag that marks a subtree as archived.
4218 An archived subtree does not open during visibility cycling, and does
4219 not contribute to the agenda listings.
4220 After changing this, font-lock must be restarted in the relevant buffers to
4221 get the proper fontification."
4223 :group
'org-keywords
4226 (defcustom org-agenda-skip-archived-trees t
4227 "Non-nil means the agenda will skip any items located in archived trees.
4228 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4229 variable is no longer recommended, you should leave it at the value t.
4230 Instead, use the key `v' to cycle the archives-mode in the agenda."
4232 :group
'org-agenda-skip
4235 (defcustom org-columns-skip-archived-trees t
4236 "Non-nil means ignore archived trees when creating column view."
4238 :group
'org-properties
4241 (defcustom org-cycle-open-archived-trees nil
4242 "Non-nil means `org-cycle' will open archived trees.
4243 An archived tree is a tree marked with the tag ARCHIVE.
4244 When nil, archived trees will stay folded. You can still open them with
4245 normal outline commands like `show-all', but not with the cycling commands."
4250 (defcustom org-sparse-tree-open-archived-trees nil
4251 "Non-nil means sparse tree construction shows matches in archived trees.
4252 When nil, matches in these trees are highlighted, but the trees are kept in
4255 :group
'org-sparse-trees
4258 (defcustom org-sparse-tree-default-date-type
'scheduled-or-deadline
4259 "The default date type when building a sparse tree.
4260 When this is nil, a date is a scheduled or a deadline timestamp.
4261 Otherwise, these types are allowed:
4264 active: only active timestamps (<...>)
4265 inactive: only inactive timestamps (<...)
4266 scheduled: only scheduled timestamps
4267 deadline: only deadline timestamps"
4268 :type
'(choice (const :tag
"Scheduled or deadline" 'scheduled-or-deadline
)
4269 (const :tag
"All timestamps" all
)
4270 (const :tag
"Only active timestamps" active
)
4271 (const :tag
"Only inactive timestamps" inactive
)
4272 (const :tag
"Only scheduled timestamps" scheduled
)
4273 (const :tag
"Only deadline timestamps" deadline
))
4275 :group
'org-sparse-trees
)
4277 (defun org-cycle-hide-archived-subtrees (state)
4278 "Re-hide all archived subtrees after a visibility state change."
4279 (when (and (not org-cycle-open-archived-trees
)
4280 (not (memq state
'(overview folded
))))
4282 (let* ((globalp (memq state
'(contents all
)))
4283 (beg (if globalp
(point-min) (point)))
4284 (end (if globalp
(point-max) (org-end-of-subtree t
))))
4285 (org-hide-archived-subtrees beg end
)
4287 (if (looking-at (concat ".*:" org-archive-tag
":"))
4288 (message "%s" (substitute-command-keys
4289 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4291 (defun org-force-cycle-archived ()
4292 "Cycle subtree even if it is archived."
4294 (setq this-command
'org-cycle
)
4295 (let ((org-cycle-open-archived-trees t
))
4296 (call-interactively 'org-cycle
)))
4298 (defun org-hide-archived-subtrees (beg end
)
4299 "Re-hide all archived subtrees after a visibility state change."
4301 (let* ((re (concat ":" org-archive-tag
":")))
4303 (while (re-search-forward re end t
)
4304 (when (org-at-heading-p)
4305 (org-flag-subtree t
)
4306 (org-end-of-subtree t
))))))
4308 (declare-function outline-end-of-heading
"outline" ())
4309 (declare-function outline-flag-region
"outline" (from to flag
))
4310 (defun org-flag-subtree (flag)
4312 (org-back-to-heading t
)
4313 (outline-end-of-heading)
4314 (outline-flag-region (point)
4315 (progn (org-end-of-subtree t
) (point))
4318 (defalias 'org-advertized-archive-subtree
'org-archive-subtree
)
4321 (org-autoload "org-archive"
4322 '(org-add-archive-files org-archive-subtree
4323 org-archive-to-archive-sibling org-toggle-archive-tag
4324 org-archive-subtree-default
4325 org-archive-subtree-default-with-confirmation
)))
4327 ;; Autoload Column View Code
4329 (declare-function org-columns-number-to-string
"org-colview" (n fmt
&optional printf
))
4330 (declare-function org-columns-get-format-and-top-level
"org-colview" ())
4331 (declare-function org-columns-compute
"org-colview" (property))
4333 (org-autoload (if (featurep 'xemacs
) "org-colview-xemacs" "org-colview")
4334 '(org-columns-number-to-string org-columns-get-format-and-top-level
4335 org-columns-compute org-agenda-columns org-columns-remove-overlays
4336 org-columns org-insert-columns-dblock org-dblock-write
:columnview
))
4340 (declare-function org-id-store-link
"org-id")
4341 (declare-function org-id-locations-load
"org-id")
4342 (declare-function org-id-locations-save
"org-id")
4343 (defvar org-id-track-globally
)
4344 (org-autoload "org-id"
4345 '(org-id-get-create org-id-new org-id-copy org-id-get
4346 org-id-get-with-outline-path-completion
4347 org-id-get-with-outline-drilling org-id-store-link
4348 org-id-goto org-id-find org-id-store-link
))
4350 ;; Autoload Plotting Code
4352 (org-autoload "org-plot"
4353 '(org-plot/gnuplot
))
4355 ;;; Variables for pre-computed regular expressions, all buffer local
4357 (defvar org-drawer-regexp
"^[ \t]*:PROPERTIES:[ \t]*$"
4358 "Matches first line of a hidden block.")
4359 (make-variable-buffer-local 'org-drawer-regexp
)
4360 (defvar org-todo-regexp nil
4361 "Matches any of the TODO state keywords.")
4362 (make-variable-buffer-local 'org-todo-regexp
)
4363 (defvar org-not-done-regexp nil
4364 "Matches any of the TODO state keywords except the last one.")
4365 (make-variable-buffer-local 'org-not-done-regexp
)
4366 (defvar org-not-done-heading-regexp nil
4367 "Matches a TODO headline that is not done.")
4368 (make-variable-buffer-local 'org-not-done-regexp
)
4369 (defvar org-todo-line-regexp nil
4370 "Matches a headline and puts TODO state into group 2 if present.")
4371 (make-variable-buffer-local 'org-todo-line-regexp
)
4372 (defvar org-complex-heading-regexp nil
4373 "Matches a headline and puts everything into groups:
4375 group 2: The todo keyword, maybe
4376 group 3: Priority cookie
4377 group 4: True headline
4379 (make-variable-buffer-local 'org-complex-heading-regexp
)
4380 (defvar org-complex-heading-regexp-format nil
4381 "Printf format to make regexp to match an exact headline.
4382 This regexp will match the headline of any node which has the
4383 exact headline text that is put into the format, but may have any
4384 TODO state, priority and tags.")
4385 (make-variable-buffer-local 'org-complex-heading-regexp-format
)
4386 (defvar org-todo-line-tags-regexp nil
4387 "Matches a headline and puts TODO state into group 2 if present.
4388 Also put tags into group 4 if tags are present.")
4389 (make-variable-buffer-local 'org-todo-line-tags-regexp
)
4390 (defvar org-ds-keyword-length
12
4391 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4392 (make-variable-buffer-local 'org-ds-keyword-length
)
4393 (defvar org-deadline-regexp nil
4394 "Matches the DEADLINE keyword.")
4395 (make-variable-buffer-local 'org-deadline-regexp
)
4396 (defvar org-deadline-time-regexp nil
4397 "Matches the DEADLINE keyword together with a time stamp.")
4398 (make-variable-buffer-local 'org-deadline-time-regexp
)
4399 (defvar org-deadline-line-regexp nil
4400 "Matches the DEADLINE keyword and the rest of the line.")
4401 (make-variable-buffer-local 'org-deadline-line-regexp
)
4402 (defvar org-scheduled-regexp nil
4403 "Matches the SCHEDULED keyword.")
4404 (make-variable-buffer-local 'org-scheduled-regexp
)
4405 (defvar org-scheduled-time-regexp nil
4406 "Matches the SCHEDULED keyword together with a time stamp.")
4407 (make-variable-buffer-local 'org-scheduled-time-regexp
)
4408 (defvar org-closed-time-regexp nil
4409 "Matches the CLOSED keyword together with a time stamp.")
4410 (make-variable-buffer-local 'org-closed-time-regexp
)
4412 (defvar org-keyword-time-regexp nil
4413 "Matches any of the 4 keywords, together with the time stamp.")
4414 (make-variable-buffer-local 'org-keyword-time-regexp
)
4415 (defvar org-keyword-time-not-clock-regexp nil
4416 "Matches any of the 3 keywords, together with the time stamp.")
4417 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp
)
4418 (defvar org-maybe-keyword-time-regexp nil
4419 "Matches a timestamp, possibly preceded by a keyword.")
4420 (make-variable-buffer-local 'org-maybe-keyword-time-regexp
)
4421 (defvar org-all-time-keywords nil
4422 "List of time keywords.")
4423 (make-variable-buffer-local 'org-all-time-keywords
)
4425 (defconst org-plain-time-of-day-regexp
4428 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4431 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4433 "Regular expression to match a plain time or time range.
4434 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4435 groups carry important information:
4437 1 the first time, range or not
4438 8 the second time, if it is a range.")
4440 (defconst org-plain-time-extension-regexp
4443 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4444 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4445 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4446 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4447 groups carry important information:
4450 9 minutes of duration")
4452 (defconst org-stamp-time-of-day-regexp
4454 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4455 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4457 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4458 "Regular expression to match a timestamp time or time range.
4459 After a match, the following groups carry important information:
4461 1 date plus weekday, for back referencing to make sure both times are on the same day
4462 2 the first time, range or not
4463 4 the second time, if it is a range.")
4465 (defconst org-startup-options
4466 '(("fold" org-startup-folded t
)
4467 ("overview" org-startup-folded t
)
4468 ("nofold" org-startup-folded nil
)
4469 ("showall" org-startup-folded nil
)
4470 ("showeverything" org-startup-folded showeverything
)
4471 ("content" org-startup-folded content
)
4472 ("indent" org-startup-indented t
)
4473 ("noindent" org-startup-indented nil
)
4474 ("hidestars" org-hide-leading-stars t
)
4475 ("showstars" org-hide-leading-stars nil
)
4476 ("odd" org-odd-levels-only t
)
4477 ("oddeven" org-odd-levels-only nil
)
4478 ("align" org-startup-align-all-tables t
)
4479 ("noalign" org-startup-align-all-tables nil
)
4480 ("inlineimages" org-startup-with-inline-images t
)
4481 ("noinlineimages" org-startup-with-inline-images nil
)
4482 ("customtime" org-display-custom-times t
)
4483 ("logdone" org-log-done time
)
4484 ("lognotedone" org-log-done note
)
4485 ("nologdone" org-log-done nil
)
4486 ("lognoteclock-out" org-log-note-clock-out t
)
4487 ("nolognoteclock-out" org-log-note-clock-out nil
)
4488 ("logrepeat" org-log-repeat state
)
4489 ("lognoterepeat" org-log-repeat note
)
4490 ("nologrepeat" org-log-repeat nil
)
4491 ("logreschedule" org-log-reschedule time
)
4492 ("lognotereschedule" org-log-reschedule note
)
4493 ("nologreschedule" org-log-reschedule nil
)
4494 ("logredeadline" org-log-redeadline time
)
4495 ("lognoteredeadline" org-log-redeadline note
)
4496 ("nologredeadline" org-log-redeadline nil
)
4497 ("logrefile" org-log-refile time
)
4498 ("lognoterefile" org-log-refile note
)
4499 ("nologrefile" org-log-refile nil
)
4500 ("fninline" org-footnote-define-inline t
)
4501 ("nofninline" org-footnote-define-inline nil
)
4502 ("fnlocal" org-footnote-section nil
)
4503 ("fnauto" org-footnote-auto-label t
)
4504 ("fnprompt" org-footnote-auto-label nil
)
4505 ("fnconfirm" org-footnote-auto-label confirm
)
4506 ("fnplain" org-footnote-auto-label plain
)
4507 ("fnadjust" org-footnote-auto-adjust t
)
4508 ("nofnadjust" org-footnote-auto-adjust nil
)
4509 ("constcgs" constants-unit-system cgs
)
4510 ("constSI" constants-unit-system SI
)
4511 ("noptag" org-tag-persistent-alist nil
)
4512 ("hideblocks" org-hide-block-startup t
)
4513 ("nohideblocks" org-hide-block-startup nil
)
4514 ("beamer" org-startup-with-beamer-mode t
)
4515 ("entitiespretty" org-pretty-entities t
)
4516 ("entitiesplain" org-pretty-entities nil
))
4517 "Variable associated with STARTUP options for org-mode.
4518 Each element is a list of three items: the startup options (as written
4519 in the #+STARTUP line), the corresponding variable, and the value to set
4520 this variable to if the option is found. An optional forth element PUSH
4521 means to push this value onto the list in the variable.")
4523 (defun org-update-property-plist (key val props
)
4524 "Update PROPS with KEY and VAL."
4525 (let* ((appending (string= "+" (substring key
(- (length key
) 1))))
4526 (key (if appending
(substring key
0 (- (length key
) 1)) key
))
4527 (remainder (org-remove-if (lambda (p) (string= (car p
) key
)) props
))
4528 (previous (cdr (assoc key props
))))
4530 (cons (cons key
(if previous
(concat previous
" " val
) val
)) remainder
)
4531 (cons (cons key val
) remainder
))))
4533 (defconst org-block-regexp
4534 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4535 "Regular expression for hiding blocks.")
4536 (defconst org-heading-keyword-regexp-format
4537 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4538 "Printf format for a regexp matching an headline with some keyword.
4539 This regexp will match the headline of any node which has the
4540 exact keyword that is put into the format. The keyword isn't in
4541 any group by default, but the stars and the body are.")
4542 (defconst org-heading-keyword-maybe-regexp-format
4543 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4544 "Printf format for a regexp matching an headline, possibly with some keyword.
4545 This regexp can match any headline with the specified keyword, or
4546 without a keyword. The keyword isn't in any group by default,
4547 but the stars and the body are.")
4549 (defun org-set-regexps-and-options ()
4550 "Precompute regular expressions for current buffer."
4551 (when (derived-mode-p 'org-mode
)
4552 (org-set-local 'org-todo-kwd-alist nil
)
4553 (org-set-local 'org-todo-key-alist nil
)
4554 (org-set-local 'org-todo-key-trigger nil
)
4555 (org-set-local 'org-todo-keywords-1 nil
)
4556 (org-set-local 'org-done-keywords nil
)
4557 (org-set-local 'org-todo-heads nil
)
4558 (org-set-local 'org-todo-sets nil
)
4559 (org-set-local 'org-todo-log-states nil
)
4560 (org-set-local 'org-file-properties nil
)
4561 (org-set-local 'org-file-tags nil
)
4562 (let ((re (org-make-options-regexp
4563 '("CATEGORY" "TODO" "COLUMNS"
4564 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4565 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4567 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4569 (scripts org-use-sub-superscripts
)
4570 kwds kws0 kwsa key log value cat arch tags const links hw dws
4571 tail sep kws1 prio props ftags drawers beamer-p
4572 ext-setup-or-nil setup-contents
(start 0))
4576 (goto-char (point-min))
4577 (while (or (and ext-setup-or-nil
4578 (string-match re ext-setup-or-nil start
)
4579 (setq start
(match-end 0)))
4580 (and (setq ext-setup-or-nil nil start
0)
4581 (re-search-forward re nil t
)))
4582 (setq key
(upcase (match-string 1 ext-setup-or-nil
))
4583 value
(org-match-string-no-properties 2 ext-setup-or-nil
))
4584 (if (stringp value
) (setq value
(org-trim value
)))
4586 ((equal key
"CATEGORY")
4588 ((member key
'("SEQ_TODO" "TODO"))
4589 (push (cons 'sequence
(org-split-string value splitre
)) kwds
))
4590 ((equal key
"TYP_TODO")
4591 (push (cons 'type
(org-split-string value splitre
)) kwds
))
4592 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key
)
4593 ;; general TODO-like setup
4594 (push (cons (intern (downcase (match-string 1 key
)))
4595 (org-split-string value splitre
)) kwds
))
4597 (setq tags
(append tags
(if tags
'("\\n") nil
)
4598 (org-split-string value splitre
))))
4599 ((equal key
"COLUMNS")
4600 (org-set-local 'org-columns-default-format value
))
4602 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value
)
4603 (push (cons (match-string 1 value
)
4604 (org-trim (match-string 2 value
)))
4606 ((equal key
"PRIORITIES")
4607 (setq prio
(org-split-string value
" +")))
4608 ((equal key
"PROPERTY")
4609 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value
)
4610 (setq props
(org-update-property-plist (match-string 1 value
)
4611 (match-string 2 value
)
4613 ((equal key
"FILETAGS")
4614 (when (string-match "\\S-" value
)
4619 (mapcar (lambda (x) (org-split-string x
":"))
4620 (org-split-string value
)))))))
4621 ((equal key
"DRAWERS")
4622 (setq drawers
(delete-dups (append org-drawers
(org-split-string value splitre
)))))
4623 ((equal key
"CONSTANTS")
4624 (setq const
(append const
(org-split-string value splitre
))))
4625 ((equal key
"STARTUP")
4626 (let ((opts (org-split-string value splitre
))
4628 (while (setq l
(pop opts
))
4629 (when (setq l
(assoc l org-startup-options
))
4630 (setq var
(nth 1 l
) val
(nth 2 l
))
4632 (set (make-local-variable var
) val
)
4633 (if (not (listp (symbol-value var
)))
4634 (set (make-local-variable var
) nil
))
4635 (set (make-local-variable var
) (symbol-value var
))
4636 (add-to-list var val
))))))
4637 ((equal key
"ARCHIVE")
4639 (remove-text-properties 0 (length arch
)
4640 '(face t fontified t
) arch
))
4641 ((equal key
"LATEX_CLASS")
4642 (setq beamer-p
(equal value
"beamer")))
4643 ((equal key
"OPTIONS")
4644 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value
)
4645 (setq scripts
(read (match-string 2 value
)))))
4646 ((equal key
"SETUPFILE")
4647 (setq setup-contents
(org-file-contents
4649 (org-remove-double-quotes value
))
4651 (if (not ext-setup-or-nil
)
4652 (setq ext-setup-or-nil setup-contents start
0)
4653 (setq ext-setup-or-nil
4654 (concat (substring ext-setup-or-nil
0 start
)
4655 "\n" setup-contents
"\n"
4656 (substring ext-setup-or-nil start
)))))))
4657 ;; search for property blocks
4658 (goto-char (point-min))
4659 (while (re-search-forward org-block-regexp nil t
)
4660 (when (equal "PROPERTY" (upcase (match-string 1)))
4661 (setq value
(replace-regexp-in-string
4662 "[\n\r]" " " (match-string 4)))
4663 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value
)
4664 (setq props
(org-update-property-plist (match-string 1 value
)
4665 (match-string 2 value
)
4667 (org-set-local 'org-use-sub-superscripts scripts
)
4669 (org-set-local 'org-category
(intern cat
))
4670 (push (cons "CATEGORY" cat
) props
))
4672 (if (< (length prio
) 3) (setq prio
'("A" "C" "B")))
4673 (setq prio
(mapcar 'string-to-char prio
))
4674 (org-set-local 'org-highest-priority
(nth 0 prio
))
4675 (org-set-local 'org-lowest-priority
(nth 1 prio
))
4676 (org-set-local 'org-default-priority
(nth 2 prio
)))
4677 (and props
(org-set-local 'org-file-properties
(nreverse props
)))
4678 (and ftags
(org-set-local 'org-file-tags
4679 (mapcar 'org-add-prop-inherited ftags
)))
4680 (and drawers
(org-set-local 'org-drawers drawers
))
4681 (and arch
(org-set-local 'org-archive-location arch
))
4682 (and links
(setq org-link-abbrev-alist-local
(nreverse links
)))
4683 ;; Process the TODO keywords
4685 ;; Use the global values as if they had been given locally.
4686 (setq kwds
(default-value 'org-todo-keywords
))
4687 (if (stringp (car kwds
))
4688 (setq kwds
(list (cons org-todo-interpretation
4689 (default-value 'org-todo-keywords
)))))
4690 (setq kwds
(reverse kwds
)))
4691 (setq kwds
(nreverse kwds
))
4693 (while (setq kws
(pop kwds
))
4695 (run-hook-with-args-until-success
4696 'org-todo-setup-filter-hook kws
)
4698 (setq inter
(pop kws
) sep
(member "|" kws
)
4699 kws0
(delete "|" (copy-sequence kws
))
4704 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x
)
4706 (setq kw
(match-string 1 x
)
4707 key
(and (match-end 2) (match-string 2 x
))
4708 log
(org-extract-log-state-settings x
))
4709 (push (cons kw
(and key
(string-to-char key
))) kwsa
)
4710 (and log
(push log org-todo-log-states
))
4712 (error "Invalid TODO keyword %s" x
)))
4714 kwsa
(if kwsa
(append '((:startgroup
))
4718 dws
(if sep
(org-remove-keyword-keys (cdr sep
)) (last kws1
))
4719 tail
(list inter hw
(car dws
) (org-last dws
))))
4720 (add-to-list 'org-todo-heads hw
'append
)
4721 (push kws1 org-todo-sets
)
4722 (setq org-done-keywords
(append org-done-keywords dws nil
))
4723 (setq org-todo-key-alist
(append org-todo-key-alist kwsa
))
4724 (mapc (lambda (x) (push (cons x tail
) org-todo-kwd-alist
)) kws1
)
4725 (setq org-todo-keywords-1
(append org-todo-keywords-1 kws1 nil
)))
4726 (setq org-todo-sets
(nreverse org-todo-sets
)
4727 org-todo-kwd-alist
(nreverse org-todo-kwd-alist
)
4728 org-todo-key-trigger
(delq nil
(mapcar 'cdr org-todo-key-alist
))
4729 org-todo-key-alist
(org-assign-fast-keys org-todo-key-alist
)))
4730 ;; Process the constants
4733 (while (setq e
(pop const
))
4734 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e
)
4735 (push (cons (match-string 1 e
) (match-string 2 e
)) cst
)))
4736 (setq org-table-formula-constants-local cst
)))
4738 ;; Process the tags.
4741 (while (setq e
(pop tags
))
4743 ((equal e
"{") (push '(:startgroup
) tgs
))
4744 ((equal e
"}") (push '(:endgroup
) tgs
))
4745 ((equal e
"\\n") (push '(:newline
) tgs
))
4746 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e
)
4747 (push (cons (match-string 1 e
)
4748 (string-to-char (match-string 2 e
)))
4750 (t (push (list e
) tgs
))))
4751 (org-set-local 'org-tag-alist nil
)
4752 (while (setq e
(pop tgs
))
4753 (or (and (stringp (car e
))
4754 (assoc (car e
) org-tag-alist
))
4755 (push e org-tag-alist
)))))
4757 ;; Compute the regular expressions and other local variables.
4758 ;; Using `org-outline-regexp-bol' would complicate them much,
4759 ;; because of the fixed white space at the end of that string.
4760 (if (not org-done-keywords
)
4761 (setq org-done-keywords
(and org-todo-keywords-1
4762 (list (org-last org-todo-keywords-1
)))))
4763 (setq org-ds-keyword-length
(+ 2 (max (length org-deadline-string
)
4764 (length org-scheduled-string
)
4765 (length org-clock-string
)
4766 (length org-closed-string
)))
4768 (concat "^[ \t]*:\\("
4769 (mapconcat 'regexp-quote org-drawers
"\\|")
4771 org-not-done-keywords
4772 (org-delete-all org-done-keywords
(copy-sequence org-todo-keywords-1
))
4775 (mapconcat 'regexp-quote org-todo-keywords-1
"\\|")
4779 (mapconcat 'regexp-quote org-not-done-keywords
"\\|")
4781 org-not-done-heading-regexp
4782 (format org-heading-keyword-regexp-format org-not-done-regexp
)
4783 org-todo-line-regexp
4784 (format org-heading-keyword-maybe-regexp-format org-todo-regexp
)
4785 org-complex-heading-regexp
4786 (concat "^\\(\\*+\\)"
4787 "\\(?: +" org-todo-regexp
"\\)?"
4788 "\\(?: +\\(\\[#.\\]\\)\\)?"
4789 "\\(?: +\\(.*?\\)\\)??"
4790 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4792 org-complex-heading-regexp-format
4793 (concat "^\\(\\*+\\)"
4794 "\\(?: +" org-todo-regexp
"\\)?"
4795 "\\(?: +\\(\\[#.\\]\\)\\)?"
4797 ;; Stats cookies can be stuck to body.
4798 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4800 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4802 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4804 org-todo-line-tags-regexp
4805 (concat "^\\(\\*+\\)"
4806 "\\(?: +" org-todo-regexp
"\\)?"
4807 "\\(?: +\\(.*?\\)\\)??"
4808 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4810 org-deadline-regexp
(concat "\\<" org-deadline-string
)
4811 org-deadline-time-regexp
4812 (concat "\\<" org-deadline-string
" *<\\([^>]+\\)>")
4813 org-deadline-line-regexp
4814 (concat "\\<\\(" org-deadline-string
"\\).*")
4815 org-scheduled-regexp
4816 (concat "\\<" org-scheduled-string
)
4817 org-scheduled-time-regexp
4818 (concat "\\<" org-scheduled-string
" *<\\([^>]+\\)>")
4819 org-closed-time-regexp
4820 (concat "\\<" org-closed-string
" *\\[\\([^]]+\\)\\]")
4821 org-keyword-time-regexp
4822 (concat "\\<\\(" org-scheduled-string
4823 "\\|" org-deadline-string
4824 "\\|" org-closed-string
4825 "\\|" org-clock-string
"\\)"
4826 " *[[<]\\([^]>]+\\)[]>]")
4827 org-keyword-time-not-clock-regexp
4828 (concat "\\<\\(" org-scheduled-string
4829 "\\|" org-deadline-string
4830 "\\|" org-closed-string
4832 " *[[<]\\([^]>]+\\)[]>]")
4833 org-maybe-keyword-time-regexp
4834 (concat "\\(\\<\\(" org-scheduled-string
4835 "\\|" org-deadline-string
4836 "\\|" org-closed-string
4837 "\\|" org-clock-string
"\\)\\)?"
4838 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4839 org-all-time-keywords
4840 (mapcar (lambda (w) (substring w
0 -
1))
4841 (list org-scheduled-string org-deadline-string
4842 org-clock-string org-closed-string
))
4844 (org-compute-latex-and-specials-regexp)
4845 (org-set-font-lock-defaults))))
4847 (defun org-file-contents (file &optional noerror
)
4848 "Return the contents of FILE, as a string."
4850 (not (file-readable-p file
)))
4853 (message "Cannot read file \"%s\"" file
)
4856 (error "Cannot read file \"%s\"" file
))
4858 (insert-file-contents file
)
4861 (defun org-extract-log-state-settings (x)
4862 "Extract the log state setting from a TODO keyword string.
4863 This will extract info from a string like \"WAIT(w@/!)\"."
4864 (let (kw key log1 log2
)
4865 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x
)
4866 (setq kw
(match-string 1 x
)
4867 key
(and (match-end 2) (match-string 2 x
))
4868 log1
(and (match-end 3) (match-string 3 x
))
4869 log2
(and (match-end 4) (match-string 4 x
)))
4872 (and log1
(if (equal log1
"!") 'time
'note
))
4873 (and log2
(if (equal log2
"!") 'time
'note
)))))))
4875 (defun org-remove-keyword-keys (list)
4876 "Remove a pair of parenthesis at the end of each string in LIST."
4878 (if (string-match "(.*)$" x
)
4879 (substring x
0 (match-beginning 0))
4883 (defun org-assign-fast-keys (alist)
4884 "Assign fast keys to a keyword-key alist.
4885 Respect keys that are already there."
4886 (let (new e
(alt ?
0))
4887 (while (setq e
(pop alist
))
4888 (if (or (memq (car e
) '(:newline
:endgroup
:startgroup
))
4889 (cdr e
)) ;; Key already assigned.
4891 (let ((clist (string-to-list (downcase (car e
))))
4892 (used (append new alist
)))
4893 (when (= (car clist
) ?
@)
4895 (while (and clist
(rassoc (car clist
) used
))
4898 (while (rassoc alt used
)
4900 (push (cons (car e
) (or (car clist
) alt
)) new
))))
4903 ;;; Some variables used in various places
4905 (defvar org-window-configuration nil
4906 "Used in various places to store a window configuration.")
4907 (defvar org-selected-window nil
4908 "Used in various places to store a window configuration.")
4909 (defvar org-finish-function nil
4910 "Function to be called when `C-c C-c' is used.
4911 This is for getting out of special buffers like capture.")
4914 ;; FIXME: Occasionally check by commenting these, to make sure
4915 ;; no other functions uses these, forgetting to let-bind them.
4916 (org-no-warnings (defvar entry
)) ;; unprefixed, from calendar.el
4917 (defvar org-last-state
)
4918 (org-no-warnings (defvar date
)) ;; unprefixed, from calendar.el
4920 ;; Defined somewhere in this file, but used before definition.
4921 (defvar org-entities
) ;; defined in org-entities.el
4922 (defvar org-struct-menu
)
4923 (defvar org-org-menu
)
4924 (defvar org-tbl-menu
)
4926 ;;;; Define the Org-mode
4928 ;; We use a before-change function to check if a table might need
4930 (defvar org-table-may-need-update t
4931 "Indicates that a table might need an update.
4932 This variable is set by `org-before-change-function'.
4933 `org-table-align' sets it back to nil.")
4934 (defun org-before-change-function (beg end
)
4935 "Every change indicates that a table might need an update."
4936 (setq org-table-may-need-update t
))
4937 (defvar org-mode-map
)
4938 (defvar org-inhibit-startup nil
) ; Dynamically-scoped param.
4939 (defvar org-inhibit-startup-visibility-stuff nil
) ; Dynamically-scoped param.
4940 (defvar org-agenda-keep-modes nil
) ; Dynamically-scoped param.
4941 (defvar org-inhibit-logging nil
) ; Dynamically-scoped param.
4942 (defvar org-inhibit-blocking nil
) ; Dynamically-scoped param.
4943 (defvar org-table-buffer-is-an nil
)
4945 (defvar bidi-paragraph-direction
)
4946 (defvar buffer-face-mode-face
)
4949 (if (and (not (keymapp outline-mode-map
)) (featurep 'allout
))
4950 (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"))
4951 (require 'noutline
"noutline" 'noerror
) ;; stock XEmacs does not have it
4953 ;; Other stuff we need.
4954 (require 'time-date
)
4955 (unless (fboundp 'time-subtract
) (defalias 'time-subtract
'subtract-time
))
4960 (require 'org-entities
)
4961 ;; (require 'org-compat) moved higher up in the file before it is first used
4962 (require 'org-faces
)
4964 (require 'org-pcomplete
)
4966 (require 'org-footnote
)
4973 (require 'ob-tangle
)
4974 (require 'ob-comint
)
4978 (define-derived-mode org-mode outline-mode
"Org"
4979 "Outline-based notes management and organizer, alias
4980 \"Carsten's outline-mode for keeping track of everything.\"
4982 Org-mode develops organizational tasks around a NOTES file which
4983 contains information about projects as plain text. Org-mode is
4984 implemented on top of outline-mode, which is ideal to keep the content
4985 of large files well structured. It supports ToDo items, deadlines and
4986 time stamps, which magically appear in the diary listing of the Emacs
4987 calendar. Tables are easily created with a built-in table editor.
4988 Plain text URL-like links connect to websites, emails (VM), Usenet
4989 messages (Gnus), BBDB entries, and any files related to the project.
4990 For printing and sharing of notes, an Org-mode file (or a part of it)
4991 can be exported as a structured ASCII or HTML file.
4993 The following commands are available:
4997 ;; Get rid of Outline menus, they are not needed
4998 ;; Need to do this here because define-derived-mode sets up
4999 ;; the keymap so late. Still, it is a waste to call this each time
5000 ;; we switch another buffer into org-mode.
5001 (if (featurep 'xemacs
)
5002 (when (boundp 'outline-mode-menu-heading
)
5003 ;; Assume this is Greg's port, it uses easymenu
5004 (easy-menu-remove outline-mode-menu-heading
)
5005 (easy-menu-remove outline-mode-menu-show
)
5006 (easy-menu-remove outline-mode-menu-hide
))
5007 (define-key org-mode-map
[menu-bar headings
] 'undefined
)
5008 (define-key org-mode-map
[menu-bar hide
] 'undefined
)
5009 (define-key org-mode-map
[menu-bar show
] 'undefined
))
5011 (org-load-modules-maybe)
5012 (easy-menu-add org-org-menu
)
5013 (easy-menu-add org-tbl-menu
)
5014 (org-install-agenda-files-menu)
5015 (if org-descriptive-links
(add-to-invisibility-spec '(org-link)))
5016 (add-to-invisibility-spec '(org-cwidth))
5017 (add-to-invisibility-spec '(org-hide-block . t
))
5018 (when (featurep 'xemacs
)
5019 (org-set-local 'line-move-ignore-invisible t
))
5020 (org-set-local 'outline-regexp org-outline-regexp
)
5021 (org-set-local 'outline-level
'org-outline-level
)
5022 (setq bidi-paragraph-direction
'left-to-right
)
5023 (when (and org-ellipsis
5024 (fboundp 'set-display-table-slot
) (boundp 'buffer-display-table
)
5025 (fboundp 'make-glyph-code
))
5026 (unless org-display-table
5027 (setq org-display-table
(make-display-table)))
5028 (set-display-table-slot
5031 (lambda (c) (make-glyph-code c
(and (not (stringp org-ellipsis
))
5033 (if (stringp org-ellipsis
) org-ellipsis
"..."))))
5034 (setq buffer-display-table org-display-table
))
5035 (org-set-regexps-and-options)
5036 (when (and org-tag-faces
(not org-tags-special-faces-re
))
5037 ;; tag faces set outside customize.... force initialization.
5038 (org-set-tag-faces 'org-tag-faces org-tag-faces
))
5040 (org-set-local 'calc-embedded-open-mode
"# ")
5041 (modify-syntax-entry ?
@ "w")
5042 (if org-startup-truncated
(setq truncate-lines t
))
5043 (org-set-local 'font-lock-unfontify-region-function
5044 'org-unfontify-region
)
5045 ;; Activate before-change-function
5046 (org-set-local 'org-table-may-need-update t
)
5047 (org-add-hook 'before-change-functions
'org-before-change-function nil
5049 ;; Check for running clock before killing a buffer
5050 (org-add-hook 'kill-buffer-hook
'org-check-running-clock nil
'local
)
5052 (org-set-local 'indent-line-function
'org-indent-line
)
5053 (org-set-local 'indent-region-function
'org-indent-region
)
5054 ;; Initialize radio targets.
5055 (org-update-radio-target-regexp)
5056 ;; Filling and auto-filling.
5059 (org-setup-comments-handling)
5060 ;; Beginning/end of defun
5061 (org-set-local 'beginning-of-defun-function
'org-back-to-heading
)
5062 (org-set-local 'end-of-defun-function
(lambda () (interactive) (org-end-of-subtree nil t
)))
5063 ;; Next error for sparse trees
5064 (org-set-local 'next-error-function
'org-occur-next-match
)
5065 ;; Make sure dependence stuff works reliably, even for users who set it
5067 (if org-enforce-todo-dependencies
5068 (add-hook 'org-blocker-hook
5069 'org-block-todo-from-children-or-siblings-or-parent
)
5070 (remove-hook 'org-blocker-hook
5071 'org-block-todo-from-children-or-siblings-or-parent
))
5072 (if org-enforce-todo-checkbox-dependencies
5073 (add-hook 'org-blocker-hook
5074 'org-block-todo-from-checkboxes
)
5075 (remove-hook 'org-blocker-hook
5076 'org-block-todo-from-checkboxes
))
5078 ;; Align options lines
5080 'align-mode-rules-list
5081 '((org-in-buffer-settings
5082 (regexp .
"^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5083 (modes .
'(org-mode)))))
5086 (org-set-local 'imenu-create-index-function
5087 'org-imenu-get-tree
)
5089 ;; Make isearch reveal context
5090 (if (or (featurep 'xemacs
)
5091 (not (boundp 'outline-isearch-open-invisible-function
)))
5092 ;; Emacs 21 and XEmacs make use of the hook
5093 (org-add-hook 'isearch-mode-end-hook
'org-isearch-end
'append
'local
)
5094 ;; Emacs 22 deals with this through a special variable
5095 (org-set-local 'outline-isearch-open-invisible-function
5096 (lambda (&rest ignore
) (org-show-context 'isearch
))))
5098 ;; Turn on org-beamer-mode?
5099 (and org-startup-with-beamer-mode
(org-beamer-mode 1))
5101 ;; Setup the pcomplete hooks
5102 (set (make-local-variable 'pcomplete-command-completion-function
)
5103 'org-pcomplete-initial
)
5104 (set (make-local-variable 'pcomplete-command-name-function
)
5105 'org-command-at-point
)
5106 (set (make-local-variable 'pcomplete-default-completion-function
)
5108 (set (make-local-variable 'pcomplete-parse-arguments-function
)
5109 'org-parse-arguments
)
5110 (set (make-local-variable 'pcomplete-termination-string
) "")
5111 (when (>= emacs-major-version
23)
5112 (set (make-local-variable 'buffer-face-mode-face
) 'org-default
))
5114 ;; If empty file that did not turn on org-mode automatically, make it to.
5115 (if (and org-insert-mode-line-in-empty-file
5116 (org-called-interactively-p 'any
)
5117 (= (point-min) (point-max)))
5118 (insert "# -*- mode: org -*-\n\n"))
5119 (unless org-inhibit-startup
5120 (when org-startup-align-all-tables
5121 (let ((bmp (buffer-modified-p)))
5122 (org-table-map-tables 'org-table-align
'quietly
)
5123 (set-buffer-modified-p bmp
)))
5124 (when org-startup-with-inline-images
5125 (org-display-inline-images))
5126 (when org-startup-indented
5127 (require 'org-indent
)
5128 (org-indent-mode 1))
5129 (unless org-inhibit-startup-visibility-stuff
5130 (org-set-startup-visibility)))
5131 ;; Try to set org-hide correctly
5132 (set-face-foreground 'org-hide
(org-find-invisible-foreground)))
5134 (when (fboundp 'abbrev-table-put
)
5135 (abbrev-table-put org-mode-abbrev-table
5136 :parents
(list text-mode-abbrev-table
)))
5138 (put 'org-mode
'flyspell-mode-predicate
'org-mode-flyspell-verify
)
5141 (defun org-find-invisible-foreground ()
5142 (let ((candidates (remove
5145 (face-background 'default
)
5146 (face-background 'org-default
)
5147 (cdr (assoc 'background-color default-frame-alist
))
5148 (cdr (assoc 'background-color initial-frame-alist
))
5149 (cdr (assoc 'background-color window-system-default-frame-alist
))
5150 (face-foreground 'org-hide
)))))
5151 (car (remove nil candidates
))))
5153 (defun org-current-time ()
5154 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5155 (if (> (car org-time-stamp-rounding-minutes
) 1)
5156 (let ((r (car org-time-stamp-rounding-minutes
))
5157 (time (decode-time)))
5159 (append (list 0 (* r
(floor (+ .5 (/ (float (nth 1 time
)) r
)))))
5164 "Return today date, considering `org-extend-today-until'."
5166 (time-subtract (current-time)
5167 (list 0 (* 3600 org-extend-today-until
) 0))))
5169 ;;;; Font-Lock stuff, including the activators
5171 (defvar org-mouse-map
(make-sparse-keymap))
5172 (org-defkey org-mouse-map
[mouse-2
] 'org-open-at-mouse
)
5173 (org-defkey org-mouse-map
[mouse-3
] 'org-find-file-at-mouse
)
5174 (when org-mouse-1-follows-link
5175 (org-defkey org-mouse-map
[follow-link
] 'mouse-face
))
5176 (when org-tab-follows-link
5177 (org-defkey org-mouse-map
[(tab)] 'org-open-at-point
)
5178 (org-defkey org-mouse-map
"\C-i" 'org-open-at-point
))
5180 (require 'font-lock
)
5182 (defconst org-non-link-chars
"]\t\n\r<>")
5183 (defvar org-link-types
'("http" "https" "ftp" "mailto" "file" "news"
5184 "shell" "elisp" "doi" "message"))
5185 (defvar org-link-types-re nil
5186 "Matches a link that has a url-like prefix like \"http:\"")
5187 (defvar org-link-re-with-space nil
5188 "Matches a link with spaces, optional angular brackets around it.")
5189 (defvar org-link-re-with-space2 nil
5190 "Matches a link with spaces, optional angular brackets around it.")
5191 (defvar org-link-re-with-space3 nil
5192 "Matches a link with spaces, only for internal part in bracket links.")
5193 (defvar org-angle-link-re nil
5194 "Matches link with angular brackets, spaces are allowed.")
5195 (defvar org-plain-link-re nil
5196 "Matches plain link, without spaces.")
5197 (defvar org-bracket-link-regexp nil
5198 "Matches a link in double brackets.")
5199 (defvar org-bracket-link-analytic-regexp nil
5200 "Regular expression used to analyze links.
5201 Here is what the match groups contain after a match:
5207 (defvar org-bracket-link-analytic-regexp
++ nil
5208 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5209 (defvar org-any-link-re nil
5210 "Regular expression matching any link.")
5212 (defcustom org-match-sexp-depth
3
5213 "Number of stacked braces for sub/superscript matching.
5214 This has to be set before loading org.el to be effective."
5215 :group
'org-export-translation
; ??????????????????????????/
5218 (defun org-create-multibrace-regexp (left right n
)
5219 "Create a regular expression which will match a balanced sexp.
5220 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5221 as single character strings.
5222 The regexp returned will match the entire expression including the
5223 delimiters. It will also define a single group which contains the
5224 match except for the outermost delimiters. The maximum depth of
5225 stacked delimiters is N. Escaping delimiters is not possible."
5226 (let* ((nothing (concat "[^" left right
"]*?"))
5229 (next (concat "\\(?:" nothing left nothing right
"\\)+" nothing
)))
5232 re
(concat re or next
)
5233 next
(concat "\\(?:" nothing left next right
"\\)+" nothing
)))
5234 (concat left
"\\(" re
"\\)" right
)))
5236 (defvar org-match-substring-regexp
5238 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5239 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth
) "\\)"
5241 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth
) "\\)"
5243 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5244 "The regular expression matching a sub- or superscript.")
5246 (defvar org-match-substring-with-braces-regexp
5248 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5249 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth
) "\\)"
5251 "The regular expression matching a sub- or superscript, forcing braces.")
5253 (defun org-make-link-regexps ()
5254 "Update the link regular expressions.
5255 This should be called after the variable `org-link-types' has changed."
5256 (setq org-link-types-re
5258 "\\`\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):")
5259 org-link-re-with-space
5261 "<?\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):"
5262 "\\([^" org-non-link-chars
" ]"
5263 "[^" org-non-link-chars
"]*"
5264 "[^" org-non-link-chars
" ]\\)>?")
5265 org-link-re-with-space2
5267 "<?\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):"
5268 "\\([^" org-non-link-chars
" ]"
5270 "[^" org-non-link-chars
" ]\\)>?")
5271 org-link-re-with-space3
5273 "<?\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):"
5274 "\\([^" org-non-link-chars
" ]"
5278 "<\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):"
5279 "\\([^" org-non-link-chars
" ]"
5280 "[^" org-non-link-chars
"]*"
5284 "\\<\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):"
5285 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5286 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5287 org-bracket-link-regexp
5288 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5289 org-bracket-link-analytic-regexp
5292 "\\(\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):\\)?"
5295 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5297 org-bracket-link-analytic-regexp
++
5300 "\\(\\(" (mapconcat 'regexp-quote
(cons "coderef" org-link-types
) "\\|") "\\):\\)?"
5303 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5306 (concat "\\(" org-bracket-link-regexp
"\\)\\|\\("
5307 org-angle-link-re
"\\)\\|\\("
5308 org-plain-link-re
"\\)")))
5310 (org-make-link-regexps)
5312 (defconst org-ts-regexp
"<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5313 "Regular expression for fast time stamp matching.")
5314 (defconst org-ts-regexp-both
"[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5315 "Regular expression for fast time stamp matching.")
5316 (defconst org-ts-regexp0
5317 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5318 "Regular expression matching time strings for analysis.
5319 This one does not require the space after the date, so it can be used
5320 on a string that terminates immediately after the date.")
5321 (defconst org-ts-regexp1
"\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5322 "Regular expression matching time strings for analysis.")
5323 (defconst org-ts-regexp2
(concat "<" org-ts-regexp1
"[^>\n]\\{0,16\\}>")
5324 "Regular expression matching time stamps, with groups.")
5325 (defconst org-ts-regexp3
(concat "[[<]" org-ts-regexp1
"[^]>\n]\\{0,16\\}[]>]")
5326 "Regular expression matching time stamps (also [..]), with groups.")
5327 (defconst org-tr-regexp
(concat org-ts-regexp
"--?-?" org-ts-regexp
)
5328 "Regular expression matching a time stamp range.")
5329 (defconst org-tr-regexp-both
5330 (concat org-ts-regexp-both
"--?-?" org-ts-regexp-both
)
5331 "Regular expression matching a time stamp range.")
5332 (defconst org-tsr-regexp
(concat org-ts-regexp
"\\(--?-?"
5333 org-ts-regexp
"\\)?")
5334 "Regular expression matching a time stamp or time stamp range.")
5335 (defconst org-tsr-regexp-both
(concat org-ts-regexp-both
"\\(--?-?"
5336 org-ts-regexp-both
"\\)?")
5337 "Regular expression matching a time stamp or time stamp range.
5338 The time stamps may be either active or inactive.")
5340 (defvar org-emph-face nil
)
5342 (defun org-do-emphasis-faces (limit)
5343 "Run through the buffer and add overlays to emphasized strings."
5345 (while (and (not rtn
) (re-search-forward org-emph-re limit t
))
5346 (if (not (= (char-after (match-beginning 3))
5347 (char-after (match-beginning 4))))
5350 (setq a
(assoc (match-string 3) org-emphasis-alist
))
5351 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5355 (org-remove-flyspell-overlays-in
5356 (match-beginning 0) (match-end 0)))
5357 (add-text-properties (match-beginning 2) (match-end 2)
5358 '(font-lock-multiline t org-emphasis t
))
5359 (when org-hide-emphasis-markers
5360 (add-text-properties (match-end 4) (match-beginning 5)
5361 '(invisible org-link
))
5362 (add-text-properties (match-beginning 3) (match-end 3)
5363 '(invisible org-link
)))))
5367 (defun org-emphasize (&optional char
)
5368 "Insert or change an emphasis, i.e. a font like bold or italic.
5369 If there is an active region, change that region to a new emphasis.
5370 If there is no region, just insert the marker characters and position
5371 the cursor between them.
5372 CHAR should be either the marker character, or the first character of the
5373 HTML tag associated with that emphasis. If CHAR is a space, the means
5374 to remove the emphasis of the selected region.
5375 If char is not given (for example in an interactive call) it
5376 will be prompted for."
5378 (let ((eal org-emphasis-alist
) e det
5379 (erc org-emphasis-regexp-components
)
5381 (string "") beg end move tag c s
)
5382 (if (org-region-active-p)
5383 (setq beg
(region-beginning) end
(region-end)
5384 string
(buffer-substring beg end
))
5387 (while (setq e
(pop eal
))
5388 (setq tag
(car (org-split-string (nth 2 e
) "[ <>/]+"))
5390 (push (cons c
(string-to-char (car e
))) det
)
5391 (setq prompt
(concat prompt
(format " [%s%c]%s" (car e
) c
5392 (substring tag
1)))))
5393 (setq det
(nreverse det
))
5395 (message "%s" (concat "Emphasis marker or tag:" prompt
))
5396 (setq char
(read-char-exclusive)))
5397 (setq char
(or (cdr (assoc char det
)) char
))
5398 (if (equal char ?\
)
5399 (setq s
"" move nil
)
5400 (unless (assoc (char-to-string char
) org-emphasis-alist
)
5401 (error "No such emphasis marker: \"%c\"" char
))
5402 (setq s
(char-to-string char
)))
5403 (while (and (> (length string
) 1)
5404 (equal (substring string
0 1) (substring string -
1))
5405 (assoc (substring string
0 1) org-emphasis-alist
))
5406 (setq string
(substring string
1 -
1)))
5407 (setq string
(concat s string s
))
5408 (if beg
(delete-region beg end
))
5410 (string-match (concat "[" (nth 0 erc
) "\n]")
5411 (char-to-string (char-before (point)))))
5414 (string-match (concat "[" (nth 1 erc
) "\n]")
5415 (char-to-string (char-after (point)))))
5416 (insert " ") (backward-char 1))
5418 (and move
(backward-char 1))))
5420 (defconst org-nonsticky-props
5421 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text
))
5423 (defsubst org-rear-nonsticky-at
(pos)
5424 (add-text-properties (1- pos
) pos
(list 'rear-nonsticky org-nonsticky-props
)))
5426 (defun org-activate-plain-links (limit)
5427 "Run through the buffer and add overlays to links."
5430 (when (re-search-forward (concat org-plain-link-re
) limit t
)
5431 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5432 (setq f
(get-text-property (match-beginning 0) 'face
))
5433 (if (or (eq f
'org-tag
)
5434 (and (listp f
) (memq 'org-tag f
)))
5436 (add-text-properties (match-beginning 0) (match-end 0)
5437 (list 'mouse-face
'highlight
5439 'keymap org-mouse-map
))
5440 (org-rear-nonsticky-at (match-end 0)))
5443 (defun org-activate-code (limit)
5444 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t
)
5446 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5447 (remove-text-properties (match-beginning 0) (match-end 0)
5448 '(display t invisible t intangible t
))
5451 (defcustom org-src-fontify-natively nil
5452 "When non-nil, fontify code in code blocks."
5455 :group
'org-appearance
5458 (defcustom org-allow-promoting-top-level-subtree nil
5459 "When non-nil, allow promoting a top level subtree.
5460 The leading star of the top level headline will be replaced
5464 :group
'org-appearance
)
5466 (defun org-fontify-meta-lines-and-blocks (limit)
5468 (org-fontify-meta-lines-and-blocks-1 limit
)
5469 (error (message "org-mode fontification error"))))
5471 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5472 "Fontify #+ lines and blocks, in the correct ways."
5473 (let ((case-fold-search t
))
5474 (if (re-search-forward
5475 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5477 (let ((beg (match-beginning 0))
5478 (block-start (match-end 0))
5480 (lang (match-string 7))
5481 (beg1 (line-beginning-position 2))
5482 (dc1 (downcase (match-string 2)))
5483 (dc3 (downcase (match-string 3)))
5484 end end1 quoting block-type ovl
)
5486 ((member dc1
'("+html:" "+ascii:" "+latex:" "+docbook:"))
5487 ;; a single line of backend-specific content
5488 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5489 (remove-text-properties (match-beginning 0) (match-end 0)
5490 '(display t invisible t intangible t
))
5491 (add-text-properties (match-beginning 1) (match-end 3)
5492 '(font-lock-fontified t face org-meta-line
))
5493 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5494 '(font-lock-fontified t face org-block
))
5495 ; for backend-specific code
5497 ((and (match-end 4) (equal dc3
"+begin"))
5499 (setq block-type
(downcase (match-string 5))
5500 quoting
(member block-type org-protecting-blocks
))
5501 (when (re-search-forward
5502 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5503 nil t
) ;; on purpose, we look further than LIMIT
5504 (setq end
(min (point-max) (match-end 0))
5505 end1
(min (point-max) (1- (match-beginning 0))))
5506 (setq block-end
(match-beginning 0))
5508 (remove-text-properties beg end
5509 '(display t invisible t intangible t
)))
5510 (add-text-properties
5512 '(font-lock-fontified t font-lock-multiline t
))
5513 (add-text-properties beg beg1
'(face org-meta-line
))
5514 (add-text-properties end1
(min (point-max) (1+ end
))
5515 '(face org-meta-line
)) ; for end_src
5517 ((and lang
(not (string= lang
"")) org-src-fontify-natively
)
5518 (org-src-font-lock-fontify-block lang block-start block-end
)
5519 ;; remove old background overlays
5521 (if (eq (overlay-get ov
'face
) 'org-block-background
)
5522 (delete-overlay ov
)))
5523 (overlays-at (/ (+ beg1 block-end
) 2)))
5524 ;; add a background overlay
5525 (setq ovl
(make-overlay beg1 block-end
))
5526 (overlay-put ovl
'face
'org-block-background
)
5527 (overlay-put ovl
'evaporate t
)) ;; make it go away when empty
5529 (add-text-properties beg1
(min (point-max) (1+ end1
))
5530 '(face org-block
))) ; end of source block
5531 ((not org-fontify-quote-and-verse-blocks
))
5532 ((string= block-type
"quote")
5533 (add-text-properties beg1
(min (point-max) (1+ end1
)) '(face org-quote
)))
5534 ((string= block-type
"verse")
5535 (add-text-properties beg1
(min (point-max) (1+ end1
)) '(face org-verse
))))
5536 (add-text-properties beg beg1
'(face org-block-begin-line
))
5537 (add-text-properties (min (point-max) (1+ end
)) (min (point-max) (1+ end1
))
5538 '(face org-block-end-line
))
5540 ((member dc1
'("+title:" "+author:" "+email:" "+date:"))
5541 (add-text-properties
5543 (if (member (intern (substring dc1
0 -
1)) org-hidden-keywords
)
5544 '(font-lock-fontified t invisible t
)
5545 '(font-lock-fontified t face org-document-info-keyword
)))
5546 (add-text-properties
5547 (match-beginning 6) (match-end 6)
5548 (if (string-equal dc1
"+title:")
5549 '(font-lock-fontified t face org-document-title
)
5550 '(font-lock-fontified t face org-document-info
))))
5551 ((or (equal dc1
"+results")
5552 (member dc1
'("+begin:" "+end:" "+caption:" "+label:"
5553 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5554 "+call:" "+header:" "+headers:" "+name:"))
5555 (and (match-end 4) (equal dc3
"+attr")))
5556 (add-text-properties
5558 '(font-lock-fontified t face org-meta-line
))
5560 ((member dc3
'(" " ""))
5561 (add-text-properties
5563 '(font-lock-fontified t face font-lock-comment-face
)))
5564 ((not (member (char-after beg
) '(?\ ?
\t)))
5565 ;; just any other in-buffer setting, but not indented
5566 (add-text-properties
5568 '(font-lock-fontified t face org-meta-line
))
5572 (defun org-strip-protective-commas (beg end
)
5573 "Strip protective commas between BEG and END in the current buffer."
5578 (let ((front-line (save-excursion
5580 "[^[:space:]]" end t
)
5581 (goto-char (match-beginning 0))
5583 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\)" end t
)
5584 (goto-char (match-beginning 1))
5585 (when (= (current-column) front-line
)
5586 (replace-match "" nil nil nil
1)))))))
5588 (defun org-activate-angle-links (limit)
5589 "Run through the buffer and add overlays to links."
5590 (if (re-search-forward org-angle-link-re limit t
)
5592 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5593 (add-text-properties (match-beginning 0) (match-end 0)
5594 (list 'mouse-face
'highlight
5595 'keymap org-mouse-map
))
5596 (org-rear-nonsticky-at (match-end 0))
5599 (defun org-activate-footnote-links (limit)
5600 "Run through the buffer and add overlays to footnotes."
5601 (let ((fn (org-footnote-next-reference-or-definition limit
)))
5603 (let ((beg (nth 1 fn
)) (end (nth 2 fn
)))
5604 (org-remove-flyspell-overlays-in beg end
)
5605 (add-text-properties beg end
5606 (list 'mouse-face
'highlight
5607 'keymap org-mouse-map
5609 (if (= (point-at-bol) beg
)
5610 "Footnote definition"
5611 "Footnote reference")
5612 'font-lock-fontified t
5613 'font-lock-multiline t
5614 'face
'org-footnote
))))))
5616 (defun org-activate-bracket-links (limit)
5617 "Run through the buffer and add overlays to bracketed links."
5618 (if (re-search-forward org-bracket-link-regexp limit t
)
5619 (let* ((help (concat "LINK: "
5620 (org-match-string-no-properties 1)))
5621 ;; FIXME: above we should remove the escapes.
5622 ;; but that requires another match, protecting match data,
5623 ;; a lot of overhead for font-lock.
5624 (ip (org-maybe-intangible
5625 (list 'invisible
'org-link
5626 'keymap org-mouse-map
'mouse-face
'highlight
5627 'font-lock-multiline t
'help-echo help
)))
5628 (vp (list 'keymap org-mouse-map
'mouse-face
'highlight
5629 'font-lock-multiline t
'help-echo help
)))
5630 ;; We need to remove the invisible property here. Table narrowing
5631 ;; may have made some of this invisible.
5632 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5633 (remove-text-properties (match-beginning 0) (match-end 0)
5637 (add-text-properties (match-beginning 0) (match-beginning 3) ip
)
5638 (org-rear-nonsticky-at (match-beginning 3))
5639 (add-text-properties (match-beginning 3) (match-end 3) vp
)
5640 (org-rear-nonsticky-at (match-end 3))
5641 (add-text-properties (match-end 3) (match-end 0) ip
)
5642 (org-rear-nonsticky-at (match-end 0)))
5643 (add-text-properties (match-beginning 0) (match-beginning 1) ip
)
5644 (org-rear-nonsticky-at (match-beginning 1))
5645 (add-text-properties (match-beginning 1) (match-end 1) vp
)
5646 (org-rear-nonsticky-at (match-end 1))
5647 (add-text-properties (match-end 1) (match-end 0) ip
)
5648 (org-rear-nonsticky-at (match-end 0)))
5651 (defun org-activate-dates (limit)
5652 "Run through the buffer and add overlays to dates."
5653 (if (re-search-forward org-tsr-regexp-both limit t
)
5655 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5656 (add-text-properties (match-beginning 0) (match-end 0)
5657 (list 'mouse-face
'highlight
5658 'keymap org-mouse-map
))
5659 (org-rear-nonsticky-at (match-end 0))
5660 (when org-display-custom-times
5662 (org-display-custom-time (match-beginning 3) (match-end 3)))
5663 (org-display-custom-time (match-beginning 1) (match-end 1)))
5666 (defvar org-target-link-regexp nil
5667 "Regular expression matching radio targets in plain text.")
5668 (make-variable-buffer-local 'org-target-link-regexp
)
5669 (defvar org-target-regexp
"<<\\([^<>\n\r]+\\)>>"
5670 "Regular expression matching a link target.")
5671 (defvar org-radio-target-regexp
"<<<\\([^<>\n\r]+\\)>>>"
5672 "Regular expression matching a radio target.")
5673 (defvar org-any-target-regexp
"<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5674 "Regular expression matching any target.")
5676 (defun org-activate-target-links (limit)
5677 "Run through the buffer and add overlays to target matches."
5678 (when org-target-link-regexp
5679 (let ((case-fold-search t
))
5680 (if (re-search-forward org-target-link-regexp limit t
)
5682 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5683 (add-text-properties (match-beginning 0) (match-end 0)
5684 (list 'mouse-face
'highlight
5685 'keymap org-mouse-map
5686 'help-echo
"Radio target link"
5687 'org-linked-text t
))
5688 (org-rear-nonsticky-at (match-end 0))
5691 (defun org-update-radio-target-regexp ()
5692 "Find all radio targets in this file and update the regular expression."
5694 (when (memq 'radio org-activate-links
)
5695 (setq org-target-link-regexp
5696 (org-make-target-link-regexp (org-all-targets 'radio
)))
5697 (org-restart-font-lock)))
5699 (defun org-hide-wide-columns (limit)
5701 (setq s
(text-property-any (point) (or limit
(point-max))
5704 (setq e
(next-single-property-change s
'org-cwidth
))
5705 (add-text-properties s e
(org-maybe-intangible '(invisible org-cwidth
)))
5709 (defvar org-latex-and-specials-regexp nil
5710 "Regular expression for highlighting export special stuff.")
5711 (defvar org-match-substring-regexp
)
5712 (defvar org-match-substring-with-braces-regexp
)
5714 ;; This should be with the exporter code, but we also use if for font-locking
5715 (defconst org-export-html-special-string-regexps
5716 '(("\\\\-" .
"­")
5717 ("---\\([^-]\\)" .
"—\\1")
5718 ("--\\([^-]\\)" .
"–\\1")
5719 ("\\.\\.\\." .
"…"))
5720 "Regular expressions for special string conversion.")
5723 (defun org-compute-latex-and-specials-regexp ()
5724 "Compute regular expression for stuff treated specially by exporters."
5725 (if (not org-highlight-latex-fragments-and-specials
)
5726 (org-set-local 'org-latex-and-specials-regexp nil
)
5729 ((matchers (plist-get org-format-latex-options
:matchers
))
5730 (latexs (delq nil
(mapcar (lambda (x) (if (member (car x
) matchers
) x
))
5731 org-latex-regexps
)))
5732 (org-export-allow-BIND nil
)
5733 (options (org-combine-plists (org-default-export-plist)
5734 (org-infile-export-plist)))
5735 (org-export-with-sub-superscripts (plist-get options
:sub-superscript
))
5736 (org-export-with-LaTeX-fragments (plist-get options
:LaTeX-fragments
))
5737 (org-export-with-TeX-macros (plist-get options
:TeX-macros
))
5738 (org-export-html-expand (plist-get options
:expand-quoted-html
))
5739 (org-export-with-special-strings (plist-get options
:special-strings
))
5742 ((equal org-export-with-sub-superscripts
'{})
5743 (list org-match-substring-with-braces-regexp
))
5744 (org-export-with-sub-superscripts
5745 (list org-match-substring-regexp
))))
5747 (if org-export-with-LaTeX-fragments
5748 (mapcar (lambda (x) (nth 1 x
)) latexs
)))
5750 (if org-export-with-TeX-macros
5751 (list (concat "\\\\"
5757 (append org-entities-user
5759 (if (boundp 'org-latex-entities
)
5761 (or (car-safe x
) x
))
5766 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5767 (re-special (if org-export-with-special-strings
5768 (mapcar (lambda (x) (car x
))
5769 org-export-html-special-string-regexps
)))
5773 (if org-export-html-expand
"@<[^>\n]+>")
5776 'org-latex-and-specials-regexp
5777 (mapconcat 'identity
(append re-latex re-sub re-macros re-special
5780 (defun org-do-latex-and-special-faces (limit)
5781 "Run through the buffer and add overlays to links."
5782 (when org-latex-and-specials-regexp
5784 (while (and (not rtn
) (re-search-forward org-latex-and-specials-regexp
5786 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5788 '(org-code org-verbatim underline
)))
5791 d
(cond ((member (char-after (1+ (match-beginning 0)))
5794 (font-lock-prepend-text-property
5795 (+ d
(match-beginning 0)) (match-end 0)
5796 'face
'org-latex-and-export-specials
)
5797 (add-text-properties (+ d
(match-beginning 0)) (match-end 0)
5798 '(font-lock-multiline t
)))))
5801 (defun org-restart-font-lock ()
5802 "Restart `font-lock-mode', to force refontification."
5803 (when (and (boundp 'font-lock-mode
) font-lock-mode
)
5805 (font-lock-mode 1)))
5807 (defun org-all-targets (&optional radio
)
5808 "Return a list of all targets in this file.
5809 With optional argument RADIO, only find radio targets."
5810 (let ((re (if radio org-radio-target-regexp org-target-regexp
))
5813 (goto-char (point-min))
5814 (while (re-search-forward re nil t
)
5815 (add-to-list 'rtn
(downcase (org-match-string-no-properties 1))))
5818 (defun org-make-target-link-regexp (targets)
5819 "Make regular expression matching all strings in TARGETS.
5820 The regular expression finds the targets also if there is a line break
5827 (setq x
(regexp-quote x
))
5828 (while (string-match " +" x
)
5829 (setq x
(replace-match "\\s-+" t t x
)))
5835 (defun org-activate-tags (limit)
5836 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t
)
5838 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5839 (add-text-properties (match-beginning 1) (match-end 1)
5840 (list 'mouse-face
'highlight
5841 'keymap org-mouse-map
))
5842 (org-rear-nonsticky-at (match-end 1))
5845 (defun org-outline-level ()
5846 "Compute the outline level of the heading at point.
5847 This function assumes that the cursor is at the beginning of a line matched
5848 by `outline-regexp'. Otherwise it returns garbage.
5849 If this is called at a normal headline, the level is the number of stars.
5850 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5852 (looking-at org-outline-regexp
)
5853 (1- (- (match-end 0) (match-beginning 0)))))
5855 (defvar org-font-lock-keywords nil
)
5857 (defconst org-property-re
(org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5858 "Regular expression matching a property line.")
5860 (defvar org-font-lock-hook nil
5861 "Functions to be called for special font lock stuff.")
5863 (defvar org-font-lock-set-keywords-hook nil
5864 "Functions that can manipulate `org-font-lock-extra-keywords'.
5865 This is called after `org-font-lock-extra-keywords' is defined, but before
5866 it is installed to be used by font lock. This can be useful if something
5867 needs to be inserted at a specific position in the font-lock sequence.")
5869 (defun org-font-lock-hook (limit)
5870 "Run `org-font-lock-hook' within LIMIT."
5871 (run-hook-with-args 'org-font-lock-hook limit
))
5873 (defun org-set-font-lock-defaults ()
5874 "Set font lock defaults for the current buffer."
5875 (let* ((em org-fontify-emphasized-text
)
5876 (lk org-activate-links
)
5877 (org-font-lock-extra-keywords
5880 '(org-font-lock-hook)
5882 `(,(if org-fontify-whole-heading-line
5883 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5884 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5885 (1 (org-get-level-face 1))
5886 (2 (org-get-level-face 2))
5887 (3 (org-get-level-face 3)))
5889 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5892 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t
))
5893 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t
))
5894 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t
))
5895 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t
))
5897 (list org-drawer-regexp
'(0 'org-special-keyword t
))
5898 (list "^[ \t]*:END:" '(0 'org-special-keyword t
))
5900 (list org-property-re
5901 '(1 'org-special-keyword t
)
5902 '(3 'org-property-value t
))
5904 (if (memq 'tag lk
) '(org-activate-tags (1 'org-tag prepend
)))
5905 (if (memq 'angle lk
) '(org-activate-angle-links (0 'org-link t
)))
5906 (if (memq 'plain lk
) '(org-activate-plain-links))
5907 (if (memq 'bracket lk
) '(org-activate-bracket-links (0 'org-link t
)))
5908 (if (memq 'radio lk
) '(org-activate-target-links (0 'org-link t
)))
5909 (if (memq 'date lk
) '(org-activate-dates (0 'org-date t
)))
5910 (if (memq 'footnote lk
) '(org-activate-footnote-links))
5911 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t
))
5912 '(org-hide-wide-columns (0 nil append
))
5914 (list (format org-heading-keyword-regexp-format
5916 '(2 (org-get-todo-face 2) t
))
5918 (if org-fontify-done-headline
5919 (list (format org-heading-keyword-regexp-format
5922 (mapconcat 'regexp-quote org-done-keywords
"\\|")
5924 '(2 'org-headline-done t
))
5927 '(org-font-lock-add-priority-faces)
5929 '(org-font-lock-add-tag-faces)
5931 (list (concat "\\<" org-deadline-string
) '(0 'org-special-keyword t
))
5932 (list (concat "\\<" org-scheduled-string
) '(0 'org-special-keyword t
))
5933 (list (concat "\\<" org-closed-string
) '(0 'org-special-keyword t
))
5934 (list (concat "\\<" org-clock-string
) '(0 'org-special-keyword t
))
5937 (if (featurep 'xemacs
)
5938 '(org-do-emphasis-faces (0 nil append
))
5939 '(org-do-emphasis-faces)))
5941 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5942 1 'org-checkbox prepend
)
5943 (if (cdr (assq 'checkbox org-list-automatic-rules
))
5944 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5945 (0 (org-get-checkbox-statistics-face) t
)))
5946 ;; Description list items
5947 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5948 1 'org-list-dt prepend
)
5949 ;; ARCHIVEd headings
5951 org-outline-regexp-bol
5952 "\\(.*:" org-archive-tag
":.*\\)")
5953 '(1 'org-archived prepend
))
5955 '(org-do-latex-and-special-faces)
5956 '(org-fontify-entities)
5957 '(org-raise-scripts)
5959 '(org-activate-code (1 'org-code t
))
5961 (list (format org-heading-keyword-regexp-format
5963 org-comment-string
"\\|" org-quote-string
5965 '(2 'org-special-keyword t
))
5966 ;; Blocks and meta lines
5967 '(org-fontify-meta-lines-and-blocks)
5969 (setq org-font-lock-extra-keywords
(delq nil org-font-lock-extra-keywords
))
5970 (run-hooks 'org-font-lock-set-keywords-hook
)
5971 ;; Now set the full font-lock-keywords
5972 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords
)
5973 (org-set-local 'font-lock-defaults
5974 '(org-font-lock-keywords t nil nil backward-paragraph
))
5975 (kill-local-variable 'font-lock-keywords
) nil
))
5977 (defun org-toggle-pretty-entities ()
5978 "Toggle the composition display of entities as UTF8 characters."
5980 (org-set-local 'org-pretty-entities
(not org-pretty-entities
))
5981 (org-restart-font-lock)
5982 (if org-pretty-entities
5983 (message "Entities are displayed as UTF8 characters")
5986 (org-decompose-region (point-min) (point-max))
5987 (message "Entities are displayed plain"))))
5989 (defvar org-custom-properties-overlays nil
5990 "List of overlays used for custom properties.")
5991 (make-variable-buffer-local 'org-custom-properties-overlays
)
5993 (defun org-toggle-custom-properties-visibility ()
5994 "Display or hide properties in `org-custom-properties'."
5996 (if org-custom-properties-overlays
5997 (progn (mapc 'delete-overlay org-custom-properties-overlays
)
5998 (setq org-custom-properties-overlays nil
))
5999 (unless (not org-custom-properties
)
6003 (goto-char (point-min))
6004 (while (re-search-forward org-property-re nil t
)
6006 (when (equal p
(substring (match-string 1) 1 -
1))
6007 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6008 (overlay-put o
'invisible t
)
6009 (overlay-put o
'org-custom-property t
)
6010 (push o org-custom-properties-overlays
))))
6011 org-custom-properties
)))))))
6013 (defun org-fontify-entities (limit)
6014 "Find an entity to fontify."
6016 (when org-pretty-entities
6018 (while (re-search-forward
6019 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6021 (if (and (not (org-in-indented-comment-line))
6022 (setq ee
(org-entity-get (match-string 1)))
6023 (= (length (nth 6 ee
)) 1))
6025 ((end (if (equal (match-string 2) "{}")
6028 (add-text-properties
6029 (match-beginning 0) end
6030 (list 'font-lock-fontified t
))
6031 (compose-region (match-beginning 0) end
6037 (defun org-fontify-like-in-org-mode (s &optional odd-levels
)
6038 "Fontify string S like in Org-mode."
6041 (let ((org-odd-levels-only odd-levels
))
6043 (font-lock-fontify-buffer)
6049 (defun org-get-level-face (n)
6050 "Get the right face for match N in font-lock matching of headlines."
6051 (setq org-l
(- (match-end 2) (match-beginning 1) 1))
6052 (if org-odd-levels-only
(setq org-l
(1+ (/ org-l
2))))
6053 (if org-cycle-level-faces
6054 (setq org-f
(nth (%
(1- org-l
) org-n-level-faces
) org-level-faces
))
6055 (setq org-f
(nth (1- (min org-l org-n-level-faces
)) org-level-faces
)))
6057 ((eq n
1) (if org-hide-leading-stars
'org-hide org-f
))
6059 (t (if org-level-color-stars-only nil org-f
))))
6062 (defun org-get-todo-face (kwd)
6063 "Get the right face for a TODO keyword KWD.
6064 If KWD is a number, get the corresponding match group."
6065 (if (numberp kwd
) (setq kwd
(match-string kwd
)))
6066 (or (org-face-from-face-or-color
6067 'todo
'org-todo
(cdr (assoc kwd org-todo-keyword-faces
)))
6068 (and (member kwd org-done-keywords
) 'org-done
)
6071 (defun org-face-from-face-or-color (context inherit face-or-color
)
6072 "Create a face list that inherits INHERIT, but sets the foreground color.
6073 When FACE-OR-COLOR is not a string, just return it."
6074 (if (stringp face-or-color
)
6075 (list :inherit inherit
6076 (cdr (assoc context org-faces-easy-properties
))
6080 (defun org-font-lock-add-tag-faces (limit)
6081 "Add the special tag faces."
6082 (when (and org-tag-faces org-tags-special-faces-re
)
6083 (while (re-search-forward org-tags-special-faces-re limit t
)
6084 (add-text-properties (match-beginning 1) (match-end 1)
6085 (list 'face
(org-get-tag-face 1)
6086 'font-lock-fontified t
))
6087 (backward-char 1))))
6089 (defun org-font-lock-add-priority-faces (limit)
6090 "Add the special priority faces."
6091 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t
)
6092 (when (save-match-data (org-at-heading-p))
6093 (add-text-properties
6094 (match-beginning 0) (match-end 0)
6095 (list 'face
(or (org-face-from-face-or-color
6096 'priority
'org-special-keyword
6097 (cdr (assoc (char-after (match-beginning 1))
6098 org-priority-faces
)))
6099 'org-special-keyword
)
6100 'font-lock-fontified t
)))))
6102 (defun org-get-tag-face (kwd)
6103 "Get the right face for a TODO keyword KWD.
6104 If KWD is a number, get the corresponding match group."
6105 (if (numberp kwd
) (setq kwd
(match-string kwd
)))
6106 (or (org-face-from-face-or-color
6107 'tag
'org-tag
(cdr (assoc kwd org-tag-faces
)))
6110 (defun org-unfontify-region (beg end
&optional maybe_loudly
)
6111 "Remove fontification and activation overlays from links."
6112 (font-lock-default-unfontify-region beg end
)
6113 (let* ((buffer-undo-list t
)
6114 (inhibit-read-only t
) (inhibit-point-motion-hooks t
)
6115 (inhibit-modification-hooks t
)
6116 deactivate-mark buffer-file-name buffer-file-truename
)
6117 (org-decompose-region beg end
)
6118 (remove-text-properties beg end
6119 '(mouse-face t keymap t org-linked-text t
6120 invisible t intangible t
6121 org-no-flyspell t org-emphasis t
))
6122 (org-remove-font-lock-display-properties beg end
)))
6124 (defconst org-script-display
'(((raise -
0.3) (height 0.7))
6125 ((raise 0.3) (height 0.7))
6128 "Display properties for showing superscripts and subscripts.")
6130 (defun org-remove-font-lock-display-properties (beg end
)
6131 "Remove specific display properties that have been added by font lock.
6132 The will remove the raise properties that are used to show superscripts
6136 (setq next
(next-single-property-change beg
'display nil end
)
6137 prop
(get-text-property beg
'display
))
6138 (if (member prop org-script-display
)
6139 (put-text-property beg next
'display nil
))
6142 (defun org-raise-scripts (limit)
6143 "Add raise properties to sub/superscripts."
6144 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
)
6145 (if (re-search-forward
6146 (if (eq org-use-sub-superscripts t
)
6147 org-match-substring-regexp
6148 org-match-substring-with-braces-regexp
)
6150 (let* ((pos (point)) table-p comment-p
6151 (mpos (match-beginning 3))
6152 (emph-p (get-text-property mpos
'org-emphasis
))
6153 (link-p (get-text-property mpos
'mouse-face
))
6154 (keyw-p (eq 'org-special-keyword
(get-text-property mpos
'face
))))
6155 (goto-char (point-at-bol))
6156 (setq table-p
(org-looking-at-p org-table-dataline-regexp
)
6157 comment-p
(org-looking-at-p "[ \t]*#"))
6159 ;; FIXME: Should we go back one character here, for a_b^c
6160 ;; (goto-char (1- pos)) ;????????????????????
6161 (if (or comment-p emph-p link-p keyw-p
)
6163 (put-text-property (match-beginning 3) (match-end 0)
6165 (if (equal (char-after (match-beginning 2)) ?^
)
6166 (nth (if table-p
3 1) org-script-display
)
6167 (nth (if table-p
2 0) org-script-display
)))
6168 (add-text-properties (match-beginning 2) (match-end 2)
6170 'org-dwidth t
'org-dwidth-n
1))
6171 (if (and (eq (char-after (match-beginning 3)) ?
{)
6172 (eq (char-before (match-end 3)) ?
}))
6174 (add-text-properties
6175 (match-beginning 3) (1+ (match-beginning 3))
6176 (list 'invisible t
'org-dwidth t
'org-dwidth-n
1))
6177 (add-text-properties
6178 (1- (match-end 3)) (match-end 3)
6179 (list 'invisible t
'org-dwidth t
'org-dwidth-n
1))))
6182 ;;;; Visibility cycling, including org-goto and indirect buffer
6186 (defvar org-cycle-global-status nil
)
6187 (make-variable-buffer-local 'org-cycle-global-status
)
6188 (defvar org-cycle-subtree-status nil
)
6189 (make-variable-buffer-local 'org-cycle-subtree-status
)
6193 (defvar org-inlinetask-min-level
)
6195 (defun org-cycle (&optional arg
)
6196 "TAB-action and visibility cycling for Org-mode.
6198 This is the command invoked in Org-mode by the TAB key. Its main purpose
6199 is outline visibility cycling, but it also invokes other actions
6200 in special contexts.
6202 - When this function is called with a prefix argument, rotate the entire
6203 buffer through 3 states (global cycling)
6204 1. OVERVIEW: Show only top-level headlines.
6205 2. CONTENTS: Show all headlines of all levels, but no body text.
6206 3. SHOW ALL: Show everything.
6207 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6208 determined by the variable `org-startup-folded', and by any VISIBILITY
6209 properties in the buffer.
6210 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6211 including any drawers.
6213 - When inside a table, re-align the table and move to the next field.
6215 - When point is at the beginning of a headline, rotate the subtree started
6216 by this line through 3 different states (local cycling)
6217 1. FOLDED: Only the main headline is shown.
6218 2. CHILDREN: The main headline and the direct children are shown.
6219 From this state, you can move to one of the children
6220 and zoom in further.
6221 3. SUBTREE: Show the entire subtree, including body text.
6222 If there is no subtree, switch directly from CHILDREN to FOLDED.
6224 - When point is at the beginning of an empty headline and the variable
6225 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6226 of the headline by demoting and promoting it to likely levels. This
6227 speeds up creation document structure by pressing TAB once or several
6228 times right after creating a new headline.
6230 - When there is a numeric prefix, go up to a heading with level ARG, do
6231 a `show-subtree' and return to the previous cursor position. If ARG
6232 is negative, go up that many levels.
6234 - When point is not at the beginning of a headline, execute the global
6235 binding for TAB, which is re-indenting the line. See the option
6236 `org-cycle-emulate-tab' for details.
6238 - Special case: if point is at the beginning of the buffer and there is
6239 no headline in line 1, this function will act as if called with prefix arg
6240 (C-u TAB, same as S-TAB) also when called without prefix arg.
6241 But only if also the variable `org-cycle-global-at-bob' is t."
6243 (org-load-modules-maybe)
6244 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook
)
6245 (and org-cycle-level-after-item
/entry-creation
6246 (or (org-cycle-level)
6247 (org-cycle-item-indentation))))
6249 (or org-cycle-max-level
6250 (and (boundp 'org-inlinetask-min-level
)
6251 org-inlinetask-min-level
6252 (1- org-inlinetask-min-level
))))
6253 (nstars (and limit-level
6254 (if org-odd-levels-only
6255 (and limit-level
(1- (* limit-level
2)))
6258 (if (not (derived-mode-p 'org-mode
))
6260 (concat "\\*" (if nstars
(format "\\{1,%d\\} " nstars
) "+ "))))
6261 (bob-special (and org-cycle-global-at-bob
(not arg
) (bobp)
6262 (not (looking-at org-outline-regexp
))))
6265 (delq 'org-optimize-window-after-visibility-change
6266 (copy-sequence org-cycle-hook
))
6270 (if (or bob-special
(equal arg
'(4)))
6271 ;; special case: use global cycling
6277 (setq last-command
'dummy
)
6278 (org-set-startup-visibility)
6279 (message "Startup visibility, plus VISIBILITY properties"))
6283 (message "Entire buffer visible, including drawers"))
6285 ;; Table: enter it or move to the next field.
6286 ((org-at-table-p 'any
)
6287 (if (org-at-table.el-p
)
6288 (message "Use C-c ' to edit table.el tables")
6289 (if arg
(org-table-edit-field t
)
6290 (org-table-justify-field-maybe)
6291 (call-interactively 'org-table-next-field
))))
6293 ((run-hook-with-args-until-success
6294 'org-tab-after-check-for-table-hook
))
6296 ;; Global cycling: delegate to `org-cycle-internal-global'.
6297 ((eq arg t
) (org-cycle-internal-global))
6299 ;; Drawers: delegate to `org-flag-drawer'.
6300 ((and org-drawers org-drawer-regexp
6302 (beginning-of-line 1)
6303 (looking-at org-drawer-regexp
)))
6304 (org-flag-drawer ; toggle block visibility
6305 (not (get-char-property (match-end 0) 'invisible
))))
6307 ;; Show-subtree, ARG levels up from here.
6310 (org-back-to-heading)
6311 (outline-up-heading (if (< arg
0) (- arg
)
6312 (- (funcall outline-level
) arg
)))
6313 (org-show-subtree)))
6315 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6316 ((and (featurep 'org-inlinetask
)
6317 (org-inlinetask-at-task-p)
6318 (or (bolp) (not (eq org-cycle-emulate-tab
'exc-hl-bol
))))
6319 (org-inlinetask-toggle-visibility))
6321 ((org-try-cdlatex-tab))
6323 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6324 ((and (or (and org-cycle-include-plain-lists
(org-at-item-p))
6325 (save-excursion (beginning-of-line 1)
6326 (looking-at org-outline-regexp
)))
6327 (or (bolp) (not (eq org-cycle-emulate-tab
'exc-hl-bol
))))
6328 (org-cycle-internal-local))
6330 ;; From there: TAB emulation and template completion.
6331 (buffer-read-only (org-back-to-heading))
6333 ((run-hook-with-args-until-success
6334 'org-tab-after-check-for-cycling-hook
))
6336 ((org-try-structure-completion))
6338 ((run-hook-with-args-until-success
6339 'org-tab-before-tab-emulation-hook
))
6341 ((and (eq org-cycle-emulate-tab
'exc-hl-bol
)
6343 (not (looking-at org-outline-regexp
))))
6344 (call-interactively (global-key-binding "\t")))
6346 ((if (and (memq org-cycle-emulate-tab
'(white whitestart
))
6347 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6348 (or (and (eq org-cycle-emulate-tab
'white
)
6349 (= (match-end 0) (point-at-eol)))
6350 (and (eq org-cycle-emulate-tab
'whitestart
)
6351 (>= (match-end 0) pos
))))
6353 (eq org-cycle-emulate-tab t
))
6354 (call-interactively (global-key-binding "\t")))
6357 (org-back-to-heading)
6360 (defun org-cycle-internal-global ()
6361 "Do the global cycling action."
6362 ;; Hack to avoid display of messages for .org attachments in Gnus
6363 (let ((ga (string-match "\\*fontification" (buffer-name))))
6365 ((and (eq last-command this-command
)
6366 (eq org-cycle-global-status
'overview
))
6367 ;; We just created the overview - now do table of contents
6368 ;; This can be slow in very large buffers, so indicate action
6369 (run-hook-with-args 'org-pre-cycle-hook
'contents
)
6370 (unless ga
(message "CONTENTS..."))
6372 (unless ga
(message "CONTENTS...done"))
6373 (setq org-cycle-global-status
'contents
)
6374 (run-hook-with-args 'org-cycle-hook
'contents
))
6376 ((and (eq last-command this-command
)
6377 (eq org-cycle-global-status
'contents
))
6378 ;; We just showed the table of contents - now show everything
6379 (run-hook-with-args 'org-pre-cycle-hook
'all
)
6381 (unless ga
(message "SHOW ALL"))
6382 (setq org-cycle-global-status
'all
)
6383 (run-hook-with-args 'org-cycle-hook
'all
))
6386 ;; Default action: go to overview
6387 (run-hook-with-args 'org-pre-cycle-hook
'overview
)
6389 (unless ga
(message "OVERVIEW"))
6390 (setq org-cycle-global-status
'overview
)
6391 (run-hook-with-args 'org-cycle-hook
'overview
)))))
6393 (defun org-cycle-internal-local ()
6394 "Do the local cycling action."
6395 (let ((goal-column 0) eoh eol eos has-children children-skipped struct
)
6396 ;; First, determine end of headline (EOH), end of subtree or item
6397 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6402 (setq struct
(org-list-struct))
6403 (setq eoh
(point-at-eol))
6404 (setq eos
(org-list-get-item-end-before-blank (point) struct
))
6405 (setq has-children
(org-list-has-child-p (point) struct
)))
6406 (org-back-to-heading)
6407 (setq eoh
(save-excursion (outline-end-of-heading) (point)))
6408 (setq eos
(save-excursion
6409 (org-end-of-subtree t
)
6411 (skip-chars-forward " \t\n"))
6412 (if (eobp) (point) (1- (point)))))
6415 (let ((level (funcall outline-level
)))
6416 (outline-next-heading)
6417 (and (org-at-heading-p t
)
6418 (> (funcall outline-level
) level
))))
6420 (org-list-search-forward (org-item-beginning-re) eos t
)))))
6421 ;; Determine end invisible part of buffer (EOL)
6422 (beginning-of-line 2)
6423 ;; XEmacs doesn't have `next-single-char-property-change'
6424 (if (featurep 'xemacs
)
6425 (while (and (not (eobp)) ;; this is like `next-line'
6426 (get-char-property (1- (point)) 'invisible
))
6427 (beginning-of-line 2))
6428 (while (and (not (eobp)) ;; this is like `next-line'
6429 (get-char-property (1- (point)) 'invisible
))
6430 (goto-char (next-single-char-property-change (point) 'invisible
))
6431 (and (eolp) (beginning-of-line 2))))
6433 ;; Find out what to do next and set `this-command'
6436 ;; Nothing is hidden behind this heading
6437 (run-hook-with-args 'org-pre-cycle-hook
'empty
)
6438 (message "EMPTY ENTRY")
6439 (setq org-cycle-subtree-status nil
)
6442 (outline-next-heading)
6443 (if (outline-invisible-p) (org-flag-heading nil
))))
6444 ((and (or (>= eol eos
)
6445 (not (string-match "\\S-" (buffer-substring eol eos
))))
6447 (not (setq children-skipped
6448 org-cycle-skip-children-state-if-no-children
))))
6449 ;; Entire subtree is hidden in one line: children view
6450 (run-hook-with-args 'org-pre-cycle-hook
'children
)
6452 (org-list-set-item-visibility (point-at-bol) struct
'children
)
6454 (org-with-limited-levels (show-children))
6455 ;; FIXME: This slows down the func way too much.
6456 ;; How keep drawers hidden in subtree anyway?
6457 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6458 ;; (org-cycle-hide-drawers 'subtree))
6460 ;; Fold every list in subtree to top-level items.
6461 (when (eq org-cycle-include-plain-lists
'integrate
)
6463 (org-back-to-heading)
6464 (while (org-list-search-forward (org-item-beginning-re) eos t
)
6465 (beginning-of-line 1)
6466 (let* ((struct (org-list-struct))
6467 (prevs (org-list-prevs-alist struct
))
6468 (end (org-list-get-bottom-point struct
)))
6469 (mapc (lambda (e) (org-list-set-item-visibility e struct
'folded
))
6470 (org-list-get-all-items (point) struct prevs
))
6471 (goto-char end
))))))
6472 (message "CHILDREN")
6475 (outline-next-heading)
6476 (if (outline-invisible-p) (org-flag-heading nil
)))
6477 (setq org-cycle-subtree-status
'children
)
6478 (run-hook-with-args 'org-cycle-hook
'children
))
6479 ((or children-skipped
6480 (and (eq last-command this-command
)
6481 (eq org-cycle-subtree-status
'children
)))
6482 ;; We just showed the children, or no children are there,
6483 ;; now show everything.
6484 (run-hook-with-args 'org-pre-cycle-hook
'subtree
)
6485 (outline-flag-region eoh eos nil
)
6486 (message (if children-skipped
"SUBTREE (NO CHILDREN)" "SUBTREE"))
6487 (setq org-cycle-subtree-status
'subtree
)
6488 (run-hook-with-args 'org-cycle-hook
'subtree
))
6490 ;; Default action: hide the subtree.
6491 (run-hook-with-args 'org-pre-cycle-hook
'folded
)
6492 (outline-flag-region eoh eos t
)
6494 (setq org-cycle-subtree-status
'folded
)
6495 (run-hook-with-args 'org-cycle-hook
'folded
)))))
6498 (defun org-global-cycle (&optional arg
)
6499 "Cycle the global visibility. For details see `org-cycle'.
6500 With \\[universal-argument] prefix arg, switch to startup visibility.
6501 With a numeric prefix, show all headlines up to that level."
6503 (let ((org-cycle-include-plain-lists
6504 (if (derived-mode-p 'org-mode
) org-cycle-include-plain-lists nil
)))
6508 (hide-sublevels arg
)
6509 (setq org-cycle-global-status
'contents
))
6511 (org-set-startup-visibility)
6512 (message "Startup visibility, plus VISIBILITY properties."))
6514 (org-cycle '(4))))))
6516 (defun org-set-startup-visibility ()
6517 "Set the visibility required by startup options and properties."
6519 ((eq org-startup-folded t
)
6521 ((eq org-startup-folded
'content
)
6522 (let ((this-command 'org-cycle
) (last-command 'org-cycle
))
6523 (org-cycle '(4)) (org-cycle '(4)))))
6524 (unless (eq org-startup-folded
'showeverything
)
6525 (if org-hide-block-startup
(org-hide-block-all))
6526 (org-set-visibility-according-to-property 'no-cleanup
)
6527 (org-cycle-hide-archived-subtrees 'all
)
6528 (org-cycle-hide-drawers 'all
)
6529 (org-cycle-show-empty-lines t
)))
6531 (defun org-set-visibility-according-to-property (&optional no-cleanup
)
6532 "Switch subtree visibilities according to :VISIBILITY: property."
6534 (let (org-show-entry-below state
)
6536 (goto-char (point-min))
6537 (while (re-search-forward
6538 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6540 (setq state
(match-string 1))
6542 (org-back-to-heading t
)
6546 ((equal state
'("fold" "folded"))
6548 ((equal state
"children")
6549 (org-show-hidden-entry)
6551 ((equal state
"content")
6554 (org-narrow-to-subtree)
6556 ((member state
'("all" "showall"))
6559 (org-cycle-hide-archived-subtrees 'all
)
6560 (org-cycle-hide-drawers 'all
)
6561 (org-cycle-show-empty-lines 'all
)))))
6563 ;; This function uses outline-regexp instead of the more fundamental
6564 ;; org-outline-regexp so that org-cycle-global works outside of Org
6565 ;; buffers, where outline-regexp is needed.
6566 (defun org-overview ()
6567 "Switch to overview mode, showing only top-level headlines.
6568 Really, this shows all headlines with level equal or greater than the level
6569 of the first headline in the buffer. This is important, because if the
6570 first headline is not level one, then (hide-sublevels 1) gives confusing
6573 (let ((level (save-excursion
6574 (goto-char (point-min))
6575 (if (re-search-forward (concat "^" outline-regexp
) nil t
)
6577 (goto-char (match-beginning 0))
6578 (funcall outline-level
))))))
6579 (and level
(hide-sublevels level
))))
6581 (defun org-content (&optional arg
)
6582 "Show all headlines in the buffer, like a table of contents.
6583 With numerical argument N, show content up to level N."
6586 ;; Visit all headings and show their offspring
6587 (and (integerp arg
) (org-overview))
6588 (goto-char (point-max))
6590 (while (and (progn (condition-case nil
6591 (outline-previous-visible-heading 1)
6592 (error (goto-char (point-min))))
6594 (looking-at org-outline-regexp
))
6596 (show-children (1- arg
))
6598 (if (bobp) (throw 'exit nil
))))))
6601 (defun org-optimize-window-after-visibility-change (state)
6602 "Adjust the window after a change in outline visibility.
6603 This function is the default value of the hook `org-cycle-hook'."
6604 (when (get-buffer-window (current-buffer))
6606 ((eq state
'content
) nil
)
6607 ((eq state
'all
) nil
)
6608 ((eq state
'folded
) nil
)
6609 ((eq state
'children
) (or (org-subtree-end-visible-p) (recenter 1)))
6610 ((eq state
'subtree
) (or (org-subtree-end-visible-p) (recenter 1))))))
6612 (defun org-remove-empty-overlays-at (pos)
6613 "Remove outline overlays that do not contain non-white stuff."
6616 (and (eq 'outline
(overlay-get o
'invisible
))
6617 (not (string-match "\\S-" (buffer-substring (overlay-start o
)
6619 (delete-overlay o
)))
6622 (defun org-clean-visibility-after-subtree-move ()
6623 "Fix visibility issues after moving a subtree."
6624 ;; First, find a reasonable region to look at:
6625 ;; Start two siblings above, end three below
6626 (let* ((beg (save-excursion
6627 (and (org-get-last-sibling)
6628 (org-get-last-sibling))
6630 (end (save-excursion
6631 (and (org-get-next-sibling)
6632 (org-get-next-sibling)
6633 (org-get-next-sibling))
6634 (if (org-at-heading-p)
6637 (level (looking-at "\\*+"))
6638 (re (if level
(concat "^" (regexp-quote (match-string 0)) " "))))
6641 (narrow-to-region beg end
)
6643 ;; Properly fold already folded siblings
6644 (goto-char (point-min))
6645 (while (re-search-forward re nil t
)
6646 (if (and (not (outline-invisible-p))
6648 (goto-char (point-at-eol)) (outline-invisible-p)))
6650 (org-cycle-show-empty-lines 'overview
)
6651 (org-cycle-hide-drawers 'overview
)))))
6653 (defun org-cycle-show-empty-lines (state)
6654 "Show empty lines above all visible headlines.
6655 The region to be covered depends on STATE when called through
6656 `org-cycle-hook'. Lisp program can use t for STATE to get the
6657 entire buffer covered. Note that an empty line is only shown if there
6658 are at least `org-cycle-separator-lines' empty lines before the headline."
6659 (when (not (= org-cycle-separator-lines
0))
6661 (let* ((n (abs org-cycle-separator-lines
))
6663 ((= n
1) "\\(\n[ \t]*\n\\*+\\) ")
6664 ((= n
2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6665 (t (let ((ns (number-to-string (- n
2))))
6666 (concat "^\\(?:[ \t]*\n\\)\\{" ns
"," ns
"\\}"
6667 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6670 ((memq state
'(overview contents t
))
6671 (setq beg
(point-min) end
(point-max)))
6672 ((memq state
'(children folded
))
6673 (setq beg
(point) end
(progn (org-end-of-subtree t t
)
6674 (beginning-of-line 2)
6678 (while (re-search-forward re end t
)
6679 (unless (get-char-property (match-end 1) 'invisible
)
6680 (setq e
(match-end 1))
6681 (if (< org-cycle-separator-lines
0)
6682 (setq b
(save-excursion
6683 (goto-char (match-beginning 0))
6684 (org-back-over-empty-lines)
6686 (goto-char (max (point-min) (1- (point))))
6690 (setq b
(match-beginning 1)))
6691 (outline-flag-region b e nil
)))))))
6692 ;; Never hide empty lines at the end of the file.
6694 (goto-char (point-max))
6695 (outline-previous-heading)
6696 (outline-end-of-heading)
6697 (if (and (looking-at "[ \t\n]+")
6698 (= (match-end 0) (point-max)))
6699 (outline-flag-region (point) (match-end 0) nil
))))
6701 (defun org-show-empty-lines-in-parent ()
6702 "Move to the parent and re-show empty lines before visible headlines."
6704 (let ((context (if (org-up-heading-safe) 'children
'overview
)))
6705 (org-cycle-show-empty-lines context
))))
6707 (defun org-files-list ()
6708 "Return `org-agenda-files' list, plus all open org-mode files.
6709 This is useful for operations that need to scan all of a user's
6710 open and agenda-wise Org files."
6711 (let ((files (mapcar 'expand-file-name
(org-agenda-files))))
6712 (dolist (buf (buffer-list))
6713 (with-current-buffer buf
6714 (if (and (derived-mode-p 'org-mode
) (buffer-file-name))
6715 (let ((file (expand-file-name (buffer-file-name))))
6716 (unless (member file files
)
6717 (push file files
))))))
6720 (defsubst org-entry-beginning-position
()
6721 "Return the beginning position of the current entry."
6722 (save-excursion (outline-back-to-heading t
) (point)))
6724 (defsubst org-entry-end-position
()
6725 "Return the end position of the current entry."
6726 (save-excursion (outline-next-heading) (point)))
6728 (defun org-cycle-hide-drawers (state)
6729 "Re-hide all drawers after a visibility state change."
6730 (when (and (derived-mode-p 'org-mode
)
6731 (not (memq state
'(overview folded contents
))))
6733 (let* ((globalp (memq state
'(contents all
)))
6734 (beg (if globalp
(point-min) (point)))
6735 (end (if globalp
(point-max)
6736 (if (eq state
'children
)
6737 (save-excursion (outline-next-heading) (point))
6738 (org-end-of-subtree t
)))))
6740 (while (re-search-forward org-drawer-regexp end t
)
6741 (org-flag-drawer t
))))))
6743 (defun org-flag-drawer (flag)
6744 "When FLAG is non-nil, hide the drawer we are within.
6745 Otherwise make it visible."
6747 (beginning-of-line 1)
6748 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6749 (let ((b (match-end 0)))
6750 (if (re-search-forward
6752 (save-excursion (outline-next-heading) (point)) t
)
6753 (outline-flag-region b
(point-at-eol) flag
)
6754 (error ":END: line missing at position %s" b
))))))
6756 (defun org-subtree-end-visible-p ()
6757 "Is the end of the current subtree visible?"
6758 (pos-visible-in-window-p
6759 (save-excursion (org-end-of-subtree t
) (point))))
6761 (defun org-first-headline-recenter (&optional N
)
6762 "Move cursor to the first headline and recenter the headline.
6763 Optional argument N means put the headline into the Nth line of the window."
6764 (goto-char (point-min))
6765 (when (re-search-forward (concat "^\\(" org-outline-regexp
"\\)") nil t
)
6767 (recenter (prefix-numeric-value N
))))
6769 ;;; Saving and restoring visibility
6771 (defun org-outline-overlay-data (&optional use-markers
)
6772 "Return a list of the locations of all outline overlays.
6773 These are overlays with the `invisible' property value `outline'.
6774 The return value is a list of cons cells, with start and stop
6775 positions for each overlay.
6776 If USE-MARKERS is set, return the positions as markers."
6783 (when (eq (overlay-get o
'invisible
) 'outline
)
6784 (setq beg
(overlay-start o
)
6785 end
(overlay-end o
))
6786 (and beg end
(> end beg
)
6788 (cons (move-marker (make-marker) beg
)
6789 (move-marker (make-marker) end
))
6791 (overlays-in (point-min) (point-max))))))))
6793 (defun org-set-outline-overlay-data (data)
6794 "Create visibility overlays for all positions in DATA.
6795 DATA should have been made by `org-outline-overlay-data'."
6802 (outline-flag-region (car c
) (cdr c
) t
))
6805 ;;; Folding of blocks
6807 (defvar org-hide-block-overlays nil
6808 "Overlays hiding blocks.")
6809 (make-variable-buffer-local 'org-hide-block-overlays
)
6811 (defun org-block-map (function &optional start end
)
6812 "Call FUNCTION at the head of all source blocks in the current buffer.
6813 Optional arguments START and END can be used to limit the range."
6814 (let ((start (or start
(point-min)))
6815 (end (or end
(point-max))))
6818 (while (and (< (point) end
) (re-search-forward org-block-regexp end t
))
6821 (goto-char (match-beginning 0))
6822 (funcall function
)))))))
6824 (defun org-hide-block-toggle-all ()
6825 "Toggle the visibility of all blocks in the current buffer."
6826 (org-block-map #'org-hide-block-toggle
))
6828 (defun org-hide-block-all ()
6829 "Fold all blocks in the current buffer."
6831 (org-show-block-all)
6832 (org-block-map #'org-hide-block-toggle-maybe
))
6834 (defun org-show-block-all ()
6835 "Unfold all blocks in the current buffer."
6837 (mapc 'delete-overlay org-hide-block-overlays
)
6838 (setq org-hide-block-overlays nil
))
6840 (defun org-hide-block-toggle-maybe ()
6841 "Toggle visibility of block at point."
6843 (let ((case-fold-search t
))
6845 (beginning-of-line 1)
6846 (looking-at org-block-regexp
))
6847 (progn (org-hide-block-toggle)
6848 t
) ;; to signal that we took action
6849 nil
))) ;; to signal that we did not
6851 (defun org-hide-block-toggle (&optional force
)
6852 "Toggle the visibility of the current block."
6856 (if (re-search-forward org-block-regexp nil t
)
6857 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6858 (end (match-end 0)) ;; end of entire body
6860 (if (memq t
(mapcar (lambda (overlay)
6861 (eq (overlay-get overlay
'invisible
)
6863 (overlays-at start
)))
6864 (if (or (not force
) (eq force
'off
))
6866 (when (member ov org-hide-block-overlays
)
6867 (setq org-hide-block-overlays
6868 (delq ov org-hide-block-overlays
)))
6869 (when (eq (overlay-get ov
'invisible
)
6871 (delete-overlay ov
)))
6872 (overlays-at start
)))
6873 (setq ov
(make-overlay start end
))
6874 (overlay-put ov
'invisible
'org-hide-block
)
6875 ;; make the block accessible to isearch
6877 ov
'isearch-open-invisible
6879 (when (member ov org-hide-block-overlays
)
6880 (setq org-hide-block-overlays
6881 (delq ov org-hide-block-overlays
)))
6882 (when (eq (overlay-get ov
'invisible
)
6884 (delete-overlay ov
))))
6885 (push ov org-hide-block-overlays
)))
6886 (error "Not looking at a source block"))))
6888 ;; org-tab-after-check-for-cycling-hook
6889 (add-hook 'org-tab-first-hook
'org-hide-block-toggle-maybe
)
6890 ;; Remove overlays when changing major mode
6891 (add-hook 'org-mode-hook
6892 (lambda () (org-add-hook 'change-major-mode-hook
6893 'org-show-block-all
'append
'local
)))
6897 (defvar org-goto-window-configuration nil
)
6898 (defvar org-goto-marker nil
)
6899 (defvar org-goto-map
6900 (let ((map (make-sparse-keymap)))
6901 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur
)) cmd
)
6902 (while (setq cmd
(pop cmds
))
6903 (substitute-key-definition cmd cmd map global-map
)))
6904 (suppress-keymap map
)
6905 (org-defkey map
"\C-m" 'org-goto-ret
)
6906 (org-defkey map
[(return)] 'org-goto-ret
)
6907 (org-defkey map
[(left)] 'org-goto-left
)
6908 (org-defkey map
[(right)] 'org-goto-right
)
6909 (org-defkey map
[(control ?g
)] 'org-goto-quit
)
6910 (org-defkey map
"\C-i" 'org-cycle
)
6911 (org-defkey map
[(tab)] 'org-cycle
)
6912 (org-defkey map
[(down)] 'outline-next-visible-heading
)
6913 (org-defkey map
[(up)] 'outline-previous-visible-heading
)
6914 (if org-goto-auto-isearch
6915 (if (fboundp 'define-key-after
)
6916 (define-key-after map
[t] 'org-goto-local-auto-isearch)
6918 (org-defkey map "q" 'org-goto-quit)
6919 (org-defkey map "n" 'outline-next-visible-heading)
6920 (org-defkey map "p" 'outline-previous-visible-heading)
6921 (org-defkey map "f" 'outline-forward-same-level)
6922 (org-defkey map "b" 'outline-backward-same-level)
6923 (org-defkey map "u" 'outline-up-heading))
6924 (org-defkey map "/" 'org-occur)
6925 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6926 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6927 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6928 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6929 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6932 (defconst org-goto-help
6933 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6934 RET=jump to location [Q]uit and return to previous location
6935 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6937 (defvar org-goto-start-pos) ; dynamically scoped parameter
6939 ;; FIXME: Docstring does not mention both interfaces
6940 (defun org-goto (&optional alternative-interface)
6941 "Look up a different location in the current file, keeping current visibility.
6943 When you want look-up or go to a different location in a
6944 document, the fastest way is often to fold the entire buffer and
6945 then dive into the tree. This method has the disadvantage, that
6946 the previous location will be folded, which may not be what you
6949 This command works around this by showing a copy of the current
6950 buffer in an indirect buffer, in overview mode. You can dive
6951 into the tree in that copy, use org-occur and incremental search
6952 to find a location. When pressing RET or `Q', the command
6953 returns to the original buffer in which the visibility is still
6954 unchanged. After RET it will also jump to the location selected
6955 in the indirect buffer and expose the headline hierarchy above.
6957 With a prefix argument, use the alternative interface: e.g. if
6958 `org-goto-interface' is 'outline use 'outline-path-completion."
6960 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6961 (org-refile-use-outline-path t)
6962 (org-refile-target-verify-function nil)
6964 (if (not alternative-interface)
6966 (if (eq org-goto-interface 'outline)
6967 'outline-path-completion
6969 (org-goto-start-pos (point))
6971 (if (eq interface 'outline)
6972 (car (org-get-location (current-buffer) org-goto-help))
6973 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6974 (org-refile-check-position pa)
6978 (org-mark-ring-push org-goto-start-pos)
6979 (goto-char selected-point)
6980 (if (or (outline-invisible-p) (org-invisible-p2))
6981 (org-show-context 'org-goto)))
6984 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6985 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6986 (defvar org-goto-local-auto-isearch-map) ; defined below
6988 (defun org-get-location (buf help)
6989 "Let the user select a location in the Org-mode buffer BUF.
6990 This function uses a recursive edit. It returns the selected position
6992 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6993 (isearch-hide-immediately nil)
6994 (isearch-search-fun-function
6995 (lambda () 'org-goto-local-search-headings))
6996 (org-goto-selected-point org-goto-exit-command)
6998 (special-display-buffer-names nil)
6999 (special-display-regexps nil)
7000 (special-display-function nil))
7002 (save-window-excursion
7003 (delete-other-windows)
7004 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7005 (org-pop-to-buffer-same-window
7007 (make-indirect-buffer (current-buffer) "*org-goto*")
7008 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7009 (with-output-to-temp-buffer "*Help*"
7011 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
7012 (setq buffer-read-only nil)
7013 (let ((org-startup-truncated t)
7014 (org-startup-folded nil)
7015 (org-startup-align-all-tables nil))
7018 (setq buffer-read-only t)
7019 (if (and (boundp 'org-goto-start-pos)
7020 (integer-or-marker-p org-goto-start-pos))
7021 (let ((org-show-hierarchy-above t)
7022 (org-show-siblings t)
7023 (org-show-following-heading t))
7024 (goto-char org-goto-start-pos)
7025 (and (outline-invisible-p) (org-show-context)))
7026 (goto-char (point-min)))
7027 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7028 (message "Select location and press RET")
7029 (use-local-map org-goto-map)
7032 (kill-buffer "*org-goto*")
7033 (cons org-goto-selected-point org-goto-exit-command)))
7035 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7036 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7037 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7038 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7040 (defun org-goto-local-search-headings (string bound noerror)
7041 "Search and make sure that any matches are in headlines."
7043 (while (if isearch-forward
7044 (search-forward string bound noerror)
7045 (search-backward string bound noerror))
7046 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7047 (and (member :headline context)
7048 (not (member :tags context))))
7049 (throw 'return (point))))))
7051 (defun org-goto-local-auto-isearch ()
7054 (goto-char (point-min))
7055 (let ((keys (this-command-keys)))
7056 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7058 (isearch-process-search-char (string-to-char keys)))))
7060 (defun org-goto-ret (&optional arg)
7061 "Finish `org-goto' by going to the new location."
7063 (setq org-goto-selected-point (point)
7064 org-goto-exit-command 'return)
7067 (defun org-goto-left ()
7068 "Finish `org-goto' by going to the new location."
7070 (if (org-at-heading-p)
7072 (beginning-of-line 1)
7073 (setq org-goto-selected-point (point)
7074 org-goto-exit-command 'left)
7076 (error "Not on a heading")))
7078 (defun org-goto-right ()
7079 "Finish `org-goto' by going to the new location."
7081 (if (org-at-heading-p)
7083 (setq org-goto-selected-point (point)
7084 org-goto-exit-command 'right)
7086 (error "Not on a heading")))
7088 (defun org-goto-quit ()
7089 "Finish `org-goto' without cursor motion."
7091 (setq org-goto-selected-point nil)
7092 (setq org-goto-exit-command 'quit)
7095 ;;; Indirect buffer display of subtrees
7097 (defvar org-indirect-dedicated-frame nil
7098 "This is the frame being used for indirect tree display.")
7099 (defvar org-last-indirect-buffer nil)
7101 (defun org-tree-to-indirect-buffer (&optional arg)
7102 "Create indirect buffer and narrow it to current subtree.
7103 With a numerical prefix ARG, go up to this level and then take that tree.
7104 If ARG is negative, go up that many levels.
7106 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7107 indirect buffer previously made with this command, to avoid proliferation of
7108 indirect buffers. However, when you call the command with a \
7109 \\[universal-argument] prefix, or
7110 when `org-indirect-buffer-display' is `new-frame', the last buffer
7111 is kept so that you can work with several indirect buffers at the same time.
7112 If `org-indirect-buffer-display' is `dedicated-frame', the \
7113 \\[universal-argument] prefix also
7114 requests that a new frame be made for the new buffer, so that the dedicated
7115 frame is not changed."
7117 (let ((cbuf (current-buffer))
7118 (cwin (selected-window))
7120 beg end level heading ibuf)
7122 (org-back-to-heading t)
7124 (setq level (org-outline-level))
7125 (if (< arg 0) (setq arg (+ level arg)))
7126 (while (> (setq level (org-outline-level)) arg)
7127 (org-up-heading-safe)))
7129 heading (org-get-heading))
7130 (org-end-of-subtree t t)
7131 (if (org-at-heading-p) (backward-char 1))
7133 (if (and (buffer-live-p org-last-indirect-buffer)
7134 (not (eq org-indirect-buffer-display 'new-frame))
7136 (kill-buffer org-last-indirect-buffer))
7137 (setq ibuf (org-get-indirect-buffer cbuf)
7138 org-last-indirect-buffer ibuf)
7140 ((or (eq org-indirect-buffer-display 'new-frame)
7141 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7142 (select-frame (make-frame))
7143 (delete-other-windows)
7144 (org-pop-to-buffer-same-window ibuf)
7145 (org-set-frame-title heading))
7146 ((eq org-indirect-buffer-display 'dedicated-frame)
7148 (select-frame (or (and org-indirect-dedicated-frame
7149 (frame-live-p org-indirect-dedicated-frame)
7150 org-indirect-dedicated-frame)
7151 (setq org-indirect-dedicated-frame (make-frame)))))
7152 (delete-other-windows)
7153 (org-pop-to-buffer-same-window ibuf)
7154 (org-set-frame-title (concat "Indirect: " heading)))
7155 ((eq org-indirect-buffer-display 'current-window)
7156 (org-pop-to-buffer-same-window ibuf))
7157 ((eq org-indirect-buffer-display 'other-window)
7158 (pop-to-buffer ibuf))
7159 (t (error "Invalid value")))
7160 (if (featurep 'xemacs)
7161 (save-excursion (org-mode) (turn-on-font-lock)))
7162 (narrow-to-region beg end)
7165 (run-hook-with-args 'org-cycle-hook 'all)
7166 (and (window-live-p cwin) (select-window cwin))))
7168 (defun org-get-indirect-buffer (&optional buffer)
7169 (setq buffer (or buffer (current-buffer)))
7170 (let ((n 1) (base (buffer-name buffer)) bname)
7171 (while (buffer-live-p
7172 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7175 (make-indirect-buffer buffer bname 'clone)
7176 (error (make-indirect-buffer buffer bname)))))
7178 (defun org-set-frame-title (title)
7179 "Set the title of the current frame to the string TITLE."
7180 ;; FIXME: how to name a single frame in XEmacs???
7181 (unless (featurep 'xemacs)
7182 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7184 ;;;; Structure editing
7186 ;;; Inserting headlines
7188 (defun org-previous-line-empty-p ()
7191 (or (beginning-of-line 0) t)
7193 (looking-at "[ \t]*$")))))
7195 (defun org-insert-heading (&optional force-heading invisible-ok)
7196 "Insert a new heading or item with same depth at point.
7197 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7198 If point is at the beginning of a headline, insert a sibling before the
7199 current headline. If point is not at the beginning, split the line,
7200 create the new headline with the text in the current line after point
7201 \(but see also the variable `org-M-RET-may-split-line').
7203 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7204 This is important for non-interactive uses of the command."
7206 (if (or (= (buffer-size) 0)
7207 (and (not (save-excursion
7208 (and (ignore-errors (org-back-to-heading invisible-ok))
7209 (org-at-heading-p))))
7210 (or force-heading (not (org-in-item-p)))))
7213 (run-hooks 'org-insert-heading-hook))
7214 (when (or force-heading (not (org-insert-item)))
7215 (let* ((empty-line-p nil)
7217 (on-heading (org-at-heading-p))
7218 (head (save-excursion
7221 (org-back-to-heading invisible-ok)
7222 (when (and (not on-heading)
7223 (featurep 'org-inlinetask)
7224 (integerp org-inlinetask-min-level)
7225 (>= (length (match-string 0))
7226 org-inlinetask-min-level))
7227 ;; Find a heading level before the inline task
7228 (while (and (setq level (org-up-heading-safe))
7229 (>= level org-inlinetask-min-level)))
7230 (if (org-at-heading-p)
7231 (org-back-to-heading invisible-ok)
7232 (error "This should not happen")))
7233 (setq empty-line-p (org-previous-line-empty-p))
7236 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7237 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7238 pos hide-previous previous-pos)
7240 ((and (org-at-heading-p) (bolp)
7242 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7243 ;; insert before the current line
7244 (open-line (if blank 2 1)))
7246 (not org-insert-heading-respect-content)
7249 (backward-char 1) (not (outline-invisible-p)))))
7250 ;; insert right here
7253 ;; somewhere in the line
7255 (setq previous-pos (point-at-bol))
7257 (setq hide-previous (outline-invisible-p)))
7258 (and org-insert-heading-respect-content (org-show-subtree))
7260 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7263 (goto-char (point-at-bol))
7264 (and (looking-at org-complex-heading-regexp)
7266 (> p (match-beginning 4)))))))
7269 (org-insert-heading-respect-content
7270 (org-end-of-subtree nil t)
7271 (when (featurep 'org-inlinetask)
7272 (while (and (not (eobp))
7273 (looking-at "\\(\\*+\\)[ \t]+")
7274 (>= (length (match-string 1))
7275 org-inlinetask-min-level))
7276 (org-end-of-subtree nil t)))
7277 (or (bolp) (newline))
7278 (or (org-previous-line-empty-p)
7279 (and blank (newline)))
7285 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7286 (setq tags (and (match-end 2) (match-string 2)))
7288 (delete-region (match-beginning 1) (match-end 1)))
7289 (setq pos (point-at-bol))
7290 (or split (end-of-line 1))
7291 (delete-horizontal-space)
7292 (if (string-match "\\`\\*+\\'"
7293 (buffer-substring (point-at-bol) (point)))
7295 (newline (if blank 2 1))
7301 (org-set-tags nil 'align))))
7303 (or split (end-of-line 1))
7304 (newline (if blank 2 1)))))))
7305 (insert head) (just-one-space)
7308 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7309 (when (and org-insert-heading-respect-content hide-previous)
7311 (goto-char previous-pos)
7313 (run-hooks 'org-insert-heading-hook)))))
7315 (defun org-get-heading (&optional no-tags no-todo)
7316 "Return the heading of the current entry, without the stars.
7317 When NO-TAGS is non-nil, don't include tags.
7318 When NO-TODO is non-nil, don't include TODO keywords."
7320 (org-back-to-heading t)
7322 ((and no-tags no-todo)
7323 (looking-at org-complex-heading-regexp)
7326 (looking-at (concat org-outline-regexp
7328 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7331 (looking-at org-todo-line-regexp)
7333 (t (looking-at org-heading-regexp)
7334 (match-string 2)))))
7336 (defun org-heading-components ()
7337 "Return the components of the current heading.
7338 This is a list with the following elements:
7339 - the level as an integer
7340 - the reduced level, different if `org-odd-levels-only' is set.
7341 - the TODO keyword, or nil
7342 - the priority character, like ?A, or nil if no priority is given
7343 - the headline text itself, or the tags string if no headline text
7344 - the tags string, or nil."
7346 (org-back-to-heading t)
7347 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7348 (list (length (match-string 1))
7349 (org-reduced-level (length (match-string 1)))
7350 (org-match-string-no-properties 2)
7351 (and (match-end 3) (aref (match-string 3) 2))
7352 (org-match-string-no-properties 4)
7353 (org-match-string-no-properties 5)))))
7355 (defun org-get-entry ()
7356 "Get the entry text, after heading, entire subtree."
7358 (org-back-to-heading t)
7359 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7361 (defun org-insert-heading-after-current ()
7362 "Insert a new heading with same level as current, after current subtree."
7364 (org-back-to-heading)
7365 (org-insert-heading)
7366 (org-move-subtree-down)
7369 (defun org-insert-heading-respect-content ()
7371 (let ((org-insert-heading-respect-content t))
7372 (org-insert-heading t)))
7374 (defun org-insert-todo-heading-respect-content (&optional force-state)
7376 (let ((org-insert-heading-respect-content t))
7377 (org-insert-todo-heading force-state t)))
7379 (defun org-insert-todo-heading (arg &optional force-heading)
7380 "Insert a new heading with the same level and TODO state as current heading.
7381 If the heading has no TODO state, or if the state is DONE, use the first
7382 state (TODO by default). Also with prefix arg, force first state."
7384 (when (or force-heading (not (org-insert-item 'checkbox)))
7385 (org-insert-heading force-heading)
7387 (org-back-to-heading)
7388 (outline-previous-heading)
7389 (looking-at org-todo-line-regexp))
7393 (not (match-beginning 2))
7394 (member (match-string 2) org-done-keywords))
7395 (car org-todo-keywords-1)
7399 (run-hook-with-args-until-success
7400 'org-todo-get-default-hook new-mark-x nil)
7402 (beginning-of-line 1)
7403 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7404 (if org-treat-insert-todo-heading-as-state-change
7406 (insert new-mark " "))))
7407 (when org-provide-todo-statistics
7408 (org-update-parent-todo-statistics))))
7410 (defun org-insert-subheading (arg)
7411 "Insert a new subheading and demote it.
7412 Works for outline headings and for plain lists alike."
7414 (org-insert-heading arg)
7416 ((org-at-heading-p) (org-do-demote))
7417 ((org-at-item-p) (org-indent-item))))
7419 (defun org-insert-todo-subheading (arg)
7420 "Insert a new subheading with TODO keyword or checkbox and demote it.
7421 Works for outline headings and for plain lists alike."
7423 (org-insert-todo-heading arg)
7425 ((org-at-heading-p) (org-do-demote))
7426 ((org-at-item-p) (org-indent-item))))
7428 ;;; Promotion and Demotion
7430 (defvar org-after-demote-entry-hook nil
7431 "Hook run after an entry has been demoted.
7432 The cursor will be at the beginning of the entry.
7433 When a subtree is being demoted, the hook will be called for each node.")
7435 (defvar org-after-promote-entry-hook nil
7436 "Hook run after an entry has been promoted.
7437 The cursor will be at the beginning of the entry.
7438 When a subtree is being promoted, the hook will be called for each node.")
7440 (defun org-promote-subtree ()
7441 "Promote the entire subtree.
7442 See also `org-promote'."
7445 (org-with-limited-levels (org-map-tree 'org-promote)))
7446 (org-fix-position-after-promote))
7448 (defun org-demote-subtree ()
7449 "Demote the entire subtree. See `org-demote'.
7450 See also `org-promote'."
7453 (org-with-limited-levels (org-map-tree 'org-demote)))
7454 (org-fix-position-after-promote))
7457 (defun org-do-promote ()
7458 "Promote the current heading higher up the tree.
7459 If the region is active in `transient-mark-mode', promote all headings
7463 (if (org-region-active-p)
7464 (org-map-region 'org-promote (region-beginning) (region-end))
7466 (org-fix-position-after-promote))
7468 (defun org-do-demote ()
7469 "Demote the current heading lower down the tree.
7470 If the region is active in `transient-mark-mode', demote all headings
7474 (if (org-region-active-p)
7475 (org-map-region 'org-demote (region-beginning) (region-end))
7477 (org-fix-position-after-promote))
7479 (defun org-fix-position-after-promote ()
7480 "Make sure that after pro/demotion cursor position is right."
7481 (let ((pos (point)))
7482 (when (save-excursion
7483 (beginning-of-line 1)
7484 (looking-at org-todo-line-regexp)
7485 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7486 (cond ((eobp) (insert " "))
7487 ((eolp) (insert " "))
7488 ((equal (char-after) ?\ ) (forward-char 1))))))
7490 (defun org-current-level ()
7491 "Return the level of the current entry, or nil if before the first headline.
7492 The level is the number of stars at the beginning of the headline."
7494 (org-with-limited-levels
7495 (if (ignore-errors (org-back-to-heading t))
7496 (funcall outline-level)))))
7498 (defun org-get-previous-line-level ()
7499 "Return the outline depth of the last headline before the current line.
7500 Returns 0 for the first headline in the buffer, and nil if before the
7502 (let ((current-level (org-current-level))
7503 (prev-level (when (> (line-number-at-pos) 1)
7505 (beginning-of-line 0)
7506 (org-current-level)))))
7507 (cond ((null current-level) nil) ; Before first headline
7508 ((null prev-level) 0) ; At first headline
7511 (defun org-reduced-level (l)
7512 "Compute the effective level of a heading.
7513 This takes into account the setting of `org-odd-levels-only'."
7516 (org-odd-levels-only (1+ (floor (/ l 2))))
7519 (defun org-level-increment ()
7520 "Return the number of stars that will be added or removed at a
7521 time to headlines when structure editing, based on the value of
7522 `org-odd-levels-only'."
7523 (if org-odd-levels-only 2 1))
7525 (defun org-get-valid-level (level &optional change)
7526 "Rectify a level change under the influence of `org-odd-levels-only'
7527 LEVEL is a current level, CHANGE is by how much the level should be
7528 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7529 even level numbers will become the next higher odd number."
7530 (if org-odd-levels-only
7531 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7532 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7533 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7534 (max 1 (+ level (or change 0)))))
7536 (if (boundp 'define-obsolete-function-alias)
7537 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7538 (define-obsolete-function-alias 'org-get-legal-level
7539 'org-get-valid-level)
7540 (define-obsolete-function-alias 'org-get-legal-level
7541 'org-get-valid-level "23.1")))
7543 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7544 ;; ̀org-with-limited-levels'
7545 (defun org-promote ()
7546 "Promote the current heading higher up the tree.
7547 If the region is active in `transient-mark-mode', promote all headings
7549 (org-back-to-heading t)
7550 (let* ((level (save-match-data (funcall outline-level)))
7551 (after-change-functions (remove 'flyspell-after-change-function
7552 after-change-functions))
7553 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7554 (diff (abs (- level (length up-head) -1))))
7555 (cond ((and (= level 1) org-called-with-limited-levels
7556 org-allow-promoting-top-level-subtree)
7557 (replace-match "# " nil t))
7559 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7560 (t (replace-match up-head nil t)))
7561 ;; Fixup tag positioning
7563 (and org-auto-align-tags (org-set-tags nil t))
7564 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7565 (run-hooks 'org-after-promote-entry-hook)))
7567 (defun org-demote ()
7568 "Demote the current heading lower down the tree.
7569 If the region is active in `transient-mark-mode', demote all headings
7571 (org-back-to-heading t)
7572 (let* ((level (save-match-data (funcall outline-level)))
7573 (after-change-functions (remove 'flyspell-after-change-function
7574 after-change-functions))
7575 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7576 (diff (abs (- level (length down-head) -1))))
7577 (replace-match down-head nil t)
7578 ;; Fixup tag positioning
7579 (and org-auto-align-tags (org-set-tags nil t))
7580 (if org-adapt-indentation (org-fixup-indentation diff))
7581 (run-hooks 'org-after-demote-entry-hook)))
7583 (defun org-cycle-level ()
7584 "Cycle the level of an empty headline through possible states.
7585 This goes first to child, then to parent, level, then up the hierarchy.
7586 After top level, it switches back to sibling level."
7588 (let ((org-adapt-indentation nil))
7589 (when (org-point-at-end-of-empty-headline)
7590 (setq this-command 'org-cycle-level) ; Only needed for caching
7591 (let ((cur-level (org-current-level))
7592 (prev-level (org-get-previous-line-level)))
7594 ;; If first headline in file, promote to top-level.
7596 (loop repeat (/ (- cur-level 1) (org-level-increment))
7597 do (org-do-promote)))
7598 ;; If same level as prev, demote one.
7599 ((= prev-level cur-level)
7601 ;; If parent is top-level, promote to top level if not already.
7603 (loop repeat (/ (- cur-level 1) (org-level-increment))
7604 do (org-do-promote)))
7605 ;; If top-level, return to prev-level.
7607 (loop repeat (/ (- prev-level 1) (org-level-increment))
7608 do (org-do-demote)))
7609 ;; If less than prev-level, promote one.
7610 ((< cur-level prev-level)
7612 ;; If deeper than prev-level, promote until higher than
7614 ((> cur-level prev-level)
7615 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7616 do (org-do-promote))))
7619 (defun org-map-tree (fun)
7620 "Call FUN for every heading underneath the current one."
7621 (org-back-to-heading)
7622 (let ((level (funcall outline-level)))
7626 (outline-next-heading)
7627 (> (funcall outline-level) level))
7631 (defun org-map-region (fun beg end)
7632 "Call FUN for every heading between BEG and END."
7633 (let ((org-ignore-region t))
7635 (setq end (copy-marker end))
7637 (if (and (re-search-forward org-outline-regexp-bol nil t)
7641 (outline-next-heading)
7646 (defvar org-property-end-re) ; silence byte-compiler
7647 (defun org-fixup-indentation (diff)
7648 "Change the indentation in the current entry by DIFF.
7649 However, if any line in the current entry has no indentation, or if it
7650 would end up with no indentation after the change, nothing at all is done."
7652 (let ((end (save-excursion (outline-next-heading)
7654 (prohibit (if (> diff 0)
7656 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7658 (unless (save-excursion (end-of-line 1)
7659 (re-search-forward prohibit end t))
7660 (while (and (< (point) end)
7661 (re-search-forward "^[ \t]+" end t))
7662 (goto-char (match-end 0))
7663 (setq col (current-column))
7664 (if (< diff 0) (replace-match ""))
7665 (org-indent-to-column (+ diff col))))
7666 (move-marker end nil))))
7668 (defun org-convert-to-odd-levels ()
7669 "Convert an org-mode file with all levels allowed to one with odd levels.
7670 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7673 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7674 (let ((outline-level 'org-outline-level)
7675 (org-odd-levels-only nil) n)
7677 (goto-char (point-min))
7678 (while (re-search-forward "^\\*\\*+ " nil t)
7679 (setq n (- (length (match-string 0)) 2))
7680 (while (>= (setq n (1- n)) 0)
7682 (end-of-line 1))))))
7684 (defun org-convert-to-oddeven-levels ()
7685 "Convert an org-mode file with only odd levels to one with odd/even levels.
7686 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7687 file contains a section with an even level, conversion would
7688 destroy the structure of the file. An error is signaled in this
7691 (goto-char (point-min))
7692 ;; First check if there are no even levels
7693 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7694 (org-show-context t)
7695 (error "Not all levels are odd in this file. Conversion not possible"))
7696 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7697 (let ((outline-regexp org-outline-regexp)
7698 (outline-level 'org-outline-level)
7699 (org-odd-levels-only nil) n)
7701 (goto-char (point-min))
7702 (while (re-search-forward "^\\*\\*+ " nil t)
7703 (setq n (/ (1- (length (match-string 0))) 2))
7704 (while (>= (setq n (1- n)) 0)
7706 (end-of-line 1))))))
7708 (defun org-tr-level (n)
7709 "Make N odd if required."
7710 (if org-odd-levels-only (1+ (/ n 2)) n))
7712 ;;; Vertical tree motion, cutting and pasting of subtrees
7714 (defun org-move-subtree-up (&optional arg)
7715 "Move the current subtree up past ARG headlines of the same level."
7717 (org-move-subtree-down (- (prefix-numeric-value arg))))
7719 (defun org-move-subtree-down (&optional arg)
7720 "Move the current subtree down past ARG headlines of the same level."
7722 (setq arg (prefix-numeric-value arg))
7723 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7724 'org-get-last-sibling))
7725 (ins-point (make-marker))
7727 (col (current-column))
7728 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7730 (org-back-to-heading)
7733 (setq ne-beg (org-back-over-empty-lines))
7736 (save-excursion (outline-end-of-heading)
7737 (setq folded (outline-invisible-p)))
7738 (outline-end-of-subtree))
7739 (outline-next-heading)
7740 (setq ne-end (org-back-over-empty-lines))
7743 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7744 ;; include less whitespace
7747 (forward-line (- ne-beg ne-end))
7748 (setq beg (point))))
7749 ;; Find insertion point, with error handling
7751 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7752 (progn (goto-char beg0)
7753 (error "Cannot move past superior level or buffer limit")))
7754 (setq cnt (1- cnt)))
7756 ;; Moving forward - still need to move over subtree
7757 (progn (org-end-of-subtree t t)
7759 (org-back-over-empty-lines)
7760 (or (bolp) (newline)))))
7761 (setq ne-ins (org-back-over-empty-lines))
7762 (move-marker ins-point (point))
7763 (setq txt (buffer-substring beg end))
7764 (org-save-markers-in-region beg end)
7765 (delete-region beg end)
7766 (org-remove-empty-overlays-at beg)
7767 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7768 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7769 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7770 (let ((bbb (point)))
7771 (insert-before-markers txt)
7772 (org-reinstall-markers-in-region bbb)
7773 (move-marker ins-point bbb))
7774 (or (bolp) (insert "\n"))
7775 (setq ins-end (point))
7776 (goto-char ins-point)
7777 (org-skip-whitespace)
7778 (when (and (< arg 0)
7779 (org-first-sibling-p)
7781 ;; Move whitespace back to beginning
7784 (let ((kill-whole-line t))
7785 (kill-line (- ne-ins ne-beg)) (point)))
7786 (insert (make-string (- ne-ins ne-beg) ?\n)))
7787 (move-marker ins-point nil)
7792 (org-cycle-hide-drawers 'children))
7793 (org-clean-visibility-after-subtree-move)
7794 ;; move back to the initial column we were at
7795 (move-to-column col)))
7797 (defvar org-subtree-clip ""
7798 "Clipboard for cut and paste of subtrees.
7799 This is actually only a copy of the kill, because we use the normal kill
7800 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7802 (defvar org-subtree-clip-folded nil
7803 "Was the last copied subtree folded?
7804 This is used to fold the tree back after pasting.")
7806 (defun org-cut-subtree (&optional n)
7807 "Cut the current subtree into the clipboard.
7808 With prefix arg N, cut this many sequential subtrees.
7809 This is a short-hand for marking the subtree and then cutting it."
7811 (org-copy-subtree n 'cut))
7813 (defun org-copy-subtree (&optional n cut force-store-markers)
7814 "Cut the current subtree into the clipboard.
7815 With prefix arg N, cut this many sequential subtrees.
7816 This is a short-hand for marking the subtree and then copying it.
7817 If CUT is non-nil, actually cut the subtree.
7818 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7819 of some markers in the region, even if CUT is non-nil. This is
7820 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7822 (let (beg end folded (beg0 (point)))
7823 (if (org-called-interactively-p 'any)
7824 (org-back-to-heading nil) ; take what looks like a subtree
7825 (org-back-to-heading t)) ; take what is really there
7826 (org-back-over-empty-lines)
7828 (skip-chars-forward " \t\r\n")
7830 (save-excursion (outline-end-of-heading)
7831 (setq folded (outline-invisible-p)))
7833 (org-forward-heading-same-level (1- n) t)
7835 (org-end-of-subtree t t))
7836 (org-back-over-empty-lines)
7840 (setq org-subtree-clip-folded folded)
7841 (when (or cut force-store-markers)
7842 (org-save-markers-in-region beg end))
7843 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7844 (setq org-subtree-clip (current-kill 0))
7845 (message "%s: Subtree(s) with %d characters"
7846 (if cut "Cut" "Copied")
7847 (length org-subtree-clip)))))
7849 (defun org-paste-subtree (&optional level tree for-yank)
7850 "Paste the clipboard as a subtree, with modification of headline level.
7851 The entire subtree is promoted or demoted in order to match a new headline
7854 If the cursor is at the beginning of a headline, the same level as
7855 that headline is used to paste the tree
7857 If not, the new level is derived from the *visible* headings
7858 before and after the insertion point, and taken to be the inferior headline
7859 level of the two. So if the previous visible heading is level 3 and the
7860 next is level 4 (or vice versa), level 4 will be used for insertion.
7861 This makes sure that the subtree remains an independent subtree and does
7862 not swallow low level entries.
7864 You can also force a different level, either by using a numeric prefix
7865 argument, or by inserting the heading marker by hand. For example, if the
7866 cursor is after \"*****\", then the tree will be shifted to level 5.
7868 If optional TREE is given, use this text instead of the kill ring.
7870 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7871 move back over whitespace before inserting, and move point to the end of
7872 the inserted text when done."
7874 (setq tree (or tree (and kill-ring (current-kill 0))))
7875 (unless (org-kill-is-subtree-p tree)
7877 (substitute-command-keys
7878 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7879 (org-with-limited-levels
7880 (let* ((visp (not (outline-invisible-p)))
7882 (^re_ "\\(\\*+\\)[ \t]*")
7883 (old-level (if (string-match org-outline-regexp-bol txt)
7884 (- (match-end 0) (match-beginning 0) 1)
7886 (force-level (cond (level (prefix-numeric-value level))
7887 ((and (looking-at "[ \t]*$")
7889 "^\\*+$" (buffer-substring
7890 (point-at-bol) (point))))
7891 (- (match-end 1) (match-beginning 1)))
7893 (looking-at org-outline-regexp))
7894 (- (match-end 0) (point) 1))))
7895 (previous-level (save-excursion
7898 (outline-previous-visible-heading 1)
7899 (if (looking-at ^re_)
7900 (- (match-end 0) (match-beginning 0) 1)
7903 (next-level (save-excursion
7906 (or (looking-at org-outline-regexp)
7907 (outline-next-visible-heading 1))
7908 (if (looking-at ^re_)
7909 (- (match-end 0) (match-beginning 0) 1)
7912 (new-level (or force-level (max previous-level next-level)))
7913 (shift (if (or (= old-level -1)
7915 (= old-level new-level))
7917 (- new-level old-level)))
7918 (delta (if (> shift 0) -1 1))
7919 (func (if (> shift 0) 'org-demote 'org-promote))
7920 (org-odd-levels-only nil)
7922 ;; Remove the forced level indicator
7924 (delete-region (point-at-bol) (point)))
7926 (beginning-of-line (if (bolp) 1 2))
7927 (unless for-yank (org-back-over-empty-lines))
7929 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7930 (insert-before-markers txt)
7931 (unless (string-match "\n\\'" txt) (insert "\n"))
7932 (setq newend (point))
7933 (org-reinstall-markers-in-region beg)
7936 (skip-chars-forward " \t\n\r")
7938 (if (and (outline-invisible-p) visp)
7939 (save-excursion (outline-show-heading)))
7940 ;; Shift if necessary
7943 (narrow-to-region beg end)
7944 (while (not (= shift 0))
7945 (org-map-region func (point-min) (point-max))
7946 (setq shift (+ delta shift)))
7947 (goto-char (point-min))
7948 (setq newend (point-max))))
7949 (when (or (org-called-interactively-p 'interactive) for-yank)
7950 (message "Clipboard pasted as level %d subtree" new-level))
7951 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7953 (eq org-subtree-clip (current-kill 0))
7954 org-subtree-clip-folded)
7955 ;; The tree was folded before it was killed/copied
7957 (and for-yank (goto-char newend)))))
7959 (defun org-kill-is-subtree-p (&optional txt)
7960 "Check if the current kill is an outline subtree, or a set of trees.
7961 Returns nil if kill does not start with a headline, or if the first
7962 headline level is not the largest headline level in the tree.
7963 So this will actually accept several entries of equal levels as well,
7964 which is OK for `org-paste-subtree'.
7965 If optional TXT is given, check this string instead of the current kill."
7966 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7967 (re (org-get-limited-outline-regexp))
7968 (^re (concat "^" re))
7969 (start-level (and kill
7971 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7973 (- (match-end 2) (match-beginning 2) 1)))
7974 (start (1+ (or (match-beginning 2) -1))))
7975 (if (not start-level)
7977 nil) ;; does not even start with a heading
7979 (while (setq start (string-match ^re kill (1+ start)))
7980 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7984 (defvar org-markers-to-move nil
7985 "Markers that should be moved with a cut-and-paste operation.
7986 Those markers are stored together with their positions relative to
7987 the start of the region.")
7989 (defun org-save-markers-in-region (beg end)
7990 "Check markers in region.
7991 If these markers are between BEG and END, record their position relative
7992 to BEG, so that after moving the block of text, we can put the markers back
7994 This function gets called just before an entry or tree gets cut from the
7995 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7996 called immediately, to move the markers with the entries."
7997 (setq org-markers-to-move nil)
7998 (when (featurep 'org-clock)
7999 (org-clock-save-markers-for-cut-and-paste beg end))
8000 (when (featurep 'org-agenda)
8001 (org-agenda-save-markers-for-cut-and-paste beg end)))
8003 (defun org-check-and-save-marker (marker beg end)
8004 "Check if MARKER is between BEG and END.
8005 If yes, remember the marker and the distance to BEG."
8006 (when (and (marker-buffer marker)
8007 (equal (marker-buffer marker) (current-buffer)))
8008 (if (and (>= marker beg) (< marker end))
8009 (push (cons marker (- marker beg)) org-markers-to-move))))
8011 (defun org-reinstall-markers-in-region (beg)
8012 "Move all remembered markers to their position relative to BEG."
8014 (move-marker (car x) (+ beg (cdr x))))
8015 org-markers-to-move)
8016 (setq org-markers-to-move nil))
8018 (defun org-narrow-to-subtree ()
8019 "Narrow buffer to the current subtree."
8023 (org-with-limited-levels
8025 (progn (org-back-to-heading t) (point))
8026 (progn (org-end-of-subtree t t)
8027 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8030 (defun org-narrow-to-block ()
8031 "Narrow buffer to the current block."
8033 (let* ((case-fold-search t)
8034 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8035 "^[ \t]*#\\+end_.*")))
8037 (narrow-to-region (car blockp) (cdr blockp))
8038 (error "Not in a block"))))
8041 (defvar org-property-drawer-re))
8043 (defvar org-property-start-re) ;; defined below
8044 (defun org-clone-subtree-with-time-shift (n &optional shift)
8045 "Clone the task (subtree) at point N times.
8046 The clones will be inserted as siblings.
8048 In interactive use, the user will be prompted for the number of
8049 clones to be produced, and for a time SHIFT, which may be a
8050 repeater as used in time stamps, for example `+3d'.
8052 When a valid repeater is given and the entry contains any time
8053 stamps, the clones will become a sequence in time, with time
8054 stamps in the subtree shifted for each clone produced. If SHIFT
8055 is nil or the empty string, time stamps will be left alone. The
8056 ID property of the original subtree is removed.
8058 If the original subtree did contain time stamps with a repeater,
8059 the following will happen:
8060 - the repeater will be removed in each clone
8061 - an additional clone will be produced, with the current, unshifted
8062 date(s) in the entry.
8063 - the original entry will be placed *after* all the clones, with
8065 - the start days in the repeater in the original entry will be shifted
8066 to past the last clone.
8067 In this way you can spell out a number of instances of a repeating task,
8068 and still retain the repeater to cover future instances of the task."
8069 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8070 (let (beg end template task idprop
8071 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8072 (drawer-re org-drawer-regexp))
8073 (if (not (and (integerp n) (> n 0)))
8074 (error "Invalid number of replications %s" n))
8075 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8076 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8078 (error "Invalid shift specification %s" shift))
8080 (setq shift-n (string-to-number (match-string 1 shift))
8081 shift-what (cdr (assoc (match-string 2 shift)
8082 '(("d" . day) ("w" . week)
8083 ("m" . month) ("y" . year))))))
8084 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8085 (setq nmin 1 nmax n)
8086 (org-back-to-heading t)
8088 (setq idprop (org-entry-get nil "ID"))
8089 (org-end-of-subtree t t)
8090 (or (bolp) (insert "\n"))
8092 (setq template (buffer-substring beg end))
8094 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8095 (delete-region beg end)
8097 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8099 (loop for n from nmin to nmax do
8104 (goto-char (point-min))
8106 (and idprop (if org-clone-delete-id
8107 (org-entry-delete nil "ID")
8108 (org-id-get-create t)))
8110 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8112 (goto-char (point-min))
8113 (while (re-search-forward drawer-re nil t)
8115 (org-remove-empty-drawer-at d (point))) org-drawers)))
8116 (goto-char (point-min))
8118 (while (re-search-forward org-ts-regexp-both nil t)
8119 (org-timestamp-change (* n shift-n) shift-what))
8120 (unless (= n n-no-remove)
8121 (goto-char (point-min))
8122 (while (re-search-forward org-ts-regexp nil t)
8124 (goto-char (match-beginning 0))
8125 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8126 (delete-region (match-beginning 1) (match-end 1)))))))
8127 (setq task (buffer-string)))
8133 (defun org-sort (with-case)
8134 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8135 Optional argument WITH-CASE means sort case-sensitively."
8138 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8139 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8141 (org-call-with-arg 'org-sort-entries with-case))))
8143 (defun org-sort-remove-invisible (s)
8144 (remove-text-properties 0 (length s) org-rm-props s)
8145 (while (string-match org-bracket-link-regexp s)
8146 (setq s (replace-match (if (match-end 2)
8148 (match-string 1 s)) t t s)))
8151 (defvar org-priority-regexp) ; defined later in the file
8153 (defvar org-after-sorting-entries-or-items-hook nil
8154 "Hook that is run after a bunch of entries or items have been sorted.
8155 When children are sorted, the cursor is in the parent line when this
8156 hook gets called. When a region or a plain list is sorted, the cursor
8157 will be in the first entry of the sorted region/list.")
8159 (defun org-sort-entries
8160 (&optional with-case sorting-type getkey-func compare-func property)
8161 "Sort entries on a certain level of an outline tree.
8162 If there is an active region, the entries in the region are sorted.
8163 Else, if the cursor is before the first entry, sort the top-level items.
8164 Else, the children of the entry at point are sorted.
8166 Sorting can be alphabetically, numerically, by date/time as given by
8167 a time stamp, by a property or by priority.
8169 The command prompts for the sorting type unless it has been given to the
8170 function through the SORTING-TYPE argument, which needs to be a character,
8171 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8172 precise meaning of each character:
8174 n Numerically, by converting the beginning of the entry/item to a number.
8175 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8176 t By date/time, either the first active time stamp in the entry, or, if
8177 none exist, by the first inactive one.
8178 s By the scheduled date/time.
8179 d By deadline date/time.
8180 c By creation time, which is assumed to be the first inactive time stamp
8181 at the beginning of a line.
8182 p By priority according to the cookie.
8183 r By the value of a property.
8185 Capital letters will reverse the sort order.
8187 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8188 called with point at the beginning of the record. It must return either
8189 a string or a number that should serve as the sorting key for that record.
8191 Comparing entries ignores case by default. However, with an optional argument
8192 WITH-CASE, the sorting considers case as well."
8194 (let ((case-func (if with-case 'identity 'downcase))
8195 start beg end stars re re2
8197 ;; Find beginning and end of region to sort
8199 ((org-region-active-p)
8200 ;; we will sort the region
8201 (setq end (region-end)
8203 (goto-char (region-beginning))
8204 (if (not (org-at-heading-p)) (outline-next-heading))
8205 (setq start (point)))
8206 ((or (org-at-heading-p)
8207 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8208 ;; we will sort the children of the current headline
8209 (org-back-to-heading)
8211 end (progn (org-end-of-subtree t t)
8212 (or (bolp) (insert "\n"))
8213 (org-back-over-empty-lines)
8218 (outline-next-heading))
8220 ;; we will sort the top-level entries in this file
8221 (goto-char (point-min))
8222 (or (org-at-heading-p) (outline-next-heading))
8223 (setq start (point))
8224 (goto-char (point-max))
8225 (beginning-of-line 1)
8226 (when (looking-at ".*?\\S-")
8227 ;; File ends in a non-white line
8230 (setq end (point-max))
8231 (setq what "top-level")
8236 (if (>= beg end) (error "Nothing to sort"))
8238 (looking-at "\\(\\*+\\)")
8239 (setq stars (match-string 1)
8240 re (concat "^" (regexp-quote stars) " +")
8241 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8242 txt (buffer-substring beg end))
8243 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8244 (if (and (not (equal stars "*")) (string-match re2 txt))
8245 (error "Region to sort contains a level above the first entry"))
8247 (unless sorting-type
8249 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8250 [t]ime
[s]cheduled [d]eadline [c]reated
8251 A/N/T/S/D/C/P/O/F means reversed:"
8253 (setq sorting-type (read-char-exclusive))
8255 (and (= (downcase sorting-type) ?f)
8257 (org-icompleting-read "Sort using function: "
8258 obarray 'fboundp t nil nil))
8259 (setq getkey-func (intern getkey-func)))
8261 (and (= (downcase sorting-type) ?r)
8263 (org-icompleting-read "Property: "
8264 (mapcar 'list (org-buffer-property-keys t))
8267 (message "Sorting entries...")
8270 (narrow-to-region start end)
8271 (let ((dcst (downcase sorting-type))
8272 (case-fold-search nil)
8273 (now (current-time)))
8275 (/= dcst sorting-type)
8276 ;; This function moves to the beginning character of the "record" to
8279 (if (re-search-forward re nil t)
8280 (goto-char (match-beginning 0))
8281 (goto-char (point-max))))
8282 ;; This function moves to the last character of the "record" being
8287 (outline-forward-same-level 1)
8289 (goto-char (point-max))))))
8290 ;; This function returns the value that gets sorted against.
8294 (if (looking-at org-complex-heading-regexp)
8295 (string-to-number (match-string 4))
8298 (if (looking-at org-complex-heading-regexp)
8299 (funcall case-func (match-string 4))
8302 (let ((end (save-excursion (outline-next-heading) (point))))
8303 (if (or (re-search-forward org-ts-regexp end t)
8304 (re-search-forward org-ts-regexp-both end t))
8305 (org-time-string-to-seconds (match-string 0))
8306 (org-float-time now))))
8308 (let ((end (save-excursion (outline-next-heading) (point))))
8309 (if (re-search-forward
8310 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8312 (org-time-string-to-seconds (match-string 0))
8313 (org-float-time now))))
8315 (let ((end (save-excursion (outline-next-heading) (point))))
8316 (if (re-search-forward org-scheduled-time-regexp end t)
8317 (org-time-string-to-seconds (match-string 1))
8318 (org-float-time now))))
8320 (let ((end (save-excursion (outline-next-heading) (point))))
8321 (if (re-search-forward org-deadline-time-regexp end t)
8322 (org-time-string-to-seconds (match-string 1))
8323 (org-float-time now))))
8325 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8326 (string-to-char (match-string 2))
8327 org-default-priority))
8329 (or (org-entry-get nil property) ""))
8331 (if (looking-at org-complex-heading-regexp)
8332 (- 9999 (length (member (match-string 2)
8333 org-todo-keywords-1)))))
8337 (setq tmp (funcall getkey-func))
8338 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8340 (error "Invalid key function `%s'" getkey-func)))
8341 (t (error "Invalid sorting type `%c'" sorting-type))))
8344 ((= dcst ?a) 'string<)
8345 ((= dcst ?f) compare-func)
8346 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8347 (run-hooks 'org-after-sorting-entries-or-items-hook)
8348 (message "Sorting entries...done")))
8350 (defun org-do-sort (table what &optional with-case sorting-type)
8351 "Sort TABLE of WHAT according to SORTING-TYPE.
8352 The user will be prompted for the SORTING-TYPE if the call to this
8353 function does not specify it. WHAT is only for the prompt, to indicate
8354 what is being sorted. The sorting key will be extracted from
8355 the car of the elements of the table.
8356 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8357 (unless sorting-type
8359 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8361 (setq sorting-type (read-char-exclusive)))
8362 (let ((dcst (downcase sorting-type))
8363 extractfun comparefun)
8364 ;; Define the appropriate functions
8367 (setq extractfun 'string-to-number
8368 comparefun (if (= dcst sorting-type) '< '>)))
8370 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8371 (lambda(x) (downcase (org-sort-remove-invisible x))))
8372 comparefun (if (= dcst sorting-type)
8374 (lambda (a b) (and (not (string< a b))
8375 (not (string= a b)))))))
8379 (if (or (string-match org-ts-regexp x)
8380 (string-match org-ts-regexp-both x))
8382 (org-time-string-to-time (match-string 0 x)))
8384 comparefun (if (= dcst sorting-type) '< '>)))
8385 (t (error "Invalid sorting type `%c'" sorting-type)))
8387 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8389 (lambda (a b) (funcall comparefun (car a) (car b))))))
8392 ;;; The orgstruct minor mode
8394 ;; Define a minor mode which can be used in other modes in order to
8395 ;; integrate the org-mode structure editing commands.
8397 ;; This is really a hack, because the org-mode structure commands use
8398 ;; keys which normally belong to the major mode. Here is how it
8399 ;; works: The minor mode defines all the keys necessary to operate the
8400 ;; structure commands, but wraps the commands into a function which
8401 ;; tests if the cursor is currently at a headline or a plain list
8402 ;; item. If that is the case, the structure command is used,
8403 ;; temporarily setting many Org-mode variables like regular
8404 ;; expressions for filling etc. However, when any of those keys is
8405 ;; used at a different location, function uses `key-binding' to look
8406 ;; up if the key has an associated command in another currently active
8407 ;; keymap (minor modes, major mode, global), and executes that
8408 ;; command. There might be problems if any of the keys is otherwise
8409 ;; used as a prefix key.
8411 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8412 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8413 ;; addresses this by checking explicitly for both bindings.
8415 (defvar orgstruct-mode-map (make-sparse-keymap)
8416 "Keymap for the minor `orgstruct-mode'.")
8418 (defvar org-local-vars nil
8419 "List of local variables, for use by `orgstruct-mode'.")
8422 (define-minor-mode orgstruct-mode
8423 "Toggle the minor mode `orgstruct-mode'.
8424 This mode is for using Org-mode structure commands in other
8425 modes. The following keys behave as if Org-mode were active, if
8426 the cursor is on a headline, or on a plain list item (both as
8427 defined by Org-mode).
8429 M-up Move entry/item up
8430 M-down Move entry/item down
8433 M-S-up Move entry/item up
8434 M-S-down Move entry/item down
8435 M-S-left Promote subtree
8436 M-S-right Demote subtree
8437 M-q Fill paragraph and items like in Org-mode
8439 C-c - Cycle list bullet
8440 TAB Cycle item visibility
8441 M-RET Insert new heading/item
8442 S-M-RET Insert new TODO heading / Checkbox item
8443 C-c C-c Set tags / toggle checkbox"
8444 nil " OrgStruct" nil
8445 (org-load-modules-maybe)
8446 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8449 (defun turn-on-orgstruct ()
8450 "Unconditionally turn on `orgstruct-mode'."
8453 (defvar org-fb-vars nil)
8454 (make-variable-buffer-local 'org-fb-vars)
8455 (defun orgstruct++-mode (&optional arg)
8456 "Toggle `orgstruct-mode', the enhanced version of it.
8457 In addition to setting orgstruct-mode, this also exports all
8458 indentation and autofilling variables from org-mode into the
8459 buffer. It will also recognize item context in multiline items."
8461 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8463 (progn (orgstruct-mode -1)
8465 (org-set-local (car v)
8466 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8469 (setq org-fb-vars nil)
8474 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8475 (symbol-name (car x)))
8476 (setq var (car x) val (nth 1 x))
8477 (push (list var `(quote ,(eval var))) org-fb-vars)
8478 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8480 (org-set-local 'orgstruct-is-++ t))))
8482 (defvar orgstruct-is-++ nil
8483 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8484 (make-variable-buffer-local 'orgstruct-is-++)
8487 (defun turn-on-orgstruct++ ()
8488 "Unconditionally turn on `orgstruct++-mode'."
8489 (orgstruct++-mode 1))
8491 (defun orgstruct-error ()
8492 "Error when there is no default binding for a structure key."
8494 (error "This key has no function outside structure elements"))
8496 (defun orgstruct-setup ()
8497 "Setup orgstruct keymaps."
8501 '([(meta up)] org-metaup)
8502 '([(meta down)] org-metadown)
8503 '([(meta left)] org-metaleft)
8504 '([(meta right)] org-metaright)
8505 '([(meta shift up)] org-shiftmetaup)
8506 '([(meta shift down)] org-shiftmetadown)
8507 '([(meta shift left)] org-shiftmetaleft)
8508 '([(meta shift right)] org-shiftmetaright)
8509 '([?\e (up)] org-metaup)
8510 '([?\e (down)] org-metadown)
8511 '([?\e (left)] org-metaleft)
8512 '([?\e (right)] org-metaright)
8513 '([?\e (shift up)] org-shiftmetaup)
8514 '([?\e (shift down)] org-shiftmetadown)
8515 '([?\e (shift left)] org-shiftmetaleft)
8516 '([?\e (shift right)] org-shiftmetaright)
8517 '([(shift up)] org-shiftup)
8518 '([(shift down)] org-shiftdown)
8519 '([(shift left)] org-shiftleft)
8520 '([(shift right)] org-shiftright)
8521 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8522 '("\M-q" fill-paragraph)
8524 '("\C-c-" org-cycle-list-bullet)))
8526 (while (setq elt (pop bindings))
8527 (setq nfunc (1+ nfunc))
8528 (setq key (org-key (car elt))
8530 cmd (orgstruct-make-binding fun nfunc key))
8531 (org-defkey orgstruct-mode-map key cmd))
8533 ;; Prevent an error for users who forgot to make autoloads
8534 (require 'org-element)
8536 ;; Special treatment needed for TAB and RET
8537 (org-defkey orgstruct-mode-map [(tab)]
8538 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8539 (org-defkey orgstruct-mode-map "\C-i"
8540 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8542 (org-defkey orgstruct-mode-map "\M-\C-m"
8543 (orgstruct-make-binding 'org-insert-heading 105
8544 "\M-\C-m" [(meta return)]))
8545 (org-defkey orgstruct-mode-map [(meta return)]
8546 (orgstruct-make-binding 'org-insert-heading 106
8547 [(meta return)] "\M-\C-m"))
8549 (org-defkey orgstruct-mode-map [(shift meta return)]
8550 (orgstruct-make-binding 'org-insert-todo-heading 107
8551 [(meta return)] "\M-\C-m"))
8553 (org-defkey orgstruct-mode-map "\e\C-m"
8554 (orgstruct-make-binding 'org-insert-heading 108
8555 "\e\C-m" [?\e (return)]))
8556 (org-defkey orgstruct-mode-map [?\e (return)]
8557 (orgstruct-make-binding 'org-insert-heading 109
8558 [?\e (return)] "\e\C-m"))
8559 (org-defkey orgstruct-mode-map [?\e (shift return)]
8560 (orgstruct-make-binding 'org-insert-todo-heading 110
8561 [?\e (return)] "\e\C-m"))
8563 (unless org-local-vars
8564 (setq org-local-vars (org-get-local-variables)))
8568 (defun orgstruct-make-binding (fun n &rest keys)
8569 "Create a function for binding in the structure minor mode.
8570 FUN is the command to call inside a table. N is used to create a unique
8571 command name. KEYS are keys that should be checked in for a command
8572 to execute outside of tables."
8575 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8577 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8578 "Outside of structure, run the binding of `"
8579 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8583 `(org-context-p 'headline 'item
8584 (and orgstruct-is-++
8585 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8587 (list 'org-run-like-in-org-mode (list 'quote fun))
8588 (list 'let '(orgstruct-mode)
8589 (list 'call-interactively
8592 (list 'key-binding k))
8594 '('orgstruct-error))))))))
8596 (defun org-contextualize-keys (alist contexts)
8597 "Return valid elements in ALIST depending on CONTEXTS.
8599 `org-agenda-custom-commands' or `org-capture-templates' are the
8600 values used for ALIST, and `org-agenda-custom-commands-contexts'
8601 or `org-capture-templates-contexts' are the associated contexts
8604 ;; normalize contexts
8606 (lambda(c) (cond ((listp (cadr c))
8607 (list (car c) (car c) (cadr c)))
8608 ((string= "" (cadr c))
8609 (list (car c) (car c) (caddr c)))
8612 ;; loop over all commands or templates
8613 (while (setq c (pop a))
8616 ((not (assoc (car c) contexts))
8618 ((and (assoc (car c) contexts)
8619 (setq vrules (org-contextualize-validate-key
8622 (when (not (equal (car vr) (cadr vr)))
8623 (setq repl vr))) vrules)
8624 (if (not repl) (push c r)
8625 (push (cadr repl) s)
8628 (cdr (or (assoc (cadr repl) alist)
8629 (error "Undefined key `%s' as contextual replacement for `%s'"
8630 (cadr repl) (car c)))))
8632 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8637 (let ((tpl (car x)))
8641 (equal y tpl)) s))) x)))
8644 (defun org-contextualize-validate-key (key contexts)
8645 "Check CONTEXTS for agenda or capture KEY."
8647 (while (setq r (pop contexts))
8651 (and (equal key (car r))
8652 (if (functionp rr) (funcall rr)
8653 (or (and (eq (car rr) 'in-file)
8655 (string-match (cdr rr) (buffer-file-name)))
8656 (and (eq (car rr) 'in-mode)
8657 (string-match (cdr rr) (symbol-name major-mode)))
8658 (when (and (eq (car rr) 'not-in-file)
8660 (not (string-match (cdr rr) (buffer-file-name))))
8661 (when (eq (car rr) 'not-in-mode)
8662 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8665 (delete-dups (delq nil res))))
8667 (defun org-context-p (&rest contexts)
8668 "Check if local context is any of CONTEXTS.
8669 Possible values in the list of contexts are `table', `headline', and `item'."
8670 (let ((pos (point)))
8671 (goto-char (point-at-bol))
8672 (prog1 (or (and (memq 'table contexts)
8673 (looking-at "[ \t]*|"))
8674 (and (memq 'headline contexts)
8675 (looking-at org-outline-regexp))
8676 (and (memq 'item contexts)
8677 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8678 (and (memq 'item-body contexts)
8682 (defun org-get-local-variables ()
8683 "Return a list of all local variables in an Org mode buffer."
8685 (with-current-buffer (get-buffer-create "*Org tmp*")
8688 (setq varlist (buffer-local-variables)))
8689 (kill-buffer "*Org tmp*")
8696 (list (car x) (list 'quote (cdr x)))))
8698 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8699 (symbol-name (car x)))
8703 (defun org-clone-local-variables (from-buffer &optional regexp)
8704 "Clone local variables from FROM-BUFFER.
8705 Optional argument REGEXP selects variables to clone."
8708 (and (symbolp (car pair))
8710 (string-match regexp (symbol-name (car pair))))
8711 (set (make-local-variable (car pair))
8713 (buffer-local-variables from-buffer)))
8716 (defun org-run-like-in-org-mode (cmd)
8717 "Run a command, pretending that the current buffer is in Org-mode.
8718 This will temporarily bind local variables that are typically bound in
8719 Org-mode to the values they have in Org-mode, and then interactively
8721 (org-load-modules-maybe)
8722 (unless org-local-vars
8723 (setq org-local-vars (org-get-local-variables)))
8724 (eval (list 'let org-local-vars
8725 (list 'call-interactively (list 'quote cmd)))))
8729 (defun org-get-category (&optional pos force-refresh)
8730 "Get the category applying to position POS."
8732 (if force-refresh (org-refresh-category-properties))
8733 (let ((pos (or pos (point))))
8734 (or (get-text-property pos 'org-category)
8735 (progn (org-refresh-category-properties)
8736 (get-text-property pos 'org-category))))))
8738 (defun org-refresh-category-properties ()
8739 "Refresh category text properties in the buffer."
8740 (let ((case-fold-search t)
8741 (inhibit-read-only t)
8743 ((null org-category)
8744 (if buffer-file-name
8745 (file-name-sans-extension
8746 (file-name-nondirectory buffer-file-name))
8748 ((symbolp org-category) (symbol-name org-category))
8750 beg end cat pos optionp)
8755 (goto-char (point-min))
8756 (put-text-property (point) (point-max) 'org-category def-cat)
8757 (while (re-search-forward
8758 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8759 (setq pos (match-end 0)
8760 optionp (equal (char-after (match-beginning 0)) ?#)
8761 cat (org-trim (match-string 2)))
8763 (setq beg (point-at-bol) end (point-max))
8764 (org-back-to-heading t)
8765 (setq beg (point) end (org-end-of-subtree t t)))
8766 (put-text-property beg end 'org-category cat)
8767 (put-text-property beg end 'org-category-position beg)
8768 (goto-char pos)))))))
8773 ;;; Link abbreviations
8775 (defun org-link-expand-abbrev (link)
8776 "Apply replacements as defined in `org-link-abbrev-alist'."
8777 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8778 (let* ((key (match-string 1 link))
8779 (as (or (assoc key org-link-abbrev-alist-local)
8780 (assoc key org-link-abbrev-alist)))
8781 (tag (and (match-end 2) (match-string 3 link)))
8787 ((symbolp rpl) (funcall rpl tag))
8788 ((string-match "%(\\([^)]+\\))" rpl)
8789 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8790 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8791 ((string-match "%h" rpl)
8792 (replace-match (url-hexify-string (or tag "")) t t rpl))
8793 (t (concat rpl tag)))))
8796 ;;; Storing and inserting links
8798 (defvar org-insert-link-history nil
8799 "Minibuffer history for links inserted with `org-insert-link'.")
8801 (defvar org-stored-links nil
8802 "Contains the links stored with `org-store-link'.")
8804 (defvar org-store-link-plist nil
8805 "Plist with info about the most recently link created with `org-store-link'.")
8807 (defvar org-link-protocols nil
8808 "Link protocols added to Org-mode using `org-add-link-type'.")
8810 (defvar org-store-link-functions nil
8811 "List of functions that are called to create and store a link.
8812 Each function will be called in turn until one returns a non-nil
8813 value. Each function should check if it is responsible for creating
8814 this link (for example by looking at the major mode).
8815 If not, it must exit and return nil.
8816 If yes, it should return a non-nil value after a calling
8817 `org-store-link-props' with a list of properties and values.
8818 Special properties are:
8820 :type The link prefix, like \"http\". This must be given.
8821 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8822 This is obligatory as well.
8823 :description Optional default description for the second pair
8824 of brackets in an Org-mode link. The user can still change
8825 this when inserting this link into an Org-mode buffer.
8827 In addition to these, any additional properties can be specified
8828 and then used in capture templates.")
8830 (defun org-add-link-type (type &optional follow export)
8831 "Add TYPE to the list of `org-link-types'.
8832 Re-compute all regular expressions depending on `org-link-types'
8834 FOLLOW and EXPORT are two functions.
8836 FOLLOW should take the link path as the single argument and do whatever
8837 is necessary to follow the link, for example find a file or display
8840 EXPORT should format the link path for export to one of the export formats.
8841 It should be a function accepting three arguments:
8843 path the path of the link, the text after the prefix (like \"http:\")
8844 desc the description of the link, if any, or a description added by
8845 org-export-normalize-links if there is none
8846 format the export format, a symbol like `html' or `latex' or `ascii'..
8848 The function may use the FORMAT information to return different values
8849 depending on the format. The return value will be put literally into
8850 the exported file. If the return value is nil, this means Org should
8851 do what it normally does with links which do not have EXPORT defined.
8853 Org-mode has a built-in default for exporting links. If you are happy with
8854 this default, there is no need to define an export function for the link
8855 type. For a simple example of an export function, see `org-bbdb.el'."
8856 (add-to-list 'org-link-types type t)
8857 (org-make-link-regexps)
8858 (if (assoc type org-link-protocols)
8859 (setcdr (assoc type org-link-protocols) (list follow export))
8860 (push (list type follow export) org-link-protocols)))
8862 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8863 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8866 (defun org-store-link (arg)
8867 "\\<org-mode-map>Store an org-link to the current location.
8868 This link is added to `org-stored-links' and can later be inserted
8869 into an org-buffer with \\[org-insert-link].
8871 For some link types, a prefix arg is interpreted:
8872 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8873 For file links, arg negates `org-context-in-file-links'."
8875 (org-load-modules-maybe)
8876 (setq org-store-link-plist nil) ; reset
8877 (org-with-limited-levels
8878 (let (link cpltxt desc description search txt custom-id agenda-link)
8881 ((run-hook-with-args-until-success 'org-store-link-functions)
8882 (setq link (plist-get org-store-link-plist :link)
8883 desc (or (plist-get org-store-link-plist :description) link)))
8885 ((org-src-edit-buffer-p)
8887 (while (or (not label)
8891 (goto-char (point-min))
8893 (regexp-quote (format org-coderef-label-format label))
8895 (when label (message "Label exists already") (sit-for 2))
8896 (setq label (read-string "Code line label: " label)))
8898 (setq link (format org-coderef-label-format label))
8899 (setq gc (- 79 (length link)))
8900 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8902 (setq link (concat "(" label ")") desc nil)))
8904 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8905 ;; We are in the agenda, link to referenced location
8906 (let ((m (or (get-text-property (point) 'org-hd-marker)
8907 (get-text-property (point) 'org-marker))))
8909 (org-with-point-at m
8911 (if (org-called-interactively-p 'any)
8912 (call-interactively 'org-store-link)
8913 (org-store-link nil)))))))
8915 ((eq major-mode 'calendar-mode)
8916 (let ((cd (calendar-cursor-to-date)))
8919 (car org-time-stamp-formats)
8921 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8923 (org-store-link-props :type "calendar" :date cd)))
8925 ((eq major-mode 'help-mode)
8926 (setq link (concat "help:" (save-excursion
8927 (goto-char (point-min))
8928 (looking-at "^[^ ]+")
8930 (org-store-link-props :type "help"))
8932 ((eq major-mode 'w3-mode)
8933 (setq cpltxt (if (and (buffer-name)
8934 (not (string-match "Untitled" (buffer-name))))
8937 link (url-view-url t))
8938 (org-store-link-props :type "w3" :url (url-view-url t)))
8940 ((eq major-mode 'w3m-mode)
8941 (setq cpltxt (or w3m-current-title w3m-current-url)
8942 link w3m-current-url)
8943 (org-store-link-props :type "w3m" :url (url-view-url t)))
8945 ((setq search (run-hook-with-args-until-success
8946 'org-create-file-search-functions))
8947 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8949 (setq cpltxt (or description link)))
8951 ((eq major-mode 'image-mode)
8952 (setq cpltxt (concat "file:"
8953 (abbreviate-file-name buffer-file-name))
8955 (org-store-link-props :type "image" :file buffer-file-name))
8957 ((eq major-mode 'dired-mode)
8958 ;; link to the file in the current line
8959 (let ((file (dired-get-filename nil t)))
8961 (abbreviate-file-name
8962 (expand-file-name (dired-get-filename nil t)))
8963 ;; otherwise, no file so use current directory.
8965 (setq cpltxt (concat "file:" file)
8968 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8969 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8971 ((org-in-regexp "<<\\(.*?\\)>>")
8974 (abbreviate-file-name
8975 (buffer-file-name (buffer-base-buffer)))
8976 "::" (match-string 1))
8978 ((and (featurep 'org-id)
8979 (or (eq org-link-to-org-use-id t)
8980 (and (org-called-interactively-p 'any)
8981 (or (eq org-link-to-org-use-id 'create-if-interactive)
8982 (and (eq org-link-to-org-use-id
8983 'create-if-interactive-and-no-custom-id)
8985 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
8986 ;; We can make a link using the ID.
8987 (setq link (condition-case nil
8988 (prog1 (org-id-store-link)
8989 (setq desc (plist-get org-store-link-plist :description)))
8991 ;; probably before first headline, link to file only
8993 (abbreviate-file-name
8994 (buffer-file-name (buffer-base-buffer))))))))
8996 ;; Just link to current headline
8997 (setq cpltxt (concat "file:"
8998 (abbreviate-file-name
8999 (buffer-file-name (buffer-base-buffer)))))
9000 ;; Add a context search string
9001 (when (org-xor org-context-in-file-links arg)
9003 ((org-at-heading-p) nil)
9004 ((org-region-active-p)
9005 (buffer-substring (region-beginning) (region-end)))))
9006 (when (or (null txt) (string-match "\\S-" txt))
9010 (org-make-org-heading-search-string txt)
9012 desc (or (nth 4 (ignore-errors
9013 (org-heading-components))) "NONE"))))
9014 (if (string-match "::\\'" cpltxt)
9015 (setq cpltxt (substring cpltxt 0 -2)))
9016 (setq link cpltxt))))
9018 ((buffer-file-name (buffer-base-buffer))
9019 ;; Just link to this file here.
9020 (setq cpltxt (concat "file:"
9021 (abbreviate-file-name
9022 (buffer-file-name (buffer-base-buffer)))))
9023 ;; Add a context string
9024 (when (org-xor org-context-in-file-links arg)
9025 (setq txt (if (org-region-active-p)
9026 (buffer-substring (region-beginning) (region-end))
9027 (buffer-substring (point-at-bol) (point-at-eol))))
9028 ;; Only use search option if there is some text.
9029 (when (string-match "\\S-" txt)
9031 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9035 ((org-called-interactively-p 'interactive)
9036 (error "Cannot link to a buffer which is not visiting a file"))
9038 (t (setq link nil)))
9040 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9041 (setq link (or link cpltxt)
9042 desc (or desc cpltxt))
9043 (if (equal desc "NONE") (setq desc nil))
9045 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9047 (setq org-stored-links
9048 (cons (list link desc) org-stored-links))
9049 (message "Stored: %s" (or desc link))
9051 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9053 (setq org-stored-links
9054 (cons (list link desc) org-stored-links))))
9055 (or agenda-link (and link (org-make-link-string link desc)))))))
9057 (defun org-store-link-props (&rest plist)
9058 "Store link properties, extract names and addresses."
9060 (when (setq x (plist-get plist :from))
9061 (setq adr (mail-extract-address-components x))
9062 (setq plist (plist-put plist :fromname (car adr)))
9063 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9064 (when (setq x (plist-get plist :to))
9065 (setq adr (mail-extract-address-components x))
9066 (setq plist (plist-put plist :toname (car adr)))
9067 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9068 (let ((from (plist-get plist :from))
9069 (to (plist-get plist :to)))
9070 (when (and from to org-from-is-user-regexp)
9072 (plist-put plist :fromto
9073 (if (string-match org-from-is-user-regexp from)
9075 (concat "from %f"))))))
9076 (setq org-store-link-plist plist))
9078 (defun org-add-link-props (&rest plist)
9079 "Add these properties to the link property list."
9082 (setq key (pop plist) value (pop plist))
9083 (setq org-store-link-plist
9084 (plist-put org-store-link-plist key value)))))
9086 (defun org-email-link-description (&optional fmt)
9087 "Return the description part of an email link.
9088 This takes information from `org-store-link-plist' and formats it
9089 according to FMT (default from `org-email-link-description-format')."
9090 (setq fmt (or fmt org-email-link-description-format))
9091 (let* ((p org-store-link-plist)
9092 (to (plist-get p :toaddress))
9093 (from (plist-get p :fromaddress))
9096 (cons "%c" (plist-get p :fromto))
9097 (cons "%F" (plist-get p :from))
9098 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9099 (cons "%T" (plist-get p :to))
9100 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9101 (cons "%s" (plist-get p :subject))
9102 (cons "%d" (plist-get p :date))
9103 (cons "%m" (plist-get p :message-id)))))
9104 (when (string-match "%c" fmt)
9105 ;; Check if the user wrote this message
9106 (if (and org-from-is-user-regexp from to
9107 (save-match-data (string-match org-from-is-user-regexp from)))
9108 (setq fmt (replace-match "to %t" t t fmt))
9109 (setq fmt (replace-match "from %f" t t fmt))))
9110 (org-replace-escapes fmt table)))
9112 (defun org-make-org-heading-search-string (&optional string heading)
9113 "Make search string for STRING or current headline."
9115 (let ((s (or string (org-get-heading)))
9116 (lines org-context-in-file-links))
9117 (unless (and string (not heading))
9118 ;; We are using a headline, clean up garbage in there.
9119 (if (string-match org-todo-regexp s)
9120 (setq s (replace-match "" t t s)))
9121 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9122 (setq s (replace-match "" t t s)))
9123 (setq s (org-trim s))
9124 (if (string-match (concat "^\\(" org-quote-string "\\|"
9125 org-comment-string "\\)") s)
9126 (setq s (replace-match "" t t s)))
9127 (while (string-match org-ts-regexp s)
9128 (setq s (replace-match "" t t s))))
9129 (or string (setq s (concat "*" s))) ; Add * for headlines
9130 (when (and string (integerp lines) (> lines 0))
9131 (let ((slines (org-split-string s "\n")))
9132 (when (< lines (length slines))
9135 (reverse (nthcdr (- (length slines) lines)
9136 (reverse slines))) "\n")))))
9137 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9139 (defun org-make-link-string (link &optional description)
9140 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9141 (unless (string-match "\\S-" link)
9142 (error "Empty link"))
9143 (when (and description
9144 (stringp description)
9145 (not (string-match "\\S-" description)))
9146 (setq description nil))
9147 (when (stringp description)
9148 ;; Remove brackets from the description, they are fatal.
9149 (while (string-match "\\[" description)
9150 (setq description (replace-match "{" t t description)))
9151 (while (string-match "\\]" description)
9152 (setq description (replace-match "}" t t description))))
9153 (when (equal link description)
9154 ;; No description needed, it is identical
9155 (setq description nil))
9156 (when (and (not description)
9157 (not (string-match (org-image-file-name-regexp) link))
9158 (not (equal link (org-link-escape link))))
9159 (setq description (org-extract-attributes link)))
9161 (cond ((string-match (org-image-file-name-regexp) link) link)
9162 ((string-match org-link-types-re link)
9163 (concat (match-string 1 link)
9164 (org-link-escape (substring link (match-end 1)))))
9165 (t (org-link-escape link))))
9166 (concat "[[" link "]"
9167 (if description (concat "[" description "]") "")
9170 (defconst org-link-escape-chars
9171 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9172 "List of characters that should be escaped in link.
9173 This is the list that is used for internal purposes.")
9175 (defconst org-link-escape-chars-browser
9177 "List of escapes for characters that are problematic in links.
9178 This is the list that is used before handing over to the browser.")
9180 (defun org-link-escape (text &optional table merge)
9181 "Return percent escaped representation of TEXT.
9182 TEXT is a string with the text to escape.
9183 Optional argument TABLE is a list with characters that should be
9184 escaped. When nil, `org-link-escape-chars' is used.
9185 If optional argument MERGE is set, merge TABLE into
9186 `org-link-escape-chars'."
9189 (mapc (lambda (defchr)
9190 (unless (member defchr table)
9191 (setq table (cons defchr table)))) org-link-escape-chars))
9193 (setq table org-link-escape-chars)))
9196 (if (or (member char table)
9197 (and (or (< char 32) (= char 37) (> char 126))
9199 (mapconcat (lambda (sequence-element)
9200 (format "%%%.2X" sequence-element))
9201 (or (encode-coding-char char 'utf-8)
9202 (error "Unable to percent escape character: %s"
9203 (char-to-string char))) "")
9204 (char-to-string char))) text ""))
9206 (defun org-link-unescape (str)
9207 "Unhex hexified Unicode strings as returned from the JavaScript function
9208 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9209 (unless (and (null str) (string= "" str))
9210 (let ((pos 0) (case-fold-search t) unhexed)
9211 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9212 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9213 (setq str (replace-match unhexed t t str))
9214 (setq pos (+ pos (length unhexed))))))
9217 (defun org-link-unescape-compound (hex)
9218 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9219 Note: this function also decodes single byte encodings like
9220 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9222 (let* ((bytes (cdr (split-string hex "%")))
9227 (let* ((val (string-to-number (pop bytes) 16))
9231 ((>= val 252) (cons 6 252))
9232 ((>= val 248) (cons 5 248))
9233 ((>= val 240) (cons 4 240))
9234 ((>= val 224) (cons 3 224))
9235 ((>= val 192) (cons 2 192))
9238 (if (>= val 192) (setq eat (car shift-xor)))
9239 (setq val (logxor val (cdr shift-xor)))
9240 (setq sum (+ (lsh sum (car shift-xor)) val))
9241 (if (> eat 0) (setq eat (- eat 1)))
9243 ((= 0 eat) ;multi byte
9244 (setq ret (concat ret (org-char-to-string sum)))
9246 ((not bytes) ; single byte(s)
9247 (setq ret (org-link-unescape-single-byte-sequence hex))))
9248 )) ;; end (while bytes
9251 (defun org-link-unescape-single-byte-sequence (hex)
9252 "Unhexify hex-encoded single byte character sequences."
9253 (mapconcat (lambda (byte)
9254 (char-to-string (string-to-number byte 16)))
9255 (cdr (split-string hex "%")) ""))
9257 (defun org-xor (a b)
9261 (defun org-fixup-message-id-for-http (s)
9262 "Replace special characters in a message id, so it can be used in an http query."
9263 (when (string-match "%" s)
9264 (setq s (mapconcat (lambda (c)
9267 (char-to-string c)))
9269 (while (string-match "<" s)
9270 (setq s (replace-match "%3C" t t s)))
9271 (while (string-match ">" s)
9272 (setq s (replace-match "%3E" t t s)))
9273 (while (string-match "@" s)
9274 (setq s (replace-match "%40" t t s)))
9277 (defun org-link-prettify (link)
9278 "Return a human-readable representation of LINK.
9279 The car of LINK must be a raw link the cdr of LINK must be either
9280 a link description or nil."
9281 (let ((desc (or (cadr link) "<no description>")))
9282 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9283 "<" (car link) ">")))
9286 (defun org-insert-link-global ()
9287 "Insert a link like Org-mode does.
9288 This command can be called in any mode to insert a link in Org-mode syntax."
9290 (org-load-modules-maybe)
9291 (org-run-like-in-org-mode 'org-insert-link))
9293 (defun org-insert-all-links (&optional keep)
9294 "Insert all links in `org-stored-links'."
9296 (let ((links (copy-sequence org-stored-links)) l)
9297 (while (setq l (if keep (pop links) (pop org-stored-links)))
9299 (org-insert-link nil (car l) (cadr l))
9302 (defun org-link-fontify-links-to-this-file ()
9303 "Fontify links to the current file in `org-stored-links'."
9304 (let ((f (buffer-file-name)) a b)
9305 (setq a (mapcar (lambda(l)
9307 (when (and (string-match "^file:\\(.+\\)::" ll)
9308 (equal f (expand-file-name (match-string 1 ll))))
9311 (when (featurep 'org-id)
9312 (setq b (mapcar (lambda(l)
9314 (when (and (string-match "^id:\\(.+\\)$" ll)
9315 (equal f (expand-file-name
9316 (or (org-id-find-id-file
9317 (match-string 1 ll)) ""))))
9321 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9322 (delq nil (append a b)))))
9324 (defvar org-link-links-in-this-file nil)
9325 (defun org-insert-link (&optional complete-file link-location default-description)
9326 "Insert a link. At the prompt, enter the link.
9328 Completion can be used to insert any of the link protocol prefixes like
9331 The history can be used to select a link previously stored with
9332 `org-store-link'. When the empty string is entered (i.e. if you just
9333 press RET at the prompt), the link defaults to the most recently
9334 stored link. As SPC triggers completion in the minibuffer, you need to
9335 use M-SPC or C-q SPC to force the insertion of a space character.
9337 You will also be prompted for a description, and if one is given, it will
9338 be displayed in the buffer instead of the link.
9340 If there is already a link at point, this command will allow you to edit link
9341 and description parts.
9343 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9344 be selected using completion. The path to the file will be relative to the
9345 current directory if the file is in the current directory or a subdirectory.
9346 Otherwise, the link will be the absolute path as completed in the minibuffer
9347 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9348 option `org-link-file-path-type'.
9350 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9351 the current directory or below.
9353 With three \\[universal-argument] prefixes, negate the meaning of
9354 `org-keep-stored-link-after-insertion'.
9356 If `org-make-link-description-function' is non-nil, this function will be
9357 called with the link target, and the result will be the default
9360 If the LINK-LOCATION parameter is non-nil, this value will be
9361 used as the link location instead of reading one interactively.
9363 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9364 be used as the default description."
9366 (let* ((wcf (current-window-configuration))
9367 (region (if (org-region-active-p)
9368 (buffer-substring (region-beginning) (region-end))))
9369 (remove (and region (list (region-beginning) (region-end))))
9371 tmphist ; byte-compile incorrectly complains about this
9372 (link link-location)
9373 (abbrevs org-link-abbrev-alist-local)
9374 entry file all-prefixes auto-desc)
9376 (link-location) ; specified by arg, just use it.
9377 ((org-in-regexp org-bracket-link-regexp 1)
9378 ;; We do have a link at point, and we are going to edit it.
9379 (setq remove (list (match-beginning 0) (match-end 0)))
9380 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9381 (setq link (read-string "Link: "
9383 (org-match-string-no-properties 1)))))
9384 ((or (org-in-regexp org-angle-link-re)
9385 (org-in-regexp org-plain-link-re))
9386 ;; Convert to bracket link
9387 (setq remove (list (match-beginning 0) (match-end 0))
9388 link (read-string "Link: "
9389 (org-remove-angle-brackets (match-string 0)))))
9390 ((member complete-file '((4) (16)))
9391 ;; Completing read for file names.
9392 (setq link (org-file-complete-link complete-file)))
9394 ;; Read link, with completion for stored links.
9395 (org-link-fontify-links-to-this-file)
9396 (org-switch-to-buffer-other-window "*Org Links*")
9397 (with-current-buffer "*Org Links*"
9399 (insert "Insert a link.
9400 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9401 (when org-stored-links
9402 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9403 (insert (mapconcat 'org-link-prettify
9404 (reverse org-stored-links) "\n")))
9405 (goto-char (point-min)))
9406 (let ((cw (selected-window)))
9407 (select-window (get-buffer-window "*Org Links*" 'visible))
9408 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9409 (unless (pos-visible-in-window-p (point-max))
9410 (org-fit-window-to-buffer))
9411 (and (window-live-p cw) (select-window cw)))
9412 ;; Fake a link history, containing the stored links.
9413 (setq tmphist (append (mapcar 'car org-stored-links)
9414 org-insert-link-history))
9415 (setq all-prefixes (append (mapcar 'car abbrevs)
9416 (mapcar 'car org-link-abbrev-alist)
9421 (let ((org-completion-use-ido nil)
9422 (org-completion-use-iswitchb nil))
9423 (org-completing-read
9426 (mapcar (lambda (x) (list (concat x ":")))
9428 (mapcar 'car org-stored-links)
9429 (mapcar 'cadr org-stored-links))
9432 (caar org-stored-links))))
9433 (if (not (string-match "\\S-" link))
9434 (error "No link selected"))
9436 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9438 (if (or (member link all-prefixes)
9439 (and (equal ":" (substring link -1))
9440 (member (substring link 0 -1) all-prefixes)
9441 (setq link (substring link 0 -1))))
9442 (setq link (org-link-try-special-completion link))))
9443 (set-window-configuration wcf)
9444 (kill-buffer "*Org Links*"))
9445 (setq entry (assoc link org-stored-links))
9446 (or entry (push link org-insert-link-history))
9447 (setq desc (or desc (nth 1 entry)))))
9449 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9450 (not org-keep-stored-link-after-insertion))
9451 (setq org-stored-links (delq (assoc link org-stored-links)
9454 (if (string-match org-plain-link-re link)
9455 ;; URL-like link, normalize the use of angular brackets.
9456 (setq link (org-remove-angle-brackets link)))
9458 ;; Check if we are linking to the current file with a search option
9459 ;; If yes, simplify the link by using only the search option.
9460 (when (and buffer-file-name
9461 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9462 (let* ((path (match-string 1 link))
9463 (case-fold-search nil)
9464 (search (match-string 2 link)))
9466 (if (equal (file-truename buffer-file-name) (file-truename path))
9467 ;; We are linking to this same file, with a search option
9468 (setq link search)))))
9470 ;; Check if we can/should use a relative path. If yes, simplify the link
9471 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9472 (let* ((type (match-string 1 link))
9473 (path (match-string 2 link))
9475 (case-fold-search nil))
9477 ((or (eq org-link-file-path-type 'absolute)
9478 (equal complete-file '(16)))
9479 (setq path (abbreviate-file-name (expand-file-name path))))
9480 ((eq org-link-file-path-type 'noabbrev)
9481 (setq path (expand-file-name path)))
9482 ((eq org-link-file-path-type 'relative)
9483 (setq path (file-relative-name path)))
9486 (if (string-match (concat "^" (regexp-quote
9488 (file-name-as-directory
9489 default-directory))))
9490 (expand-file-name path))
9491 ;; We are linking a file with relative path name.
9492 (setq path (substring (expand-file-name path)
9494 (setq path (abbreviate-file-name (expand-file-name path)))))))
9495 (setq link (concat type path))
9496 (if (equal desc origpath)
9499 (if org-make-link-description-function
9501 (or (condition-case nil
9502 (funcall org-make-link-description-function link desc)
9503 (error (progn (message "Can't get link description from `%s'"
9504 (symbol-name org-make-link-description-function))
9506 (read-string "Description: " default-description)))
9507 (if default-description (setq desc default-description)
9508 (setq desc (or (and auto-desc desc)
9509 (read-string "Description: " desc)))))
9511 (unless (string-match "\\S-" desc) (setq desc nil))
9512 (if remove (apply 'delete-region remove))
9513 (insert (org-make-link-string link desc))))
9515 (defun org-link-try-special-completion (type)
9516 "If there is completion support for link type TYPE, offer it."
9517 (let ((fun (intern (concat "org-" type "-complete-link"))))
9520 (read-string "Link (no completion support): " (concat type ":")))))
9522 (defun org-file-complete-link (&optional arg)
9523 "Create a file link using completion."
9525 (setq file (read-file-name "File: "))
9526 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9527 (pwd1 (file-name-as-directory (abbreviate-file-name
9528 (expand-file-name ".")))))
9533 (abbreviate-file-name (expand-file-name file)))))
9534 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9535 (setq link (concat "file:" (match-string 1 file))))
9536 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9537 (expand-file-name file))
9539 "file:" (match-string 1 (expand-file-name file)))))
9540 (t (setq link (concat "file:" file)))))
9543 (defun org-completing-read (&rest args)
9544 "Completing-read with SPACE being a normal character."
9545 (let ((enable-recursive-minibuffers t)
9546 (minibuffer-local-completion-map
9547 (copy-keymap minibuffer-local-completion-map)))
9548 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9549 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9550 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9551 (apply 'org-icompleting-read args)))
9553 (defun org-completing-read-no-i (&rest args)
9554 (let (org-completion-use-ido org-completion-use-iswitchb)
9555 (apply 'org-completing-read args)))
9557 (defun org-iswitchb-completing-read (prompt choices &rest args)
9558 "Use iswitch as a completing-read replacement to choose from choices.
9559 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9561 (let* ((iswitchb-use-virtual-buffers nil)
9562 (iswitchb-make-buflist-hook
9564 (setq iswitchb-temp-buflist choices))))
9565 (iswitchb-read-buffer prompt)))
9567 (defun org-icompleting-read (&rest args)
9568 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9569 (org-without-partial-completion
9570 (if (and org-completion-use-ido
9571 (fboundp 'ido-completing-read)
9572 (boundp 'ido-mode) ido-mode
9573 (listp (second args)))
9574 (let ((ido-enter-matching-directory nil))
9575 (apply 'ido-completing-read (concat (car args))
9576 (if (consp (car (nth 1 args)))
9577 (mapcar 'car (nth 1 args))
9580 (if (and org-completion-use-iswitchb
9581 (boundp 'iswitchb-mode) iswitchb-mode
9582 (listp (second args)))
9583 (apply 'org-iswitchb-completing-read (concat (car args))
9584 (if (consp (car (nth 1 args)))
9585 (mapcar 'car (nth 1 args))
9588 (apply 'completing-read args)))))
9590 (defun org-extract-attributes (s)
9591 "Extract the attributes cookie from a string and set as text property."
9592 (let (a attr (start 0) key value)
9594 (when (string-match "{{\\([^}]+\\)}}$" s)
9595 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9596 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9597 (setq key (match-string 1 a) value (match-string 2 a)
9599 attr (plist-put attr (intern key) value))))
9600 (org-add-props s nil 'org-attr attr))
9603 (defun org-extract-attributes-from-string (tag)
9604 (let (key value attr)
9605 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9606 (setq key (match-string 1 tag) value (match-string 2 tag)
9607 tag (replace-match "" t t tag)
9608 attr (plist-put attr (intern key) value)))
9611 (defun org-attributes-to-string (plist)
9612 "Format a property list into an HTML attribute list."
9613 (let ((s "") key value)
9615 (setq key (pop plist) value (pop plist))
9617 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9620 ;;; Opening/following a link
9622 (defvar org-link-search-failed nil)
9624 (defvar org-open-link-functions nil
9625 "Hook for functions finding a plain text link.
9626 These functions must take a single argument, the link content.
9627 They will be called for links that look like [[link text][description]]
9628 when LINK TEXT does not have a protocol like \"http:\" and does not look
9629 like a filename (e.g. \"./blue.png\").
9631 These functions will be called *before* Org attempts to resolve the
9632 link by doing text searches in the current buffer - so if you want a
9633 link \"[[target]]\" to still find \"<<target>>\", your function should
9634 handle this as a special case.
9636 When the function does handle the link, it must return a non-nil value.
9637 If it decides that it is not responsible for this link, it must return
9638 nil to indicate that that Org-mode can continue with other options
9639 like exact and fuzzy text search.")
9641 (defun org-next-link ()
9642 "Move forward to the next link.
9643 If the link is in hidden text, expose it."
9645 (when (and org-link-search-failed (eq this-command last-command))
9646 (goto-char (point-min))
9647 (message "Link search wrapped back to beginning of buffer"))
9648 (setq org-link-search-failed nil)
9649 (let* ((pos (point))
9651 (a (assoc :link ct)))
9652 (if a (goto-char (nth 2 a)))
9653 (if (re-search-forward org-any-link-re nil t)
9655 (goto-char (match-beginning 0))
9656 (if (outline-invisible-p) (org-show-context)))
9658 (setq org-link-search-failed t)
9659 (error "No further link found"))))
9661 (defun org-previous-link ()
9662 "Move backward to the previous link.
9663 If the link is in hidden text, expose it."
9665 (when (and org-link-search-failed (eq this-command last-command))
9666 (goto-char (point-max))
9667 (message "Link search wrapped back to end of buffer"))
9668 (setq org-link-search-failed nil)
9669 (let* ((pos (point))
9671 (a (assoc :link ct)))
9672 (if a (goto-char (nth 1 a)))
9673 (if (re-search-backward org-any-link-re nil t)
9675 (goto-char (match-beginning 0))
9676 (if (outline-invisible-p) (org-show-context)))
9678 (setq org-link-search-failed t)
9679 (error "No further link found"))))
9681 (defun org-translate-link (s)
9682 "Translate a link string if a translation function has been defined."
9683 (if (and org-link-translation-function
9684 (fboundp org-link-translation-function)
9685 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9687 (setq s (funcall org-link-translation-function
9688 (match-string 1 s) (match-string 2 s)))
9689 (concat (car s) ":" (cdr s)))
9692 (defun org-translate-link-from-planner (type path)
9693 "Translate a link from Emacs Planner syntax so that Org can follow it.
9694 This is still an experimental function, your mileage may vary."
9696 ((member type '("http" "https" "news" "ftp"))
9697 ;; standard Internet links are the same.
9699 ((and (equal type "irc") (string-match "^//" path))
9700 ;; Planner has two / at the beginning of an irc link, we have 1.
9701 ;; We should have zero, actually....
9702 (setq path (substring path 1)))
9703 ((and (equal type "lisp") (string-match "^/" path))
9704 ;; Planner has a slash, we do not.
9705 (setq type "elisp" path (substring path 1)))
9706 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9707 ;; A typical message link. Planner has the id after the final slash,
9708 ;; we separate it with a hash mark
9709 (setq path (concat (match-string 1 path) "#"
9710 (org-remove-angle-brackets (match-string 2 path)))))
9714 (defun org-find-file-at-mouse (ev)
9715 "Open file link or URL at mouse."
9717 (mouse-set-point ev)
9718 (org-open-at-point 'in-emacs))
9720 (defun org-open-at-mouse (ev)
9721 "Open file link or URL at mouse.
9722 See the docstring of `org-open-file' for details."
9724 (mouse-set-point ev)
9725 (if (eq major-mode 'org-agenda-mode)
9726 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9727 (org-open-at-point))
9729 (defvar org-window-config-before-follow-link nil
9730 "The window configuration before following a link.
9731 This is saved in case the need arises to restore it.")
9733 (defvar org-open-link-marker (make-marker)
9734 "Marker pointing to the location where `org-open-at-point; was called.")
9737 (defun org-open-at-point-global ()
9738 "Follow a link like Org-mode does.
9739 This command can be called in any mode to follow a link that has
9742 (org-run-like-in-org-mode 'org-open-at-point))
9745 (defun org-open-link-from-string (s &optional arg reference-buffer)
9746 "Open a link in the string S, as if it was in Org-mode."
9747 (interactive "sLink: \nP")
9748 (let ((reference-buffer (or reference-buffer (current-buffer))))
9750 (let ((org-inhibit-startup (not reference-buffer)))
9753 (goto-char (point-min))
9754 (when reference-buffer
9755 (setq org-link-abbrev-alist-local
9756 (with-current-buffer reference-buffer
9757 org-link-abbrev-alist-local)))
9758 (org-open-at-point arg reference-buffer)))))
9760 (defvar org-open-at-point-functions nil
9761 "Hook that is run when following a link at point.
9763 Functions in this hook must return t if they identify and follow
9764 a link at point. If they don't find anything interesting at point,
9765 they must return nil.")
9767 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9768 (defun org-open-at-point (&optional arg reference-buffer)
9769 "Open link at or after point.
9770 If there is no link at point, this function will search forward up to
9771 the end of the current line.
9772 Normally, files will be opened by an appropriate application. If the
9773 optional prefix argument ARG is non-nil, Emacs will visit the file.
9774 With a double prefix argument, try to open outside of Emacs, in the
9775 application the system uses for this file type."
9777 ;; if in a code block, then open the block's results
9778 (unless (call-interactively #'org-babel-open-src-block-result)
9779 (org-load-modules-maybe)
9780 (move-marker org-open-link-marker (point))
9781 (setq org-window-config-before-follow-link (current-window-configuration))
9782 (org-remove-occur-highlights nil nil t)
9784 ((and (org-at-heading-p)
9785 (not (org-at-timestamp-p t))
9787 (concat org-plain-link-re "\\|"
9788 org-bracket-link-regexp "\\|"
9789 org-angle-link-re "\\|"
9790 "[ \t]:[^ \t\n]+:[ \t]*$")))
9791 (not (get-text-property (point) 'org-linked-text)))
9792 (or (org-offer-links-in-entry arg)
9793 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9794 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9795 ((and (org-at-timestamp-p t)
9796 (not (org-in-regexp org-bracket-link-regexp)))
9797 (org-follow-timestamp-link))
9798 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9799 (not (org-in-regexp org-bracket-link-regexp)))
9800 (org-footnote-action))
9802 (let (type path link line search (pos (point)))
9805 (skip-chars-forward "^]\n\r")
9806 (when (org-in-regexp org-bracket-link-regexp 1)
9807 (setq link (org-extract-attributes
9808 (org-link-unescape (org-match-string-no-properties 1))))
9809 (while (string-match " *\n *" link)
9810 (setq link (replace-match " " t t link)))
9811 (setq link (org-link-expand-abbrev link))
9813 ((or (file-name-absolute-p link)
9814 (string-match "^\\.\\.?/" link))
9815 (setq type "file" path link))
9816 ((string-match org-link-re-with-space3 link)
9817 (setq type (match-string 1 link) path (match-string 2 link)))
9818 ((string-match "^help:+\\(.+\\)" link)
9819 (setq type "help" path (match-string 1 link)))
9820 (t (setq type "thisfile" path link)))
9823 (when (get-text-property (point) 'org-linked-text)
9824 (setq type "thisfile"
9825 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9826 (1+ (point)) (point))
9827 path (buffer-substring
9828 (or (previous-single-property-change pos 'org-linked-text)
9830 (or (next-single-property-change pos 'org-linked-text)
9835 (when (or (org-in-regexp org-angle-link-re)
9836 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9837 (save-match-data (not (looking-back "\\[\\[")))))
9838 (setq type (match-string 1)
9839 path (org-link-unescape (match-string 2)))
9842 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9844 path (match-string 1))
9845 (while (string-match ":" path)
9846 (setq path (replace-match "+" t t path)))
9848 (when (org-in-regexp "<\\([^><\n]+\\)>")
9849 (setq type "tree-match"
9850 path (match-string 1))
9853 (error "No link found"))
9855 ;; switch back to reference buffer
9856 ;; needed when if called in a temporary buffer through
9857 ;; org-open-link-from-string
9858 (with-current-buffer (or reference-buffer (current-buffer))
9860 ;; Remove any trailing spaces in path
9861 (if (string-match " +\\'" path)
9862 (setq path (replace-match "" t t path)))
9863 (if (and org-link-translation-function
9864 (fboundp org-link-translation-function))
9865 ;; Check if we need to translate the link
9866 (let ((tmp (funcall org-link-translation-function type path)))
9867 (setq type (car tmp) path (cdr tmp))))
9871 ((assoc type org-link-protocols)
9872 (funcall (nth 1 (assoc type org-link-protocols)) path))
9874 ((equal type "help")
9875 (let ((f-or-v (intern path)))
9876 (cond ((fboundp f-or-v)
9877 (describe-function f-or-v))
9879 (describe-variable f-or-v))
9880 (t (error "Not a known function or variable")))))
9882 ((equal type "mailto")
9883 (let ((cmd (car org-link-mailto-program))
9884 (args (cdr org-link-mailto-program)) args1
9885 (address path) (subject "") a)
9886 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9887 (setq address (match-string 1 path)
9888 subject (org-link-escape (match-string 2 path))))
9891 ((not (stringp (car args))) (push (pop args) args1))
9892 (t (setq a (pop args))
9893 (if (string-match "%a" a)
9894 (setq a (replace-match address t t a)))
9895 (if (string-match "%s" a)
9896 (setq a (replace-match subject t t a)))
9898 (apply cmd (nreverse args1))))
9900 ((member type '("http" "https" "ftp" "news"))
9901 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9903 path org-link-escape-chars-browser)
9906 ((string= type "doi")
9907 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9909 path org-link-escape-chars-browser)
9912 ((member type '("message"))
9913 (browse-url (concat type ":" path)))
9915 ((string= type "tags")
9916 (org-tags-view arg path))
9918 ((string= type "tree-match")
9919 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9921 ((string= type "file")
9922 (if (string-match "::\\([0-9]+\\)\\'" path)
9923 (setq line (string-to-number (match-string 1 path))
9924 path (substring path 0 (match-beginning 0)))
9925 (if (string-match "::\\(.+\\)\\'" path)
9926 (setq search (match-string 1 path)
9927 path (substring path 0 (match-beginning 0)))))
9928 (if (string-match "[*?{]" (file-name-nondirectory path))
9930 (org-open-file path arg line search)))
9932 ((string= type "shell")
9933 (let ((buf (generate-new-buffer "*Org Shell Output"))
9935 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9936 (string-match org-confirm-shell-link-not-regexp cmd))
9937 (not org-confirm-shell-link-function)
9938 (funcall org-confirm-shell-link-function
9939 (format "Execute \"%s\" in shell? "
9940 (org-add-props cmd nil
9941 'face 'org-warning))))
9943 (message "Executing %s" cmd)
9944 (shell-command cmd buf)
9945 (if (featurep 'midnight)
9946 (setq clean-buffer-list-kill-buffer-names
9947 (cons buf clean-buffer-list-kill-buffer-names))))
9950 ((string= type "elisp")
9952 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9953 (string-match org-confirm-elisp-link-not-regexp cmd))
9954 (not org-confirm-elisp-link-function)
9955 (funcall org-confirm-elisp-link-function
9956 (format "Execute \"%s\" as elisp? "
9957 (org-add-props cmd nil
9958 'face 'org-warning))))
9959 (message "%s => %s" cmd
9960 (if (equal (string-to-char cmd) ?\()
9962 (call-interactively (read cmd))))
9965 ((and (string= type "thisfile")
9966 (run-hook-with-args-until-success
9967 'org-open-link-functions path)))
9969 ((string= type "thisfile")
9971 (switch-to-buffer-other-window
9972 (org-get-buffer-for-internal-link (current-buffer)))
9973 (org-mark-ring-push))
9974 (let ((cmd `(org-link-search
9976 ,(cond ((equal arg '(4)) ''occur)
9977 ((equal arg '(16)) ''org-occur))
9979 (condition-case nil (let ((org-link-search-inhibit-query t))
9981 (error (progn (widen) (eval cmd))))))
9983 (t (browse-url-at-point)))))))
9984 (move-marker org-open-link-marker nil)
9985 (run-hook-with-args 'org-follow-link-hook)))
9987 (defun org-offer-links-in-entry (&optional nth zero)
9988 "Offer links in the current entry and follow the selected link.
9989 If there is only one link, follow it immediately as well.
9990 If NTH is an integer, immediately pick the NTH link found.
9991 If ZERO is a string, check also this string for a link, and if
9992 there is one, offer it as link number zero."
9993 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9994 "\\(" org-angle-link-re "\\)\\|"
9995 "\\(" org-plain-link-re "\\)"))
9997 (in-emacs (if (integerp nth) nil nth))
9998 have-zero end links link c)
9999 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10000 (push (match-string 0 zero) links)
10001 (setq cnt (1- cnt) have-zero t))
10003 (org-back-to-heading t)
10004 (setq end (save-excursion (outline-next-heading) (point)))
10005 (while (re-search-forward re end t)
10006 (push (match-string 0) links))
10007 (setq links (org-uniquify (reverse links))))
10011 (message "No links"))
10012 ((equal (length links) 1)
10013 (setq link (list (car links))))
10014 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10015 (setq link (list (nth (if have-zero nth (1- nth)) links))))
10016 (t ; we have to select a link
10018 (save-window-excursion
10019 (delete-other-windows)
10020 (with-output-to-temp-buffer "*Select Link*"
10022 (if (not (string-match org-bracket-link-regexp l))
10023 (princ (format "[%c] %s\n" (incf cnt)
10024 (org-remove-angle-brackets l)))
10026 (princ (format "[%c] %s (%s)\n" (incf cnt)
10027 (match-string 3 l) (match-string 1 l)))
10028 (princ (format "[%c] %s\n" (incf cnt)
10029 (match-string 1 l))))))
10031 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10032 (message "Select link to open, RET to open all:")
10033 (setq c (read-char-exclusive))
10034 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10035 (when (equal c ?q) (error "Abort"))
10036 (if (equal c ?\C-m)
10038 (setq nth (- c ?0))
10039 (if have-zero (setq nth (1+ nth)))
10040 (unless (and (integerp nth) (>= (length links) nth))
10041 (error "Invalid link selection"))
10042 (setq link (list (nth (1- nth) links))))))
10044 (let ((buf (current-buffer)))
10046 (org-open-link-from-string l in-emacs buf))
10050 ;; Add special file links that specify the way of opening
10052 (org-add-link-type "file+sys" 'org-open-file-with-system)
10053 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10054 (defun org-open-file-with-system (path)
10055 "Open file at PATH using the system way of opening it."
10056 (org-open-file path 'system))
10057 (defun org-open-file-with-emacs (path)
10058 "Open file at PATH in Emacs."
10059 (org-open-file path 'emacs))
10060 (defun org-remove-file-link-modifiers ()
10061 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10062 (goto-char (point-min))
10063 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10064 (org-if-unprotected
10065 (replace-match "file:" t t))))
10066 (eval-after-load "org-exp"
10067 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10068 'org-remove-file-link-modifiers))
10070 ;;;; Time estimates
10072 (defun org-get-effort (&optional pom)
10073 "Get the effort estimate for the current entry."
10074 (org-entry-get pom org-effort-property))
10078 (defvar org-create-file-search-functions nil
10079 "List of functions to construct the right search string for a file link.
10080 These functions are called in turn with point at the location to
10081 which the link should point.
10083 A function in the hook should first test if it would like to
10084 handle this file type, for example by checking the `major-mode'
10085 or the file extension. If it decides not to handle this file, it
10086 should just return nil to give other functions a chance. If it
10087 does handle the file, it must return the search string to be used
10088 when following the link. The search string will be part of the
10089 file link, given after a double colon, and `org-open-at-point'
10090 will automatically search for it. If special measures must be
10091 taken to make the search successful, another function should be
10092 added to the companion hook `org-execute-file-search-functions',
10095 A function in this hook may also use `setq' to set the variable
10096 `description' to provide a suggestion for the descriptive text to
10097 be used for this link when it gets inserted into an Org-mode
10098 buffer with \\[org-insert-link].")
10100 (defvar org-execute-file-search-functions nil
10101 "List of functions to execute a file search triggered by a link.
10103 Functions added to this hook must accept a single argument, the
10104 search string that was part of the file link, the part after the
10105 double colon. The function must first check if it would like to
10106 handle this search, for example by checking the `major-mode' or
10107 the file extension. If it decides not to handle this search, it
10108 should just return nil to give other functions a chance. If it
10109 does handle the search, it must return a non-nil value to keep
10110 other functions from trying.
10112 Each function can access the current prefix argument through the
10113 variable `current-prefix-argument'. Note that a single prefix is
10114 used to force opening a link in Emacs, so it may be good to only
10115 use a numeric or double prefix to guide the search function.
10117 In case this is needed, a function in this hook can also restore
10118 the window configuration before `org-open-at-point' was called using:
10120 (set-window-configuration org-window-config-before-follow-link)")
10122 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10123 (defun org-link-search (s &optional type avoid-pos stealth)
10124 "Search for a link search option.
10125 If S is surrounded by forward slashes, it is interpreted as a
10126 regular expression. In org-mode files, this will create an `org-occur'
10127 sparse tree. In ordinary files, `occur' will be used to list matches.
10128 If the current buffer is in `dired-mode', grep will be used to search
10129 in all files. If AVOID-POS is given, ignore matches near that position.
10131 When optional argument STEALTH is non-nil, do not modify
10132 visibility around point, thus ignoring
10133 `org-show-hierarchy-above', `org-show-following-heading' and
10134 `org-show-siblings' variables."
10135 (let ((case-fold-search t)
10136 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10137 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10138 (append '(("") (" ") ("\t") ("\n"))
10139 org-emphasis-alist)
10142 (pre nil) (post nil)
10143 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10145 ;; First check if there are any special search functions
10146 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10147 ;; Now try the builtin stuff
10148 ((and (equal (string-to-char s0) ?#)
10151 (goto-char (point-min))
10154 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10155 (setq type 'dedicated
10156 pos (match-beginning 0))))
10157 ;; There is an exact target for this
10159 (org-back-to-heading t)))
10161 (goto-char (point-min))
10164 (concat "<<" (regexp-quote s0) ">>") nil t)
10165 (setq type 'dedicated
10166 pos (match-beginning 0))))
10167 ;; There is an exact target for this
10170 (goto-char (point-min))
10173 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10174 (setq type 'dedicated pos (match-beginning 0))))
10175 ;; Found an invisible target.
10178 (goto-char (point-min))
10181 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10182 (setq type 'dedicated pos (match-beginning 0))))
10183 ;; Found an element with a matching #+name affiliated keyword.
10185 ((and (string-match "^(\\(.*\\))$" s0)
10187 (goto-char (point-min))
10190 (concat "[^[]" (regexp-quote
10191 (format org-coderef-label-format
10192 (match-string 1 s0))))
10194 (setq type 'dedicated
10195 pos (1+ (match-beginning 0))))))
10196 ;; There is a coderef target for this
10198 ((string-match "^/\\(.*\\)/$" s)
10199 ;; A regular expression
10201 ((derived-mode-p 'org-mode)
10202 (org-occur (match-string 1 s)))
10203 ;;((eq major-mode 'dired-mode)
10204 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10205 (t (org-do-occur (match-string 1 s)))))
10206 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10207 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10208 (goto-char (point-min))
10210 ((let (case-fold-search)
10211 (re-search-forward (format org-complex-heading-regexp-format
10214 ;; OK, found a match
10215 (setq type 'dedicated)
10216 (goto-char (match-beginning 0)))
10217 ((and (not org-link-search-inhibit-query)
10218 (eq org-link-search-must-match-exact-headline 'query-to-create)
10219 (y-or-n-p "No match - create this as a new heading? "))
10220 (goto-char (point-max))
10221 (or (bolp) (newline))
10222 (insert "* " s "\n")
10223 (beginning-of-line 0))
10226 (error "No match"))))
10228 ;; A normal search string
10229 (when (equal (string-to-char s) ?*)
10230 ;; Anchor on headlines, post may include tags.
10231 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10232 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10233 s (substring s 1)))
10234 (remove-text-properties
10236 '(face nil mouse-face nil keymap nil fontified nil) s)
10237 ;; Make a series of regular expressions to find a match
10238 (setq words (org-split-string s "[ \n\r\t]+")
10240 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10241 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10243 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10244 re2a (concat "[ \t\r\n]" re2a_)
10245 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10246 re4 (concat "[^a-zA-Z_]" re4_)
10248 re1 (concat pre re2 post)
10249 re3 (concat pre (if pre re4_ re4) post)
10250 re5 (concat pre ".*" re4)
10251 re2 (concat pre re2)
10252 re2a (concat pre (if pre re2a_ re2a))
10253 re4 (concat pre (if pre re4_ re4))
10254 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10255 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10259 ((eq type 'org-occur) (org-occur reall))
10260 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10261 (t (goto-char (point-min))
10263 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10264 (org-search-not-self 1 re1 nil t)
10265 (org-search-not-self 1 re2 nil t)
10266 (org-search-not-self 1 re2a nil t)
10267 (org-search-not-self 1 re3 nil t)
10268 (org-search-not-self 1 re4 nil t)
10269 (org-search-not-self 1 re5 nil t)
10271 (goto-char (match-beginning 1))
10273 (error "No match"))))))
10274 (and (derived-mode-p 'org-mode)
10276 (org-show-context 'link-search))
10279 (defun org-search-not-self (group &rest args)
10280 "Execute `re-search-forward', but only accept matches that do not
10281 enclose the position of `org-open-link-marker'."
10282 (let ((m org-open-link-marker))
10284 (while (apply 're-search-forward args)
10285 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10286 (goto-char (match-end group))
10287 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10288 (> (match-beginning 0) (marker-position m))
10289 (< (match-end 0) (marker-position m)))
10291 (or (not (org-in-regexp
10292 org-bracket-link-analytic-regexp 1))
10293 (not (match-end 4)) ; no description
10294 (and (<= (match-beginning 4) (point))
10295 (>= (match-end 4) (point))))))
10296 (throw 'exit (point))))))))
10298 (defun org-get-buffer-for-internal-link (buffer)
10299 "Return a buffer to be used for displaying the link target of internal links."
10301 ((not org-display-internal-link-with-indirect-buffer)
10303 ((string-match "(Clone)$" (buffer-name buffer))
10304 (message "Buffer is already a clone, not making another one")
10305 ;; we also do not modify visibility in this case
10307 (t ; make a new indirect buffer for displaying the link
10308 (let* ((bn (buffer-name buffer))
10309 (ibn (concat bn "(Clone)"))
10310 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10311 (with-current-buffer ib (org-overview))
10314 (defun org-do-occur (regexp &optional cleanup)
10315 "Call the Emacs command `occur'.
10316 If CLEANUP is non-nil, remove the printout of the regular expression
10317 in the *Occur* buffer. This is useful if the regex is long and not useful
10321 (let ((cwin (selected-window)) win beg end)
10322 (when (setq win (get-buffer-window "*Occur*"))
10323 (select-window win))
10324 (goto-char (point-min))
10325 (when (re-search-forward "match[a-z]+" nil t)
10326 (setq beg (match-end 0))
10327 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10328 (setq end (1- (match-beginning 0)))))
10329 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10330 (goto-char (point-min))
10331 (select-window cwin))))
10333 ;;; The mark ring for links jumps
10335 (defvar org-mark-ring nil
10336 "Mark ring for positions before jumps in Org-mode.")
10337 (defvar org-mark-ring-last-goto nil
10338 "Last position in the mark ring used to go back.")
10339 ;; Fill and close the ring
10340 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10341 (loop for i from 1 to org-mark-ring-length do
10342 (push (make-marker) org-mark-ring))
10343 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10346 (defun org-mark-ring-push (&optional pos buffer)
10347 "Put the current position or POS into the mark ring and rotate it."
10349 (setq pos (or pos (point)))
10350 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10351 (move-marker (car org-mark-ring)
10353 (or buffer (current-buffer)))
10355 (substitute-command-keys
10356 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10358 (defun org-mark-ring-goto (&optional n)
10359 "Jump to the previous position in the mark ring.
10360 With prefix arg N, jump back that many stored positions. When
10361 called several times in succession, walk through the entire ring.
10362 Org-mode commands jumping to a different position in the current file,
10363 or to another Org-mode file, automatically push the old position
10367 (if (eq last-command this-command)
10368 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10369 (setq p org-mark-ring))
10370 (setq org-mark-ring-last-goto p)
10372 (org-pop-to-buffer-same-window (marker-buffer m))
10374 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10376 (defun org-remove-angle-brackets (s)
10377 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10378 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10380 (defun org-add-angle-brackets (s)
10381 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10382 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10384 (defun org-remove-double-quotes (s)
10385 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10386 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10389 ;;; Following specific links
10391 (defun org-follow-timestamp-link ()
10392 "Open an agenda view for the time-stamp date/range at point."
10394 ((org-at-date-range-p t)
10395 (let ((org-agenda-start-on-weekday)
10396 (t1 (match-string 1))
10397 (t2 (match-string 2)) tt1 tt2)
10398 (setq tt1 (time-to-days (org-time-string-to-time t1))
10399 tt2 (time-to-days (org-time-string-to-time t2)))
10400 (let ((org-agenda-buffer-tmp-name
10401 (format "*Org Agenda(a:%s)"
10402 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10403 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10404 ((org-at-timestamp-p t)
10405 (let ((org-agenda-buffer-tmp-name
10406 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10407 (org-agenda-list nil (time-to-days (org-time-string-to-time
10408 (substring (match-string 1) 0 10)))
10410 (t (error "This should not happen"))))
10413 ;;; Following file links
10414 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10415 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10416 (declare-function mailcap-mime-info
10417 "mailcap" (string &optional request no-decode))
10418 (defvar org-wait nil)
10419 (defun org-open-file (path &optional in-emacs line search)
10420 "Open the file at PATH.
10421 First, this expands any special file name abbreviations. Then the
10422 configuration variable `org-file-apps' is checked if it contains an
10423 entry for this file type, and if yes, the corresponding command is launched.
10425 If no application is found, Emacs simply visits the file.
10427 With optional prefix argument IN-EMACS, Emacs will visit the file.
10428 With a double \\[universal-argument] \\[universal-argument] \
10429 prefix arg, Org tries to avoid opening in Emacs
10430 and to use an external application to visit the file.
10432 Optional LINE specifies a line to go to, optional SEARCH a string
10433 to search for. If LINE or SEARCH is given, the file will be
10434 opened in Emacs, unless an entry from org-file-apps that makes
10435 use of groups in a regexp matches.
10437 If you want to change the way frames are used when following a
10438 link, please customize `org-link-frame-setup'.
10440 If the file does not exist, an error is thrown."
10441 (let* ((file (if (equal path "")
10443 (substitute-in-file-name (expand-file-name path))))
10444 (file-apps (append org-file-apps (org-default-apps)))
10445 (apps (org-remove-if
10446 'org-file-apps-entry-match-against-dlink-p file-apps))
10447 (apps-dlink (org-remove-if-not
10448 'org-file-apps-entry-match-against-dlink-p file-apps))
10449 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10450 (dirp (if remp nil (file-directory-p file)))
10451 (file (if (and dirp org-open-directory-means-index-dot-org)
10452 (concat (file-name-as-directory file) "index.org")
10454 (a-m-a-p (assq 'auto-mode apps))
10455 (dfile (downcase file))
10456 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10457 (link (cond ((and (eq line nil)
10461 (concat file "::" (number-to-string line)))
10463 (concat file "::" search))))
10464 (dlink (downcase link))
10465 (old-buffer (current-buffer))
10467 (old-mode major-mode)
10468 ext cmd link-match-data)
10469 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10470 (setq ext (match-string 1 dfile))
10471 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10472 (setq ext (match-string 1 dfile))))
10474 ((member in-emacs '((16) system))
10475 (setq cmd (cdr (assoc 'system apps))))
10476 (in-emacs (setq cmd 'emacs))
10478 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10479 (and dirp (cdr (assoc 'directory apps)))
10480 ; first, try matching against apps-dlink
10481 ; if we get a match here, store the match data for later
10482 (let ((match (assoc-default dlink apps-dlink
10485 (progn (setq link-match-data (match-data))
10487 (progn (setq in-emacs (or in-emacs line search))
10488 nil))) ; if we have no match in apps-dlink,
10489 ; always open the file in emacs if line or search
10490 ; is given (for backwards compatibility)
10491 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10493 (cdr (assoc ext apps))
10494 (cdr (assoc t apps))))))
10495 (when (eq cmd 'system)
10496 (setq cmd (cdr (assoc 'system apps))))
10497 (when (eq cmd 'default)
10498 (setq cmd (cdr (assoc t apps))))
10499 (when (eq cmd 'mailcap)
10501 (mailcap-parse-mailcaps)
10502 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10503 (command (mailcap-mime-info mime-type)))
10504 (if (stringp command)
10506 (setq cmd 'emacs))))
10507 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10508 (not (file-exists-p file))
10509 (not org-open-non-existing-files))
10510 (error "No such file: %s" file))
10512 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10513 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10514 (while (string-match "['\"]%s['\"]" cmd)
10515 (setq cmd (replace-match "%s" t t cmd)))
10516 (while (string-match "%s" cmd)
10517 (setq cmd (replace-match
10519 (shell-quote-argument
10520 (convert-standard-filename file)))
10523 ;; Replace "%1", "%2" etc. in command with group matches from regex
10525 (let ((match-index 1)
10526 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10527 (set-match-data link-match-data)
10528 (while (<= match-index number-of-groups)
10529 (let ((regex (concat "%" (number-to-string match-index)))
10530 (replace-with (match-string match-index dlink)))
10531 (while (string-match regex cmd)
10532 (setq cmd (replace-match replace-with t t cmd))))
10533 (setq match-index (+ match-index 1)))))
10535 (save-window-excursion
10536 (start-process-shell-command cmd nil cmd)
10537 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10541 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10543 (if line (org-goto-line line)
10544 (if search (org-link-search search))))
10546 (let ((file (convert-standard-filename file)))
10548 (set-match-data link-match-data)
10550 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10551 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10552 (or (not (equal old-buffer (current-buffer)))
10553 (not (equal old-pos (point))))
10554 (org-mark-ring-push old-pos old-buffer))))
10556 (defun org-file-apps-entry-match-against-dlink-p (entry)
10557 "This function returns non-nil if `entry' uses a regular
10558 expression which should be matched against the whole link by
10561 It assumes that is the case when the entry uses a regular
10562 expression which has at least one grouping construct and the
10563 action is either a lisp form or a command string containing
10564 '%1', i.e. using at least one subexpression match as a
10566 (let ((selector (car entry))
10567 (action (cdr entry)))
10568 (if (stringp selector)
10569 (and (> (regexp-opt-depth selector) 0)
10570 (or (and (stringp action)
10571 (string-match "%[0-9]" action))
10575 (defun org-default-apps ()
10576 "Return the default applications for this operating system."
10578 ((eq system-type 'darwin)
10579 org-file-apps-defaults-macosx)
10580 ((eq system-type 'windows-nt)
10581 org-file-apps-defaults-windowsnt)
10582 (t org-file-apps-defaults-gnu)))
10584 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10585 "Convert extensions to regular expressions in the cars of LIST.
10586 Also, weed out any non-string entries, because the return value is used
10587 only for regexp matching.
10588 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10589 point to the symbol `emacs', indicating that the file should
10590 be opened in Emacs."
10593 (mapcar (lambda (x)
10594 (if (not (stringp (car x)))
10596 (if (string-match "\\W" (car x))
10598 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10601 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10603 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10604 (defun org-file-remote-p (file)
10605 "Test whether FILE specifies a location on a remote system.
10606 Return non-nil if the location is indeed remote.
10608 For example, the filename \"/user@host:/foo\" specifies a location
10609 on the system \"/user@host:\"."
10610 (cond ((fboundp 'file-remote-p)
10611 (file-remote-p file))
10612 ((fboundp 'tramp-handle-file-remote-p)
10613 (tramp-handle-file-remote-p file))
10614 ((and (boundp 'ange-ftp-name-format)
10615 (string-match (car ange-ftp-name-format) file))
10621 (defun org-get-org-file ()
10622 "Read a filename, with default directory `org-directory'."
10623 (let ((default (or org-default-notes-file remember-data-file)))
10624 (read-file-name (format "File name [%s]: " default)
10625 (file-name-as-directory org-directory)
10628 (defun org-notes-order-reversed-p ()
10629 "Check if the current file should receive notes in reversed order."
10631 ((not org-reverse-note-order) nil)
10632 ((eq t org-reverse-note-order) t)
10633 ((not (listp org-reverse-note-order)) nil)
10635 (let ((all org-reverse-note-order)
10637 (while (setq entry (pop all))
10638 (if (string-match (car entry) buffer-file-name)
10639 (throw 'exit (cdr entry))))
10642 (defvar org-refile-target-table nil
10643 "The list of refile targets, created by `org-refile'.")
10645 (defvar org-agenda-new-buffers nil
10646 "Buffers created to visit agenda files.")
10648 (defvar org-refile-cache nil
10649 "Cache for refile targets.")
10651 (defvar org-refile-markers nil
10652 "All the markers used for caching refile locations.")
10654 (defun org-refile-marker (pos)
10655 "Get a new refile marker, but only if caching is in use."
10656 (if (not org-refile-use-cache)
10658 (let ((m (make-marker)))
10659 (move-marker m pos)
10660 (push m org-refile-markers)
10663 (defun org-refile-cache-clear ()
10664 "Clear the refile cache and disable all the markers."
10665 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10666 (setq org-refile-markers nil)
10667 (setq org-refile-cache nil)
10668 (message "Refile cache has been cleared"))
10670 (defun org-refile-cache-check-set (set)
10671 "Check if all the markers in the cache still have live buffers."
10674 (while (and set (setq marker (nth 3 (pop set))))
10675 ;; if org-refile-use-outline-path is 'file, marker may be nil
10676 (when (and marker (null (marker-buffer marker)))
10677 (message "not found") (sit-for 3)
10678 (throw 'exit nil)))
10681 (defun org-refile-cache-put (set &rest identifiers)
10682 "Push the refile targets SET into the cache, under IDENTIFIERS."
10683 (let* ((key (sha1 (prin1-to-string identifiers)))
10684 (entry (assoc key org-refile-cache)))
10687 (push (cons key set) org-refile-cache))))
10689 (defun org-refile-cache-get (&rest identifiers)
10690 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10692 ((not org-refile-cache) nil)
10693 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10695 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10696 org-refile-cache))))
10697 (and set (org-refile-cache-check-set set) set)))))
10699 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10700 "Produce a table with refile targets."
10701 (let ((case-fold-search nil)
10702 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10703 (entries (or org-refile-targets '((nil . (:level . 1)))))
10704 targets tgs txt re files f desc descre fast-path-p level pos0)
10705 (message "Getting targets...")
10706 (with-current-buffer (or default-buffer (current-buffer))
10707 (while (setq entry (pop entries))
10708 (setq files (car entry) desc (cdr entry))
10709 (setq fast-path-p nil)
10711 ((null files) (setq files (list (current-buffer))))
10712 ((eq files 'org-agenda-files)
10713 (setq files (org-agenda-files 'unrestricted)))
10714 ((and (symbolp files) (fboundp files))
10715 (setq files (funcall files)))
10716 ((and (symbolp files) (boundp files))
10717 (setq files (symbol-value files))))
10718 (if (stringp files) (setq files (list files)))
10720 ((eq (car desc) :tag)
10721 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10722 ((eq (car desc) :todo)
10723 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10724 ((eq (car desc) :regexp)
10725 (setq descre (cdr desc)))
10726 ((eq (car desc) :level)
10727 (setq descre (concat "^\\*\\{" (number-to-string
10728 (if org-odd-levels-only
10729 (1- (* 2 (cdr desc)))
10732 ((eq (car desc) :maxlevel)
10733 (setq fast-path-p t)
10734 (setq descre (concat "^\\*\\{1," (number-to-string
10735 (if org-odd-levels-only
10736 (1- (* 2 (cdr desc)))
10739 (t (error "Bad refiling target description %s" desc)))
10740 (while (setq f (pop files))
10741 (with-current-buffer
10742 (if (bufferp f) f (org-get-agenda-file-buffer f))
10744 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10746 (if (bufferp f) (setq f (buffer-file-name
10747 (buffer-base-buffer f))))
10748 (setq f (and f (expand-file-name f)))
10749 (if (eq org-refile-use-outline-path 'file)
10750 (push (list (file-name-nondirectory f) f nil nil) tgs))
10754 (goto-char (point-min))
10755 (while (re-search-forward descre nil t)
10756 (goto-char (setq pos0 (point-at-bol)))
10758 (when org-refile-target-verify-function
10760 (or (funcall org-refile-target-verify-function)
10762 (when (and (looking-at org-complex-heading-regexp)
10763 (not (member (match-string 4) excluded-entries))
10765 (setq level (org-reduced-level
10766 (- (match-end 1) (match-beginning 1)))
10767 txt (org-link-display-format (match-string 4))
10768 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10769 re (format org-complex-heading-regexp-format
10770 (regexp-quote (match-string 4))))
10771 (when org-refile-use-outline-path
10772 (setq txt (mapconcat
10775 (if (eq org-refile-use-outline-path
10777 (list (file-name-nondirectory
10779 (buffer-base-buffer))))
10780 (if (eq org-refile-use-outline-path
10782 (list (buffer-file-name
10783 (buffer-base-buffer)))))
10784 (org-get-outline-path fast-path-p
10788 (push (list txt f re (org-refile-marker (point)))
10790 (when (= (point) pos0)
10791 ;; verification function has not moved point
10792 (goto-char (point-at-eol))))))))
10793 (when org-refile-use-cache
10794 (org-refile-cache-put tgs (buffer-file-name) descre))
10795 (setq targets (append tgs targets))
10797 (message "Getting targets...done")
10798 (nreverse targets)))
10800 (defun org-protect-slash (s)
10801 (while (string-match "/" s)
10802 (setq s (replace-match "\\" t t s)))
10805 (defvar org-olpa (make-vector 20 nil))
10807 (defun org-get-outline-path (&optional fastp level heading)
10808 "Return the outline path to the current entry, as a list.
10810 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10811 routine which makes outline path derivations for an entire file,
10812 avoiding backtracing. Refile target collection makes use of that."
10816 (error "Outline path failure, more than 19 levels"))
10817 (loop for i from level upto 19 do
10818 (aset org-olpa i nil))
10820 (delq nil (append org-olpa nil))
10821 (aset org-olpa level heading)))
10822 (let (rtn case-fold-search)
10826 (while (org-up-heading-safe)
10827 (when (looking-at org-complex-heading-regexp)
10828 (push (org-match-string-no-properties 4) rtn)))
10831 (defun org-format-outline-path (path &optional width prefix)
10832 "Format the outline path PATH for display.
10833 Width is the maximum number of characters that is available.
10834 Prefix is a prefix to be included in the returned string,
10835 such as the file name."
10836 (setq width (or width 79))
10837 (if prefix (setq width (- width (length prefix))))
10840 (let* ((nsteps (length path))
10841 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10842 (maxwidth (if (<= total-width width)
10843 10000 ;; everything fits
10844 ;; we need to shorten the level headings
10845 (/ (- width nsteps) nsteps)))
10846 (org-odd-levels-only nil)
10848 (total (1+ (length prefix))))
10849 (setq maxwidth (max maxwidth 10))
10854 (if (and (= n nsteps) (< maxwidth 10000))
10855 (setq maxwidth (- total-width total)))
10856 (if (< (length h) maxwidth)
10857 (progn (setq total (+ total (length h) 1)) h)
10858 (setq h (substring h 0 (- maxwidth 2))
10859 total (+ total maxwidth 1))
10860 (if (string-match "[ \t]+\\'" h)
10861 (setq h (substring h 0 (match-beginning 0))))
10862 (setq h (concat h "..")))
10863 (org-add-props h nil 'face
10864 (nth (% (1- n) org-n-level-faces)
10869 (defun org-display-outline-path (&optional file current)
10870 "Display the current outline path in the echo area."
10872 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10873 (case-fold-search nil)
10874 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10875 (if current (setq path (append path
10877 (org-back-to-heading t)
10878 (if (looking-at org-complex-heading-regexp)
10879 (list (match-string 4)))))))
10881 (org-format-outline-path
10884 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10886 (defvar org-refile-history nil
10887 "History for refiling operations.")
10889 (defvar org-after-refile-insert-hook nil
10890 "Hook run after `org-refile' has inserted its stuff at the new location.
10891 Note that this is still *before* the stuff will be removed from
10892 the *old* location.")
10894 (defvar org-capture-last-stored-marker)
10895 (defun org-refile (&optional goto default-buffer rfloc)
10896 "Move the entry or entries at point to another heading.
10897 The list of target headings is compiled using the information in
10898 `org-refile-targets', which see.
10900 At the target location, the entry is filed as a subitem of the target
10901 heading. Depending on `org-reverse-note-order', the new subitem will
10902 either be the first or the last subitem.
10904 If there is an active region, all entries in that region will be moved.
10905 However, the region must fulfill the requirement that the first heading
10906 is the first one sets the top-level of the moved text - at most siblings
10907 below it are allowed.
10909 With prefix arg GOTO, the command will only visit the target location
10910 and not actually move anything.
10912 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10913 go to the location where the last refiling operation has put the subtree.
10914 With a prefix argument of `2', refile to the running clock.
10916 RFLOC can be a refile location obtained in a different way.
10918 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10920 If you are using target caching (see `org-refile-use-cache'),
10921 you have to clear the target cache in order to find new targets.
10922 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10923 prefix argument (`C-u C-u C-u C-c C-w')."
10926 (if (member goto '(0 (64)))
10927 (org-refile-cache-clear)
10928 (let* ((cbuf (current-buffer))
10929 (regionp (org-region-active-p))
10930 (region-start (and regionp (region-beginning)))
10931 (region-end (and regionp (region-end)))
10932 (region-length (and regionp (- region-end region-start)))
10933 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10934 pos it nbuf file re level reversed)
10935 (setq last-command nil)
10937 (goto-char region-start)
10938 (or (bolp) (goto-char (point-at-bol)))
10939 (setq region-start (point))
10940 (unless (or (org-kill-is-subtree-p
10941 (buffer-substring region-start region-end))
10942 (prog1 org-refile-active-region-within-subtree
10943 (org-toggle-heading)))
10944 (error "The region is not a (sequence of) subtree(s)")))
10945 (if (equal goto '(16))
10946 (org-refile-goto-last-stored)
10948 (and (equal goto 2)
10949 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10951 (setq it (list (or org-clock-heading "running clock")
10953 (marker-buffer org-clock-hd-marker))
10955 (marker-position org-clock-hd-marker)))
10958 (let (heading-text)
10961 (org-back-to-heading t)
10963 (nth 4 (org-heading-components))))
10964 (org-refile-get-location
10965 (cond (goto "Goto")
10966 (regionp "Refile region to")
10967 (t (concat "Refile subtree \""
10968 heading-text "\" to")))
10970 (and (not (equal '(4) goto))
10971 org-refile-allow-creating-parent-nodes)
10973 (setq file (nth 1 it)
10976 (if (and (not goto)
10978 (equal (buffer-file-name) file)
10980 (and (>= pos region-start)
10981 (<= pos region-end))
10982 (and (>= pos (point))
10983 (< pos (save-excursion
10984 (org-end-of-subtree t t))))))
10985 (error "Cannot refile to position inside the tree or region"))
10987 (setq nbuf (or (find-buffer-visiting file)
10988 (find-file-noselect file)))
10991 (org-pop-to-buffer-same-window nbuf)
10993 (org-show-context 'org-goto))
10996 (org-kill-new (buffer-substring region-start region-end))
10997 (org-save-markers-in-region region-start region-end))
10998 (org-copy-subtree 1 nil t))
10999 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11000 (find-file-noselect file)))
11001 (setq reversed (org-notes-order-reversed-p))
11008 (looking-at org-outline-regexp)
11009 (setq level (org-get-valid-level (funcall outline-level) 1))
11012 (or (outline-next-heading) (point-max))
11013 (or (save-excursion (org-get-next-sibling))
11014 (org-end-of-subtree t t)
11018 (goto-char (point-max))
11019 (goto-char (point-min))
11020 (or (outline-next-heading) (goto-char (point-max)))))
11021 (if (not (bolp)) (newline))
11022 (org-paste-subtree level)
11023 (when org-log-refile
11024 (org-add-log-setup 'refile nil nil 'findpos
11026 (unless (eq org-log-refile 'note)
11027 (save-excursion (org-add-log-note))))
11028 (and org-auto-align-tags
11029 (let ((org-loop-over-headlines-in-active-region nil))
11030 (org-set-tags nil t)))
11031 (bookmark-set "org-refile-last-stored")
11032 ;; If we are refiling for capture, make sure that the
11033 ;; last-capture pointers point here
11034 (when (org-bound-and-true-p org-refile-for-capture)
11035 (bookmark-set "org-capture-last-stored-marker")
11036 (move-marker org-capture-last-stored-marker (point)))
11037 (if (fboundp 'deactivate-mark) (deactivate-mark))
11038 (run-hooks 'org-after-refile-insert-hook))))
11040 (delete-region (point) (+ (point) region-length))
11042 (when (featurep 'org-inlinetask)
11043 (org-inlinetask-remove-END-maybe))
11044 (setq org-markers-to-move nil)
11045 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
11047 (defun org-refile-goto-last-stored ()
11048 "Go to the location where the last refile was stored."
11050 (bookmark-jump "org-refile-last-stored")
11051 (message "This is the location of the last refile"))
11053 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11055 "Prompt the user for a refile location, using PROMPT.
11056 PROMPT should not be suffixed with a colon and a space, because
11057 this function appends the default value from
11058 `org-refile-history' automatically, if that is not empty.
11059 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11060 this is used for the GOTO interface."
11061 (let ((org-refile-targets org-refile-targets)
11062 (org-refile-use-outline-path org-refile-use-outline-path)
11064 (when (and (derived-mode-p 'org-mode)
11065 (not org-refile-use-cache)
11069 (setq excluded-entries
11070 (append excluded-entries (list (org-get-heading t t)))))))
11071 (setq org-refile-target-table
11072 (org-refile-get-targets default-buffer excluded-entries)))
11073 (unless org-refile-target-table
11074 (error "No refile targets"))
11075 (let* ((prompt (concat prompt
11076 (and (car org-refile-history)
11077 (concat " (default " (car org-refile-history) ")"))
11079 (cbuf (current-buffer))
11080 (partial-completion-mode nil)
11081 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11082 (cfunc (if (and org-refile-use-outline-path
11083 org-outline-path-complete-in-steps)
11084 'org-olpath-completing-read
11085 'org-icompleting-read))
11086 (extra (if org-refile-use-outline-path "/" ""))
11087 (filename (and cfn (expand-file-name cfn)))
11090 (if (and (not (member org-refile-use-outline-path
11091 '(file full-file-path)))
11092 (not (equal filename (nth 1 x))))
11093 (cons (concat (car x) extra " ("
11094 (file-name-nondirectory (nth 1 x)) ")")
11096 (cons (concat (car x) extra) (cdr x))))
11097 org-refile-target-table))
11098 (completion-ignore-case t)
11099 pa answ parent-target child parent old-hist)
11100 (setq old-hist org-refile-history)
11101 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11102 nil 'org-refile-history (car org-refile-history)))
11103 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11104 (org-refile-check-position pa)
11107 (when (or (not org-refile-history)
11108 (not (eq old-hist org-refile-history))
11109 (not (equal (car pa) (car org-refile-history))))
11110 (setq org-refile-history
11111 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11113 (cdr org-refile-history))))
11114 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11115 (pop org-refile-history)))
11117 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11119 (setq parent (match-string 1 answ)
11120 child (match-string 2 answ))
11121 (setq parent-target (or (assoc parent tbl)
11122 (assoc (concat parent "/") tbl)))
11123 (when (and parent-target
11124 (or (eq new-nodes t)
11125 (and (eq new-nodes 'confirm)
11126 (y-or-n-p (format "Create new node \"%s\"? "
11128 (org-refile-new-child parent-target child)))
11129 (error "Invalid target location")))))
11131 (declare-function org-string-nw-p "org-macs.el" (s))
11132 (defun org-refile-check-position (refile-pointer)
11133 "Check if the refile pointer matches the readline to which it points."
11134 (let* ((file (nth 1 refile-pointer))
11135 (re (nth 2 refile-pointer))
11136 (pos (nth 3 refile-pointer))
11138 (when (org-string-nw-p re)
11139 (setq buffer (if (markerp pos)
11140 (marker-buffer pos)
11141 (or (find-buffer-visiting file)
11142 (find-file-noselect file))))
11143 (with-current-buffer buffer
11148 (beginning-of-line 1)
11149 (unless (org-looking-at-p re)
11150 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11152 (defun org-refile-new-child (parent-target child)
11153 "Use refile target PARENT-TARGET to add new CHILD below it."
11154 (unless parent-target
11155 (error "Cannot find parent for new node"))
11156 (let ((file (nth 1 parent-target))
11157 (pos (nth 3 parent-target))
11159 (with-current-buffer (or (find-buffer-visiting file)
11160 (find-file-noselect file))
11166 (goto-char (point-max))
11167 (if (not (bolp)) (newline)))
11168 (when (looking-at org-outline-regexp)
11169 (setq level (funcall outline-level))
11170 (org-end-of-subtree t t))
11171 (org-back-over-empty-lines)
11172 (insert "\n" (make-string
11173 (if pos (org-get-valid-level level 1) 1) ?*)
11175 (beginning-of-line 0)
11176 (list (concat (car parent-target) "/" child) file "" (point)))))))
11178 (defun org-olpath-completing-read (prompt collection &rest args)
11179 "Read an outline path like a file name."
11180 (let ((thetable collection)
11181 (org-completion-use-ido nil) ; does not work with ido.
11182 (org-completion-use-iswitchb nil)) ; or iswitchb
11184 'org-icompleting-read prompt
11185 (lambda (string predicate &optional flag)
11186 (let (rtn r f (l (length string)))
11190 (try-completion string thetable))
11193 (setq rtn (all-completions string thetable predicate))
11196 (setq r (substring x l))
11197 (if (string-match " ([^)]*)$" x)
11198 (setq f (match-string 0 x))
11200 (if (string-match "/" r)
11201 (concat string (substring r 0 (match-end 0)) f)
11206 (assoc string thetable)))))
11209 ;;;; Dynamic blocks
11211 (defun org-find-dblock (name)
11212 "Find the first dynamic block with name NAME in the buffer.
11213 If not found, stay at current position and return nil."
11214 (let ((case-fold-search t) pos)
11216 (goto-char (point-min))
11217 (setq pos (and (re-search-forward
11218 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11219 (match-beginning 0))))
11220 (if pos (goto-char pos))
11223 (defconst org-dblock-start-re
11224 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11225 "Matches the start line of a dynamic block, with parameters.")
11227 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11228 "Matches the end of a dynamic block.")
11230 (defun org-create-dblock (plist)
11231 "Create a dynamic block section, with parameters taken from PLIST.
11232 PLIST must contain a :name entry which is used as name of the block."
11233 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11236 (let ((col (current-column))
11237 (name (plist-get plist :name)))
11238 (insert "#+BEGIN: " name)
11240 (if (eq (car plist) :name)
11241 (setq plist (cddr plist))
11242 (insert " " (prin1-to-string (pop plist)))))
11243 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11244 (beginning-of-line -2)))
11246 (defun org-prepare-dblock ()
11247 "Prepare dynamic block for refresh.
11248 This empties the block, puts the cursor at the insert position and returns
11249 the property list including an extra property :name with the block name."
11250 (unless (looking-at org-dblock-start-re)
11251 (error "Not at a dynamic block"))
11252 (let* ((begdel (1+ (match-end 0)))
11253 (name (org-no-properties (match-string 1)))
11254 (params (append (list :name name)
11255 (read (concat "(" (match-string 3) ")")))))
11257 (beginning-of-line 1)
11258 (skip-chars-forward " \t")
11259 (setq params (plist-put params :indentation-column (current-column))))
11260 (unless (re-search-forward org-dblock-end-re nil t)
11261 (error "Dynamic block not terminated"))
11264 (list :content (buffer-substring
11265 begdel (match-beginning 0)))))
11266 (delete-region begdel (match-beginning 0))
11271 (defun org-map-dblocks (&optional command)
11272 "Apply COMMAND to all dynamic blocks in the current buffer.
11273 If COMMAND is not given, use `org-update-dblock'."
11274 (let ((cmd (or command 'org-update-dblock)))
11276 (goto-char (point-min))
11277 (while (re-search-forward org-dblock-start-re nil t)
11278 (goto-char (match-beginning 0))
11280 (condition-case nil
11282 (error (message "Error during update of dynamic block"))))
11283 (unless (re-search-forward org-dblock-end-re nil t)
11284 (error "Dynamic block not terminated"))))))
11286 (defun org-dblock-update (&optional arg)
11287 "User command for updating dynamic blocks.
11288 Update the dynamic block at point. With prefix ARG, update all dynamic
11289 blocks in the buffer."
11292 (org-update-all-dblocks)
11293 (or (looking-at org-dblock-start-re)
11294 (org-beginning-of-dblock))
11295 (org-update-dblock)))
11297 (defun org-update-dblock ()
11298 "Update the dynamic block at point.
11299 This means to empty the block, parse for parameters and then call
11300 the correct writing function."
11302 (save-window-excursion
11303 (let* ((pos (point))
11304 (line (org-current-line))
11305 (params (org-prepare-dblock))
11306 (name (plist-get params :name))
11307 (indent (plist-get params :indentation-column))
11308 (cmd (intern (concat "org-dblock-write:" name))))
11309 (message "Updating dynamic block `%s' at line %d..." name line)
11310 (funcall cmd params)
11311 (message "Updating dynamic block `%s' at line %d...done" name line)
11313 (when (and indent (> indent 0))
11314 (setq indent (make-string indent ?\ ))
11316 (org-beginning-of-dblock)
11318 (while (not (looking-at org-dblock-end-re))
11320 (beginning-of-line 2))
11321 (when (looking-at org-dblock-end-re)
11322 (and (looking-at "[ \t]+")
11323 (replace-match ""))
11324 (insert indent)))))))
11326 (defun org-beginning-of-dblock ()
11327 "Find the beginning of the dynamic block at point.
11328 Error if there is no such block at point."
11329 (let ((pos (point))
11332 (if (and (re-search-backward org-dblock-start-re nil t)
11333 (setq beg (match-beginning 0))
11334 (re-search-forward org-dblock-end-re nil t)
11335 (> (match-end 0) pos))
11338 (error "Not in a dynamic block"))))
11341 (defun org-update-all-dblocks ()
11342 "Update all dynamic blocks in the buffer.
11343 This function can be used in a hook."
11345 (when (derived-mode-p 'org-mode)
11346 (org-map-dblocks 'org-update-dblock)))
11351 (defconst org-additional-option-like-keywords
11352 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11353 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11354 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11355 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11357 "ORGTBL" "TBLFM:" "TBLNAME:"
11358 "BEGIN_EXAMPLE" "END_EXAMPLE"
11359 "BEGIN_VERBATIM" "END_VERBATIM"
11360 "BEGIN_QUOTE" "END_QUOTE"
11361 "BEGIN_VERSE" "END_VERSE"
11362 "BEGIN_CENTER" "END_CENTER"
11363 "BEGIN_SRC" "END_SRC"
11364 "BEGIN_RESULT" "END_RESULT"
11365 "BEGIN_lstlisting" "END_lstlisting"
11367 "HEADER:" "HEADERS:"
11368 "COLUMNS:" "PROPERTY:"
11369 "CAPTION:" "LABEL:"
11375 (defconst org-options-keywords
11376 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11377 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11378 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11379 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11380 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11381 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11382 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11384 (defconst org-additional-option-like-keywords-for-flyspell
11387 (mapconcat (lambda(k)
11388 (replace-regexp-in-string
11390 (concat k " " (downcase k) " " (upcase k))))
11391 (append org-options-keywords org-additional-option-like-keywords)
11395 (defcustom org-structure-template-alist
11397 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11398 "<src lang=\"?\">\n\n</src>")
11399 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11400 "<example>\n?\n</example>")
11401 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11402 "<quote>\n?\n</quote>")
11403 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11404 "<verse>\n?\n</verse>")
11405 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11406 "<center>\n?\n</center>")
11407 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11408 "<literal style=\"latex\">\n?\n</literal>")
11410 "<literal style=\"latex\">?</literal>")
11411 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11412 "<literal style=\"html\">\n?\n</literal>")
11414 "<literal style=\"html\">?</literal>")
11415 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11419 ("I" "#+INCLUDE: %file ?"
11420 "<include file=%file markup=\"?\">")
11422 "Structure completion elements.
11423 This is a list of abbreviation keys and values. The value gets inserted
11424 if you type `<' followed by the key and then press the completion key,
11425 usually `M-TAB'. %file will be replaced by a file name after prompting
11426 for the file using completion. The cursor will be placed at the position
11427 of the `?` in the template.
11428 There are two templates for each key, the first uses the original Org syntax,
11429 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11430 the default when the /org-mtags.el/ module has been loaded. See also the
11431 variable `org-mtags-prefer-muse-templates'."
11432 :group 'org-completion
11434 (string :tag "Key")
11435 (string :tag "Template")
11436 (string :tag "Muse Template")))
11438 (defun org-try-structure-completion ()
11439 "Try to complete a structure template before point.
11440 This looks for strings like \"<e\" on an otherwise empty line and
11442 (let ((l (buffer-substring (point-at-bol) (point)))
11444 (when (and (looking-at "[ \t]*$")
11445 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11446 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11447 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11448 (match-beginning 1)) a)
11451 (defun org-complete-expand-structure-template (start cell)
11452 "Expand a structure template."
11453 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11454 (rpl (nth (if musep 2 1) cell))
11456 (delete-region start (point))
11457 (when (string-match "\\`#\\+" rpl)
11460 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11461 (setq ind (buffer-substring (point-at-bol) (point))))
11463 (setq start (point))
11464 (if (string-match "%file" rpl)
11465 (setq rpl (replace-match
11469 (abbreviate-file-name (read-file-name "Include file: ")))
11472 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11473 (concat "\n" ind)))
11475 (if (re-search-backward "\\?" start t) (delete-char 1))))
11477 ;;;; TODO, DEADLINE, Comments
11479 (defun org-toggle-comment ()
11480 "Change the COMMENT state of an entry."
11483 (org-back-to-heading)
11484 (let (case-fold-search)
11486 ((looking-at (format org-heading-keyword-regexp-format
11487 org-comment-string))
11488 (goto-char (match-end 1))
11489 (looking-at (concat " +" org-comment-string))
11490 (replace-match "" t t)
11491 (when (eolp) (insert " ")))
11492 ((looking-at org-outline-regexp)
11493 (goto-char (match-end 0))
11494 (insert org-comment-string " "))))))
11496 (defvar org-last-todo-state-is-todo nil
11497 "This is non-nil when the last TODO state change led to a TODO state.
11498 If the last change removed the TODO tag or switched to DONE, then
11501 (defvar org-setting-tags nil) ; dynamically skipped
11503 (defvar org-todo-setup-filter-hook nil
11504 "Hook for functions that pre-filter todo specs.
11505 Each function takes a todo spec and returns either nil or the spec
11506 transformed into canonical form." )
11508 (defvar org-todo-get-default-hook nil
11509 "Hook for functions that get a default item for todo.
11510 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11511 nil or a string to be used for the todo mark." )
11513 (defvar org-agenda-headline-snapshot-before-repeat)
11515 (defun org-current-effective-time ()
11516 "Return current time adjusted for `org-extend-today-until' variable."
11517 (let* ((ct (org-current-time))
11518 (dct (decode-time ct))
11520 (if (and org-use-effective-time
11521 (< (nth 2 dct) org-extend-today-until))
11522 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11526 (defun org-todo-yesterday (&optional arg)
11527 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11529 (if (eq major-mode 'org-agenda-mode)
11530 (apply 'org-agenda-todo-yesterday arg)
11531 (let* ((hour (third (decode-time
11532 (org-current-time))))
11533 (org-extend-today-until (1+ hour)))
11536 (defun org-todo (&optional arg)
11537 "Change the TODO state of an item.
11538 The state of an item is given by a keyword at the start of the heading,
11540 *** TODO Write paper
11543 The different keywords are specified in the variable `org-todo-keywords'.
11544 By default the available states are \"TODO\" and \"DONE\".
11545 So for this example: when the item starts with TODO, it is changed to DONE.
11546 When it starts with DONE, the DONE is removed. And when neither TODO nor
11547 DONE are present, add TODO at the beginning of the heading.
11549 With \\[universal-argument] prefix arg, use completion to determine the new \
11551 With numeric prefix arg, switch to that state.
11552 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11553 keywords (nextset).
11554 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11555 With a numeric prefix arg of 0, inhibit note taking for the change.
11557 For calling through lisp, arg is also interpreted in the following way:
11558 'none -> empty state
11559 \"\"(empty string) -> switch to empty state
11560 'done -> switch to DONE
11561 'nextset -> switch to the next set of keywords
11562 'previousset -> switch to the previous set of keywords
11563 \"WAITING\" -> switch to the specified keyword, but only if it
11564 really is a member of `org-todo-keywords'."
11566 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11567 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11568 'region-start-level 'region))
11569 org-loop-over-headlines-in-active-region)
11572 org-loop-over-headlines-in-active-region
11573 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11574 (if (equal arg '(16)) (setq arg 'nextset))
11575 (let ((org-blocker-hook org-blocker-hook)
11576 (case-fold-search nil))
11577 (when (equal arg '(64))
11578 (setq arg nil org-blocker-hook nil))
11579 (when (and org-blocker-hook
11580 (or org-inhibit-blocking
11581 (org-entry-get nil "NOBLOCKING")))
11582 (setq org-blocker-hook nil))
11585 (org-back-to-heading t)
11586 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11587 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11588 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11589 (let* ((match-data (match-data))
11590 (startpos (point-at-bol))
11591 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11592 (org-log-done org-log-done)
11593 (org-log-repeat org-log-repeat)
11594 (org-todo-log-states org-todo-log-states)
11595 (org-inhibit-logging
11597 (progn (setq arg nil) 'note) org-inhibit-logging))
11598 (this (match-string 1))
11599 (hl-pos (match-beginning 0))
11600 (head (org-get-todo-sequence-head this))
11601 (ass (assoc head org-todo-kwd-alist))
11602 (interpret (nth 1 ass))
11603 (done-word (nth 3 ass))
11604 (final-done-word (nth 4 ass))
11605 (org-last-state (or this ""))
11606 (completion-ignore-case t)
11607 (member (member this org-todo-keywords-1))
11608 (tail (cdr member))
11610 ((and org-todo-key-trigger
11611 (or (and (equal arg '(4))
11612 (eq org-use-fast-todo-selection 'prefix))
11613 (and (not arg) org-use-fast-todo-selection
11614 (not (eq org-use-fast-todo-selection
11616 ;; Use fast selection
11617 (org-fast-todo-selection))
11618 ((and (equal arg '(4))
11619 (or (not org-use-fast-todo-selection)
11620 (not org-todo-key-trigger)))
11621 ;; Read a state with completion
11622 (org-icompleting-read
11623 "State: " (mapcar (lambda(x) (list x))
11624 org-todo-keywords-1)
11628 (if tail (car tail) nil)
11629 (car org-todo-keywords-1)))
11631 (if (equal member org-todo-keywords-1)
11634 (nth (- (length org-todo-keywords-1)
11636 org-todo-keywords-1)
11637 (org-last org-todo-keywords-1))))
11638 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11639 (setq arg nil))) ; hack to fall back to cycling
11641 ;; user or caller requests a specific state
11643 ((equal arg "") nil)
11644 ((eq arg 'none) nil)
11645 ((eq arg 'done) (or done-word (car org-done-keywords)))
11647 (or (car (cdr (member head org-todo-heads)))
11648 (car org-todo-heads)))
11649 ((eq arg 'previousset)
11650 (let ((org-todo-heads (reverse org-todo-heads)))
11651 (or (car (cdr (member head org-todo-heads)))
11652 (car org-todo-heads))))
11653 ((car (member arg org-todo-keywords-1)))
11655 (error "State `%s' not valid in this file" arg))
11656 ((nth (1- (prefix-numeric-value arg))
11657 org-todo-keywords-1))))
11658 ((null member) (or head (car org-todo-keywords-1)))
11659 ((equal this final-done-word) nil) ;; -> make empty
11660 ((null tail) nil) ;; -> first entry
11661 ((memq interpret '(type priority))
11662 (if (eq this-command last-command)
11664 (if (> (length tail) 0)
11665 (or done-word (car org-done-keywords))
11670 (run-hook-with-args-until-success
11671 'org-todo-get-default-hook org-state org-last-state)
11673 (next (if org-state (concat " " org-state " ") " "))
11674 (change-plist (list :type 'todo-state-change :from this :to org-state
11675 :position startpos))
11677 (when org-blocker-hook
11678 (setq org-last-todo-state-is-todo
11679 (not (member this org-done-keywords)))
11680 (unless (save-excursion
11682 (org-with-wide-buffer
11683 (run-hook-with-args-until-failure
11684 'org-blocker-hook change-plist))))
11685 (if (org-called-interactively-p 'interactive)
11686 (error "TODO state change from %s to %s blocked" this org-state)
11688 (message "TODO state change from %s to %s blocked" this org-state)
11689 (throw 'exit nil))))
11690 (store-match-data match-data)
11691 (replace-match next t t)
11692 (unless (pos-visible-in-window-p hl-pos)
11693 (message "TODO state changed to %s" (org-trim next)))
11695 (setq head (org-get-todo-sequence-head org-state)
11696 ass (assoc head org-todo-kwd-alist)
11697 interpret (nth 1 ass)
11698 done-word (nth 3 ass)
11699 final-done-word (nth 4 ass)))
11700 (when (memq arg '(nextset previousset))
11701 (message "Keyword-Set %d/%d: %s"
11702 (- (length org-todo-sets) -1
11703 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11704 (length org-todo-sets)
11705 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11706 (setq org-last-todo-state-is-todo
11707 (not (member org-state org-done-keywords)))
11708 (setq now-done-p (and (member org-state org-done-keywords)
11709 (not (member this org-done-keywords))))
11710 (and logging (org-local-logging logging))
11711 (when (and (or org-todo-log-states org-log-done)
11712 (not (eq org-inhibit-logging t))
11713 (not (memq arg '(nextset previousset))))
11714 ;; we need to look at recording a time and note
11715 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11716 (nth 2 (assoc this org-todo-log-states))))
11717 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11718 (setq dolog 'time))
11719 (when (and org-state
11720 (member org-state org-not-done-keywords)
11721 (not (member this org-not-done-keywords)))
11722 ;; This is now a todo state and was not one before
11723 ;; If there was a CLOSED time stamp, get rid of it.
11724 (org-add-planning-info nil nil 'closed))
11725 (when (and now-done-p org-log-done)
11726 ;; It is now done, and it was not done before
11727 (org-add-planning-info 'closed (org-current-effective-time))
11728 (if (and (not dolog) (eq 'note org-log-done))
11729 (org-add-log-setup 'done org-state this 'findpos 'note)))
11730 (when (and org-state dolog)
11731 ;; This is a non-nil state, and we need to log it
11732 (org-add-log-setup 'state org-state this 'findpos dolog)))
11733 ;; Fixup tag positioning
11734 (org-todo-trigger-tag-changes org-state)
11735 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11736 (when org-provide-todo-statistics
11737 (org-update-parent-todo-statistics))
11738 (run-hooks 'org-after-todo-state-change-hook)
11739 (if (and arg (not (member org-state org-done-keywords)))
11740 (setq head (org-get-todo-sequence-head org-state)))
11741 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11742 ;; Do we need to trigger a repeat?
11744 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11745 ;; This is for the agenda, take a snapshot of the headline.
11747 (setq org-agenda-headline-snapshot-before-repeat
11748 (org-get-heading))))
11749 (org-auto-repeat-maybe org-state))
11750 ;; Fixup cursor location if close to the keyword
11751 (if (and (outline-on-heading-p)
11753 (save-excursion (beginning-of-line 1)
11754 (looking-at org-todo-line-regexp))
11755 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11757 (goto-char (or (match-end 2) (match-end 1)))
11758 (and (looking-at " ") (just-one-space))))
11759 (when org-trigger-hook
11761 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11763 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11764 "Block turning an entry into a TODO, using the hierarchy.
11765 This checks whether the current task should be blocked from state
11766 changes. Such blocking occurs when:
11768 1. The task has children which are not all in a completed state.
11770 2. A task has a parent with the property :ORDERED:, and there
11771 are siblings prior to the current task with incomplete
11774 3. The parent of the task is blocked because it has siblings that should
11775 be done first, or is child of a block grandparent TODO entry."
11777 (if (not org-enforce-todo-dependencies)
11778 t ; if locally turned off don't block
11780 ;; If this is not a todo state change, or if this entry is already DONE,
11782 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11783 (member (plist-get change-plist :from)
11784 (cons 'done org-done-keywords))
11785 (member (plist-get change-plist :to)
11786 (cons 'todo org-not-done-keywords))
11787 (not (plist-get change-plist :to)))
11788 (throw 'dont-block t))
11789 ;; If this task has children, and any are undone, it's blocked
11791 (org-back-to-heading t)
11792 (let ((this-level (funcall outline-level)))
11793 (outline-next-heading)
11794 (let ((child-level (funcall outline-level)))
11795 (while (and (not (eobp))
11796 (> child-level this-level))
11797 ;; this todo has children, check whether they are all
11799 (if (and (not (org-entry-is-done-p))
11800 (org-entry-is-todo-p))
11801 (throw 'dont-block nil))
11802 (outline-next-heading)
11803 (setq child-level (funcall outline-level))))))
11804 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11805 ;; any previous siblings are undone, it's blocked
11807 (org-back-to-heading t)
11808 (let* ((pos (point))
11809 (parent-pos (and (org-up-heading-safe) (point))))
11810 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11811 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11813 (re-search-forward org-not-done-heading-regexp pos t))
11814 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11815 ;; Search further up the hierarchy, to see if an ancestor is blocked
11817 (goto-char parent-pos)
11818 (if (not (looking-at org-not-done-heading-regexp))
11819 (throw 'dont-block t)) ; do not block, parent is not a TODO
11821 (setq parent-pos (and (org-up-heading-safe) (point)))
11822 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11823 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11825 (re-search-forward org-not-done-heading-regexp pos t))
11826 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11828 (defcustom org-track-ordered-property-with-tag nil
11829 "Should the ORDERED property also be shown as a tag?
11830 The ORDERED property decides if an entry should require subtasks to be
11831 completed in sequence. Since a property is not very visible, setting
11832 this option means that toggling the ORDERED property with the command
11833 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11834 not relevant for the behavior, but it makes things more visible.
11836 Note that toggling the tag with tags commands will not change the property
11837 and therefore not influence behavior!
11839 This can be t, meaning the tag ORDERED should be used, It can also be a
11840 string to select a different tag for this task."
11843 (const :tag "No tracking" nil)
11844 (const :tag "Track with ORDERED tag" t)
11845 (string :tag "Use other tag")))
11847 (defun org-toggle-ordered-property ()
11848 "Toggle the ORDERED property of the current entry.
11849 For better visibility, you can track the value of this property with a tag.
11850 See variable `org-track-ordered-property-with-tag'."
11852 (let* ((t1 org-track-ordered-property-with-tag)
11853 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11855 (org-back-to-heading)
11856 (if (org-entry-get nil "ORDERED")
11858 (org-delete-property "ORDERED")
11859 (and tag (org-toggle-tag tag 'off))
11860 (message "Subtasks can be completed in arbitrary order"))
11861 (org-entry-put nil "ORDERED" "t")
11862 (and tag (org-toggle-tag tag 'on))
11863 (message "Subtasks must be completed in sequence")))))
11865 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11866 (defun org-block-todo-from-checkboxes (change-plist)
11867 "Block turning an entry into a TODO, using checkboxes.
11868 This checks whether the current task should be blocked from state
11869 changes because there are unchecked boxes in this entry."
11870 (if (not org-enforce-todo-checkbox-dependencies)
11871 t ; if locally turned off don't block
11873 ;; If this is not a todo state change, or if this entry is already DONE,
11875 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11876 (member (plist-get change-plist :from)
11877 (cons 'done org-done-keywords))
11878 (member (plist-get change-plist :to)
11879 (cons 'todo org-not-done-keywords))
11880 (not (plist-get change-plist :to)))
11881 (throw 'dont-block t))
11882 ;; If this task has checkboxes that are not checked, it's blocked
11884 (org-back-to-heading t)
11885 (let ((beg (point)) end)
11886 (outline-next-heading)
11889 (if (org-list-search-forward
11890 (concat (org-item-beginning-re)
11891 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11895 (if (boundp 'org-blocked-by-checkboxes)
11896 (setq org-blocked-by-checkboxes t))
11897 (throw 'dont-block nil)))))
11898 t))) ; do not block
11900 (defun org-entry-blocked-p ()
11901 "Is the current entry blocked?"
11902 (if (org-entry-get nil "NOBLOCKING")
11903 nil ;; Never block this entry
11905 (run-hook-with-args-until-failure
11907 (list :type 'todo-state-change
11912 (defun org-update-statistics-cookies (all)
11913 "Update the statistics cookie, either from TODO or from checkboxes.
11914 This should be called with the cursor in a line with a statistics cookie."
11918 (org-update-checkbox-count 'all)
11919 (org-map-entries 'org-update-parent-todo-statistics))
11920 (if (not (org-at-heading-p))
11921 (org-update-checkbox-count)
11922 (let ((pos (move-marker (make-marker) (point)))
11924 (ignore-errors (org-back-to-heading t))
11925 (if (not (org-at-heading-p))
11926 (org-update-checkbox-count)
11927 (setq l1 (org-outline-level))
11928 (setq end (save-excursion
11929 (outline-next-heading)
11930 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11932 (if (and (save-excursion
11934 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11935 (not (save-excursion (re-search-forward
11936 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11937 (org-update-checkbox-count)
11938 (if (and l2 (> l2 l1))
11941 (org-update-parent-todo-statistics))
11943 (beginning-of-line 1)
11944 (while (re-search-forward
11945 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11947 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11949 (move-marker pos nil)))))
11951 (defvar org-entry-property-inherited-from) ;; defined below
11952 (defun org-update-parent-todo-statistics ()
11953 "Update any statistics cookie in the parent of the current headline.
11954 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11955 the entire subtree and this will travel up the hierarchy and update
11956 statistics everywhere."
11957 (let* ((prop (save-excursion (org-up-heading-safe)
11958 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11959 (recursive (or (not org-hierarchical-todo-statistics)
11960 (and prop (string-match "\\<recursive\\>" prop))))
11961 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11964 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11965 level ltoggle l1 new ndel
11966 (cnt-all 0) (cnt-done 0) is-percent kwd
11967 checkbox-beg ov ovs ove cookie-present)
11970 (beginning-of-line 1)
11971 (setq ltoggle (funcall outline-level))
11972 ;; Three situations are to consider:
11974 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11975 ;; to the top-level ancestor on the headline;
11977 ;; 2. If parent has "recursive" property, repeat up to the
11978 ;; headline setting that property, taking inheritance into
11981 ;; 3. Else, move up to direct parent and proceed only once.
11982 (while (and (setq level (org-up-heading-safe))
11983 (or recursive first)
11985 (setq first nil cookie-present nil)
11989 (downcase (or (org-entry-get nil "COOKIE_DATA")
11992 (while (re-search-forward box-re (point-at-eol) t)
11993 (setq cnt-all 0 cnt-done 0 cookie-present t)
11994 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11996 (unless (outline-next-heading) (throw 'exit nil))
11997 (while (and (looking-at org-complex-heading-regexp)
11998 (> (setq l1 (length (match-string 1))) level))
11999 (setq kwd (and (or recursive (= l1 ltoggle))
12001 (if (or (eq org-provide-todo-statistics 'all-headlines)
12002 (and (listp org-provide-todo-statistics)
12003 (or (member kwd org-provide-todo-statistics)
12004 (member kwd org-done-keywords))))
12005 (setq cnt-all (1+ cnt-all))
12006 (if (eq org-provide-todo-statistics t)
12007 (and kwd (setq cnt-all (1+ cnt-all)))))
12008 (and (member kwd org-done-keywords)
12009 (setq cnt-done (1+ cnt-done)))
12010 (outline-next-heading)))
12013 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12014 (format "[%d/%d]" cnt-done cnt-all))
12015 ndel (- (match-end 0) checkbox-beg))
12016 ;; handle overlays when updating cookie from column view
12017 (when (setq ov (car (overlays-at checkbox-beg)))
12018 (setq ovs (overlay-start ov) ove (overlay-end ov))
12019 (delete-overlay ov))
12020 (goto-char checkbox-beg)
12022 (delete-region (point) (+ (point) ndel))
12023 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12024 (when ov (move-overlay ov ovs ove)))
12025 (when cookie-present
12026 (run-hook-with-args 'org-after-todo-statistics-hook
12027 cnt-done (- cnt-all cnt-done))))))
12028 (run-hooks 'org-todo-statistics-hook)))
12030 (defvar org-after-todo-statistics-hook nil
12031 "Hook that is called after a TODO statistics cookie has been updated.
12032 Each function is called with two arguments: the number of not-done entries
12033 and the number of done entries.
12035 For example, the following function, when added to this hook, will switch
12036 an entry to DONE when all children are done, and back to TODO when new
12037 entries are set to a TODO status. Note that this hook is only called
12038 when there is a statistics cookie in the headline!
12040 (defun org-summary-todo (n-done n-not-done)
12041 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12042 (let (org-log-done org-log-states) ; turn off logging
12043 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12046 (defvar org-todo-statistics-hook nil
12047 "Hook that is run whenever Org thinks TODO statistics should be updated.
12048 This hook runs even if there is no statistics cookie present, in which case
12049 `org-after-todo-statistics-hook' would not run.")
12051 (defun org-todo-trigger-tag-changes (state)
12052 "Apply the changes defined in `org-todo-state-tags-triggers'."
12053 (let ((l org-todo-state-tags-triggers)
12055 (when (or (not state) (equal state ""))
12056 (setq changes (append changes (cdr (assoc "" l)))))
12057 (when (and (stringp state) (> (length state) 0))
12058 (setq changes (append changes (cdr (assoc state l)))))
12059 (when (member state org-not-done-keywords)
12060 (setq changes (append changes (cdr (assoc 'todo l)))))
12061 (when (member state org-done-keywords)
12062 (setq changes (append changes (cdr (assoc 'done l)))))
12063 (dolist (c changes)
12064 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12066 (defun org-local-logging (value)
12067 "Get logging settings from a property VALUE."
12069 ;; directly set the variables, they are already local.
12070 (setq org-log-done nil
12072 org-todo-log-states nil)
12073 (setq words (org-split-string value))
12074 (while (setq w (pop words))
12076 ((setq a (assoc w org-startup-options))
12077 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12078 (set (nth 1 a) (nth 2 a))))
12079 ((setq a (org-extract-log-state-settings w))
12080 (and (member (car a) org-todo-keywords-1)
12081 (push a org-todo-log-states)))))))
12083 (defun org-get-todo-sequence-head (kwd)
12084 "Return the head of the TODO sequence to which KWD belongs.
12085 If KWD is not set, check if there is a text property remembering the
12090 (or (get-text-property (point-at-bol) 'org-todo-head)
12092 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12093 nil (point-at-eol)))
12094 (get-text-property p 'org-todo-head))))
12095 ((not (member kwd org-todo-keywords-1))
12096 (car org-todo-keywords-1))
12097 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12099 (defun org-fast-todo-selection ()
12100 "Fast TODO keyword selection with single keys.
12101 Returns the new TODO keyword, or nil if no state change should occur."
12102 (let* ((fulltable org-todo-key-alist)
12103 (done-keywords org-done-keywords) ;; needed for the faces.
12104 (maxlen (apply 'max (mapcar
12106 (if (stringp (car x)) (string-width (car x)) 0))
12109 (fwidth (+ maxlen 3 1 3))
12110 (ncol (/ (- (window-width) 4) fwidth))
12114 (save-window-excursion
12116 (set-buffer (get-buffer-create " *Org todo*"))
12117 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12119 (org-set-local 'org-done-keywords done-keywords)
12120 (setq tbl fulltable cnt 0)
12121 (while (setq e (pop tbl))
12123 ((equal e '(:startgroup))
12124 (push '() groups) (setq ingroup t)
12125 (when (not (= cnt 0))
12129 ((equal e '(:endgroup))
12130 (setq ingroup nil cnt 0)
12132 ((equal e '(:newline))
12133 (when (not (= cnt 0))
12137 (while (equal (car tbl) '(:newline))
12139 (setq tbl (cdr tbl)))))
12141 (setq tg (car e) c (cdr e))
12142 (if ingroup (push tg (car groups)))
12143 (setq tg (org-add-props tg nil 'face
12144 (org-get-todo-face tg)))
12145 (if (and (= cnt 0) (not ingroup)) (insert " "))
12146 (insert "[" c "] " tg (make-string
12147 (- fwidth 4 (length tg)) ?\ ))
12148 (when (= (setq cnt (1+ cnt)) ncol)
12150 (if ingroup (insert " "))
12153 (goto-char (point-min))
12154 (if (not expert) (org-fit-window-to-buffer))
12155 (message "[a-z..]:Set [SPC]:clear")
12156 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12159 (and (= c ?q) (not (rassoc c fulltable))))
12160 (setq quit-flag t))
12162 ((setq e (rassoc c fulltable) tg (car e))
12164 (t (setq quit-flag t)))))))
12166 (defun org-entry-is-todo-p ()
12167 (member (org-get-todo-state) org-not-done-keywords))
12169 (defun org-entry-is-done-p ()
12170 (member (org-get-todo-state) org-done-keywords))
12172 (defun org-get-todo-state ()
12174 (org-back-to-heading t)
12175 (and (looking-at org-todo-line-regexp)
12177 (match-string 2))))
12179 (defun org-at-date-range-p (&optional inactive-ok)
12180 "Is the cursor inside a date range?"
12184 (let ((pos (point)))
12185 (skip-chars-backward "^[<\r\n")
12186 (skip-chars-backward "<[")
12187 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12188 (>= (match-end 0) pos)
12190 (skip-chars-backward "^<[\r\n")
12191 (skip-chars-backward "<[")
12192 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12193 (>= (match-end 0) pos)
12197 (defun org-get-repeat (&optional tagline)
12198 "Check if there is a deadline/schedule with repeater in this entry."
12201 (org-back-to-heading t)
12202 (and (re-search-forward (if tagline
12203 (concat tagline "\\s-*" org-repeat-re)
12205 (org-entry-end-position) t)
12206 (match-string-no-properties 1)))))
12208 (defvar org-last-changed-timestamp)
12209 (defvar org-last-inserted-timestamp)
12210 (defvar org-log-post-message)
12211 (defvar org-log-note-purpose)
12212 (defvar org-log-note-how)
12213 (defvar org-log-note-extra)
12214 (defun org-auto-repeat-maybe (done-word)
12215 "Check if the current headline contains a repeated deadline/schedule.
12216 If yes, set TODO state back to what it was and change the base date
12217 of repeating deadline/scheduled time stamps to new date.
12218 This function is run automatically after each state change to a DONE state."
12219 ;; last-state is dynamically scoped into this function
12220 (let* ((repeat (org-get-repeat))
12221 (aa (assoc org-last-state org-todo-kwd-alist))
12222 (interpret (nth 1 aa))
12224 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12225 (msg "Entry repeats: ")
12227 (org-todo-log-states nil)
12228 re type n what ts time to-state)
12230 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12231 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12232 org-todo-repeat-to-state))
12233 (unless (and to-state (member to-state org-todo-keywords-1))
12234 (setq to-state (if (eq interpret 'type) org-last-state head)))
12235 (org-todo to-state)
12236 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12237 (org-entry-put nil "LAST_REPEAT" (format-time-string
12238 (org-time-stamp-format t t))))
12239 (when org-log-repeat
12240 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12241 (memq 'org-add-log-note post-command-hook))
12242 ;; OK, we are already setup for some record
12243 (if (eq org-log-repeat 'note)
12244 ;; make sure we take a note, not only a time stamp
12245 (setq org-log-note-how 'note))
12246 ;; Set up for taking a record
12247 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12249 'findpos org-log-repeat)))
12250 (org-back-to-heading t)
12251 (org-add-planning-info nil nil 'closed)
12252 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12253 org-deadline-time-regexp "\\)\\|\\("
12254 org-ts-regexp "\\)"))
12255 (while (re-search-forward
12256 re (save-excursion (outline-next-heading) (point)) t)
12257 (setq type (if (match-end 1) org-scheduled-string
12258 (if (match-end 3) org-deadline-string "Plain:"))
12259 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12260 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12261 (setq n (string-to-number (match-string 2 ts))
12262 what (match-string 3 ts))
12263 (if (equal what "w") (setq n (* n 7) what "d"))
12264 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12265 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12266 ;; Preparation, see if we need to modify the start date for the change
12267 (when (match-end 1)
12268 (setq time (save-match-data (org-time-string-to-time ts)))
12270 ((equal (match-string 1 ts) ".")
12271 ;; Shift starting date to today
12272 (org-timestamp-change
12273 (- (org-today) (time-to-days time))
12275 ((equal (match-string 1 ts) "+")
12276 (let ((nshiftmax 10) (nshift 0))
12277 (while (or (= nshift 0)
12278 (<= (time-to-days time)
12279 (time-to-days (current-time))))
12280 (when (= (incf nshift) nshiftmax)
12281 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12283 (org-timestamp-change n (cdr (assoc what whata)))
12284 (org-at-timestamp-p t)
12285 (setq ts (match-string 1))
12286 (setq time (save-match-data (org-time-string-to-time ts)))))
12287 (org-timestamp-change (- n) (cdr (assoc what whata)))
12288 ;; rematch, so that we have everything in place for the real shift
12289 (org-at-timestamp-p t)
12290 (setq ts (match-string 1))
12291 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12292 (org-timestamp-change n (cdr (assoc what whata)))
12293 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12294 (setq org-log-post-message msg)
12295 (message "%s" msg))))
12297 (defun org-show-todo-tree (arg)
12298 "Make a compact tree which shows all headlines marked with TODO.
12299 The tree will show the lines where the regexp matches, and all higher
12300 headlines above the match.
12301 With a \\[universal-argument] prefix, prompt for a regexp to match.
12302 With a numeric prefix N, construct a sparse tree for the Nth element
12303 of `org-todo-keywords-1'."
12305 (let ((case-fold-search nil)
12307 (cond ((null arg) org-not-done-regexp)
12309 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12310 (mapcar 'list org-todo-keywords-1))))
12312 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12314 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12315 (regexp-quote (nth (1- (prefix-numeric-value arg))
12316 org-todo-keywords-1)))
12317 (t (error "Invalid prefix argument: %s" arg)))))
12318 (message "%d TODO entries found"
12319 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12321 (defun org-deadline (&optional remove time)
12322 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12323 With argument REMOVE, remove any deadline from the item.
12324 With argument TIME, set the deadline at the corresponding date. TIME
12325 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12327 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12328 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12329 'region-start-level 'region))
12330 org-loop-over-headlines-in-active-region)
12332 `(org-deadline ',remove ,time)
12333 org-loop-over-headlines-in-active-region
12334 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12335 (let* ((old-date (org-entry-get nil "DEADLINE"))
12336 (repeater (and old-date
12338 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12340 (match-string 1 old-date))))
12343 (when (and old-date org-log-redeadline)
12344 (org-add-log-setup 'deldeadline nil old-date 'findpos
12345 org-log-redeadline))
12346 (org-remove-timestamp-with-keyword org-deadline-string)
12347 (message "Item no longer has a deadline."))
12348 (org-add-planning-info 'deadline time 'closed)
12349 (when (and old-date org-log-redeadline
12350 (not (equal old-date
12351 (substring org-last-inserted-timestamp 1 -1))))
12352 (org-add-log-setup 'redeadline nil old-date 'findpos
12353 org-log-redeadline))
12356 (org-back-to-heading t)
12357 (when (re-search-forward (concat org-deadline-string " "
12358 org-last-inserted-timestamp)
12360 (outline-next-heading) (point)) t)
12361 (goto-char (1- (match-end 0)))
12362 (insert " " repeater)
12363 (setq org-last-inserted-timestamp
12364 (concat (substring org-last-inserted-timestamp 0 -1)
12366 (substring org-last-inserted-timestamp -1))))))
12367 (message "Deadline on %s" org-last-inserted-timestamp)))))
12369 (defun org-schedule (&optional remove time)
12370 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12371 With argument REMOVE, remove any scheduling date from the item.
12372 With argument TIME, scheduled at the corresponding date. TIME can
12373 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12375 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12376 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12377 'region-start-level 'region))
12378 org-loop-over-headlines-in-active-region)
12380 `(org-schedule ',remove ,time)
12381 org-loop-over-headlines-in-active-region
12382 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12383 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12384 (repeater (and old-date
12386 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12388 (match-string 1 old-date))))
12391 (when (and old-date org-log-reschedule)
12392 (org-add-log-setup 'delschedule nil old-date 'findpos
12393 org-log-reschedule))
12394 (org-remove-timestamp-with-keyword org-scheduled-string)
12395 (message "Item is no longer scheduled."))
12396 (org-add-planning-info 'scheduled time 'closed)
12397 (when (and old-date org-log-reschedule
12398 (not (equal old-date
12399 (substring org-last-inserted-timestamp 1 -1))))
12400 (org-add-log-setup 'reschedule nil old-date 'findpos
12401 org-log-reschedule))
12404 (org-back-to-heading t)
12405 (when (re-search-forward (concat org-scheduled-string " "
12406 org-last-inserted-timestamp)
12408 (outline-next-heading) (point)) t)
12409 (goto-char (1- (match-end 0)))
12410 (insert " " repeater)
12411 (setq org-last-inserted-timestamp
12412 (concat (substring org-last-inserted-timestamp 0 -1)
12414 (substring org-last-inserted-timestamp -1))))))
12415 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12417 (defun org-get-scheduled-time (pom &optional inherit)
12418 "Get the scheduled time as a time tuple, of a format suitable
12419 for calling org-schedule with, or if there is no scheduling,
12421 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12423 (apply 'encode-time (org-parse-time-string time)))))
12425 (defun org-get-deadline-time (pom &optional inherit)
12426 "Get the deadline as a time tuple, of a format suitable for
12427 calling org-deadline with, or if there is no scheduling, returns
12429 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12431 (apply 'encode-time (org-parse-time-string time)))))
12433 (defun org-remove-timestamp-with-keyword (keyword)
12434 "Remove all time stamps with KEYWORD in the current entry."
12435 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12438 (org-back-to-heading t)
12440 (outline-next-heading)
12441 (while (re-search-backward re beg t)
12443 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12444 (equal (char-before) ?\ ))
12445 (backward-delete-char 1)
12446 (if (string-match "^[ \t]*$" (buffer-substring
12447 (point-at-bol) (point-at-eol)))
12448 (delete-region (point-at-bol)
12449 (min (point-max) (1+ (point-at-eol))))))))))
12451 (defun org-add-planning-info (what &optional time &rest remove)
12452 "Insert new timestamp with keyword in the line directly after the headline.
12453 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12454 If non is given, the user is prompted for a date.
12455 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12458 (let (org-time-was-given org-end-time-was-given ts
12459 end default-time default-input)
12462 (when (and (memq what '(scheduled deadline))
12464 (and (stringp time)
12465 (string-match "^[-+]+[0-9]" time))))
12466 ;; Try to get a default date/time from existing timestamp
12468 (org-back-to-heading t)
12469 (setq end (save-excursion (outline-next-heading) (point)))
12470 (when (re-search-forward (if (eq what 'scheduled)
12471 org-scheduled-time-regexp
12472 org-deadline-time-regexp)
12474 (setq ts (match-string 1)
12476 (apply 'encode-time (org-parse-time-string ts))
12477 default-input (and ts (org-get-compact-tod ts))))))
12481 ;; This is a string (relative or absolute), set proper date
12482 (apply 'encode-time
12483 (org-read-date-analyze
12484 time default-time (decode-time default-time)))
12485 ;; If necessary, get the time from the user
12486 (or time (org-read-date nil 'to-time nil nil
12487 default-time default-input)))))
12489 (when (and org-insert-labeled-timestamps-at-point
12490 (member what '(scheduled deadline)))
12492 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12493 (org-insert-time-stamp time org-time-was-given
12494 nil nil nil (list org-end-time-was-given))
12498 (let (col list elt ts buffer-invisibility-spec)
12499 (org-back-to-heading t)
12500 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12501 (goto-char (match-end 1))
12502 (setq col (current-column))
12503 (goto-char (match-end 0))
12504 (if (eobp) (insert "\n") (forward-char 1))
12505 (when (and (not what)
12508 org-keyword-time-not-clock-regexp))))
12509 ;; Nothing to add, nothing to remove...... :-)
12511 (if (and (not (looking-at org-outline-regexp))
12512 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12514 (not (equal (match-string 1) org-clock-string)))
12515 (narrow-to-region (match-beginning 0) (match-end 0))
12516 (insert-before-markers "\n")
12518 (narrow-to-region (point) (point))
12519 (and org-adapt-indentation (org-indent-to-column col)))
12520 ;; Check if we have to remove something.
12521 (setq list (cons what remove))
12523 (setq elt (pop list))
12524 (when (or (and (eq elt 'scheduled)
12525 (re-search-forward org-scheduled-time-regexp nil t))
12526 (and (eq elt 'deadline)
12527 (re-search-forward org-deadline-time-regexp nil t))
12528 (and (eq elt 'closed)
12529 (re-search-forward org-closed-time-regexp nil t)))
12531 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12532 (and (looking-at "[ \t]+") (replace-match ""))
12533 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12536 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12537 (cond ((eq what 'scheduled) org-scheduled-string)
12538 ((eq what 'deadline) org-deadline-string)
12539 ((eq what 'closed) org-closed-string))
12541 (setq ts (org-insert-time-stamp
12543 (or org-time-was-given
12544 (and (eq what 'closed) org-log-done-with-time))
12546 nil nil (list org-end-time-was-given)))
12548 (if (not (or (bolp) (eq (char-before) ?\ )
12549 (memq (char-after) '(32 10))
12552 (goto-char (point-min))
12554 (if (and (looking-at "[ \t]*\n")
12555 (equal (char-before) ?\n))
12556 (delete-region (1- (point)) (point-at-eol)))
12559 (defvar org-log-note-marker (make-marker))
12560 (defvar org-log-note-purpose nil)
12561 (defvar org-log-note-state nil)
12562 (defvar org-log-note-previous-state nil)
12563 (defvar org-log-note-how nil)
12564 (defvar org-log-note-extra nil)
12565 (defvar org-log-note-window-configuration nil)
12566 (defvar org-log-note-return-to (make-marker))
12567 (defvar org-log-note-effective-time nil
12568 "Remembered current time so that dynamically scoped
12569 `org-extend-today-until' affects tha timestamps in state change
12572 (defvar org-log-post-message nil
12573 "Message to be displayed after a log note has been stored.
12574 The auto-repeater uses this.")
12576 (defun org-add-note ()
12577 "Add a note to the current entry.
12578 This is done in the same way as adding a state change note."
12580 (org-add-log-setup 'note nil nil 'findpos nil))
12582 (defvar org-property-end-re)
12583 (defun org-add-log-setup (&optional purpose state prev-state
12585 "Set up the post command hook to take a note.
12586 If this is about to TODO state change, the new state is expected in STATE.
12587 When FINDPOS is non-nil, find the correct position for the note in
12588 the current entry. If not, assume that it can be inserted at point.
12589 HOW is an indicator what kind of note should be created.
12590 EXTRA is additional text that will be inserted into the notes buffer."
12591 (let* ((org-log-into-drawer (org-log-into-drawer))
12592 (drawer (cond ((stringp org-log-into-drawer)
12593 org-log-into-drawer)
12594 (org-log-into-drawer "LOGBOOK"))))
12598 (org-back-to-heading t)
12599 (narrow-to-region (point) (save-excursion
12600 (outline-next-heading) (point)))
12601 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12602 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12604 (goto-char (match-end 0))
12607 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12610 (goto-char (match-end 0))
12611 (or org-log-states-order-reversed
12612 (and (re-search-forward org-property-end-re nil t)
12613 (goto-char (1- (match-beginning 0))))))
12614 (insert "\n:" drawer ":\n:END:")
12615 (beginning-of-line 0)
12617 (beginning-of-line 2)
12620 ((and org-log-state-notes-insert-after-drawers
12622 (forward-line) (looking-at org-drawer-regexp)))
12624 (while (looking-at org-drawer-regexp)
12625 (goto-char (match-end 0))
12626 (re-search-forward org-property-end-re (point-max) t)
12628 (forward-line -1)))
12629 (unless org-log-states-order-reversed
12630 (and (= (char-after) ?\n) (forward-char 1))
12631 (org-skip-over-state-notes)
12632 (skip-chars-backward " \t\n\r")))
12633 (move-marker org-log-note-marker (point))
12634 (setq org-log-note-purpose purpose
12635 org-log-note-state state
12636 org-log-note-previous-state prev-state
12637 org-log-note-how how
12638 org-log-note-extra extra
12639 org-log-note-effective-time (org-current-effective-time))
12640 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12642 (defun org-skip-over-state-notes ()
12643 "Skip past the list of State notes in an entry."
12644 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12645 (when (ignore-errors (goto-char (org-in-item-p)))
12646 (let* ((struct (org-list-struct))
12647 (prevs (org-list-prevs-alist struct)))
12648 (while (looking-at "[ \t]*- State")
12649 (goto-char (or (org-list-get-next-item (point) struct prevs)
12650 (org-list-get-item-end (point) struct)))))))
12652 (defun org-add-log-note (&optional purpose)
12653 "Pop up a window for taking a note, and add this note later at point."
12654 (remove-hook 'post-command-hook 'org-add-log-note)
12655 (setq org-log-note-window-configuration (current-window-configuration))
12656 (delete-other-windows)
12657 (move-marker org-log-note-return-to (point))
12658 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12659 (goto-char org-log-note-marker)
12660 (org-switch-to-buffer-other-window "*Org Note*")
12662 (if (memq org-log-note-how '(time state))
12663 (let (current-prefix-arg) (org-store-log-note))
12664 (let ((org-inhibit-startup t)) (org-mode))
12665 (insert (format "# Insert note for %s.
12666 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12668 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12669 ((eq org-log-note-purpose 'done) "closed todo item")
12670 ((eq org-log-note-purpose 'state)
12671 (format "state change from \"%s\" to \"%s\""
12672 (or org-log-note-previous-state "")
12673 (or org-log-note-state "")))
12674 ((eq org-log-note-purpose 'reschedule)
12676 ((eq org-log-note-purpose 'delschedule)
12677 "no longer scheduled")
12678 ((eq org-log-note-purpose 'redeadline)
12679 "changing deadline")
12680 ((eq org-log-note-purpose 'deldeadline)
12681 "removing deadline")
12682 ((eq org-log-note-purpose 'refile)
12684 ((eq org-log-note-purpose 'note)
12686 (t (error "This should not happen")))))
12687 (if org-log-note-extra (insert org-log-note-extra))
12688 (org-set-local 'org-finish-function 'org-store-log-note)
12689 (run-hooks 'org-log-buffer-setup-hook)))
12691 (defvar org-note-abort nil) ; dynamically scoped
12692 (defun org-store-log-note ()
12693 "Finish taking a log note, and insert it to where it belongs."
12694 (let ((txt (buffer-string))
12695 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12697 (kill-buffer (current-buffer))
12698 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12699 (setq txt (replace-match "" t t txt)))
12700 (if (string-match "\\s-+\\'" txt)
12701 (setq txt (replace-match "" t t txt)))
12702 (setq lines (org-split-string txt "\n"))
12703 (when (and note (string-match "\\S-" note))
12705 (org-replace-escapes
12707 (list (cons "%u" (user-login-name))
12708 (cons "%U" user-full-name)
12709 (cons "%t" (format-time-string
12710 (org-time-stamp-format 'long 'inactive)
12711 org-log-note-effective-time))
12712 (cons "%T" (format-time-string
12713 (org-time-stamp-format 'long nil)
12714 org-log-note-effective-time))
12715 (cons "%d" (format-time-string
12716 (org-time-stamp-format nil 'inactive)
12717 org-log-note-effective-time))
12718 (cons "%D" (format-time-string
12719 (org-time-stamp-format nil nil)
12720 org-log-note-effective-time))
12721 (cons "%s" (if org-log-note-state
12722 (concat "\"" org-log-note-state "\"")
12724 (cons "%S" (if org-log-note-previous-state
12725 (concat "\"" org-log-note-previous-state "\"")
12727 (if lines (setq note (concat note " \\\\")))
12729 (when (or current-prefix-arg org-note-abort)
12730 (when org-log-into-drawer
12731 (org-remove-empty-drawer-at
12732 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12733 org-log-note-marker))
12736 (with-current-buffer (marker-buffer org-log-note-marker)
12738 (goto-char org-log-note-marker)
12739 (move-marker org-log-note-marker nil)
12741 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12742 (setq ind (save-excursion
12743 (if (ignore-errors (goto-char (org-in-item-p)))
12744 (let ((struct (org-list-struct)))
12746 (org-list-get-top-point struct) struct))
12747 (skip-chars-backward " \r\t\n")
12749 ((and (org-at-heading-p)
12750 org-adapt-indentation)
12751 (1+ (org-current-level)))
12752 ((org-at-heading-p) 0)
12753 (t (org-get-indentation))))))
12754 (setq bul (org-list-bullet-string "-"))
12755 (org-indent-line-to ind)
12756 (insert bul (pop lines))
12757 (let ((ind-body (+ (length bul) ind)))
12760 (org-indent-line-to ind-body)
12761 (insert (pop lines))))
12762 (message "Note stored")
12763 (org-back-to-heading t)
12764 (org-cycle-hide-drawers 'children)))))
12765 (set-window-configuration org-log-note-window-configuration)
12766 (with-current-buffer (marker-buffer org-log-note-return-to)
12767 (goto-char org-log-note-return-to))
12768 (move-marker org-log-note-return-to nil)
12769 (and org-log-post-message (message "%s" org-log-post-message)))
12771 (defun org-remove-empty-drawer-at (drawer pos)
12772 "Remove an empty drawer DRAWER at position POS.
12773 POS may also be a marker."
12774 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12780 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12781 (replace-match ""))))))
12783 (defvar org-ts-type nil)
12784 (defun org-sparse-tree (&optional arg type)
12785 "Create a sparse tree, prompt for the details.
12786 This command can create sparse trees. You first need to select the type
12787 of match used to create the tree:
12789 t Show all TODO entries.
12790 T Show entries with a specific TODO keyword.
12791 m Show entries selected by a tags/property match.
12792 p Enter a property name and its value (both with completion on existing
12793 names/values) and show entries with that property.
12794 r Show entries matching a regular expression (`/' can be used as well).
12795 b Show deadlines and scheduled items before a date.
12796 a Show deadlines and scheduled items after a date.
12797 d Show deadlines due within `org-deadline-warning-days'.
12798 D Show deadlines and scheduled items between a date range."
12800 (let (ans kwd value ts-type)
12801 (setq type (or type org-sparse-tree-default-date-type))
12802 (setq org-ts-type type)
12803 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date [D]ates range\n [c]ycle through date types: %s"
12804 (cond ((eq type 'all) "all timestamps")
12805 ((eq type 'scheduled) "only scheduled")
12806 ((eq type 'deadline) "only deadline")
12807 ((eq type 'active) "only active timestamps")
12808 ((eq type 'inactive) "only inactive timestamps")
12809 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12810 (t "scheduled/deadline")))
12811 (setq ans (read-char-exclusive))
12814 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12816 (call-interactively 'org-check-deadlines))
12818 (call-interactively 'org-check-before-date))
12820 (call-interactively 'org-check-after-date))
12822 (call-interactively 'org-check-dates-range))
12824 (org-show-todo-tree nil))
12826 (org-show-todo-tree '(4)))
12827 ((member ans '(?T ?m))
12828 (call-interactively 'org-match-sparse-tree))
12829 ((member ans '(?p ?P))
12830 (setq kwd (org-icompleting-read "Property: "
12831 (mapcar 'list (org-buffer-property-keys))))
12832 (setq value (org-icompleting-read "Value: "
12833 (mapcar 'list (org-property-values kwd))))
12834 (unless (string-match "\\`{.*}\\'" value)
12835 (setq value (concat "\"" value "\"")))
12836 (org-match-sparse-tree arg (concat kwd "=" value)))
12837 ((member ans '(?r ?R ?/))
12838 (call-interactively 'org-occur))
12839 (t (error "No such sparse tree command \"%c\"" ans)))))
12841 (defvar org-occur-highlights nil
12842 "List of overlays used for occur matches.")
12843 (make-variable-buffer-local 'org-occur-highlights)
12844 (defvar org-occur-parameters nil
12845 "Parameters of the active org-occur calls.
12846 This is a list, each call to org-occur pushes as cons cell,
12847 containing the regular expression and the callback, onto the list.
12848 The list can contain several entries if `org-occur' has been called
12849 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12850 will only contain one set of parameters. When the highlights are
12851 removed (for example with `C-c C-c', or with the next edit (depending
12852 on `org-remove-highlights-with-change'), this variable is emptied
12854 (make-variable-buffer-local 'org-occur-parameters)
12856 (defun org-occur (regexp &optional keep-previous callback)
12857 "Make a compact tree which shows all matches of REGEXP.
12858 The tree will show the lines where the regexp matches, and all higher
12859 headlines above the match. It will also show the heading after the match,
12860 to make sure editing the matching entry is easy.
12861 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12862 call to `org-occur' will be kept, to allow stacking of calls to this
12864 If CALLBACK is non-nil, it is a function which is called to confirm
12865 that the match should indeed be shown."
12866 (interactive "sRegexp: \nP")
12867 (when (equal regexp "")
12868 (error "Regexp cannot be empty"))
12869 (unless keep-previous
12870 (org-remove-occur-highlights nil nil t))
12871 (push (cons regexp callback) org-occur-parameters)
12874 (goto-char (point-min))
12875 (if (or (not keep-previous) ; do not want to keep
12876 (not org-occur-highlights)) ; no previous matches
12879 (while (re-search-forward regexp nil t)
12880 (when (or (not callback)
12881 (save-match-data (funcall callback)))
12882 (setq cnt (1+ cnt))
12883 (when org-highlight-sparse-tree-matches
12884 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12885 (org-show-context 'occur-tree))))
12886 (when org-remove-highlights-with-change
12887 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12889 (unless org-sparse-tree-open-archived-trees
12890 (org-hide-archived-subtrees (point-min) (point-max)))
12891 (run-hooks 'org-occur-hook)
12892 (if (org-called-interactively-p 'interactive)
12893 (message "%d match(es) for regexp %s" cnt regexp))
12896 (defun org-occur-next-match (&optional n reset)
12897 "Function for `next-error-function' to find sparse tree matches.
12898 N is the number of matches to move, when negative move backwards.
12899 RESET is entirely ignored - this function always goes back to the
12900 starting point when no match is found."
12901 (let* ((limit (if (< n 0) (point-min) (point-max)))
12902 (search-func (if (< n 0)
12903 'previous-single-char-property-change
12904 'next-single-char-property-change))
12909 (while (setq p1 (funcall search-func (point) 'org-type))
12910 (when (equal p1 limit)
12912 (error "No more matches"))
12913 (when (equal (get-char-property p1 'org-type) 'org-occur)
12917 (throw 'exit (point))))
12920 (error "No more matches"))))
12922 (defun org-show-context (&optional key)
12923 "Make sure point and context are visible.
12924 How much context is shown depends upon the variables
12925 `org-show-hierarchy-above', `org-show-following-heading',
12926 `org-show-entry-below' and `org-show-siblings'."
12927 (let ((heading-p (org-at-heading-p t))
12928 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12929 (following-p (org-get-alist-option org-show-following-heading key))
12930 (entry-p (org-get-alist-option org-show-entry-below key))
12931 (siblings-p (org-get-alist-option org-show-siblings key)))
12933 ;; Show heading or entry text
12934 (if (and heading-p (not entry-p))
12935 (org-flag-heading nil) ; only show the heading
12936 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12937 (org-show-hidden-entry))) ; show entire entry
12939 ;; Show next sibling, or heading below text
12941 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12942 (org-flag-heading nil))))
12943 (when siblings-p (org-show-siblings))
12945 ;; show all higher headings, possibly with siblings
12947 (while (and (condition-case nil
12948 (progn (org-up-heading-all 1) t)
12951 (org-flag-heading nil)
12952 (when siblings-p (org-show-siblings))))))))
12954 (defvar org-reveal-start-hook nil
12955 "Hook run before revealing a location.")
12957 (defun org-reveal (&optional siblings)
12958 "Show current entry, hierarchy above it, and the following headline.
12959 This can be used to show a consistent set of context around locations
12960 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12961 not t for the search context.
12963 With optional argument SIBLINGS, on each level of the hierarchy all
12964 siblings are shown. This repairs the tree structure to what it would
12965 look like when opened with hierarchical calls to `org-cycle'.
12966 With double optional argument \\[universal-argument] \\[universal-argument], \
12967 go to the parent and show the
12970 (run-hooks 'org-reveal-start-hook)
12971 (let ((org-show-hierarchy-above t)
12972 (org-show-following-heading t)
12973 (org-show-siblings (if siblings t org-show-siblings)))
12974 (org-show-context nil))
12975 (when (equal siblings '(16))
12977 (when (org-up-heading-safe)
12979 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12981 (defun org-highlight-new-match (beg end)
12982 "Highlight from BEG to END and mark the highlight is an occur headline."
12983 (let ((ov (make-overlay beg end)))
12984 (overlay-put ov 'face 'secondary-selection)
12985 (overlay-put ov 'org-type 'org-occur)
12986 (push ov org-occur-highlights)))
12988 (defun org-remove-occur-highlights (&optional beg end noremove)
12989 "Remove the occur highlights from the buffer.
12990 BEG and END are ignored. If NOREMOVE is nil, remove this function
12991 from the `before-change-functions' in the current buffer."
12993 (unless org-inhibit-highlight-removal
12994 (mapc 'delete-overlay org-occur-highlights)
12995 (setq org-occur-highlights nil)
12996 (setq org-occur-parameters nil)
12998 (remove-hook 'before-change-functions
12999 'org-remove-occur-highlights 'local))))
13003 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13004 "Regular expression matching the priority indicator.")
13006 (defvar org-remove-priority-next-time nil)
13008 (defun org-priority-up ()
13009 "Increase the priority of the current item."
13011 (org-priority 'up))
13013 (defun org-priority-down ()
13014 "Decrease the priority of the current item."
13016 (org-priority 'down))
13018 (defun org-priority (&optional action show)
13019 "Change the priority of an item.
13020 ACTION can be `set', `up', `down', or a character."
13022 (if (equal action '(4))
13023 (org-show-priority)
13024 (unless org-enable-priority-commands
13025 (error "Priority commands are disabled"))
13026 (setq action (or action 'set))
13027 (let (current new news have remove)
13029 (org-back-to-heading t)
13030 (if (looking-at org-priority-regexp)
13031 (setq current (string-to-char (match-string 2))
13034 ((eq action 'remove)
13035 (setq remove t new ?\ ))
13036 ((or (eq action 'set)
13037 (if (featurep 'xemacs) (characterp action) (integerp action)))
13038 (if (not (eq action 'set))
13040 (message "Priority %c-%c, SPC to remove: "
13041 org-highest-priority org-lowest-priority)
13043 (setq new (read-char-exclusive))))
13044 (if (and (= (upcase org-highest-priority) org-highest-priority)
13045 (= (upcase org-lowest-priority) org-lowest-priority))
13046 (setq new (upcase new)))
13047 (cond ((equal new ?\ ) (setq remove t))
13048 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13049 (error "Priority must be between `%c' and `%c'"
13050 org-highest-priority org-lowest-priority))))
13053 (1- current) ; normal cycling
13054 ;; last priority was empty
13055 (if (eq last-command this-command)
13056 org-lowest-priority ; wrap around empty to lowest
13058 (if org-priority-start-cycle-with-default
13059 org-default-priority
13060 (1- org-default-priority))))))
13063 (1+ current) ; normal cycling
13064 ;; last priority was empty
13065 (if (eq last-command this-command)
13066 org-highest-priority ; wrap around empty to highest
13068 (if org-priority-start-cycle-with-default
13069 org-default-priority
13070 (1+ org-default-priority))))))
13071 (t (error "Invalid action")))
13072 (if (or (< (upcase new) org-highest-priority)
13073 (> (upcase new) org-lowest-priority))
13074 (if (and (memq action '(up down))
13075 (not have) (not (eq last-command this-command)))
13076 ;; `new' is from default priority
13078 "The default can not be set, see `org-default-priority' why")
13079 ;; normal cycling: `new' is beyond highest/lowest priority
13080 ;; and is wrapped around to the empty priority
13082 (setq news (format "%c" new))
13085 (replace-match "" t t nil 1)
13086 (replace-match news t t nil 2))
13088 (error "No priority cookie found in line")
13089 (let ((case-fold-search nil))
13090 (looking-at org-todo-line-regexp))
13093 (goto-char (match-end 2))
13094 (insert " [#" news "]"))
13095 (goto-char (match-beginning 3))
13096 (insert "[#" news "] "))))
13097 (org-preserve-lc (org-set-tags nil 'align)))
13099 (message "Priority removed")
13100 (message "Priority of current item set to %s" news)))))
13102 (defun org-show-priority ()
13103 "Show the priority of the current item.
13104 This priority is composed of the main priority given with the [#A] cookies,
13105 and by additional input from the age of a schedules or deadline entry."
13107 (let ((pri (if (eq major-mode 'org-agenda-mode)
13108 (org-get-at-bol 'priority)
13111 (beginning-of-line)
13112 (and (looking-at org-heading-regexp)
13113 (org-get-priority (match-string 0))))))))
13114 (message "Priority is %d" (if pri pri -1000))))
13116 (defun org-get-priority (s)
13117 "Find priority cookie and return priority."
13118 (if (functionp org-get-priority-function)
13119 (funcall org-get-priority-function)
13121 (if (not (string-match org-priority-regexp s))
13122 (* 1000 (- org-lowest-priority org-default-priority))
13123 (* 1000 (- org-lowest-priority
13124 (string-to-char (match-string 2 s))))))))
13128 (defvar org-agenda-archives-mode)
13129 (defvar org-map-continue-from nil
13130 "Position from where mapping should continue.
13131 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13133 (defvar org-scanner-tags nil
13134 "The current tag list while the tags scanner is running.")
13135 (defvar org-trust-scanner-tags nil
13136 "Should `org-get-tags-at' use the tags for the scanner.
13137 This is for internal dynamical scoping only.
13138 When this is non-nil, the function `org-get-tags-at' will return the value
13139 of `org-scanner-tags' instead of building the list by itself. This
13140 can lead to large speed-ups when the tags scanner is used in a file with
13141 many entries, and when the list of tags is retrieved, for example to
13142 obtain a list of properties. Building the tags list for each entry in such
13143 a file becomes an N^2 operation - but with this variable set, it scales
13146 (defun org-scan-tags (action matcher todo-only &optional start-level)
13147 "Scan headline tags with inheritance and produce output ACTION.
13149 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13150 or `agenda' to produce an entry list for an agenda view. It can also be
13151 a Lisp form or a function that should be called at each matched headline, in
13152 this case the return value is a list of all return values from these calls.
13154 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13155 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13156 only lines with a not-done TODO keyword are included in the output.
13157 This should be the same variable that was scoped into
13158 and set by `org-make-tags-matcher' when it constructed MATCHER.
13160 START-LEVEL can be a string with asterisks, reducing the scope to
13161 headlines matching this string."
13162 (require 'org-agenda)
13163 (let* ((re (concat "^"
13165 ;; Get the correct level to match
13166 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13167 org-outline-regexp)
13169 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13170 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13171 (props (list 'face 'default
13172 'done-face 'org-agenda-done
13173 'undone-face 'default
13174 'mouse-face 'highlight
13175 'org-not-done-regexp org-not-done-regexp
13176 'org-todo-regexp org-todo-regexp
13177 'org-complex-heading-regexp org-complex-heading-regexp
13179 (format "mouse-2 or RET jump to org file %s"
13180 (abbreviate-file-name
13181 (or (buffer-file-name (buffer-base-buffer))
13182 (buffer-name (buffer-base-buffer)))))))
13183 (case-fold-search nil)
13184 (org-map-continue-from nil)
13185 lspos tags tags-list
13186 (tags-alist (list (cons 0 org-file-tags)))
13187 (llast 0) rtn rtn1 level category i txt
13188 todo marker entry priority)
13189 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13190 (setq action (list 'lambda nil action)))
13192 (goto-char (point-min))
13193 (when (eq action 'sparse-tree)
13195 (org-remove-occur-highlights))
13196 (while (re-search-forward re nil t)
13197 (setq org-map-continue-from nil)
13199 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13200 tags (if (match-end 4) (org-match-string-no-properties 4)))
13201 (goto-char (setq lspos (match-beginning 0)))
13202 (setq level (org-reduced-level (funcall outline-level))
13203 category (org-get-category))
13204 (setq i llast llast level)
13205 ;; remove tag lists from same and sublevels
13206 (while (>= i level)
13207 (when (setq entry (assoc i tags-alist))
13208 (setq tags-alist (delete entry tags-alist)))
13210 ;; add the next tags
13212 (setq tags (org-split-string tags ":")
13214 (cons (cons level tags) tags-alist)))
13215 ;; compile tags for current headline
13217 (if org-use-tag-inheritance
13218 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13220 org-scanner-tags tags-list)
13221 (when org-use-tag-inheritance
13222 (setcdr (car tags-alist)
13223 (mapcar (lambda (x)
13224 (setq x (copy-sequence x))
13225 (org-add-prop-inherited x))
13226 (cdar tags-alist))))
13227 (when (and tags org-use-tag-inheritance
13228 (or (not (eq t org-use-tag-inheritance))
13229 org-tags-exclude-from-inheritance))
13230 ;; selective inheritance, remove uninherited ones
13231 (setcdr (car tags-alist)
13232 (org-remove-uninherited-tags (cdar tags-alist))))
13235 ;; eval matcher only when the todo condition is OK
13236 (and (or (not todo-only) (member todo org-not-done-keywords))
13237 (let ((case-fold-search t) (org-trust-scanner-tags t))
13240 ;; Call the skipper, but return t if it does not skip,
13241 ;; so that the `and' form continues evaluating
13243 (unless (eq action 'sparse-tree) (org-agenda-skip))
13246 ;; Check if timestamps are deselecting this entry
13247 (or (not todo-only)
13248 (and (member todo org-not-done-keywords)
13249 (or (not org-agenda-tags-todo-honor-ignore-options)
13250 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13252 ;; Extra check for the archive tag
13253 ;; FIXME: Does the skipper already do this????
13255 (not (member org-archive-tag tags-list))
13256 ;; we have an archive tag, should we use this anyway?
13257 (or (not org-agenda-skip-archived-trees)
13258 (and (eq action 'agenda) org-agenda-archives-mode))))
13260 ;; select this headline
13263 ((eq action 'sparse-tree)
13264 (and org-highlight-sparse-tree-matches
13265 (org-get-heading) (match-end 0)
13266 (org-highlight-new-match
13267 (match-beginning 1) (match-end 1)))
13268 (org-show-context 'tags-tree))
13269 ((eq action 'agenda)
13270 (setq txt (org-agenda-format-item
13273 (if (eq org-tags-match-list-sublevels 'indented)
13274 (make-string (1- level) ?.) "")
13278 priority (org-get-priority txt))
13280 (setq marker (org-agenda-new-marker))
13281 (org-add-props txt props
13282 'org-marker marker 'org-hd-marker marker 'org-category category
13284 'priority priority 'type "tagsmatch")
13286 ((functionp action)
13287 (setq org-map-continue-from nil)
13289 (setq rtn1 (funcall action))
13291 (t (error "Invalid action")))
13293 ;; if we are to skip sublevels, jump to end of subtree
13294 (unless org-tags-match-list-sublevels
13295 (org-end-of-subtree t)
13296 (backward-char 1))))
13297 ;; Get the correct position from where to continue
13298 (if org-map-continue-from
13299 (goto-char org-map-continue-from)
13300 (and (= (point) lspos) (end-of-line 1)))))
13301 (when (and (eq action 'sparse-tree)
13302 (not org-sparse-tree-open-archived-trees))
13303 (org-hide-archived-subtrees (point-min) (point-max)))
13306 (defun org-remove-uninherited-tags (tags)
13307 "Remove all tags that are not inherited from the list TAGS."
13309 ((eq org-use-tag-inheritance t)
13310 (if org-tags-exclude-from-inheritance
13311 (org-delete-all org-tags-exclude-from-inheritance tags)
13313 ((not org-use-tag-inheritance) nil)
13314 ((stringp org-use-tag-inheritance)
13317 (if (and (string-match org-use-tag-inheritance x)
13318 (not (member x org-tags-exclude-from-inheritance)))
13321 ((listp org-use-tag-inheritance)
13324 (if (member x org-use-tag-inheritance) x nil))
13327 (defun org-match-sparse-tree (&optional todo-only match)
13328 "Create a sparse tree according to tags string MATCH.
13329 MATCH can contain positive and negative selection of tags, like
13330 \"+WORK+URGENT-WITHBOSS\".
13331 If optional argument TODO-ONLY is non-nil, only select lines that are
13334 (org-agenda-prepare-buffers (list (current-buffer)))
13335 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13337 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13339 (defvar org-cached-props nil)
13340 (defun org-cached-entry-get (pom property)
13341 (if (or (eq t org-use-property-inheritance)
13342 (and (stringp org-use-property-inheritance)
13343 (string-match org-use-property-inheritance property))
13344 (and (listp org-use-property-inheritance)
13345 (member property org-use-property-inheritance)))
13346 ;; Caching is not possible, check it directly
13347 (org-entry-get pom property 'inherit)
13348 ;; Get all properties, so that we can do complicated checks easily
13349 (cdr (assoc property (or org-cached-props
13350 (setq org-cached-props
13351 (org-entry-properties pom)))))))
13353 (defun org-global-tags-completion-table (&optional files)
13354 "Return the list of all tags in all agenda buffer/files.
13355 Optional FILES argument is a list of files which can be used
13356 instead of the agenda files."
13363 (set-buffer (find-file-noselect file))
13364 (append (org-get-buffer-tags)
13365 (mapcar (lambda (x) (if (stringp (car-safe x))
13366 (list (car-safe x)) nil))
13368 (if (and files (car files))
13370 (org-agenda-files))))))))
13372 (defun org-make-tags-matcher (match)
13373 "Create the TAGS/TODO matcher form for the selection string MATCH.
13375 The variable `todo-only' is scoped dynamically into this function.
13376 It will be set to t if the matcher restricts matching to TODO entries,
13377 otherwise will not be touched.
13379 Returns a cons of the selection string MATCH and the constructed
13380 lisp form implementing the matcher. The matcher is to be evaluated
13381 at an Org entry, with point on the headline, and returns t if the
13382 entry matches the selection string MATCH. The returned lisp form
13383 references two variables with information about the entry, which
13384 must be bound around the form's evaluation: todo, the TODO keyword
13385 at the entry (or nil of none); and tags-list, the list of all tags
13386 at the entry including inherited ones. Additionally, the category
13387 of the entry (if any) must be specified as the text property
13388 'org-category on the headline.
13390 See also `org-scan-tags'.
13392 (declare (special todo-only))
13393 (unless (boundp 'todo-only)
13394 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13396 ;; Get a new match request, with completion
13397 (let ((org-last-tags-completion-table
13398 (org-global-tags-completion-table)))
13399 (setq match (org-completing-read-no-i
13400 "Match: " 'org-tags-completion-function nil nil nil
13401 'org-tags-history))))
13403 ;; Parse the string and create a lisp form
13404 (let ((match0 match)
13405 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13407 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13408 orterms term orlist re-p str-p level-p level-op time-p
13409 prop-p pn pv po gv rest)
13410 (if (string-match "/+" match)
13411 ;; match contains also a todo-matching request
13413 (setq tagsmatch (substring match 0 (match-beginning 0))
13414 todomatch (substring match (match-end 0)))
13415 (if (string-match "^!" todomatch)
13416 (setq todo-only t todomatch (substring todomatch 1)))
13417 (if (string-match "^\\s-*$" todomatch)
13418 (setq todomatch nil)))
13419 ;; only matching tags
13420 (setq tagsmatch match todomatch nil))
13422 ;; Make the tags matcher
13423 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13424 (setq tagsmatcher t)
13425 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13426 (while (setq term (pop orterms))
13427 (while (and (equal (substring term -1) "\\") orterms)
13428 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13429 (while (string-match re term)
13430 (setq rest (substring term (match-end 0))
13431 minus (and (match-end 1)
13432 (equal (match-string 1 term) "-"))
13433 tag (save-match-data (replace-regexp-in-string
13435 (match-string 2 term)))
13436 re-p (equal (string-to-char tag) ?{)
13437 level-p (match-end 4)
13438 prop-p (match-end 5)
13440 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13442 (setq level-op (org-op-to-function (match-string 3 term)))
13443 `(,level-op level ,(string-to-number
13444 (match-string 4 term))))
13446 (setq pn (match-string 5 term)
13447 po (match-string 6 term)
13448 pv (match-string 7 term)
13449 re-p (equal (string-to-char pv) ?{)
13450 str-p (equal (string-to-char pv) ?\")
13451 time-p (save-match-data
13452 (string-match "^\"[[<].*[]>]\"$" pv))
13453 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13454 (if time-p (setq pv (org-matcher-time pv)))
13455 (setq po (org-op-to-function po (if time-p 'time str-p)))
13457 ((equal pn "CATEGORY")
13458 (setq gv '(get-text-property (point) 'org-category)))
13462 (setq gv `(org-cached-entry-get nil ,pn))))
13465 `(not (string-match ,pv (or ,gv "")))
13466 `(string-match ,pv (or ,gv "")))
13468 `(,po (or ,gv "") ,pv)
13469 `(,po (string-to-number (or ,gv ""))
13470 ,(string-to-number pv) ))))
13471 (t `(member ,tag tags-list)))
13472 mm (if minus (list 'not mm) mm)
13474 (push mm tagsmatcher))
13475 (push (if (> (length tagsmatcher) 1)
13476 (cons 'and tagsmatcher)
13479 (setq tagsmatcher nil))
13480 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13482 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13483 ;; Make the todo matcher
13484 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13485 (setq todomatcher t)
13486 (setq orterms (org-split-string todomatch "|") orlist nil)
13487 (while (setq term (pop orterms))
13488 (while (string-match re term)
13489 (setq minus (and (match-end 1)
13490 (equal (match-string 1 term) "-"))
13491 kwd (match-string 2 term)
13492 re-p (equal (string-to-char kwd) ?{)
13493 term (substring term (match-end 0))
13495 `(string-match ,(substring kwd 1 -1) todo)
13496 (list 'equal 'todo kwd))
13497 mm (if minus (list 'not mm) mm))
13498 (push mm todomatcher))
13499 (push (if (> (length todomatcher) 1)
13500 (cons 'and todomatcher)
13503 (setq todomatcher nil))
13504 (setq todomatcher (if (> (length orlist) 1)
13505 (cons 'or orlist) (car orlist))))
13507 ;; Return the string and lisp forms of the matcher
13508 (setq matcher (if todomatcher
13509 (list 'and tagsmatcher todomatcher)
13512 (setq matcher (list 'and '(member todo org-not-done-keywords)
13514 (cons match0 matcher)))
13516 (defun org-op-to-function (op &optional stringp)
13517 "Turn an operator into the appropriate function."
13520 ((equal op "<" ) '(< string< org-time<))
13521 ((equal op ">" ) '(> org-string> org-time>))
13522 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13523 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13524 ((member op '("=" "==")) '(= string= org-time=))
13525 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13526 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13528 (defun org<> (a b) (not (= a b)))
13529 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13530 (defun org-string>= (a b) (not (string< a b)))
13531 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13532 (defun org-string<> (a b) (not (string= a b)))
13533 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13534 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13535 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13536 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13537 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13538 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13540 "Convert S to a floating point time.
13541 If S is already a number, just return it. If it is a string, parse
13542 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13546 (condition-case nil
13547 (float-time (apply 'encode-time (org-parse-time-string s)))
13551 (defun org-time-today ()
13552 "Time in seconds today at 0:00.
13553 Returns the float number of seconds since the beginning of the
13554 epoch to the beginning of today (00:00)."
13555 (float-time (apply 'encode-time
13556 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13558 (defun org-matcher-time (s)
13559 "Interpret a time comparison value."
13562 ((string= s "<now>") (float-time))
13563 ((string= s "<today>") (org-time-today))
13564 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13565 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13566 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13567 (+ (org-time-today)
13568 (* (string-to-number (match-string 1 s))
13569 (cdr (assoc (match-string 2 s)
13570 '(("d" . 86400.0) ("w" . 604800.0)
13571 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13574 (defun org-match-any-p (re list)
13575 "Does re match any element of list?"
13576 (setq list (mapcar (lambda (x) (string-match re x)) list))
13579 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13580 (defvar org-tags-overlay (make-overlay 1 1))
13581 (org-detach-overlay org-tags-overlay)
13583 (defun org-get-local-tags-at (&optional pos)
13584 "Get a list of tags defined in the current headline."
13585 (org-get-tags-at pos 'local))
13587 (defun org-get-local-tags ()
13588 "Get a list of tags defined in the current headline."
13589 (org-get-tags-at nil 'local))
13591 (defun org-get-tags-at (&optional pos local)
13592 "Get a list of all headline tags applicable at POS.
13593 POS defaults to point. If tags are inherited, the list contains
13594 the targets in the same sequence as the headlines appear, i.e.
13595 the tags of the current headline come last.
13596 When LOCAL is non-nil, only return tags from the current headline,
13597 ignore inherited ones."
13599 (if (and org-trust-scanner-tags
13600 (or (not pos) (equal pos (point)))
13603 (let (tags ltags lastpos parent)
13607 (goto-char (or pos (point)))
13610 (condition-case nil
13612 (org-back-to-heading t)
13613 (while (not (equal lastpos (point)))
13614 (setq lastpos (point))
13616 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13617 (setq ltags (org-split-string
13618 (org-match-string-no-properties 1) ":"))
13620 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13623 (org-remove-uninherited-tags ltags)
13626 (or org-use-tag-inheritance (throw 'done t))
13627 (if local (throw 'done t))
13628 (or (org-up-heading-safe) (error nil))
13633 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13635 (defun org-add-prop-inherited (s)
13636 (add-text-properties 0 (length s) '(inherited t) s)
13639 (defun org-toggle-tag (tag &optional onoff)
13640 "Toggle the tag TAG for the current line.
13641 If ONOFF is `on' or `off', don't toggle but set to this state."
13644 (org-back-to-heading t)
13645 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13648 (setq current (match-string 1))
13649 (replace-match ""))
13651 (setq current (nreverse (org-split-string current ":")))
13655 (or (member tag current) (push tag current)))
13657 (or (not (member tag current)) (setq current (delete tag current))))
13658 (t (if (member tag current)
13659 (setq current (delete tag current))
13661 (push tag current))))
13665 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13666 (org-set-tags nil t))
13667 (delete-horizontal-space))
13668 (run-hooks 'org-after-tags-change-hook))
13671 (defun org-align-tags-here (to-col)
13672 ;; Assumes that this is a headline
13673 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13674 (beginning-of-line 1)
13675 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13676 (< pos (match-beginning 2)))
13678 (setq tags-l (- (match-end 2) (match-beginning 2)))
13679 (goto-char (match-beginning 1))
13681 (delete-region (point) (1+ (match-beginning 2)))
13682 (setq ncol (max (current-column)
13686 (- (abs to-col) tags-l))))
13688 (insert (make-string (- ncol (current-column)) ?\ ))
13689 (setq ncol (current-column))
13690 (when indent-tabs-mode (tabify p (point-at-eol)))
13691 (org-move-to-column (min ncol col) t))
13694 (defun org-set-tags-command (&optional arg just-align)
13695 "Call the set-tags command for the current entry."
13697 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13698 (org-set-tags arg just-align)
13700 (org-back-to-heading t)
13701 (org-set-tags arg just-align))))
13703 (defun org-set-tags-to (data)
13704 "Set the tags of the current entry to DATA, replacing the current tags.
13705 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13706 If DATA is nil or the empty string, any tags will be removed."
13707 (interactive "sTags: ")
13711 ((equal data "") "")
13713 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13716 (concat ":" (mapconcat 'identity data ":") ":"))))
13719 (org-back-to-heading t)
13720 (when (looking-at org-complex-heading-regexp)
13723 (goto-char (match-beginning 5))
13725 (delete-region (point) (point-at-eol))
13726 (org-set-tags nil 'align))
13727 (goto-char (point-at-eol))
13729 (org-set-tags nil 'align)))
13730 (beginning-of-line 1)
13731 (if (looking-at ".*?\\([ \t]+\\)$")
13732 (delete-region (match-beginning 1) (match-end 1))))))
13734 (defun org-align-all-tags ()
13735 "Align the tags i all headings."
13738 (or (ignore-errors (org-back-to-heading t))
13739 (outline-next-heading))
13740 (if (org-at-heading-p)
13742 (message "No headings"))))
13744 (defvar org-indent-indentation-per-level)
13745 (defun org-set-tags (&optional arg just-align)
13746 "Set the tags for the current headline.
13747 With prefix ARG, realign all tags in headings in the current buffer."
13749 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13750 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13751 'region-start-level 'region))
13752 org-loop-over-headlines-in-active-region)
13754 ;; We don't use ARG and JUST-ALIGN here these args are not
13755 ;; useful when looping over headlines
13757 org-loop-over-headlines-in-active-region
13758 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13759 (let* ((re org-outline-regexp-bol)
13760 (current (unless arg (org-get-tags-string)))
13761 (col (current-column))
13762 (org-setting-tags t)
13763 table current-tags inherited-tags ; computed below when needed
13764 tags p0 c0 c1 rpl di tc level)
13767 (goto-char (point-min))
13768 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13769 (while (re-search-forward re nil t)
13770 (org-set-tags nil t)
13772 (message "All tags realigned to column %d" org-tags-column))
13774 (setq tags current)
13775 ;; Get a new set of tags from the user
13777 (setq table (append org-tag-persistent-alist
13778 (or org-tag-alist (org-get-buffer-tags))
13780 org-complete-tags-always-offer-all-agenda-tags
13781 (org-global-tags-completion-table
13782 (org-agenda-files))))
13783 org-last-tags-completion-table table
13784 current-tags (org-split-string current ":")
13785 inherited-tags (nreverse
13786 (nthcdr (length current-tags)
13787 (nreverse (org-get-tags-at))))
13789 (if (or (eq t org-use-fast-tag-selection)
13790 (and org-use-fast-tag-selection
13791 (delq nil (mapcar 'cdr table))))
13792 (org-fast-tag-selection
13793 current-tags inherited-tags table
13794 (if org-fast-tag-selection-include-todo
13795 org-todo-key-alist))
13796 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13798 (org-icompleting-read "Tags: "
13799 'org-tags-completion-function
13800 nil nil current 'org-tags-history))))))
13801 (while (string-match "[-+&]+" tags)
13802 ;; No boolean logic, just a list
13803 (setq tags (replace-match ":" t t tags))))
13805 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13807 (if org-tags-sort-function
13808 (setq tags (mapconcat 'identity
13809 (sort (org-split-string
13810 tags (org-re "[^[:alnum:]_@#%]+"))
13811 org-tags-sort-function) ":")))
13813 (if (string-match "\\`[\t ]*\\'" tags)
13815 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13816 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13818 ;; Insert new tags at the correct column
13819 (beginning-of-line 1)
13820 (setq level (or (and (looking-at org-outline-regexp)
13821 (- (match-end 0) (point) 1))
13824 ((and (equal current "") (equal tags "")))
13825 ((re-search-forward
13826 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13828 (if (equal tags "")
13830 (goto-char (match-beginning 0))
13831 (setq c0 (current-column)
13832 ;; compute offset for the case of org-indent-mode active
13833 di (if org-indent-mode
13834 (* (1- org-indent-indentation-per-level) (1- level))
13836 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13837 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13838 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13839 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13840 (replace-match rpl t t)
13841 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13843 (t (error "Tags alignment failed")))
13844 (org-move-to-column col)
13846 (run-hooks 'org-after-tags-change-hook))))))
13848 (defun org-change-tag-in-region (beg end tag off)
13849 "Add or remove TAG for each entry in the region.
13850 This works in the agenda, and also in an org-mode buffer."
13852 (list (region-beginning) (region-end)
13853 (let ((org-last-tags-completion-table
13854 (if (derived-mode-p 'org-mode)
13855 (org-get-buffer-tags)
13856 (org-global-tags-completion-table))))
13857 (org-icompleting-read
13858 "Tag: " 'org-tags-completion-function nil nil nil
13859 'org-tags-history))
13861 (message "[s]et or
[r]emove? ")
13862 (equal (read-char-exclusive) ?r))))
13863 (if (fboundp 'deactivate-mark) (deactivate-mark))
13864 (let ((agendap (equal major-mode 'org-agenda-mode))
13865 l1 l2 m buf pos newhead (cnt 0))
13867 (setq l2 (1- (org-current-line)))
13869 (setq l1 (org-current-line))
13870 (loop for l from l1 to l2 do
13872 (setq m (get-text-property (point) 'org-hd-marker))
13873 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13875 (setq buf (if agendap (marker-buffer m) (current-buffer))
13876 pos (if agendap m (point)))
13877 (with-current-buffer buf
13881 (setq cnt (1+ cnt))
13882 (org-toggle-tag tag (if off 'off 'on))
13883 (setq newhead (org-get-heading)))))
13884 (and agendap (org-agenda-change-all-lines newhead m))))
13885 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13887 (defun org-tags-completion-function (string predicate &optional flag)
13888 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13889 (confirm (lambda (x) (stringp (car x)))))
13890 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13891 (setq s1 (match-string 1 string)
13892 s2 (match-string 2 string))
13893 (setq s1 "" s2 string))
13897 (setq rtn (try-completion s2 ctable confirm))
13900 (concat s1 s2 (substring rtn (length s2))
13901 (if (and org-add-colon-after-tag-completion
13902 (assoc rtn ctable))
13907 (all-completions s2 ctable confirm)
13911 (assoc s2 ctable)))
13914 (defun org-fast-tag-insert (kwd tags face &optional end)
13915 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13916 (insert (format "%-12s" (concat kwd ":"))
13917 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13920 (defun org-fast-tag-show-exit (flag)
13923 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13924 (replace-match ""))
13927 (org-move-to-column (- (window-width) 19) t)
13928 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13930 (defun org-set-current-tags-overlay (current prefix)
13931 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13932 (if (featurep 'xemacs)
13933 (org-overlay-display org-tags-overlay (concat prefix s)
13934 'secondary-selection)
13935 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13936 (org-overlay-display org-tags-overlay (concat prefix s)))))
13938 (defvar org-last-tag-selection-key nil)
13939 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13940 "Fast tag selection with single keys.
13941 CURRENT is the current list of tags in the headline, INHERITED is the
13942 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13943 possibly with grouping information. TODO-TABLE is a similar table with
13944 TODO keywords, should these have keys assigned to them.
13945 If the keys are nil, a-z are automatically assigned.
13946 Returns the new tags string, or nil to not change the current settings."
13947 (let* ((fulltable (append table todo-table))
13948 (maxlen (apply 'max (mapcar
13950 (if (stringp (car x)) (string-width (car x)) 0))
13952 (buf (current-buffer))
13953 (expert (eq org-fast-tag-selection-single-key 'expert))
13955 (fwidth (+ maxlen 3 1 3))
13956 (ncol (/ (- (window-width) 4) fwidth))
13959 tg cnt e c char c1 c2 ntable tbl rtn
13960 ov-start ov-end ov-prefix
13961 (exit-after-next org-fast-tag-selection-single-key)
13962 (done-keywords org-done-keywords)
13965 (beginning-of-line 1)
13967 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13968 (setq ov-start (match-beginning 1)
13969 ov-end (match-end 1)
13971 (setq ov-start (1- (point-at-eol))
13972 ov-end (1+ ov-start))
13973 (skip-chars-forward "^\n\r")
13976 (buffer-substring (1- (point)) (point))
13977 (if (> (current-column) org-tags-column)
13979 (make-string (- org-tags-column (current-column)) ?\ ))))))
13980 (move-overlay org-tags-overlay ov-start ov-end)
13981 (save-window-excursion
13983 (set-buffer (get-buffer-create " *Org tags*"))
13984 (delete-other-windows)
13985 (split-window-vertically)
13986 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13988 (org-set-local 'org-done-keywords done-keywords)
13989 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13990 (org-fast-tag-insert "Current" current c-face "\n\n")
13991 (org-fast-tag-show-exit exit-after-next)
13992 (org-set-current-tags-overlay current ov-prefix)
13993 (setq tbl fulltable char ?a cnt 0)
13994 (while (setq e (pop tbl))
13996 ((equal (car e) :startgroup)
13997 (push '() groups) (setq ingroup t)
13998 (when (not (= cnt 0))
14001 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14002 ((equal (car e) :endgroup)
14003 (setq ingroup nil cnt 0)
14004 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14005 ((equal e '(:newline))
14006 (when (not (= cnt 0))
14010 (while (equal (car tbl) '(:newline))
14012 (setq tbl (cdr tbl)))))
14014 (setq tg (copy-sequence (car e)) c2 nil)
14017 ;; automatically assign a character.
14018 (setq c1 (string-to-char
14019 (downcase (substring
14020 tg (if (= (string-to-char tg) ?@) 1 0)))))
14021 (if (or (rassoc c1 ntable) (rassoc c1 table))
14022 (while (or (rassoc char ntable) (rassoc char table))
14023 (setq char (1+ char)))
14025 (setq c (or c2 char)))
14026 (if ingroup (push tg (car groups)))
14027 (setq tg (org-add-props tg nil 'face
14029 ((not (assoc tg table))
14030 (org-get-todo-face tg))
14031 ((member tg current) c-face)
14032 ((member tg inherited) i-face))))
14033 (if (and (= cnt 0) (not ingroup)) (insert " "))
14034 (insert "[" c "] " tg (make-string
14035 (- fwidth 4 (length tg)) ?\ ))
14036 (push (cons tg c) ntable)
14037 (when (= (setq cnt (1+ cnt)) ncol)
14039 (if ingroup (insert " "))
14041 (setq ntable (nreverse ntable))
14043 (goto-char (point-min))
14044 (if (not expert) (org-fit-window-to-buffer))
14048 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14049 (if (not groups) "no " "")
14050 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14051 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14052 (setq org-last-tag-selection-key c)
14054 ((= c ?\r) (throw 'exit t))
14056 (setq groups (not groups))
14057 (goto-char (point-min))
14058 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14061 (org-fast-tag-show-exit
14062 (setq exit-after-next (not exit-after-next)))
14064 (delete-other-windows)
14065 (set-window-buffer (split-window-vertically) " *Org tags*")
14066 (org-switch-to-buffer-other-window " *Org tags*")
14067 (org-fit-window-to-buffer)))
14069 (and (= c ?q) (not (rassoc c ntable))))
14070 (org-detach-overlay org-tags-overlay)
14071 (setq quit-flag t))
14074 (if exit-after-next (setq exit-after-next 'now)))
14076 (condition-case nil
14077 (setq tg (org-icompleting-read
14080 (with-current-buffer buf
14081 (org-get-buffer-tags)))))
14082 (quit (setq tg "")))
14083 (when (string-match "\\S-" tg)
14084 (add-to-list 'buffer-tags (list tg))
14085 (if (member tg current)
14086 (setq current (delete tg current))
14087 (push tg current)))
14088 (if exit-after-next (setq exit-after-next 'now)))
14089 ((setq e (rassoc c todo-table) tg (car e))
14090 (with-current-buffer buf
14091 (save-excursion (org-todo tg)))
14092 (if exit-after-next (setq exit-after-next 'now)))
14093 ((setq e (rassoc c ntable) tg (car e))
14094 (if (member tg current)
14095 (setq current (delete tg current))
14096 (loop for g in groups do
14099 (setq current (delete x current)))
14102 (if exit-after-next (setq exit-after-next 'now))))
14104 ;; Create a sorted list
14108 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14109 (if (eq exit-after-next 'now) (throw 'exit t))
14110 (goto-char (point-min))
14111 (beginning-of-line 2)
14112 (delete-region (point) (point-at-eol))
14113 (org-fast-tag-insert "Current" current c-face)
14114 (org-set-current-tags-overlay current ov-prefix)
14115 (while (re-search-forward
14116 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14117 (setq tg (match-string 1))
14118 (add-text-properties
14119 (match-beginning 1) (match-end 1)
14122 ((member tg current) c-face)
14123 ((member tg inherited) i-face)
14124 (t (get-text-property (match-beginning 1) 'face))))))
14125 (goto-char (point-min)))))
14126 (org-detach-overlay org-tags-overlay)
14128 (mapconcat 'identity current ":")
14131 (defun org-get-tags-string ()
14132 "Get the TAGS string in the current headline."
14133 (unless (org-at-heading-p t)
14134 (error "Not on a heading"))
14136 (beginning-of-line 1)
14137 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14138 (org-match-string-no-properties 1)
14141 (defun org-get-tags ()
14142 "Get the list of tags specified in the current headline."
14143 (org-split-string (org-get-tags-string) ":"))
14145 (defun org-get-buffer-tags ()
14146 "Get a table of all tags used in the buffer, for completion."
14149 (goto-char (point-min))
14150 (while (re-search-forward
14151 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14152 (when (equal (char-after (point-at-bol 0)) ?*)
14153 (mapc (lambda (x) (add-to-list 'tags x))
14154 (org-split-string (org-match-string-no-properties 1) ":")))))
14155 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14156 (mapcar 'list tags)))
14158 ;;;; The mapping API
14161 (defun org-map-entries (func &optional match scope &rest skip)
14162 "Call FUNC at each headline selected by MATCH in SCOPE.
14164 FUNC is a function or a lisp form. The function will be called without
14165 arguments, with the cursor positioned at the beginning of the headline.
14166 The return values of all calls to the function will be collected and
14167 returned as a list.
14169 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14170 does not need to preserve point. After evaluation, the cursor will be
14171 moved to the end of the line (presumably of the headline of the
14172 processed entry) and search continues from there. Under some
14173 circumstances, this may not produce the wanted results. For example,
14174 if you have removed (e.g. archived) the current (sub)tree it could
14175 mean that the next entry will be skipped entirely. In such cases, you
14176 can specify the position from where search should continue by making
14177 FUNC set the variable `org-map-continue-from' to the desired buffer
14180 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14181 Only headlines that are matched by this query will be considered during
14182 the iteration. When MATCH is nil or t, all headlines will be
14183 visited by the iteration.
14185 SCOPE determines the scope of this command. It can be any of:
14187 nil The current buffer, respecting the restriction if any
14188 tree The subtree started with the entry at point
14189 region The entries within the active region, if any
14191 The entries within the active region, but only those at
14192 the same level than the first one.
14193 file The current buffer, without restriction
14195 The current buffer, and any archives associated with it
14196 agenda All agenda files
14197 agenda-with-archives
14198 All agenda files with any archive files associated with them
14200 If this is a list, all files in the list will be scanned
14202 The remaining args are treated as settings for the skipping facilities of
14203 the scanner. The following items can be given here:
14205 archive skip trees with the archive tag.
14206 comment skip trees with the COMMENT keyword
14207 function or Emacs Lisp form:
14208 will be used as value for `org-agenda-skip-function', so whenever
14209 the function returns t, FUNC will not be called for that
14210 entry and search will continue from the point where the
14211 function leaves it.
14213 If your function needs to retrieve the tags including inherited tags
14214 at the *current* entry, you can use the value of the variable
14215 `org-scanner-tags' which will be much faster than getting the value
14216 with `org-get-tags-at'. If your function gets properties with
14217 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14218 to t around the call to `org-entry-properties' to get the same speedup.
14219 Note that if your function moves around to retrieve tags and properties at
14220 a *different* entry, you cannot use these techniques."
14221 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14222 (not (org-region-active-p)))
14223 (let* ((org-agenda-archives-mode nil) ; just to make sure
14224 (org-agenda-skip-archived-trees (memq 'archive skip))
14225 (org-agenda-skip-comment-trees (memq 'comment skip))
14226 (org-agenda-skip-function
14227 (car (org-delete-all '(comment archive) skip)))
14228 (org-tags-match-list-sublevels t)
14229 (start-level (eq scope 'region-start-level))
14231 org-todo-keywords-for-agenda
14232 org-done-keywords-for-agenda
14233 org-todo-keyword-alist-for-agenda
14234 org-drawers-for-agenda
14235 org-tag-alist-for-agenda
14239 ((eq match t) (setq matcher t))
14240 ((eq match nil) (setq matcher t))
14241 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14245 (cond ((eq scope 'tree)
14246 (org-back-to-heading t)
14247 (org-narrow-to-subtree)
14249 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14250 (org-region-active-p))
14251 ;; If needed, set start-level to a string like "2"
14254 (goto-char (region-beginning))
14255 (unless (org-at-heading-p) (outline-next-heading))
14256 (setq start-level (org-current-level))))
14257 (narrow-to-region (region-beginning)
14259 (goto-char (region-end))
14260 (unless (and (bolp) (org-at-heading-p))
14261 (outline-next-heading))
14267 (org-agenda-prepare-buffers
14268 (list (buffer-file-name (current-buffer))))
14269 (setq res (org-scan-tags func matcher todo-only start-level)))
14270 ;; Get the right scope
14272 ((and scope (listp scope) (symbolp (car scope)))
14273 (setq scope (eval scope)))
14274 ((eq scope 'agenda)
14275 (setq scope (org-agenda-files t)))
14276 ((eq scope 'agenda-with-archives)
14277 (setq scope (org-agenda-files t))
14278 (setq scope (org-add-archive-files scope)))
14280 (setq scope (list (buffer-file-name))))
14281 ((eq scope 'file-with-archives)
14282 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14283 (org-agenda-prepare-buffers scope)
14284 (while (setq file (pop scope))
14285 (with-current-buffer (org-find-base-buffer-visiting file)
14289 (goto-char (point-min))
14290 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14295 ;;; Setting and retrieving properties
14297 (defconst org-special-properties
14298 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14299 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14300 "The special properties valid in Org-mode.
14302 These are properties that are not defined in the property drawer,
14303 but in some other way.")
14305 (defconst org-default-properties
14306 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14307 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14308 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14309 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14310 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14311 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14312 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14313 "Some properties that are used by Org-mode for various purposes.
14314 Being in this list makes sure that they are offered for completion.")
14316 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14317 "Regular expression matching the first line of a property drawer.")
14319 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14320 "Regular expression matching the last line of a property drawer.")
14322 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14323 "Regular expression matching the first line of a property drawer.")
14325 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14326 "Regular expression matching the first line of a property drawer.")
14328 (defconst org-property-drawer-re
14329 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14330 org-property-end-re "\\)\n?")
14331 "Matches an entire property drawer.")
14333 (defconst org-clock-drawer-re
14334 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14335 org-property-end-re "\\)\n?")
14336 "Matches an entire clock drawer.")
14338 (defsubst org-re-property (property)
14339 "Return a regexp matching a PROPERTY line.
14340 Match group 1 will be set to the value."
14341 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14343 (defsubst org-re-property-keyword (property)
14344 "Return a regexp matching a PROPERTY line, possibly with no
14345 value for the property."
14346 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14348 (defun org-property-action ()
14349 "Do an action on properties."
14352 (org-at-property-p)
14353 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14354 (setq c (read-char-exclusive))
14357 (call-interactively 'org-set-property))
14359 (call-interactively 'org-delete-property))
14361 (call-interactively 'org-delete-property-globally))
14363 (call-interactively 'org-compute-property-at-point))
14364 (t (error "No such property action %c" c)))))
14366 (defun org-inc-effort ()
14367 "Increment the value of the effort property in the current entry."
14369 (org-set-effort nil t))
14371 (defun org-set-effort (&optional value increment)
14372 "Set the effort property of the current entry.
14373 With numerical prefix arg, use the nth allowed value, 0 stands for the
14374 10th allowed value.
14376 When INCREMENT is non-nil, set the property to the next allowed value."
14378 (if (equal value 0) (setq value 10))
14379 (let* ((completion-ignore-case t)
14380 (prop org-effort-property)
14381 (cur (org-entry-get nil prop))
14382 (allowed (org-property-get-allowed-values nil prop 'table))
14383 (existing (mapcar 'list (org-property-values prop)))
14386 ((stringp value) value)
14387 ((and allowed (integerp value))
14388 (or (car (nth (1- value) allowed))
14389 (car (org-last allowed))))
14390 ((and allowed increment)
14391 (or (caadr (member (list cur) allowed))
14392 (error "Allowed effort values are not set")))
14394 (message "Select 1-9,0, [RET%s]: %s"
14395 (if cur (concat "=" cur) "")
14396 (mapconcat 'car allowed " "))
14397 (setq rpl (read-char-exclusive))
14398 (if (equal rpl ?\r)
14400 (setq rpl (- rpl ?0))
14401 (if (equal rpl 0) (setq rpl 10))
14402 (if (and (> rpl 0) (<= rpl (length allowed)))
14403 (car (nth (1- rpl) allowed))
14404 (org-completing-read "Effort: " allowed nil))))
14406 (let (org-completion-use-ido org-completion-use-iswitchb)
14407 (org-completing-read
14408 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14409 (concat "[" cur "]") "")
14411 existing nil nil "" nil cur))))))
14412 (unless (equal (org-entry-get nil prop) val)
14413 (org-entry-put nil prop val))
14414 (message "%s is now %s" prop val)))
14416 (defun org-at-property-p ()
14417 "Is cursor inside a property drawer?"
14419 (beginning-of-line 1)
14420 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14421 (save-match-data ;; Used by calling procedures
14423 (range (unless (org-before-first-heading-p)
14424 (org-get-property-block))))
14425 (and range (<= (car range) p) (< p (cdr range))))))))
14427 (defun org-get-property-block (&optional beg end force)
14428 "Return the (beg . end) range of the body of the property drawer.
14429 BEG and END are the beginning and end of the current subtree, or of
14430 the part before the first headline. If they are not given, they will
14431 be found. If the drawer does not exist and FORCE is non-nil, create
14435 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14436 (progn (org-back-to-heading t) (point))))
14437 (end (or end (and (not (outline-next-heading)) (point-max))
14440 (if (re-search-forward org-property-start-re end t)
14441 (setq beg (1+ (match-end 0)))
14444 (org-insert-property-drawer)
14445 (setq end (progn (outline-next-heading) (point))))
14448 (if (re-search-forward org-property-start-re end t)
14449 (setq beg (1+ (match-end 0)))))
14450 (if (re-search-forward org-property-end-re end t)
14451 (setq end (match-beginning 0))
14452 (or force (throw 'exit nil))
14456 (insert ":END:\n"))
14459 (defun org-entry-properties (&optional pom which specific)
14460 "Get all properties of the entry at point-or-marker POM.
14461 This includes the TODO keyword, the tags, time strings for deadline,
14462 scheduled, and clocking, and any additional properties defined in the
14463 entry. The return value is an alist, keys may occur multiple times
14464 if the property key was used several times.
14465 POM may also be nil, in which case the current entry is used.
14466 If WHICH is nil or `all', get all properties. If WHICH is
14467 `special' or `standard', only get that subclass. If WHICH
14468 is a string only get exactly this property. SPECIFIC can be a string, the
14469 specific property we are interested in. Specifying it can speed
14470 things up because then unnecessary parsing is avoided."
14471 (setq which (or which 'all))
14472 (org-with-point-at pom
14473 (let ((clockstr (substring org-clock-string 0 -1))
14474 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14475 (case-fold-search nil)
14476 beg end range props sum-props key key1 value string clocksum clocksumt)
14478 (when (condition-case nil
14479 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14482 (setq sum-props (get-text-property (point) 'org-summaries))
14483 (setq clocksum (get-text-property (point) :org-clock-minutes)
14484 clocksumt (get-text-property (point) :org-clock-minutes-today))
14485 (outline-next-heading)
14487 (when (memq which '(all special))
14488 ;; Get the special properties, like TODO and tags
14490 (when (and (or (not specific) (string= specific "TODO"))
14491 (looking-at org-todo-line-regexp) (match-end 2))
14492 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14493 (when (and (or (not specific) (string= specific "PRIORITY"))
14494 (looking-at org-priority-regexp))
14495 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14496 (when (or (not specific) (string= specific "FILE"))
14497 (push (cons "FILE" buffer-file-name) props))
14498 (when (and (or (not specific) (string= specific "TAGS"))
14499 (setq value (org-get-tags-string))
14500 (string-match "\\S-" value))
14501 (push (cons "TAGS" value) props))
14502 (when (and (or (not specific) (string= specific "ALLTAGS"))
14503 (setq value (org-get-tags-at)))
14504 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14507 (when (or (not specific) (string= specific "BLOCKED"))
14508 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14509 (when (or (not specific)
14511 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14512 "TIMESTAMP" "TIMESTAMP_IA")))
14514 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14515 (setq key (if (match-end 1)
14516 (substring (org-match-string-no-properties 1)
14518 string (if (equal key clockstr)
14520 (buffer-substring-no-properties
14521 (match-beginning 3) (goto-char
14523 (substring (org-match-string-no-properties 3)
14525 ;; Get the correct property name from the key. This is
14526 ;; necessary if the user has configured time keywords.
14527 (setq key1 (concat key ":"))
14531 (if (= (char-after (match-beginning 3)) ?\[)
14532 "TIMESTAMP_IA" "TIMESTAMP")))
14533 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14534 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14535 ((equal key1 org-closed-string) (setq key "CLOSED"))
14536 ((equal key1 org-clock-string) (setq key "CLOCK")))
14537 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14539 (push (cons key string) props)
14540 ;; no need to search further if match is found
14542 (when (or (equal key "CLOCK") (not (assoc key props)))
14543 (push (cons key string) props)))))))
14545 (when (memq which '(all standard))
14546 ;; Get the standard properties, like :PROP: ...
14547 (setq range (org-get-property-block beg end))
14549 (goto-char (car range))
14550 (while (re-search-forward
14551 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14553 (setq key (org-match-string-no-properties 1)
14554 value (org-trim (or (org-match-string-no-properties 2) "")))
14555 (unless (member key excluded)
14556 (push (cons key (or value "")) props)))))
14558 (push (cons "CLOCKSUM"
14559 (org-columns-number-to-string (/ (float clocksum) 60.)
14563 (push (cons "CLOCKSUM_T"
14564 (org-columns-number-to-string (/ (float clocksumt) 60.)
14567 (unless (assoc "CATEGORY" props)
14568 (push (cons "CATEGORY" (org-get-category)) props))
14569 (append sum-props (nreverse props)))))))
14571 (defun org-entry-get (pom property &optional inherit literal-nil)
14572 "Get value of PROPERTY for entry or content at point-or-marker POM.
14573 If INHERIT is non-nil and the entry does not have the property,
14574 then also check higher levels of the hierarchy.
14575 If INHERIT is the symbol `selective', use inheritance only if the setting
14576 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14577 If the property is present but empty, the return value is the empty string.
14578 If the property is not present at all, nil is returned.
14580 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14581 do not interpret it as the list atom nil. This is used for inheritance
14582 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14583 (org-with-point-at pom
14584 (if (and inherit (if (eq inherit 'selective)
14585 (org-property-inherit-p property)
14587 (org-entry-get-with-inheritance property literal-nil)
14588 (if (member property org-special-properties)
14589 ;; We need a special property. Use `org-entry-properties' to
14590 ;; retrieve it, but specify the wanted property
14591 (cdr (assoc property (org-entry-properties nil 'special property)))
14592 (let* ((range (org-get-property-block))
14593 (props (list (or (assoc property org-file-properties)
14594 (assoc property org-global-properties)
14595 (assoc property org-global-properties-fixed))))
14597 (when (re-search-forward
14598 (org-re-property key) (cdr range) t)
14600 (org-update-property-plist
14603 (org-match-string-no-properties 1) "")
14606 (when (and range (goto-char (car range)))
14607 (funcall ap property)
14608 (goto-char (car range))
14609 (while (funcall ap (concat property "+")))
14610 (setq val (cdr (assoc property props)))
14611 (when val (if literal-nil val (org-not-nil val)))))))))
14613 (defun org-property-or-variable-value (var &optional inherit)
14614 "Check if there is a property fixing the value of VAR.
14615 If yes, return this value. If not, return the current value of the variable."
14616 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14617 (if (and prop (stringp prop) (string-match "\\S-" prop))
14619 (symbol-value var))))
14621 (defun org-entry-delete (pom property)
14622 "Delete the property PROPERTY from entry at point-or-marker POM."
14623 (org-with-point-at pom
14624 (if (member property org-special-properties)
14625 nil ; cannot delete these properties.
14626 (let ((range (org-get-property-block)))
14628 (goto-char (car range))
14630 (org-re-property property)
14633 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14637 ;; Multi-values properties are properties that contain multiple values
14638 ;; These values are assumed to be single words, separated by whitespace.
14639 (defun org-entry-add-to-multivalued-property (pom property value)
14640 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14641 (let* ((old (org-entry-get pom property))
14642 (values (and old (org-split-string old "[ \t]"))))
14643 (setq value (org-entry-protect-space value))
14644 (unless (member value values)
14645 (setq values (cons value values))
14646 (org-entry-put pom property
14647 (mapconcat 'identity values " ")))))
14649 (defun org-entry-remove-from-multivalued-property (pom property value)
14650 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14651 (let* ((old (org-entry-get pom property))
14652 (values (and old (org-split-string old "[ \t]"))))
14653 (setq value (org-entry-protect-space value))
14654 (when (member value values)
14655 (setq values (delete value values))
14656 (org-entry-put pom property
14657 (mapconcat 'identity values " ")))))
14659 (defun org-entry-member-in-multivalued-property (pom property value)
14660 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14661 (let* ((old (org-entry-get pom property))
14662 (values (and old (org-split-string old "[ \t]"))))
14663 (setq value (org-entry-protect-space value))
14664 (member value values)))
14666 (defun org-entry-get-multivalued-property (pom property)
14667 "Return a list of values in a multivalued property."
14668 (let* ((value (org-entry-get pom property))
14669 (values (and value (org-split-string value "[ \t]"))))
14670 (mapcar 'org-entry-restore-space values)))
14672 (defun org-entry-put-multivalued-property (pom property &rest values)
14673 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14674 VALUES should be a list of strings. Spaces will be protected."
14675 (org-entry-put pom property
14676 (mapconcat 'org-entry-protect-space values " "))
14677 (let* ((value (org-entry-get pom property))
14678 (values (and value (org-split-string value "[ \t]"))))
14679 (mapcar 'org-entry-restore-space values)))
14681 (defun org-entry-protect-space (s)
14682 "Protect spaces and newline in string S."
14683 (while (string-match " " s)
14684 (setq s (replace-match "%20" t t s)))
14685 (while (string-match "\n" s)
14686 (setq s (replace-match "%0A" t t s)))
14689 (defun org-entry-restore-space (s)
14690 "Restore spaces and newline in string S."
14691 (while (string-match "%20" s)
14692 (setq s (replace-match " " t t s)))
14693 (while (string-match "%0A" s)
14694 (setq s (replace-match "\n" t t s)))
14697 (defvar org-entry-property-inherited-from (make-marker)
14698 "Marker pointing to the entry from where a property was inherited.
14699 Each call to `org-entry-get-with-inheritance' will set this marker to the
14700 location of the entry where the inheritance search matched. If there was
14701 no match, the marker will point nowhere.
14702 Note that also `org-entry-get' calls this function, if the INHERIT flag
14705 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14706 "Get PROPERTY of entry or content at point, search higher levels if needed.
14707 The search will stop at the first ancestor which has the property defined.
14708 If the value found is \"nil\", return nil to show that the property
14709 should be considered as undefined (this is the meaning of nil here).
14710 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14711 (move-marker org-entry-property-inherited-from nil)
14718 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14719 (or (ignore-errors (org-back-to-heading t))
14720 (goto-char (point-min)))
14721 (move-marker org-entry-property-inherited-from (point))
14723 (or (ignore-errors (org-up-heading-safe))
14724 (throw 'ex nil))))))
14726 (cdr (assoc property org-file-properties))
14727 (cdr (assoc property org-global-properties))
14728 (cdr (assoc property org-global-properties-fixed))))
14729 (if literal-nil tmp (org-not-nil tmp))))
14731 (defvar org-property-changed-functions nil
14732 "Hook called when the value of a property has changed.
14733 Each hook function should accept two arguments, the name of the property
14734 and the new value.")
14736 (defun org-entry-put (pom property value)
14737 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14738 (org-with-point-at pom
14739 (org-back-to-heading t)
14740 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14743 ((equal property "TODO")
14744 (when (and (stringp value) (string-match "\\S-" value)
14745 (not (member value org-todo-keywords-1)))
14746 (error "\"%s\" is not a valid TODO state" value))
14747 (if (or (not value)
14748 (not (string-match "\\S-" value)))
14749 (setq value 'none))
14751 (org-set-tags nil 'align))
14752 ((equal property "PRIORITY")
14753 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14754 (string-to-char value) ?\ ))
14755 (org-set-tags nil 'align))
14756 ((equal property "SCHEDULED")
14757 (if (re-search-forward org-scheduled-time-regexp end t)
14759 ((eq value 'earlier) (org-timestamp-change -1 'day))
14760 ((eq value 'later) (org-timestamp-change 1 'day))
14761 (t (call-interactively 'org-schedule)))
14762 (call-interactively 'org-schedule)))
14763 ((equal property "DEADLINE")
14764 (if (re-search-forward org-deadline-time-regexp end t)
14766 ((eq value 'earlier) (org-timestamp-change -1 'day))
14767 ((eq value 'later) (org-timestamp-change 1 'day))
14768 (t (call-interactively 'org-deadline)))
14769 (call-interactively 'org-deadline)))
14770 ((member property org-special-properties)
14771 (error "The %s property can not yet be set with `org-entry-put'"
14773 (t ; a non-special property
14774 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14775 (setq range (org-get-property-block beg end 'force))
14776 (goto-char (car range))
14777 (if (re-search-forward
14778 (org-re-property-keyword property) (cdr range) t)
14780 (delete-region (match-beginning 0) (match-end 0))
14781 (goto-char (match-beginning 0)))
14782 (goto-char (cdr range))
14786 (insert ":" property ":")
14787 (and value (insert " " value))
14788 (org-indent-line)))))
14789 (run-hook-with-args 'org-property-changed-functions property value)))
14791 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14792 "Get all property keys in the current buffer.
14793 With INCLUDE-SPECIALS, also list the special properties that reflect things
14794 like tags and TODO state.
14795 With INCLUDE-DEFAULTS, also include properties that has special meaning
14796 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14798 With INCLUDE-COLUMNS, also include property names given in COLUMN
14799 formats in the current buffer."
14800 (let (rtn range cfmt s p)
14804 (goto-char (point-min))
14805 (while (re-search-forward org-property-start-re nil t)
14806 (setq range (org-get-property-block))
14807 (goto-char (car range))
14808 (while (re-search-forward
14809 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14811 (add-to-list 'rtn (org-match-string-no-properties 1)))
14812 (outline-next-heading))))
14814 (when include-specials
14815 (setq rtn (append org-special-properties rtn)))
14817 (when include-defaults
14818 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14819 (add-to-list 'rtn org-effort-property))
14821 (when include-columns
14825 (goto-char (point-min))
14826 (while (re-search-forward
14827 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14829 (setq cfmt (match-string 2) s 0)
14830 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14832 (setq s (match-end 0)
14833 p (match-string 1 cfmt))
14834 (unless (or (equal p "ITEM")
14835 (member p org-special-properties))
14836 (add-to-list 'rtn (match-string 1 cfmt))))))))
14838 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14840 (defun org-property-values (key)
14841 "Return a list of all values of property KEY in the current buffer."
14845 (goto-char (point-min))
14846 (let ((re (org-re-property key))
14848 (while (re-search-forward re nil t)
14849 (add-to-list 'values (org-trim (match-string 1))))
14850 (delete "" values)))))
14852 (defun org-insert-property-drawer ()
14853 "Insert a property drawer into the current entry."
14854 (org-back-to-heading t)
14855 (looking-at org-outline-regexp)
14856 (let ((indent (if org-adapt-indentation
14857 (- (match-end 0) (match-beginning 0))
14860 (re (concat "^[ \t]*" org-keyword-time-regexp))
14862 (outline-next-heading)
14865 (while (re-search-forward re end t))
14866 (setq hiddenp (outline-invisible-p))
14868 (and (equal (char-after) ?\n) (forward-char 1))
14869 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14870 (if (member (match-string 1) '("CLOCK:" ":END:"))
14871 ;; just skip this line
14872 (beginning-of-line 2)
14873 ;; Drawer start, find the end
14874 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14875 (beginning-of-line 1)))
14876 (org-skip-over-state-notes)
14877 (skip-chars-backward " \t\n\r")
14878 (if (eq (char-before) ?*) (forward-char 1))
14879 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14880 (beginning-of-line 0)
14881 (org-indent-to-column indent)
14882 (beginning-of-line 2)
14883 (org-indent-to-column indent)
14884 (beginning-of-line 0)
14887 (org-back-to-heading t)
14889 (org-flag-drawer t))))
14891 (defun org-insert-drawer (&optional arg drawer)
14892 "Insert a drawer at point.
14894 Optional argument DRAWER, when non-nil, is a string representing
14895 drawer's name. Otherwise, the user is prompted for a name.
14897 If a region is active, insert the drawer around that region
14900 Point is left between drawer's boundaries."
14902 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14904 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14905 ;; internally by Org. They are meant to be inserted
14907 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14908 ;; Remove system drawers from list. Note: For some reason,
14909 ;; `org-completing-read' ignores the predicate while
14910 ;; `completing-read' handles it fine.
14911 (drawer (if arg "PROPERTIES"
14914 "Drawer: " org-drawers
14915 (lambda (d) (not (member d system-drawers))))))))
14917 ;; With C-u, fall back on `org-insert-property-drawer'
14918 (arg (org-insert-property-drawer))
14919 ;; With an active region, insert a drawer at point.
14920 ((not (org-region-active-p))
14922 (unless (bolp) (insert "\n"))
14923 (insert (format ":%s:\n\n:END:\n" drawer))
14924 (forward-line -2)))
14925 ;; Otherwise, insert the drawer at point
14927 (let ((rbeg (region-beginning))
14928 (rend (copy-marker (region-end))))
14932 (beginning-of-line)
14933 (when (save-excursion
14934 (re-search-forward org-outline-regexp-bol rend t))
14935 (error "Drawers cannot contain headlines"))
14936 ;; Position point at the beginning of the first
14937 ;; non-blank line in region. Insert drawer's opening
14938 ;; there, then indent it.
14939 (org-skip-whitespace)
14940 (beginning-of-line)
14941 (insert ":" drawer ":\n")
14943 (indent-for-tab-command)
14944 ;; Move point to the beginning of the first blank line
14945 ;; after the last non-blank line in region. Insert
14946 ;; drawer's closing, then indent it.
14948 (skip-chars-backward " \r\t\n")
14950 (deactivate-mark t)
14951 (indent-for-tab-command)
14952 (unless (eolp) (insert "\n")))
14953 ;; Clear marker, whatever the outcome of insertion is.
14954 (set-marker rend nil)))))))
14956 (defvar org-property-set-functions-alist nil
14957 "Property set function alist.
14958 Each entry should have the following format:
14960 (PROPERTY . READ-FUNCTION)
14962 The read function will be called with the same argument as
14963 `org-completing-read'.")
14965 (defun org-set-property-function (property)
14966 "Get the function that should be used to set PROPERTY.
14967 This is computed according to `org-property-set-functions-alist'."
14968 (or (cdr (assoc property org-property-set-functions-alist))
14969 'org-completing-read))
14971 (defun org-read-property-value (property)
14972 "Read PROPERTY value from user."
14973 (let* ((completion-ignore-case t)
14974 (allowed (org-property-get-allowed-values nil property 'table))
14975 (cur (org-entry-get nil property))
14976 (prompt (concat property " value"
14977 (if (and cur (string-match "\\S-" cur))
14978 (concat " [" cur "]") "") ": "))
14979 (set-function (org-set-property-function property))
14981 (funcall set-function prompt allowed nil
14982 (not (get-text-property 0 'org-unrestricted
14984 (let (org-completion-use-ido org-completion-use-iswitchb)
14985 (funcall set-function prompt
14986 (mapcar 'list (org-property-values property))
14987 nil nil "" nil cur)))))
14992 (defvar org-last-set-property nil)
14993 (defun org-read-property-name ()
14994 "Read a property name."
14995 (let* ((completion-ignore-case t)
14996 (keys (org-buffer-property-keys nil t t))
14997 (default-prop (or (save-excursion
14999 (beginning-of-line)
15000 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15001 (null (string= (match-string 1) "END"))
15002 (match-string 1))))
15003 org-last-set-property))
15004 (property (org-icompleting-read
15006 (if default-prop (concat " [" default-prop "]") "")
15008 (mapcar 'list keys)
15012 (if (member property keys)
15014 (or (cdr (assoc (downcase property)
15015 (mapcar (lambda (x) (cons (downcase x) x))
15019 (defun org-set-property (property value)
15020 "In the current entry, set PROPERTY to VALUE.
15021 When called interactively, this will prompt for a property name, offering
15022 completion on existing and default properties. And then it will prompt
15023 for a value, offering completion either on allowed values (via an inherited
15024 xxx_ALL property) or on existing values in other instances of this property
15025 in the current file."
15026 (interactive (list nil nil))
15027 (let* ((property (or property (org-read-property-name)))
15028 (value (or value (org-read-property-value property)))
15029 (fn (cdr (assoc property org-properties-postprocess-alist))))
15030 (setq org-last-set-property property)
15031 ;; Possibly postprocess the inserted value:
15032 (when fn (setq value (funcall fn value)))
15033 (unless (equal (org-entry-get nil property) value)
15034 (org-entry-put nil property value))))
15036 (defun org-delete-property (property)
15037 "In the current entry, delete PROPERTY."
15039 (let* ((completion-ignore-case t)
15040 (prop (org-icompleting-read "Property: "
15041 (org-entry-properties nil 'standard))))
15043 (message "Property %s %s" property
15044 (if (org-entry-delete nil property)
15046 "was not present in the entry")))
15048 (defun org-delete-property-globally (property)
15049 "Remove PROPERTY globally, from all entries."
15051 (let* ((completion-ignore-case t)
15052 (prop (org-icompleting-read
15053 "Globally remove property: "
15054 (mapcar 'list (org-buffer-property-keys)))))
15059 (goto-char (point-min))
15061 (while (re-search-forward
15062 (org-re-property property)
15064 (setq cnt (1+ cnt))
15065 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15066 (message "Property \"%s\" removed from %d entries" property cnt)))))
15068 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15070 (defun org-compute-property-at-point ()
15071 "Compute the property at point.
15072 This looks for an enclosing column format, extracts the operator and
15073 then applies it to the property in the column format's scope."
15075 (unless (org-at-property-p)
15076 (error "Not at a property"))
15077 (let ((prop (org-match-string-no-properties 2)))
15078 (org-columns-get-format-and-top-level)
15079 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15080 (error "No operator defined for property %s" prop))
15081 (org-columns-compute prop)))
15083 (defvar org-property-allowed-value-functions nil
15084 "Hook for functions supplying allowed values for a specific property.
15085 The functions must take a single argument, the name of the property, and
15086 return a flat list of allowed values. If \":ETC\" is one of
15087 the values, this means that these values are intended as defaults for
15088 completion, but that other values should be allowed too.
15089 The functions must return nil if they are not responsible for this
15092 (defun org-property-get-allowed-values (pom property &optional table)
15093 "Get allowed values for the property PROPERTY.
15094 When TABLE is non-nil, return an alist that can directly be used for
15098 ((equal property "TODO")
15099 (setq vals (org-with-point-at pom
15100 (append org-todo-keywords-1 '("")))))
15101 ((equal property "PRIORITY")
15102 (let ((n org-lowest-priority))
15103 (while (>= n org-highest-priority)
15104 (push (char-to-string n) vals)
15106 ((member property org-special-properties))
15107 ((setq vals (run-hook-with-args-until-success
15108 'org-property-allowed-value-functions property)))
15110 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15111 (when (and vals (string-match "\\S-" vals))
15112 (setq vals (car (read-from-string (concat "(" vals ")"))))
15113 (setq vals (mapcar (lambda (x)
15114 (cond ((stringp x) x)
15115 ((numberp x) (number-to-string x))
15116 ((symbolp x) (symbol-name x))
15119 (when (member ":ETC" vals)
15120 (setq vals (remove ":ETC" vals))
15121 (org-add-props (car vals) '(org-unrestricted t)))
15122 (if table (mapcar 'list vals) vals)))
15124 (defun org-property-previous-allowed-value (&optional previous)
15125 "Switch to the next allowed value for this property."
15127 (org-property-next-allowed-value t))
15129 (defun org-property-next-allowed-value (&optional previous)
15130 "Switch to the next allowed value for this property."
15132 (unless (org-at-property-p)
15133 (error "Not at a property"))
15134 (let* ((key (match-string 2))
15135 (value (match-string 3))
15136 (allowed (or (org-property-get-allowed-values (point) key)
15137 (and (member value '("[ ]" "[-]" "[X]"))
15141 (error "Allowed values for this property have not been defined"))
15142 (if previous (setq allowed (reverse allowed)))
15143 (if (member value allowed)
15144 (setq nval (car (cdr (member value allowed)))))
15145 (setq nval (or nval (car allowed)))
15146 (if (equal nval value)
15147 (error "Only one allowed value for this property"))
15148 (org-at-property-p)
15149 (replace-match (concat " :" key ": " nval) t t)
15151 (beginning-of-line 1)
15152 (skip-chars-forward " \t")
15153 (run-hook-with-args 'org-property-changed-functions key nval)))
15155 (defun org-find-olp (path &optional this-buffer)
15156 "Return a marker pointing to the entry at outline path OLP.
15157 If anything goes wrong, throw an error.
15158 You can wrap this call to catch the error like this:
15160 (condition-case msg
15161 (org-mobile-locate-entry (match-string 4))
15162 (error (nth 1 msg)))
15164 The return value will then be either a string with the error message,
15165 or a marker if everything is OK.
15167 If THIS-BUFFER is set, the outline path does not contain a file,
15169 (let* ((file (if this-buffer buffer-file-name (pop path)))
15170 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15174 limit re end found pos heading cnt flevel)
15175 (unless buffer (error "File not found :%s" file))
15176 (with-current-buffer buffer
15180 (setq limit (point-max))
15181 (goto-char (point-min))
15182 (while (setq heading (pop path))
15183 (setq re (format org-complex-heading-regexp-format
15184 (regexp-quote heading)))
15185 (setq cnt 0 pos (point))
15186 (while (re-search-forward re end t)
15187 (setq level (- (match-end 1) (match-beginning 1)))
15188 (if (and (>= level lmin) (<= level lmax))
15189 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15190 (when (= cnt 0) (error "Heading not found on level %d: %s"
15192 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15195 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15196 (setq end (save-excursion (org-end-of-subtree t t))))
15197 (when (org-at-heading-p)
15198 (move-marker (make-marker) (point))))))))
15200 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15201 "Find node HEADING in BUFFER.
15202 Return a marker to the heading if it was found, or nil if not.
15203 If POS-ONLY is set, return just the position instead of a marker.
15205 The heading text must match exact, but it may have a TODO keyword,
15206 a priority cookie and tags in the standard locations."
15207 (with-current-buffer (or buffer (current-buffer))
15211 (goto-char (point-min))
15212 (let (case-fold-search)
15213 (if (re-search-forward
15214 (format org-complex-heading-regexp-format
15215 (regexp-quote heading)) nil t)
15217 (match-beginning 0)
15218 (move-marker (make-marker) (match-beginning 0)))))))))
15220 (defun org-find-exact-heading-in-directory (heading &optional dir)
15221 "Find Org node headline HEADING in all .org files in directory DIR.
15222 When the target headline is found, return a marker to this location."
15223 (let ((files (directory-files (or dir default-directory)
15224 nil "\\`[^.#].*\\.org\\'"))
15225 file visiting m buffer)
15227 (while (setq file (pop files))
15228 (message "trying %s" file)
15229 (setq visiting (org-find-base-buffer-visiting file))
15230 (setq buffer (or visiting (find-file-noselect file)))
15231 (setq m (org-find-exact-headline-in-buffer
15233 (when (and (not m) (not visiting)) (kill-buffer buffer))
15234 (and m (throw 'found m))))))
15236 (defun org-find-entry-with-id (ident)
15237 "Locate the entry that contains the ID property with exact value IDENT.
15238 IDENT can be a string, a symbol or a number, this function will search for
15239 the string representation of it.
15240 Return the position where this entry starts, or nil if there is no such entry."
15241 (interactive "sID: ")
15243 ((stringp ident) ident)
15244 ((symbol-name ident) (symbol-name ident))
15245 ((numberp ident) (number-to-string ident))
15246 (t (error "IDENT %s must be a string, symbol or number" ident))))
15247 (case-fold-search nil))
15251 (goto-char (point-min))
15252 (when (re-search-forward
15253 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15255 (org-back-to-heading t)
15260 (defvar org-last-changed-timestamp nil)
15261 (defvar org-last-inserted-timestamp nil
15262 "The last time stamp inserted with `org-insert-time-stamp'.")
15263 (defvar org-time-was-given) ; dynamically scoped parameter
15264 (defvar org-end-time-was-given) ; dynamically scoped parameter
15265 (defvar org-ts-what) ; dynamically scoped parameter
15267 (defun org-time-stamp (arg &optional inactive)
15268 "Prompt for a date/time and insert a time stamp.
15269 If the user specifies a time like HH:MM or if this command is
15270 called with at least one prefix argument, the time stamp contains
15271 the date and the time. Otherwise, only the date is be included.
15273 All parts of a date not specified by the user is filled in from
15274 the current date/time. So if you just press return without
15275 typing anything, the time stamp will represent the current
15278 If there is already a timestamp at the cursor, it will be
15281 With two universal prefix arguments, insert an active timestamp
15282 with the current time without prompting the user."
15286 ;; Default time is either today, or, when entering a range,
15287 ;; the range start.
15288 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15290 (re-search-backward
15291 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15292 (- (point) 20) t)))
15293 (apply 'encode-time (org-parse-time-string (match-string 1)))
15295 (default-input (and ts (org-get-compact-tod ts)))
15296 (repeater (save-excursion
15298 (beginning-of-line)
15299 (when (re-search-forward
15300 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15301 (save-excursion (progn (end-of-line) (point))) t)
15302 (match-string 0)))))
15303 org-time-was-given org-end-time-was-given time)
15305 ((and (org-at-timestamp-p t)
15306 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15307 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15309 (setq time (let ((this-command this-command))
15310 (org-read-date arg 'totime nil nil
15311 default-time default-input inactive)))
15312 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15313 ((org-at-timestamp-p t)
15314 (setq time (let ((this-command this-command))
15315 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15316 (when (org-at-timestamp-p t) ; just to get the match data
15317 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15319 (setq org-last-changed-timestamp
15320 (org-insert-time-stamp
15321 time (or org-time-was-given arg)
15322 inactive nil nil (list org-end-time-was-given)))
15323 (when repeater (goto-char (1- (point))) (insert " " repeater)
15324 (setq org-last-changed-timestamp
15325 (concat (substring org-last-inserted-timestamp 0 -1)
15326 " " repeater ">"))))
15327 (message "Timestamp updated"))
15329 (org-insert-time-stamp (current-time) t))
15331 (setq time (let ((this-command this-command))
15332 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15333 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15334 nil nil (list org-end-time-was-given))))))
15336 ;; FIXME: can we use this for something else, like computing time differences?
15337 (defun org-get-compact-tod (s)
15338 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15339 (let* ((t1 (match-string 1 s))
15340 (h1 (string-to-number (match-string 2 s)))
15341 (m1 (string-to-number (match-string 3 s)))
15342 (t2 (and (match-end 4) (match-string 5 s)))
15343 (h2 (and t2 (string-to-number (match-string 6 s))))
15344 (m2 (and t2 (string-to-number (match-string 7 s))))
15348 (setq dh (- h2 h1) dm (- m2 m1))
15349 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15350 (concat t1 "+" (number-to-string dh)
15351 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15353 (defun org-time-stamp-inactive (&optional arg)
15354 "Insert an inactive time stamp.
15355 An inactive time stamp is enclosed in square brackets instead of angle
15356 brackets. It is inactive in the sense that it does not trigger agenda entries,
15357 does not link to the calendar and cannot be changed with the S-cursor keys.
15358 So these are more for recording a certain time/date."
15360 (org-time-stamp arg 'inactive))
15362 (defvar org-date-ovl (make-overlay 1 1))
15363 (overlay-put org-date-ovl 'face 'org-date-selected)
15364 (org-detach-overlay org-date-ovl)
15366 (defvar org-ans1) ; dynamically scoped parameter
15367 (defvar org-ans2) ; dynamically scoped parameter
15369 (defvar org-plain-time-of-day-regexp) ; defined below
15371 (defvar org-overriding-default-time nil) ; dynamically scoped
15372 (defvar org-read-date-overlay nil)
15373 (defvar org-dcst nil) ; dynamically scoped
15374 (defvar org-read-date-history nil)
15375 (defvar org-read-date-final-answer nil)
15376 (defvar org-read-date-analyze-futurep nil)
15377 (defvar org-read-date-analyze-forced-year nil)
15378 (defvar org-read-date-inactive)
15380 (defun org-read-date (&optional org-with-time to-time from-string prompt
15381 default-time default-input inactive)
15382 "Read a date, possibly a time, and make things smooth for the user.
15383 The prompt will suggest to enter an ISO date, but you can also enter anything
15384 which will at least partially be understood by `parse-time-string'.
15385 Unrecognized parts of the date will default to the current day, month, year,
15386 hour and minute. If this command is called to replace a timestamp at point,
15387 or to enter the second timestamp of a range, the default time is taken
15388 from the existing stamp. Furthermore, the command prefers the future,
15389 so if you are giving a date where the year is not given, and the day-month
15390 combination is already past in the current year, it will assume you
15391 mean next year. For details, see the manual. A few examples:
15393 3-2-5 --> 2003-02-05
15394 feb 15 --> currentyear-02-15
15395 2/15 --> currentyear-02-15
15396 sep 12 9 --> 2009-09-12
15397 12:45 --> today 12:45
15398 22 sept 0:34 --> currentyear-09-22 0:34
15399 12 --> currentyear-currentmonth-12
15400 Fri --> nearest Friday (today or later)
15403 Furthermore you can specify a relative date by giving, as the *first* thing
15404 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15405 change in days weeks, months, years.
15406 With a single plus or minus, the date is relative to today. With a double
15407 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15408 +4d --> four days from today
15409 +4 --> same as above
15410 +2w --> two weeks from today
15411 ++5 --> five days from default date
15413 The function understands only English month and weekday abbreviations.
15415 While prompting, a calendar is popped up - you can also select the
15416 date with the mouse (button 1). The calendar shows a period of three
15417 months. To scroll it to other months, use the keys `>' and `<'.
15418 If you don't like the calendar, turn it off with
15419 \(setq org-read-date-popup-calendar nil)
15421 With optional argument TO-TIME, the date will immediately be converted
15422 to an internal time.
15423 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15424 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15425 still enter a time, and this function will inform the calling routine
15426 about this change. The calling routine may then choose to change the
15427 format used to insert the time stamp into the buffer to include the time.
15428 With optional argument FROM-STRING, read from this string instead from
15429 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15430 the time/date that is used for everything that is not specified by the
15432 (require 'parse-time)
15433 (let* ((org-time-stamp-rounding-minutes
15434 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15435 (org-dcst org-display-custom-times)
15436 (ct (org-current-time))
15437 (org-def (or org-overriding-default-time default-time ct))
15438 (org-defdecode (decode-time org-def))
15440 (when (< (nth 2 org-defdecode) org-extend-today-until)
15441 (setcar (nthcdr 2 org-defdecode) -1)
15442 (setcar (nthcdr 1 org-defdecode) 59)
15443 (setq org-def (apply 'encode-time org-defdecode)
15444 org-defdecode (decode-time org-def)))))
15445 (calendar-frame-setup nil)
15446 (calendar-setup nil)
15447 (calendar-move-hook nil)
15448 (calendar-view-diary-initially-flag nil)
15449 (calendar-view-holidays-initially-flag nil)
15450 (timestr (format-time-string
15451 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15452 (prompt (concat (if prompt (concat prompt " ") "")
15453 (format "Date+time [%s]: " timestr)))
15454 ans (org-ans0 "") org-ans1 org-ans2 final)
15457 (from-string (setq ans from-string))
15458 (org-read-date-popup-calendar
15460 (save-window-excursion
15462 (org-eval-in-calendar '(setq cursor-type nil) t)
15465 (calendar-forward-day (- (time-to-days org-def)
15466 (calendar-absolute-from-gregorian
15467 (calendar-current-date))))
15468 (org-eval-in-calendar nil t)
15469 (let* ((old-map (current-local-map))
15470 (map (copy-keymap calendar-mode-map))
15471 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15472 (org-defkey map (kbd "RET") 'org-calendar-select)
15473 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15474 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15475 (org-defkey minibuffer-local-map [(meta shift left)]
15476 (lambda () (interactive)
15477 (org-eval-in-calendar '(calendar-backward-month 1))))
15478 (org-defkey minibuffer-local-map [(meta shift right)]
15479 (lambda () (interactive)
15480 (org-eval-in-calendar '(calendar-forward-month 1))))
15481 (org-defkey minibuffer-local-map [(meta shift up)]
15482 (lambda () (interactive)
15483 (org-eval-in-calendar '(calendar-backward-year 1))))
15484 (org-defkey minibuffer-local-map [(meta shift down)]
15485 (lambda () (interactive)
15486 (org-eval-in-calendar '(calendar-forward-year 1))))
15487 (org-defkey minibuffer-local-map [?\e (shift left)]
15488 (lambda () (interactive)
15489 (org-eval-in-calendar '(calendar-backward-month 1))))
15490 (org-defkey minibuffer-local-map [?\e (shift right)]
15491 (lambda () (interactive)
15492 (org-eval-in-calendar '(calendar-forward-month 1))))
15493 (org-defkey minibuffer-local-map [?\e (shift up)]
15494 (lambda () (interactive)
15495 (org-eval-in-calendar '(calendar-backward-year 1))))
15496 (org-defkey minibuffer-local-map [?\e (shift down)]
15497 (lambda () (interactive)
15498 (org-eval-in-calendar '(calendar-forward-year 1))))
15499 (org-defkey minibuffer-local-map [(shift up)]
15500 (lambda () (interactive)
15501 (org-eval-in-calendar '(calendar-backward-week 1))))
15502 (org-defkey minibuffer-local-map [(shift down)]
15503 (lambda () (interactive)
15504 (org-eval-in-calendar '(calendar-forward-week 1))))
15505 (org-defkey minibuffer-local-map [(shift left)]
15506 (lambda () (interactive)
15507 (org-eval-in-calendar '(calendar-backward-day 1))))
15508 (org-defkey minibuffer-local-map [(shift right)]
15509 (lambda () (interactive)
15510 (org-eval-in-calendar '(calendar-forward-day 1))))
15511 (org-defkey minibuffer-local-map ">"
15512 (lambda () (interactive)
15513 (org-eval-in-calendar '(scroll-calendar-left 1))))
15514 (org-defkey minibuffer-local-map "<"
15515 (lambda () (interactive)
15516 (org-eval-in-calendar '(scroll-calendar-right 1))))
15517 (org-defkey minibuffer-local-map "\C-v"
15518 (lambda () (interactive)
15519 (org-eval-in-calendar
15520 '(calendar-scroll-left-three-months 1))))
15521 (org-defkey minibuffer-local-map "\M-v"
15522 (lambda () (interactive)
15523 (org-eval-in-calendar
15524 '(calendar-scroll-right-three-months 1))))
15525 (run-hooks 'org-read-date-minibuffer-setup-hook)
15528 (use-local-map map)
15529 (setq org-read-date-inactive inactive)
15530 (add-hook 'post-command-hook 'org-read-date-display)
15531 (setq org-ans0 (read-string prompt default-input
15532 'org-read-date-history nil))
15533 ;; org-ans0: from prompt
15534 ;; org-ans1: from mouse click
15535 ;; org-ans2: from calendar motion
15536 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15537 (remove-hook 'post-command-hook 'org-read-date-display)
15538 (use-local-map old-map)
15539 (when org-read-date-overlay
15540 (delete-overlay org-read-date-overlay)
15541 (setq org-read-date-overlay nil)))))
15542 (bury-buffer "*Calendar*")))))
15544 (t ; Naked prompt only
15546 (setq ans (read-string prompt default-input
15547 'org-read-date-history timestr))
15548 (when org-read-date-overlay
15549 (delete-overlay org-read-date-overlay)
15550 (setq org-read-date-overlay nil)))))
15552 (setq final (org-read-date-analyze ans org-def org-defdecode))
15554 (when org-read-date-analyze-forced-year
15555 (message "Year was forced into %s"
15556 (if org-read-date-force-compatible-dates
15557 "compatible range (1970-2037)"
15558 "range representable on this machine"))
15561 ;; One round trip to get rid of 34th of August and stuff like that....
15562 (setq final (decode-time (apply 'encode-time final)))
15564 (setq org-read-date-final-answer ans)
15567 (apply 'encode-time final)
15568 (if (and (boundp 'org-time-was-given) org-time-was-given)
15569 (format "%04d-%02d-%02d %02d:%02d"
15570 (nth 5 final) (nth 4 final) (nth 3 final)
15571 (nth 2 final) (nth 1 final))
15572 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15575 (defvar org-defdecode)
15576 (defvar org-with-time)
15577 (defun org-read-date-display ()
15578 "Display the current date prompt interpretation in the minibuffer."
15579 (when org-read-date-display-live
15580 (when org-read-date-overlay
15581 (delete-overlay org-read-date-overlay))
15582 (when (minibufferp (current-buffer))
15585 (while (not (equal (buffer-substring
15586 (max (point-min) (- (point) 4)) (point))
15589 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15590 " " (or org-ans1 org-ans2)))
15591 (org-end-time-was-given nil)
15592 (f (org-read-date-analyze ans org-def org-defdecode))
15594 org-time-stamp-custom-formats
15595 org-time-stamp-formats))
15596 (fmt (if (or org-with-time
15597 (and (boundp 'org-time-was-given) org-time-was-given))
15600 (txt (format-time-string fmt (apply 'encode-time f)))
15601 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15602 (txt (concat "=> " txt)))
15603 (when (and org-end-time-was-given
15604 (string-match org-plain-time-of-day-regexp txt))
15605 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15606 org-end-time-was-given
15607 (substring txt (match-end 0)))))
15608 (when org-read-date-analyze-futurep
15609 (setq txt (concat txt " (=>F)")))
15610 (setq org-read-date-overlay
15611 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15612 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15614 (defun org-read-date-analyze (ans org-def org-defdecode)
15615 "Analyze the combined answer of the date prompt."
15616 ;; FIXME: cleanup and comment
15617 (let ((nowdecode (decode-time (current-time)))
15618 delta deltan deltaw deltadef year month day
15619 hour minute second wday pm h2 m2 tl wday1
15620 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15621 (setq org-read-date-analyze-futurep nil
15622 org-read-date-analyze-forced-year nil)
15623 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15626 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15627 (setq ans (replace-match "" t t ans)
15629 deltaw (nth 1 delta)
15630 deltadef (nth 2 delta)))
15632 ;; Check if there is an iso week date in there. If yes, store the
15633 ;; info and postpone interpreting it until the rest of the parsing
15635 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15636 (setq iso-year (if (match-end 1)
15637 (org-small-year-to-year
15638 (string-to-number (match-string 1 ans))))
15639 iso-weekday (if (match-end 3)
15640 (string-to-number (match-string 3 ans)))
15641 iso-week (string-to-number (match-string 2 ans)))
15642 (setq ans (replace-match "" t t ans)))
15644 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15645 (when (string-match
15646 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15647 (setq year (if (match-end 2)
15648 (string-to-number (match-string 2 ans))
15649 (progn (setq kill-year t)
15650 (string-to-number (format-time-string "%Y"))))
15651 month (string-to-number (match-string 3 ans))
15652 day (string-to-number (match-string 4 ans)))
15653 (if (< year 100) (setq year (+ 2000 year)))
15654 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15657 ;; Help matching dotted european dates
15658 (when (string-match
15659 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15660 (setq year (if (match-end 3)
15661 (string-to-number (match-string 3 ans))
15662 (progn (setq kill-year t)
15663 (string-to-number (format-time-string "%Y"))))
15664 day (string-to-number (match-string 1 ans))
15665 month (string-to-number (match-string 2 ans))
15666 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15669 ;; Help matching american dates, like 5/30 or 5/30/7
15670 (when (string-match
15671 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15672 (setq year (if (match-end 4)
15673 (string-to-number (match-string 4 ans))
15674 (progn (setq kill-year t)
15675 (string-to-number (format-time-string "%Y"))))
15676 month (string-to-number (match-string 1 ans))
15677 day (string-to-number (match-string 2 ans)))
15678 (if (< year 100) (setq year (+ 2000 year)))
15679 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15681 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15682 ;; If there is a time with am/pm, and *no* time without it, we convert
15683 ;; so that matching will be successful.
15684 (loop for i from 1 to 2 do ; twice, for end time as well
15685 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15686 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15687 (setq hour (string-to-number (match-string 1 ans))
15688 minute (if (match-end 3)
15689 (string-to-number (match-string 3 ans))
15692 (string-to-char (downcase (match-string 4 ans)))))
15693 (if (and (= hour 12) (not pm))
15695 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15696 (setq ans (replace-match (format "%02d:%02d" hour minute)
15699 ;; Check if a time range is given as a duration
15700 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15701 (setq hour (string-to-number (match-string 1 ans))
15702 h2 (+ hour (string-to-number (match-string 3 ans)))
15703 minute (string-to-number (match-string 2 ans))
15704 m2 (+ minute (if (match-end 5) (string-to-number
15705 (match-string 5 ans))0)))
15706 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15707 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15710 ;; Check if there is a time range
15711 (when (boundp 'org-end-time-was-given)
15712 (setq org-time-was-given nil)
15713 (when (and (string-match org-plain-time-of-day-regexp ans)
15715 (setq org-end-time-was-given (match-string 8 ans))
15716 (setq ans (concat (substring ans 0 (match-beginning 7))
15717 (substring ans (match-end 7))))))
15719 (setq tl (parse-time-string ans)
15720 day (or (nth 3 tl) (nth 3 org-defdecode))
15721 month (or (nth 4 tl)
15722 (if (and org-read-date-prefer-future
15723 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15724 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15725 (nth 4 org-defdecode)))
15726 year (or (and (not kill-year) (nth 5 tl))
15727 (if (and org-read-date-prefer-future
15728 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15729 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15730 (nth 5 org-defdecode)))
15731 hour (or (nth 2 tl) (nth 2 org-defdecode))
15732 minute (or (nth 1 tl) (nth 1 org-defdecode))
15733 second (or (nth 0 tl) 0)
15736 (when (and (eq org-read-date-prefer-future 'time)
15737 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15738 (equal day (nth 3 nowdecode))
15739 (equal month (nth 4 nowdecode))
15740 (equal year (nth 5 nowdecode))
15742 (or (< (nth 2 tl) (nth 2 nowdecode))
15743 (and (= (nth 2 tl) (nth 2 nowdecode))
15745 (< (nth 1 tl) (nth 1 nowdecode)))))
15749 ;; Special date definitions below
15752 ;; There was an iso week
15755 (setq year (or iso-year year)
15756 day (or iso-weekday wday 1)
15757 wday nil ; to make sure that the trigger below does not match
15758 iso-date (calendar-gregorian-from-absolute
15759 (calendar-absolute-from-iso
15760 (list iso-week day year))))
15761 ; FIXME: Should we also push ISO weeks into the future?
15762 ; (when (and org-read-date-prefer-future
15764 ; (< (calendar-absolute-from-gregorian iso-date)
15765 ; (time-to-days (current-time))))
15766 ; (setq year (1+ year)
15767 ; iso-date (calendar-gregorian-from-absolute
15768 ; (calendar-absolute-from-iso
15769 ; (list iso-week day year)))))
15770 (setq month (car iso-date)
15771 year (nth 2 iso-date)
15772 day (nth 1 iso-date)))
15776 (let ((now (decode-time (current-time))))
15777 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15778 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15779 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15780 ((equal deltaw "m") (setq month (+ month deltan)))
15781 ((equal deltaw "y") (setq year (+ year deltan)))))
15782 ((and wday (not (nth 3 tl)))
15783 ;; Weekday was given, but no day, so pick that day in the week
15784 ;; on or after the derived date.
15785 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15786 (unless (equal wday wday1)
15787 (setq day (+ day (% (- wday wday1 -7) 7))))))
15788 (if (and (boundp 'org-time-was-given)
15790 (setq org-time-was-given t))
15791 (if (< year 100) (setq year (+ 2000 year)))
15792 ;; Check of the date is representable
15793 (if org-read-date-force-compatible-dates
15796 (setq year 1970 org-read-date-analyze-forced-year t))
15798 (setq year 2037 org-read-date-analyze-forced-year t)))
15799 (condition-case nil
15800 (ignore (encode-time second minute hour day month year))
15802 (setq year (nth 5 org-defdecode))
15803 (setq org-read-date-analyze-forced-year t))))
15804 (setq org-read-date-analyze-futurep futurep)
15805 (list second minute hour day month year)))
15807 (defvar parse-time-weekdays)
15808 (defun org-read-date-get-relative (s today default)
15809 "Check string S for special relative date string.
15810 TODAY and DEFAULT are internal times, for today and for a default.
15811 Return shift list (N what def-flag)
15812 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15813 N is the number of WHATs to shift.
15814 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15815 the DEFAULT date rather than TODAY."
15816 (require 'parse-time)
15820 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15822 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15823 "\\([ \t]\\|$\\)") s)
15824 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15825 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15826 (string-to-char (substring (match-string 1 s) -1))
15828 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15829 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15830 (what (if (match-end 3) (match-string 3 s) "d"))
15831 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15832 (date (if rel default today))
15833 (wday (nth 6 (decode-time date)))
15837 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15838 (if (= dir ?-) (setq delta (- delta 7)))
15839 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15840 (list delta "d" rel))
15841 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15843 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15844 "Turn a user-specified date into the internal representation.
15845 The internal representation needed by the calendar is (month day year).
15846 This is a wrapper to handle the brain-dead convention in calendar that
15847 user function argument order change dependent on argument order."
15848 (if (boundp 'calendar-date-style)
15850 ((eq calendar-date-style 'american)
15851 (list arg1 arg2 arg3))
15852 ((eq calendar-date-style 'european)
15853 (list arg2 arg1 arg3))
15854 ((eq calendar-date-style 'iso)
15855 (list arg2 arg3 arg1)))
15856 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15857 (if (org-bound-and-true-p european-calendar-style)
15858 (list arg2 arg1 arg3)
15859 (list arg1 arg2 arg3)))))
15861 (defun org-eval-in-calendar (form &optional keepdate)
15862 "Eval FORM in the calendar window and return to current window.
15863 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15864 otherwise stick to the current value of `org-ans2'."
15865 (let ((sf (selected-frame))
15866 (sw (selected-window)))
15867 (select-window (get-buffer-window "*Calendar*" t))
15869 (when (and (not keepdate) (calendar-cursor-to-date))
15870 (let* ((date (calendar-cursor-to-date))
15871 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15872 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15873 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15875 (org-select-frame-set-input-focus sf)))
15877 (defun org-calendar-select ()
15878 "Return to `org-read-date' with the date currently selected.
15879 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15881 (when (calendar-cursor-to-date)
15882 (let* ((date (calendar-cursor-to-date))
15883 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15884 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15885 (if (active-minibuffer-window) (exit-minibuffer))))
15887 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15888 "Insert a date stamp for the date given by the internal TIME.
15889 WITH-HM means use the stamp format that includes the time of the day.
15890 INACTIVE means use square brackets instead of angular ones, so that the
15891 stamp will not contribute to the agenda.
15892 PRE and POST are optional strings to be inserted before and after the
15894 The command returns the inserted time stamp."
15895 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15897 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15898 (insert-before-markers (or pre ""))
15899 (when (listp extra)
15900 (setq extra (car extra))
15901 (if (and (stringp extra)
15902 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15903 (setq extra (format "-%02d:%02d"
15904 (string-to-number (match-string 1 extra))
15905 (string-to-number (match-string 2 extra))))
15908 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15909 (insert-before-markers (setq stamp (format-time-string fmt time)))
15910 (insert-before-markers (or post ""))
15911 (setq org-last-inserted-timestamp stamp)))
15913 (defun org-toggle-time-stamp-overlays ()
15914 "Toggle the use of custom time stamp formats."
15916 (setq org-display-custom-times (not org-display-custom-times))
15917 (unless org-display-custom-times
15918 (let ((p (point-min)) (bmp (buffer-modified-p)))
15919 (while (setq p (next-single-property-change p 'display))
15920 (if (and (get-text-property p 'display)
15921 (eq (get-text-property p 'face) 'org-date))
15922 (remove-text-properties
15923 p (setq p (next-single-property-change p 'display))
15925 (set-buffer-modified-p bmp)))
15926 (if (featurep 'xemacs)
15927 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15928 (org-restart-font-lock)
15929 (setq org-table-may-need-update t)
15930 (if org-display-custom-times
15931 (message "Time stamps are overlaid with custom format")
15932 (message "Time stamp overlays removed")))
15934 (defun org-display-custom-time (beg end)
15935 "Overlay modified time stamp format over timestamp between BEG and END."
15936 (let* ((ts (buffer-substring beg end))
15937 t1 w1 with-hm tf time str w2 (off 0))
15939 (setq t1 (org-parse-time-string ts t))
15940 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15941 (setq off (- (match-end 0) (match-beginning 0)))))
15942 (setq end (- end off))
15943 (setq w1 (- end beg)
15944 with-hm (and (nth 1 t1) (nth 2 t1))
15945 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15946 time (org-fix-decoded-time t1)
15948 (format-time-string
15949 (substring tf 1 -1) (apply 'encode-time time))
15950 nil 'mouse-face 'highlight)
15952 (if (not (= w2 w1))
15953 (add-text-properties (1+ beg) (+ 2 beg)
15954 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15955 (if (featurep 'xemacs)
15957 (put-text-property beg end 'invisible t)
15958 (put-text-property beg end 'end-glyph (make-glyph str)))
15959 (put-text-property beg end 'display str))))
15961 (defun org-translate-time (string)
15962 "Translate all timestamps in STRING to custom format.
15963 But do this only if the variable `org-display-custom-times' is set."
15964 (when org-display-custom-times
15967 (re org-ts-regexp-both)
15968 t1 with-hm inactive tf time str beg end)
15969 (while (setq start (string-match re string start))
15970 (setq beg (match-beginning 0)
15972 t1 (save-match-data
15973 (org-parse-time-string (substring string beg end) t))
15974 with-hm (and (nth 1 t1) (nth 2 t1))
15975 inactive (equal (substring string beg (1+ beg)) "[")
15976 tf (funcall (if with-hm 'cdr 'car)
15977 org-time-stamp-custom-formats)
15978 time (org-fix-decoded-time t1)
15979 str (format-time-string
15981 (if inactive "[" "<") (substring tf 1 -1)
15982 (if inactive "]" ">"))
15983 (apply 'encode-time time))
15984 string (replace-match str t t string)
15985 start (+ start (length str)))))))
15988 (defun org-fix-decoded-time (time)
15989 "Set 0 instead of nil for the first 6 elements of time.
15990 Don't touch the rest."
15992 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15994 (defun org-days-to-time (timestamp-string)
15995 "Difference between TIMESTAMP-STRING and now in days."
15996 (- (time-to-days (org-time-string-to-time timestamp-string))
15997 (time-to-days (current-time))))
15999 (defun org-deadline-close (timestamp-string &optional ndays)
16000 "Is the time in TIMESTAMP-STRING close to the current date?"
16001 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16002 (and (< (org-days-to-time timestamp-string) ndays)
16003 (not (org-entry-is-done-p))))
16005 (defun org-get-wdays (ts)
16006 "Get the deadline lead time appropriate for timestring TS."
16008 ((<= org-deadline-warning-days 0)
16009 ;; 0 or negative, enforce this value no matter what
16010 (- org-deadline-warning-days))
16011 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16012 ;; lead time is specified.
16013 (floor (* (string-to-number (match-string 1 ts))
16014 (cdr (assoc (match-string 2 ts)
16015 '(("d" . 1) ("w" . 7)
16016 ("m" . 30.4) ("y" . 365.25)))))))
16017 ;; go for the default.
16018 (t org-deadline-warning-days)))
16020 (defun org-calendar-select-mouse (ev)
16021 "Return to `org-read-date' with the date currently selected.
16022 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16024 (mouse-set-point ev)
16025 (when (calendar-cursor-to-date)
16026 (let* ((date (calendar-cursor-to-date))
16027 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16028 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16029 (if (active-minibuffer-window) (exit-minibuffer))))
16031 (defun org-check-deadlines (ndays)
16032 "Check if there are any deadlines due or past due.
16033 A deadline is considered due if it happens within `org-deadline-warning-days'
16034 days from today's date. If the deadline appears in an entry marked DONE,
16035 it is not shown. The prefix arg NDAYS can be used to test that many
16036 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16038 (let* ((org-warn-days
16040 ((equal ndays '(4)) 100000)
16041 (ndays (prefix-numeric-value ndays))
16042 (t (abs org-deadline-warning-days))))
16043 (case-fold-search nil)
16044 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16046 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16048 (message "%d deadlines past-due or due within %d days"
16049 (org-occur regexp nil callback)
16052 (defsubst org-re-timestamp (type)
16053 "Return a regexp for timestamp TYPE.
16054 Allowed values for TYPE are:
16056 all: all timestamps
16057 active: only active timestamps (<...>)
16058 inactive: only inactive timestamps ([...])
16059 scheduled: only scheduled timestamps
16060 deadline: only deadline timestamps
16062 When TYPE is nil, fall back on returning a regexp that matches
16063 both scheduled and deadline timestamps."
16064 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9>
\n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16065 ((eq type 'active) org-ts-regexp)
16066 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^
\n>]*?\\)\\]")
16067 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16068 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16069 ((eq type 'scheduled-or-deadline)
16070 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16072 (defun org-check-before-date (date)
16073 "Check if there are deadlines or scheduled entries before DATE."
16074 (interactive (list (org-read-date)))
16075 (let ((case-fold-search nil)
16076 (regexp (org-re-timestamp org-ts-type))
16078 (lambda () (time-less-p
16079 (org-time-string-to-time (match-string 1))
16080 (org-time-string-to-time date)))))
16081 (message "%d entries before %s"
16082 (org-occur regexp nil callback) date)))
16084 (defun org-check-after-date (date)
16085 "Check if there are deadlines or scheduled entries after DATE."
16086 (interactive (list (org-read-date)))
16087 (let ((case-fold-search nil)
16088 (regexp (org-re-timestamp org-ts-type))
16092 (org-time-string-to-time (match-string 1))
16093 (org-time-string-to-time date))))))
16094 (message "%d entries after %s"
16095 (org-occur regexp nil callback) date)))
16097 (defun org-check-dates-range (start-date end-date)
16098 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16099 (interactive (list (org-read-date nil nil nil "Range starts")
16100 (org-read-date nil nil nil "Range end")))
16101 (let ((case-fold-search nil)
16102 (regexp (org-re-timestamp org-ts-type))
16105 (let ((match (match-string 1)))
16108 (org-time-string-to-time match)
16109 (org-time-string-to-time start-date)))
16111 (org-time-string-to-time match)
16112 (org-time-string-to-time end-date)))))))
16113 (message "%d entries between %s and %s"
16114 (org-occur regexp nil callback) start-date end-date)))
16116 (defun org-evaluate-time-range (&optional to-buffer)
16117 "Evaluate a time range by computing the difference between start and end.
16118 Normally the result is just printed in the echo area, but with prefix arg
16119 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16120 If the time range is actually in a table, the result is inserted into the
16122 For time difference computation, a year is assumed to be exactly 365
16123 days in order to avoid rounding problems."
16126 (org-clock-update-time-maybe)
16128 (unless (org-at-date-range-p t)
16129 (goto-char (point-at-bol))
16130 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16131 (if (not (org-at-date-range-p t))
16132 (error "Not at a time-stamp range, and none found in current line")))
16133 (let* ((ts1 (match-string 1))
16134 (ts2 (match-string 2))
16135 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16136 (match-end (match-end 0))
16137 (time1 (org-time-string-to-time ts1))
16138 (time2 (org-time-string-to-time ts2))
16139 (t1 (org-float-time time1))
16140 (t2 (org-float-time time2))
16141 (diff (abs (- t2 t1)))
16142 (negative (< (- t2 t1) 0))
16143 ;; (ys (floor (* 365 24 60 60)))
16146 (fy "%dy %dd %02d:%02d")
16148 (fd "%dd %02d:%02d")
16153 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16155 d (floor (/ diff ds)) diff (mod diff ds)
16156 h (floor (/ diff hs)) diff (mod diff hs)
16157 m (floor (/ diff 60)))
16158 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16160 d (floor (+ (/ diff ds) 0.5))
16162 (if (not to-buffer)
16163 (message "%s" (org-make-tdiff-string y d h m))
16164 (if (org-at-table-p)
16166 (goto-char match-end)
16168 (and (looking-at " *|") (goto-char (match-end 0))))
16169 (goto-char match-end))
16171 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16172 (replace-match ""))
16173 (if negative (insert " -"))
16174 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16175 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16176 (insert " " (format fh h m))))
16177 (if align (org-table-align))
16178 (message "Time difference inserted")))))
16180 (defun org-make-tdiff-string (y d h m)
16183 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16185 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16187 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16189 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16191 (apply 'format fmt (nreverse l))))
16193 (defun org-time-string-to-time (s &optional buffer pos)
16194 "Convert a timestamp string into internal time."
16195 (condition-case errdata
16196 (apply 'encode-time (org-parse-time-string s))
16197 (error (error "Bad timestamp `%s'%s\nError was: %s"
16198 s (if (not (and buffer pos))
16200 (format " at %d in buffer `%s'" pos buffer))
16203 (defun org-time-string-to-seconds (s)
16204 "Convert a timestamp string to a number of seconds."
16205 (org-float-time (org-time-string-to-time s)))
16207 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16208 "Convert a time stamp to an absolute day number.
16209 If there is a specifier for a cyclic time stamp, get the closest date to
16211 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16212 The variable date is bound by the calendar when this is called."
16214 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16215 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16218 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16219 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16220 (time-to-days (current-time))) (match-string 0 s)
16223 (condition-case errdata
16224 (apply 'encode-time (org-parse-time-string s))
16225 (error (error "Bad timestamp `%s'%s\nError was: %s"
16226 s (if (not (and buffer pos))
16228 (format " at %d in buffer `%s'" pos buffer))
16229 (cdr errdata))))))))
16231 (defun org-days-to-iso-week (days)
16232 "Return the iso week number."
16234 (car (calendar-iso-from-absolute days)))
16236 (defun org-small-year-to-year (year)
16237 "Convert 2-digit years into 4-digit years.
16238 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16239 The year 2000 cannot be abbreviated. Any year larger than 99
16240 is returned unchanged."
16242 (setq year (+ 2000 year))
16244 (setq year (+ 1900 year))))
16247 (defun org-time-from-absolute (d)
16248 "Return the time corresponding to date D.
16249 D may be an absolute day number, or a calendar-type list (month day year)."
16250 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16251 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16253 (defun org-calendar-holiday ()
16254 "List of holidays, for Diary display in Org-mode."
16255 (require 'holidays)
16257 (if (fboundp 'calendar-check-holidays)
16258 'calendar-check-holidays 'check-calendar-holidays) date)))
16259 (if hl (mapconcat 'identity hl "; "))))
16261 (defun org-diary-sexp-entry (sexp entry date)
16262 "Process a SEXP diary ENTRY for DATE."
16263 (require 'diary-lib)
16264 (let ((result (if calendar-debug-sexp
16265 (let ((stack-trace-on-error t))
16266 (eval (car (read-from-string sexp))))
16267 (condition-case nil
16268 (eval (car (read-from-string sexp)))
16271 (message "Bad sexp at line %d in %s: %s"
16273 (buffer-file-name) sexp)
16275 (cond ((stringp result) (split-string result "; "))
16276 ((and (consp result)
16277 (not (consp (cdr result)))
16278 (stringp (cdr result))) (cdr result))
16279 ((and (consp result)
16280 (stringp (car result))) result)
16283 (defun org-diary-to-ical-string (frombuf)
16284 "Get iCalendar entries from diary entries in buffer FROMBUF.
16285 This uses the icalendar.el library."
16286 (let* ((tmpdir (if (featurep 'xemacs)
16288 temporary-file-directory))
16289 (tmpfile (make-temp-name
16290 (expand-file-name "orgics" tmpdir)))
16292 (with-current-buffer frombuf
16293 (icalendar-export-region (point-min) (point-max) tmpfile)
16294 (setq buf (find-buffer-visiting tmpfile))
16296 (goto-char (point-min))
16297 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16298 (setq b (match-beginning 0)))
16299 (goto-char (point-max))
16300 (if (re-search-backward "^END:VEVENT" nil t)
16301 (setq e (match-end 0)))
16302 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16304 (delete-file tmpfile)
16307 (defun org-closest-date (start current change prefer show-all)
16308 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16309 When PREFER is `past', return a date that is either CURRENT or past.
16310 When PREFER is `future', return a date that is either CURRENT or future.
16311 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16312 ;; Make the proper lists from the dates
16314 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16315 dn dw sday cday n1 n2 n0
16316 d m y y1 y2 date1 date2 nmonths nm ny m2)
16318 (setq start (org-date-to-gregorian start)
16319 current (org-date-to-gregorian
16322 (time-to-days (current-time))))
16323 sday (calendar-absolute-from-gregorian start)
16324 cday (calendar-absolute-from-gregorian current))
16326 (if (<= cday sday) (throw 'exit sday))
16328 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16329 (setq dn (string-to-number (match-string 1 change))
16330 dw (cdr (assoc (match-string 2 change) a1)))
16331 (error "Invalid change specifier: %s" change))
16332 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16335 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16338 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16339 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16340 (setq date1 (list m d y1)
16341 n1 (calendar-absolute-from-gregorian date1)
16342 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16343 n2 (calendar-absolute-from-gregorian date2)))
16345 ;; approx number of month between the two dates
16346 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16347 ;; How often does dn fit in there?
16348 (setq d (nth 1 start) m (car start) y (nth 2 start)
16349 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16351 ny (floor (/ m 12))
16354 (while (> m 12) (setq m (- m 12) y (1+ y)))
16355 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16356 (setq m2 (+ m dn) y2 y)
16357 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16358 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16359 (while (<= n2 cday)
16360 (setq n1 n2 m m2 y y2)
16361 (setq m2 (+ m dn) y2 y)
16362 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16363 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16364 ;; Make sure n1 is the earlier date
16365 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16368 ((eq prefer 'past) (if (= cday n2) n2 n1))
16369 ((eq prefer 'future) (if (= cday n1) n1 n2))
16370 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16372 ((eq prefer 'past) (if (= cday n2) n2 n1))
16373 ((eq prefer 'future) (if (= cday n1) n1 n2))
16374 (t (if (= cday n1) n1 n2)))))))
16376 (defun org-date-to-gregorian (date)
16377 "Turn any specification of DATE into a Gregorian date for the calendar."
16378 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16379 ((and (listp date) (= (length date) 3)) date)
16381 (setq date (org-parse-time-string date))
16382 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16384 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16386 (defun org-parse-time-string (s &optional nodefault)
16387 "Parse the standard Org-mode time string.
16388 This should be a lot faster than the normal `parse-time-string'.
16389 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16390 hour and minute fields will be nil if not given."
16391 (if (string-match org-ts-regexp0 s)
16393 (if (or (match-beginning 8) (not nodefault))
16394 (string-to-number (or (match-string 8 s) "0")))
16395 (if (or (match-beginning 7) (not nodefault))
16396 (string-to-number (or (match-string 7 s) "0")))
16397 (string-to-number (match-string 4 s))
16398 (string-to-number (match-string 3 s))
16399 (string-to-number (match-string 2 s))
16401 (error "Not a standard Org-mode time string: %s" s)))
16403 (defun org-timestamp-up (&optional arg)
16404 "Increase the date item at the cursor by one.
16405 If the cursor is on the year, change the year. If it is on the month,
16406 the day or the time, change that.
16407 With prefix ARG, change by that many units."
16409 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16411 (defun org-timestamp-down (&optional arg)
16412 "Decrease the date item at the cursor by one.
16413 If the cursor is on the year, change the year. If it is on the month,
16414 the day or the time, change that.
16415 With prefix ARG, change by that many units."
16417 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16419 (defun org-timestamp-up-day (&optional arg)
16420 "Increase the date in the time stamp by one day.
16421 With prefix ARG, change that many days."
16423 (if (and (not (org-at-timestamp-p t))
16424 (org-at-heading-p))
16426 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16428 (defun org-timestamp-down-day (&optional arg)
16429 "Decrease the date in the time stamp by one day.
16430 With prefix ARG, change that many days."
16432 (if (and (not (org-at-timestamp-p t))
16433 (org-at-heading-p))
16435 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16437 (defun org-at-timestamp-p (&optional inactive-ok)
16438 "Determine if the cursor is in or at a timestamp."
16440 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16442 (ans (or (looking-at tsr)
16444 (skip-chars-backward "^[<\n\r\t")
16445 (if (> (point) (point-min)) (backward-char 1))
16446 (and (looking-at tsr)
16447 (> (- (match-end 0) pos) -1))))))
16449 (boundp 'org-ts-what)
16452 ((= pos (match-beginning 0)) 'bracket)
16453 ;; Point is considered to be "on the bracket" whether
16454 ;; it's really on it or right after it.
16455 ((= pos (1- (match-end 0))) 'bracket)
16456 ((= pos (match-end 0)) 'after)
16457 ((org-pos-in-match-range pos 2) 'year)
16458 ((org-pos-in-match-range pos 3) 'month)
16459 ((org-pos-in-match-range pos 7) 'hour)
16460 ((org-pos-in-match-range pos 8) 'minute)
16461 ((or (org-pos-in-match-range pos 4)
16462 (org-pos-in-match-range pos 5)) 'day)
16463 ((and (> pos (or (match-end 8) (match-end 5)))
16464 (< pos (match-end 0)))
16465 (- pos (or (match-end 8) (match-end 5))))
16469 (defun org-toggle-timestamp-type ()
16470 "Toggle the type (<active> or [inactive]) of a time stamp."
16472 (when (org-at-timestamp-p t)
16473 (let ((beg (match-beginning 0)) (end (match-end 0))
16474 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16477 (while (re-search-forward "[][<>]" end t)
16478 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16480 (message "Timestamp is now %sactive"
16481 (if (equal (char-after beg) ?<) "" "in")))))
16483 (defvar org-clock-history) ; defined in org-clock.el
16484 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16485 (defun org-timestamp-change (n &optional what updown)
16486 "Change the date in the time stamp at point.
16487 The date will be changed by N times WHAT. WHAT can be `day', `month',
16488 `year', `minute', `second'. If WHAT is not given, the cursor position
16489 in the timestamp determines what will be changed."
16490 (let ((origin (point)) origin-cat
16492 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16495 ts time time0 fixnext clrgx)
16496 (if (not (org-at-timestamp-p t))
16497 (error "Not at a timestamp"))
16498 (if (and (not what) (eq org-ts-what 'bracket))
16499 (org-toggle-timestamp-type)
16500 ;; Point isn't on brackets. Remember the part of the time-stamp
16501 ;; the point was in. Indeed, size of time-stamps may change,
16502 ;; but point must be kept in the same category nonetheless.
16503 (setq origin-cat org-ts-what)
16504 (if (and (not what) (not (eq org-ts-what 'day))
16505 org-display-custom-times
16506 (get-text-property (point) 'display)
16507 (not (get-text-property (1- (point)) 'display)))
16508 (setq org-ts-what 'day))
16509 (setq org-ts-what (or what org-ts-what)
16510 inactive (= (char-after (match-beginning 0)) ?\[)
16511 ts (match-string 0))
16514 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16516 (setq extra (match-string 1 ts)))
16517 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16519 (setq time0 (org-parse-time-string ts))
16521 (eq org-ts-what 'minute)
16522 (not current-prefix-arg))
16523 ;; This looks like s-up and s-down. Change by one rounding step.
16524 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16525 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16526 (setcar (cdr time0) (+ (nth 1 time0)
16527 (if (> n 0) (- rem) (- dm rem))))))
16529 (encode-time (or (car time0) 0)
16530 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16531 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16532 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16533 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16534 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16536 (when (and (member org-ts-what '(hour minute))
16538 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16539 (setq extra (org-modify-ts-extra
16541 (if (eq org-ts-what 'hour) 2 5)
16543 (when (integerp org-ts-what)
16544 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16545 (if (eq what 'calendar)
16546 (let ((cal-date (org-get-date-from-calendar)))
16547 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16548 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16549 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16550 (setcar time0 (or (car time0) 0))
16551 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16552 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16553 (setq time (apply 'encode-time time0))))
16554 ;; Insert the new time-stamp, and ensure point stays in the same
16555 ;; category as before (i.e. not after the last position in that
16557 (let ((pos (point)))
16558 ;; Stay before inserted string. `save-excursion' is of no use.
16559 (setq org-last-changed-timestamp
16560 (org-insert-time-stamp time with-hm inactive nil nil extra))
16563 (looking-at org-ts-regexp3)
16565 ;; `day' category ends before `hour' if any, or at
16566 ;; the end of the day name.
16567 ((eq origin-cat 'day)
16568 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16569 ((eq origin-cat 'hour) (min (match-end 7) origin))
16570 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16571 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16572 ;; `year' and `month' have both fixed size: point
16573 ;; couldn't have moved into another part.
16575 ;; Update clock if on a CLOCK line.
16576 (org-clock-update-time-maybe)
16577 ;; Maybe adjust the closest clock in `org-clock-history'
16578 (when org-clock-adjust-closest
16579 (if (not (and (org-at-clock-log-p)
16580 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16581 org-clock-history))))))
16582 (message "No clock to adjust")
16583 (cond ((save-excursion ; fix previous clock?
16584 (re-search-backward org-ts-regexp0 nil t)
16585 (org-looking-back (concat org-clock-string " \\[")))
16586 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16587 ((save-excursion ; fix next clock?
16588 (re-search-backward org-ts-regexp0 nil t)
16589 (looking-at (concat org-ts-regexp0 "\\] =>")))
16590 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16591 (save-window-excursion
16592 ;; Find closest clock to point, adjust the previous/next one in history
16593 (let* ((p (save-excursion (org-back-to-heading t)))
16594 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16596 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16597 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16599 (message "No clock to adjust")
16601 (org-goto-marker-or-bmk clfixpos)
16603 (when (re-search-forward clrgx nil t)
16604 (goto-char (match-beginning 1))
16605 (let (org-clock-adjust-closest)
16606 (org-timestamp-change n org-ts-what updown))
16607 (message "Clock adjusted in %s for heading: %s"
16608 (file-name-nondirectory (buffer-file-name))
16609 (org-get-heading t t)))))))))
16610 ;; Try to recenter the calendar window, if any.
16611 (if (and org-calendar-follow-timestamp-change
16612 (get-buffer-window "*Calendar*" t)
16613 (memq org-ts-what '(day month year)))
16614 (org-recenter-calendar (time-to-days time))))))
16616 (defun org-modify-ts-extra (s pos n dm)
16617 "Change the different parts of the lead-time and repeat fields in timestamp."
16618 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16620 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16622 ((or (org-pos-in-match-range pos 2)
16623 (org-pos-in-match-range pos 3))
16624 (setq m (string-to-number (match-string 3 s))
16625 h (string-to-number (match-string 2 s)))
16626 (if (org-pos-in-match-range pos 2)
16628 (setq n (* dm (org-no-warnings (signum n))))
16629 (when (not (= 0 (setq rem (% m dm))))
16630 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16632 (if (< m 0) (setq m (+ m 60) h (1- h)))
16633 (if (> m 59) (setq m (- m 60) h (1+ h)))
16634 (setq h (min 24 (max 0 h)))
16635 (setq ng 1 new (format "-%02d:%02d" h m)))
16636 ((org-pos-in-match-range pos 6)
16637 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16638 ((org-pos-in-match-range pos 5)
16639 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16641 ((org-pos-in-match-range pos 9)
16642 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16643 ((org-pos-in-match-range pos 8)
16644 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16648 (substring s 0 (match-beginning ng))
16650 (substring s (match-end ng))))))
16653 (defun org-recenter-calendar (date)
16654 "If the calendar is visible, recenter it to DATE."
16655 (let ((cwin (get-buffer-window "*Calendar*" t)))
16657 (let ((calendar-move-hook nil))
16658 (with-selected-window cwin
16659 (calendar-goto-date (if (listp date) date
16660 (calendar-gregorian-from-absolute date))))))))
16662 (defun org-goto-calendar (&optional arg)
16663 "Go to the Emacs calendar at the current date.
16664 If there is a time stamp in the current line, go to that date.
16665 A prefix ARG can be used to force the current date."
16667 (let ((tsr org-ts-regexp) diff
16668 (calendar-move-hook nil)
16669 (calendar-view-holidays-initially-flag nil)
16670 (calendar-view-diary-initially-flag nil))
16671 (if (or (org-at-timestamp-p)
16673 (beginning-of-line 1)
16674 (looking-at (concat ".*" tsr))))
16675 (let ((d1 (time-to-days (current-time)))
16677 (org-time-string-to-time (match-string 1)))))
16678 (setq diff (- d2 d1))))
16680 (calendar-goto-today)
16681 (if (and diff (not arg)) (calendar-forward-day diff))))
16683 (defun org-get-date-from-calendar ()
16684 "Return a list (month day year) of date at point in calendar."
16685 (with-current-buffer "*Calendar*"
16687 (calendar-cursor-to-date))))
16689 (defun org-date-from-calendar ()
16690 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16691 If there is already a time stamp at the cursor position, update it."
16693 (if (org-at-timestamp-p t)
16694 (org-timestamp-change 0 'calendar)
16695 (let ((cal-date (org-get-date-from-calendar)))
16696 (org-insert-time-stamp
16697 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16699 (defun org-minutes-to-hh:mm-string (m)
16700 "Compute H:MM from a number of minutes."
16701 (let ((h (/ m 60)))
16702 (setq m (- m (* 60 h)))
16703 (format org-time-clocksum-format h m)))
16705 (defun org-hh:mm-string-to-minutes (s)
16706 "Convert a string H:MM to a number of minutes.
16707 If the string is just a number, interpret it as minutes.
16708 In fact, the first hh:mm or number in the string will be taken,
16709 there can be extra stuff in the string.
16710 If no number is found, the return value is 0."
16713 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16714 (+ (* (string-to-number (match-string 1 s)) 60)
16715 (string-to-number (match-string 2 s))))
16716 ((string-match "\\([0-9]+\\)" s)
16717 (string-to-number (match-string 1 s)))
16720 (defcustom org-effort-durations
16723 ("w" . ,(* 60 8 5))
16724 ("m" . ,(* 60 8 5 4))
16725 ("y" . ,(* 60 8 5 40)))
16726 "Conversion factor to minutes for an effort modifier.
16728 Each entry has the form (MODIFIER . MINUTES).
16730 In an effort string, a number followed by MODIFIER is multiplied
16731 by the specified number of MINUTES to obtain an effort in
16734 For example, if the value of this variable is ((\"hours\" . 60)), then an
16735 effort string \"2hours\" is equivalent to 120 minutes."
16738 :type '(alist :key-type (string :tag "Modifier")
16739 :value-type (number :tag "Minutes")))
16741 (defun org-duration-string-to-minutes (s &optional output-to-string)
16742 "Convert a duration string S to minutes.
16744 A bare number is interpreted as minutes, modifiers can be set by
16745 customizing `org-effort-durations' (which see).
16747 Entries containing a colon are interpreted as H:MM by
16748 `org-hh:mm-string-to-minutes'."
16750 (re (concat "\\([0-9.]+\\) *\\("
16751 (regexp-opt (mapcar 'car org-effort-durations))
16753 (while (string-match re s)
16754 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16755 (string-to-number (match-string 1 s))))
16756 (setq s (replace-match "" nil t s)))
16757 (setq result (floor result))
16758 (incf result (org-hh:mm-string-to-minutes s))
16759 (if output-to-string (number-to-string result) result)))
16763 (defun org-save-all-org-buffers ()
16764 "Save all Org-mode buffers without user confirmation."
16766 (message "Saving all Org-mode buffers...")
16767 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16768 (when (featurep 'org-id) (org-id-locations-save))
16769 (message "Saving all Org-mode buffers... done"))
16771 (defun org-revert-all-org-buffers ()
16772 "Revert all Org-mode buffers.
16773 Prompt for confirmation when there are unsaved changes.
16774 Be sure you know what you are doing before letting this function
16775 overwrite your changes.
16777 This function is useful in a setup where one tracks org files
16778 with a version control system, to revert on one machine after pulling
16779 changes from another. I believe the procedure must be like this:
16781 1. M-x org-save-all-org-buffers
16782 2. Pull changes from the other machine, resolve conflicts
16783 3. M-x org-revert-all-org-buffers"
16785 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16788 (save-window-excursion
16791 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16792 (with-current-buffer b buffer-file-name))
16793 (org-pop-to-buffer-same-window b)
16794 (revert-buffer t 'no-confirm)))
16796 (when (and (featurep 'org-id) org-id-track-globally)
16797 (org-id-locations-load)))))
16802 (defun org-switchb (&optional arg)
16803 "Switch between Org buffers.
16804 With one prefix argument, restrict available buffers to files.
16805 With two prefix arguments, restrict available buffers to agenda files.
16807 Defaults to `iswitchb' for buffer name completion.
16808 Set `org-completion-use-ido' to make it use ido instead."
16810 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16811 ((equal arg '(16)) (org-buffer-list 'agenda))
16812 (t (org-buffer-list))))
16813 (org-completion-use-iswitchb org-completion-use-iswitchb)
16814 (org-completion-use-ido org-completion-use-ido))
16815 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16816 (setq org-completion-use-iswitchb t))
16817 (org-pop-to-buffer-same-window
16818 (org-icompleting-read "Org buffer: "
16819 (mapcar 'list (mapcar 'buffer-name blist))
16822 ;;; Define some older names previously used for this functionality
16824 (defalias 'org-ido-switchb 'org-switchb)
16826 (defalias 'org-iswitchb 'org-switchb)
16828 (defun org-buffer-list (&optional predicate exclude-tmp)
16829 "Return a list of Org buffers.
16830 PREDICATE can be `export', `files' or `agenda'.
16832 export restrict the list to Export buffers.
16833 files restrict the list to buffers visiting Org files.
16834 agenda restrict the list to buffers visiting agenda files.
16836 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16838 (agenda-files (and (eq predicate 'agenda)
16839 (mapcar 'file-truename (org-agenda-files t))))
16842 ((eq predicate 'files)
16843 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16844 ((eq predicate 'export)
16845 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16846 ((eq predicate 'agenda)
16848 (with-current-buffer b
16849 (and (derived-mode-p 'org-mode)
16850 (setq bfn (buffer-file-name b))
16851 (member (file-truename bfn) agenda-files)))))
16852 (t (lambda (b) (with-current-buffer b
16853 (or (derived-mode-p 'org-mode)
16854 (string-match "\*Org .*Export"
16855 (buffer-name b)))))))))
16859 (if (and (funcall filter b)
16860 (or (not exclude-tmp)
16861 (not (string-match "tmp" (buffer-name b)))))
16866 (defun org-agenda-files (&optional unrestricted archives)
16867 "Get the list of agenda files.
16868 Optional UNRESTRICTED means return the full list even if a restriction
16869 is currently in place.
16870 When ARCHIVES is t, include all archive files that are really being
16871 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16872 `org-agenda-archives-mode' is t."
16875 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16876 ((stringp org-agenda-files) (org-read-agenda-file-list))
16877 ((listp org-agenda-files) org-agenda-files)
16878 (t (error "Invalid value of `org-agenda-files'")))))
16879 (setq files (apply 'append
16880 (mapcar (lambda (f)
16881 (if (file-directory-p f)
16883 f t org-agenda-file-regexp)
16886 (when org-agenda-skip-unavailable-files
16887 (setq files (delq nil
16890 (and (file-readable-p file) file)))
16892 (when (or (eq archives t)
16893 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16894 (setq files (org-add-archive-files files)))
16897 (defun org-agenda-file-p (&optional file)
16898 "Return non-nil, if FILE is an agenda file.
16899 If FILE is omitted, use the file associated with the current
16901 (member (or file (buffer-file-name))
16902 (org-agenda-files t)))
16904 (defun org-edit-agenda-file-list ()
16905 "Edit the list of agenda files.
16906 Depending on setup, this either uses customize to edit the variable
16907 `org-agenda-files', or it visits the file that is holding the list. In the
16908 latter case, the buffer is set up in a way that saving it automatically kills
16909 the buffer and restores the previous window configuration."
16911 (if (stringp org-agenda-files)
16912 (let ((cw (current-window-configuration)))
16913 (find-file org-agenda-files)
16914 (org-set-local 'org-window-configuration cw)
16915 (org-add-hook 'after-save-hook
16917 (set-window-configuration
16918 (prog1 org-window-configuration
16919 (kill-buffer (current-buffer))))
16920 (org-install-agenda-files-menu)
16921 (message "New agenda file list installed"))
16923 (message "%s" (substitute-command-keys
16924 "Edit list and finish with \\[save-buffer]")))
16925 (customize-variable 'org-agenda-files)))
16927 (defun org-store-new-agenda-file-list (list)
16928 "Set new value for the agenda file list and save it correctly."
16929 (if (stringp org-agenda-files)
16930 (let ((fe (org-read-agenda-file-list t)) b u)
16931 (while (setq b (find-buffer-visiting org-agenda-files))
16933 (with-temp-file org-agenda-files
16936 (lambda (f) ;; Keep un-expanded entries.
16937 (if (setq u (assoc f fe))
16942 (let ((org-mode-hook nil) (org-inhibit-startup t)
16943 (org-insert-mode-line-in-empty-file nil))
16944 (setq org-agenda-files list)
16945 (customize-save-variable 'org-agenda-files org-agenda-files))))
16947 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16948 "Read the list of agenda files from a file.
16949 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16950 filenames, used by `org-store-new-agenda-file-list' to write back
16951 un-expanded file names."
16952 (when (file-directory-p org-agenda-files)
16953 (error "`org-agenda-files' cannot be a single directory"))
16954 (when (stringp org-agenda-files)
16956 (insert-file-contents org-agenda-files)
16959 (let ((e (expand-file-name (substitute-in-file-name f)
16961 (if pair-with-expansion
16964 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16967 (defun org-cycle-agenda-files ()
16968 "Cycle through the files in `org-agenda-files'.
16969 If the current buffer visits an agenda file, find the next one in the list.
16970 If the current buffer does not, find the first agenda file."
16972 (let* ((fs (org-agenda-files t))
16973 (files (append fs (list (car fs))))
16974 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16976 (unless files (error "No agenda files"))
16978 (while (setq file (pop files))
16979 (if (equal (file-truename file) tcf)
16981 (find-file (car files))
16983 (find-file (car fs)))
16984 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16986 (defun org-agenda-file-to-front (&optional to-end)
16987 "Move/add the current file to the top of the agenda file list.
16988 If the file is not present in the list, it is added to the front. If it is
16989 present, it is moved there. With optional argument TO-END, add/move to the
16992 (let ((org-agenda-skip-unavailable-files nil)
16993 (file-alist (mapcar (lambda (x)
16994 (cons (file-truename x) x))
16995 (org-agenda-files t)))
16996 (ctf (file-truename buffer-file-name))
16998 (setq x (assoc ctf file-alist) had x)
17000 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17002 (setq file-alist (append (delq x file-alist) (list x)))
17003 (setq file-alist (cons x (delq x file-alist))))
17004 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17005 (org-install-agenda-files-menu)
17006 (message "File %s to %s of agenda file list"
17007 (if had "moved" "added") (if to-end "end" "front"))))
17009 (defun org-remove-file (&optional file)
17010 "Remove current file from the list of files in variable `org-agenda-files'.
17011 These are the files which are being checked for agenda entries.
17012 Optional argument FILE means use this file instead of the current."
17014 (let* ((org-agenda-skip-unavailable-files nil)
17015 (file (or file buffer-file-name))
17016 (true-file (file-truename file))
17017 (afile (abbreviate-file-name file))
17018 (files (delq nil (mapcar
17020 (if (equal true-file
17023 (org-agenda-files t)))))
17024 (if (not (= (length files) (length (org-agenda-files t))))
17026 (org-store-new-agenda-file-list files)
17027 (org-install-agenda-files-menu)
17028 (message "Removed file: %s" afile))
17029 (message "File was not in list: %s (not removed)" afile))))
17031 (defun org-file-menu-entry (file)
17032 (vector file (list 'find-file file) t))
17034 (defun org-check-agenda-file (file)
17035 "Make sure FILE exists. If not, ask user what to do."
17036 (when (not (file-exists-p file))
17037 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
17038 (abbreviate-file-name file))
17039 (let ((r (downcase (read-char-exclusive))))
17042 (org-remove-file file)
17043 (throw 'nextfile t))
17044 (t (error "Abort"))))))
17046 (defun org-get-agenda-file-buffer (file)
17047 "Get a buffer visiting FILE. If the buffer needs to be created, add
17048 it to the list of buffers which might be released later."
17049 (let ((buf (org-find-base-buffer-visiting file)))
17051 buf ; just return it
17052 ;; Make a new buffer and remember it
17053 (setq buf (find-file-noselect file))
17054 (if buf (push buf org-agenda-new-buffers))
17057 (defun org-release-buffers (blist)
17058 "Release all buffers in list, asking the user for confirmation when needed.
17059 When a buffer is unmodified, it is just killed. When modified, it is saved
17060 \(if the user agrees) and then killed."
17062 (while (setq buf (pop blist))
17063 (setq file (buffer-file-name buf))
17064 (when (and (buffer-modified-p buf)
17066 (y-or-n-p (format "Save file %s? " file)))
17067 (with-current-buffer buf (save-buffer)))
17068 (kill-buffer buf))))
17070 (defun org-agenda-prepare-buffers (files)
17071 "Create buffers for all agenda files, protect archived trees and comments."
17073 (let ((pa '(:org-archived t))
17074 (pc '(:org-comment t))
17075 (pall '(:org-archived t :org-comment t))
17076 (inhibit-read-only t)
17077 (rea (concat ":" org-archive-tag ":"))
17081 (while (setq file (pop files))
17085 (org-check-agenda-file file)
17086 (set-buffer (org-get-agenda-file-buffer file)))
17088 (setq bmp (buffer-modified-p))
17089 (org-refresh-category-properties)
17090 (setq org-todo-keywords-for-agenda
17091 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17092 (setq org-done-keywords-for-agenda
17093 (append org-done-keywords-for-agenda org-done-keywords))
17094 (setq org-todo-keyword-alist-for-agenda
17095 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17096 (setq org-drawers-for-agenda
17097 (append org-drawers-for-agenda org-drawers))
17098 (setq org-tag-alist-for-agenda
17099 (append org-tag-alist-for-agenda org-tag-alist))
17102 (remove-text-properties (point-min) (point-max) pall)
17103 (when org-agenda-skip-archived-trees
17104 (goto-char (point-min))
17105 (while (re-search-forward rea nil t)
17106 (if (org-at-heading-p t)
17107 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17108 (goto-char (point-min))
17109 (setq re (format org-heading-keyword-regexp-format
17110 org-comment-string))
17111 (while (re-search-forward re nil t)
17112 (add-text-properties
17113 (match-beginning 0) (org-end-of-subtree t) pc)))
17114 (set-buffer-modified-p bmp)))))
17115 (setq org-todo-keywords-for-agenda
17116 (org-uniquify org-todo-keywords-for-agenda))
17117 (setq org-todo-keyword-alist-for-agenda
17118 (org-uniquify org-todo-keyword-alist-for-agenda)
17119 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17121 ;;;; Embedded LaTeX
17123 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17124 "Keymap for the minor `org-cdlatex-mode'.")
17126 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17127 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17128 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17129 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17130 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17132 (defvar org-cdlatex-texmathp-advice-is-done nil
17133 "Flag remembering if we have applied the advice to texmathp already.")
17135 (define-minor-mode org-cdlatex-mode
17136 "Toggle the minor `org-cdlatex-mode'.
17137 This mode supports entering LaTeX environment and math in LaTeX fragments
17139 \\{org-cdlatex-mode-map}"
17141 (when org-cdlatex-mode
17143 (run-hooks 'cdlatex-mode-hook)
17144 (cdlatex-compute-tables))
17145 (unless org-cdlatex-texmathp-advice-is-done
17146 (setq org-cdlatex-texmathp-advice-is-done t)
17147 (defadvice texmathp (around org-math-always-on activate)
17148 "Always return t in org-mode buffers.
17149 This is because we want to insert math symbols without dollars even outside
17150 the LaTeX math segments. If Orgmode thinks that point is actually inside
17151 an embedded LaTeX fragment, let texmathp do its job.
17152 \\[org-cdlatex-mode-map]"
17156 ((not (derived-mode-p 'org-mode)) ad-do-it)
17157 ((eq this-command 'cdlatex-math-symbol)
17158 (setq ad-return-value t
17159 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17161 (let ((p (org-inside-LaTeX-fragment-p)))
17162 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17163 (setq ad-return-value t
17164 texmathp-why '("Org-mode embedded math" . 0))
17165 (if p ad-do-it)))))))))
17167 (defun turn-on-org-cdlatex ()
17168 "Unconditionally turn on `org-cdlatex-mode'."
17169 (org-cdlatex-mode 1))
17171 (defun org-inside-LaTeX-fragment-p ()
17172 "Test if point is inside a LaTeX fragment.
17173 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17174 sequence appearing also before point.
17175 Even though the matchers for math are configurable, this function assumes
17176 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17177 delimiters are skipped when they have been removed by customization.
17178 The return value is nil, or a cons cell with the delimiter and the
17179 position of this delimiter.
17181 This function does a reasonably good job, but can locally be fooled by
17182 for example currency specifications. For example it will assume being in
17183 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17184 fragments that are properly closed, but during editing, we have to live
17185 with the uncertainty caused by missing closing delimiters. This function
17186 looks only before point, not after."
17188 (let ((pos (point))
17189 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17191 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17193 dd-on str (start 0) m re)
17196 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17197 re (nth 1 (assoc "$" org-latex-regexps)))
17198 (while (string-match re str start)
17200 ((= (match-end 0) (length str))
17201 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17202 ((= (match-end 0) (- (length str) 5))
17204 (t (setq start (match-end 0))))))
17205 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17207 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17208 (and (match-beginning 2) (throw 'exit nil))
17210 (while (re-search-backward "\\$\\$" lim t)
17211 (setq dd-on (not dd-on)))
17213 (if dd-on (cons "$$" m))))))
17215 (defun org-inside-latex-macro-p ()
17216 "Is point inside a LaTeX macro or its arguments?"
17219 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17221 (defun org-try-cdlatex-tab ()
17222 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17223 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17224 - inside a LaTeX fragment, or
17225 - after the first word in a line, where an abbreviation expansion could
17226 insert a LaTeX environment."
17227 (when org-cdlatex-mode
17229 ;; Before any word on the line: No expansion possible.
17230 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17231 ;; Just after first word on the line: Expand it. Make sure it
17232 ;; cannot happen on headlines, though.
17234 (skip-chars-backward "a-zA-Z0-9*")
17235 (skip-chars-backward " \t")
17236 (and (bolp) (not (org-at-heading-p))))
17238 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17240 (defun org-cdlatex-underscore-caret (&optional arg)
17241 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17242 Revert to the normal definition outside of these fragments."
17244 (if (org-inside-LaTeX-fragment-p)
17245 (call-interactively 'cdlatex-sub-superscript)
17246 (let (org-cdlatex-mode)
17247 (call-interactively (key-binding (vector last-input-event))))))
17249 (defun org-cdlatex-math-modify (&optional arg)
17250 "Execute `cdlatex-math-modify' in LaTeX fragments.
17251 Revert to the normal definition outside of these fragments."
17253 (if (org-inside-LaTeX-fragment-p)
17254 (call-interactively 'cdlatex-math-modify)
17255 (let (org-cdlatex-mode)
17256 (call-interactively (key-binding (vector last-input-event))))))
17258 (defvar org-latex-fragment-image-overlays nil
17259 "List of overlays carrying the images of latex fragments.")
17260 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17262 (defun org-remove-latex-fragment-image-overlays ()
17263 "Remove all overlays with LaTeX fragment images in current buffer."
17264 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17265 (setq org-latex-fragment-image-overlays nil))
17267 (defun org-preview-latex-fragment (&optional subtree)
17268 "Preview the LaTeX fragment at point, or all locally or globally.
17269 If the cursor is in a LaTeX fragment, create the image and overlay
17270 it over the source code. If there is no fragment at point, display
17271 all fragments in the current text, from one headline to the next. With
17272 prefix SUBTREE, display all fragments in the current subtree. With a
17273 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17274 the cursor is before the first headline,
17275 display all fragments in the buffer.
17276 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17278 (unless buffer-file-name
17279 (error "Can't preview LaTeX fragment in a non-file buffer"))
17280 (org-remove-latex-fragment-image-overlays)
17283 (let (beg end at msg)
17285 ((or (equal subtree '(16))
17286 (not (save-excursion
17287 (re-search-backward org-outline-regexp-bol nil t))))
17288 (setq beg (point-min) end (point-max)
17289 msg "Creating images for buffer...%s"))
17290 ((equal subtree '(4))
17291 (org-back-to-heading)
17292 (setq beg (point) end (org-end-of-subtree t)
17293 msg "Creating images for subtree...%s"))
17295 (if (setq at (org-inside-LaTeX-fragment-p))
17296 (goto-char (max (point-min) (- (cdr at) 2)))
17297 (org-back-to-heading))
17298 (setq beg (point) end (progn (outline-next-heading) (point))
17299 msg (if at "Creating image...%s"
17300 "Creating images for entry...%s"))))
17302 (narrow-to-region beg end)
17305 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17306 (file-name-nondirectory
17307 buffer-file-name)))
17308 default-directory 'overlays msg at 'forbuffer
17309 org-latex-create-formula-image-program)
17310 (message msg "done. Use `C-c C-c' to remove images.")))))
17312 (defvar org-latex-regexps
17313 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17314 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17315 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17316 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17317 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17318 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17319 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17320 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17321 "Regular expressions for matching embedded LaTeX.")
17323 (defvar org-export-have-math nil) ;; dynamic scoping
17324 (defun org-format-latex (prefix &optional dir overlays msg at
17325 forbuffer processing-type)
17326 "Replace LaTeX fragments with links to an image, and produce images.
17327 Some of the options can be changed using the variable
17328 `org-format-latex-options'."
17329 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17330 (let* ((prefixnodir (file-name-nondirectory prefix))
17331 (absprefix (expand-file-name prefix dir))
17332 (todir (file-name-directory absprefix))
17333 (opt org-format-latex-options)
17334 (matchers (plist-get opt :matchers))
17335 (re-list org-latex-regexps)
17336 (org-format-latex-header-extra
17337 (plist-get (org-infile-export-plist) :latex-header-extra))
17338 (cnt 0) txt hash link beg end re e checkdir
17339 executables-checked string
17340 m n block-type block linkfile movefile ov)
17341 ;; Check the different regular expressions
17342 (while (setq e (pop re-list))
17343 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17344 block (if block-type "\n\n" ""))
17345 (when (member m matchers)
17346 (goto-char (point-min))
17347 (while (re-search-forward re nil t)
17348 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17349 (not (get-text-property (match-beginning n)
17352 (not (eq (get-char-property (match-beginning n)
17354 'org-latex-overlay))))
17355 (setq org-export-have-math t)
17357 ((eq processing-type 'verbatim)
17358 ;; Leave the text verbatim, just protect it
17359 (add-text-properties (match-beginning n) (match-end n)
17360 '(org-protected t)))
17361 ((eq processing-type 'mathjax)
17362 ;; Prepare for MathJax processing
17363 (setq string (match-string n))
17364 (if (member m '("$" "$1"))
17366 (delete-region (match-beginning n) (match-end n))
17367 (goto-char (match-beginning n))
17368 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17370 '(org-protected t))))
17371 (add-text-properties (match-beginning n) (match-end n)
17372 '(org-protected t))))
17373 ((or (eq processing-type 'dvipng)
17374 (eq processing-type 'imagemagick))
17375 ;; Process to an image
17376 (setq txt (match-string n)
17377 beg (match-beginning n) end (match-end n)
17379 (let (print-length print-level) ; make sure full list is printed
17380 (setq hash (sha1 (prin1-to-string
17381 (list org-format-latex-header
17382 org-format-latex-header-extra
17383 org-export-latex-default-packages-alist
17384 org-export-latex-packages-alist
17385 org-format-latex-options
17387 linkfile (format "%s_%s.png" prefix hash)
17388 movefile (format "%s_%s.png" absprefix hash)))
17389 (setq link (concat block "[[file:" linkfile "]]" block))
17390 (if msg (message msg cnt))
17392 (unless checkdir ; make sure the directory exists
17394 (or (file-directory-p todir) (make-directory todir t)))
17396 ((eq processing-type 'dvipng)
17397 (unless executables-checked
17398 (org-check-external-command
17399 "latex" "needed to convert LaTeX fragments to images")
17400 (org-check-external-command
17401 "dvipng" "needed to convert LaTeX fragments to images")
17402 (setq executables-checked t))
17403 (unless (file-exists-p movefile)
17404 (org-create-formula-image-with-dvipng
17405 txt movefile opt forbuffer)))
17406 ((eq processing-type 'imagemagick)
17407 (unless executables-checked
17408 (org-check-external-command
17409 "convert" "you need to install imagemagick")
17410 (setq executables-checked t))
17411 (unless (file-exists-p movefile)
17412 (org-create-formula-image-with-imagemagick
17413 txt movefile opt forbuffer))))
17417 (if (eq (overlay-get o 'org-overlay-type)
17418 'org-latex-overlay)
17419 (delete-overlay o)))
17420 (overlays-in beg end))
17421 (setq ov (make-overlay beg end))
17422 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17423 (if (featurep 'xemacs)
17425 (overlay-put ov 'invisible t)
17428 (make-glyph (vector 'png :file movefile))))
17431 (list 'image :type 'png :file movefile :ascent 'center)))
17432 (push ov org-latex-fragment-image-overlays)
17434 (delete-region beg end)
17435 (insert (org-add-props link
17436 (list 'org-latex-src
17437 (replace-regexp-in-string
17439 'org-latex-src-embed-type
17440 (if block-type 'paragraph 'character))))))
17441 ((eq processing-type 'mathml)
17442 ;; Process to MathML
17443 (unless executables-checked
17444 (unless (save-match-data (org-format-latex-mathml-available-p))
17445 (error "LaTeX to MathML converter not configured"))
17446 (setq executables-checked t))
17447 (setq txt (match-string n)
17448 beg (match-beginning n) end (match-end n)
17450 (if msg (message msg cnt))
17452 (delete-region beg end)
17453 (insert (org-format-latex-as-mathml
17454 txt block-type prefix dir)))
17456 (error "Unknown conversion type %s for latex fragments"
17457 processing-type)))))))))
17459 (defun org-create-math-formula (latex-frag &optional mathml-file)
17460 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17461 Use `org-latex-to-mathml-convert-command'. If the conversion is
17462 sucessful, return the portion between \"<math...> </math>\"
17463 elements otherwise return nil. When MATHML-FILE is specified,
17464 write the results in to that file. When invoked as an
17465 interactive command, prompt for LATEX-FRAG, with initial value
17466 set to the current active region and echo the results for user
17468 (interactive (list (let ((frag (when (org-region-active-p)
17469 (buffer-substring-no-properties
17470 (region-beginning) (region-end)))))
17471 (read-string "LaTeX Fragment: " frag nil frag))))
17472 (unless latex-frag (error "Invalid latex-frag"))
17473 (let* ((tmp-in-file (file-relative-name
17474 (make-temp-name (expand-file-name "ltxmathml-in"))))
17475 (ignore (write-region latex-frag nil tmp-in-file))
17476 (tmp-out-file (file-relative-name
17477 (make-temp-name (expand-file-name "ltxmathml-out"))))
17479 org-latex-to-mathml-convert-command
17480 `((?j . ,(shell-quote-argument
17481 (expand-file-name org-latex-to-mathml-jar-file)))
17482 (?I . ,(shell-quote-argument tmp-in-file))
17483 (?o . ,(shell-quote-argument tmp-out-file)))))
17484 mathml shell-command-output)
17485 (when (org-called-interactively-p 'any)
17486 (unless (org-format-latex-mathml-available-p)
17487 (error "LaTeX to MathML converter not configured")))
17488 (message "Running %s" cmd)
17489 (setq shell-command-output (shell-command-to-string cmd))
17491 (when (file-readable-p tmp-out-file)
17492 (with-current-buffer (find-file-noselect tmp-out-file t)
17493 (goto-char (point-min))
17494 (when (re-search-forward
17497 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17499 (regexp-quote "</math>")) nil t)
17500 (prog1 (match-string 0) (kill-buffer))))))
17504 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17506 (write-region mathml nil mathml-file))
17507 (when (org-called-interactively-p 'any)
17509 ((message "LaTeX to MathML conversion failed")
17510 (message shell-command-output)))
17511 (delete-file tmp-in-file)
17512 (when (file-exists-p tmp-out-file)
17513 (delete-file tmp-out-file))
17516 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17517 prefix &optional dir)
17518 "Use `org-create-math-formula' but check local cache first."
17519 (let* ((absprefix (expand-file-name prefix dir))
17520 (print-length nil) (print-level nil)
17521 (formula-id (concat
17526 org-latex-to-mathml-convert-command)))))
17527 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17528 (formula-cache-dir (file-name-directory formula-cache)))
17530 (unless (file-directory-p formula-cache-dir)
17531 (make-directory formula-cache-dir t))
17533 (unless (file-exists-p formula-cache)
17534 (org-create-math-formula latex-frag formula-cache))
17536 (if (file-exists-p formula-cache)
17537 ;; Successful conversion. Return the link to MathML file.
17539 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17540 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17541 'org-latex-src-embed-type (if latex-frag-type
17542 'paragraph 'character)))
17543 ;; Failed conversion. Return the LaTeX fragment verbatim
17544 (add-text-properties
17545 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17548 ;; This function borrows from Ganesh Swami's latex2png.el
17549 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17550 "This calls dvipng."
17551 (require 'org-latex)
17552 (let* ((tmpdir (if (featurep 'xemacs)
17554 temporary-file-directory))
17555 (texfilebase (make-temp-name
17556 (expand-file-name "orgtex" tmpdir)))
17557 (texfile (concat texfilebase ".tex"))
17558 (dvifile (concat texfilebase ".dvi"))
17559 (pngfile (concat texfilebase ".png"))
17560 (fnh (if (featurep 'xemacs)
17561 (font-height (face-font 'default))
17562 (face-attribute 'default :height nil)))
17563 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17564 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17565 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17567 (bg (or (plist-get options (if buffer :background :html-background))
17569 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17570 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17571 (with-temp-file texfile
17572 (insert (org-splice-latex-header
17573 org-format-latex-header
17574 org-export-latex-default-packages-alist
17575 org-export-latex-packages-alist t
17576 org-format-latex-header-extra))
17577 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17578 (require 'org-latex)
17579 (org-export-latex-fix-inputenc))
17580 (let ((dir default-directory))
17581 (condition-case nil
17584 (call-process "latex" nil nil nil texfile))
17587 (if (not (file-exists-p dvifile))
17588 (progn (message "Failed to create dvi file from %s" texfile) nil)
17589 (condition-case nil
17590 (if (featurep 'xemacs)
17591 (call-process "dvipng" nil nil nil
17596 (call-process "dvipng" nil nil nil
17599 ;;"-x" scale "-y" scale
17604 (if (not (file-exists-p pngfile))
17605 (if org-format-latex-signal-error
17606 (error "Failed to create png file from %s" texfile)
17607 (message "Failed to create png file from %s" texfile)
17609 ;; Use the requested file name and clean up
17610 (copy-file pngfile tofile 'replace)
17611 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17612 (if (file-exists-p (concat texfilebase e))
17613 (delete-file (concat texfilebase e))))
17616 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17617 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17618 "This calls convert, which is included into imagemagick."
17619 (require 'org-latex)
17620 (let* ((tmpdir (if (featurep 'xemacs)
17622 temporary-file-directory))
17623 (texfilebase (make-temp-name
17624 (expand-file-name "orgtex" tmpdir)))
17625 (texfile (concat texfilebase ".tex"))
17626 (pdffile (concat texfilebase ".pdf"))
17627 (pngfile (concat texfilebase ".png"))
17628 (fnh (if (featurep 'xemacs)
17629 (font-height (face-font 'default))
17630 (face-attribute 'default :height nil)))
17631 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17632 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17633 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17635 (bg (or (plist-get options (if buffer :background :html-background))
17637 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17638 (setq fg (org-latex-color-format fg)))
17639 (if (eq bg 'default) (setq bg (org-latex-color :background))
17640 (setq bg (org-latex-color-format
17641 (if (string= bg "Transparent")(setq bg "white")))))
17642 (with-temp-file texfile
17643 (insert (org-splice-latex-header
17644 org-format-latex-header
17645 org-export-latex-default-packages-alist
17646 org-export-latex-packages-alist t
17647 org-format-latex-header-extra))
17648 (insert "\n\\begin{document}\n"
17649 "\\definecolor{fg}{rgb}{" fg "}\n"
17650 "\\definecolor{bg}{rgb}{" bg "}\n"
17651 "\n\\pagecolor{bg}\n"
17655 "\n\\end{document}\n" )
17656 (require 'org-latex)
17657 (org-export-latex-fix-inputenc))
17658 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17659 (condition-case nil
17662 (setq cmds org-latex-to-pdf-process)
17664 (setq latex-frags-cmds (pop cmds))
17665 (if (listp latex-frags-cmds)
17667 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17668 (while latex-frags-cmds
17669 (setq cmd (pop latex-frags-cmds))
17670 (while (string-match "%b" cmd)
17671 (setq cmd (replace-match
17673 (shell-quote-argument texfile))
17675 (while (string-match "%f" cmd)
17676 (setq cmd (replace-match
17678 (shell-quote-argument (file-name-nondirectory texfile)))
17680 (while (string-match "%o" cmd)
17681 (setq cmd (replace-match
17683 (shell-quote-argument (file-name-directory texfile)))
17685 (setq cmd (split-string cmd))
17686 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17689 (if (not (file-exists-p pdffile))
17690 (progn (message "Failed to create pdf file from %s" texfile) nil)
17691 (condition-case nil
17692 (if (featurep 'xemacs)
17693 (call-process "convert" nil nil nil
17699 ;; "-sharpen" "0x1.0"
17701 (call-process "convert" nil nil nil
17707 ; "-sharpen" "0x1.0"
17710 (if (not (file-exists-p pngfile))
17711 (if org-format-latex-signal-error
17712 (error "Failed to create png file from %s" texfile)
17713 (message "Failed to create png file from %s" texfile)
17715 ;; Use the requested file name and clean up
17716 (copy-file pngfile tofile 'replace)
17717 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17718 (if (file-exists-p (concat texfilebase e))
17719 (delete-file (concat texfilebase e))))
17722 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17723 "Fill a LaTeX header template TPL.
17724 In the template, the following place holders will be recognized:
17726 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17727 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17728 [PACKAGES] \\usepackage statements for PKG
17729 [NO-PACKAGES] do not include PKG
17730 [EXTRA] the string EXTRA
17731 [NO-EXTRA] do not include EXTRA
17733 For backward compatibility, if both the positive and the negative place
17734 holder is missing, the positive one (without the \"NO-\") will be
17735 assumed to be present at the end of the template.
17736 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17738 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17739 (let (rpl (end ""))
17740 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17741 (setq rpl (if (or (match-end 1) (not def-pkg))
17742 "" (org-latex-packages-to-string def-pkg snippets-p t))
17743 tpl (replace-match rpl t t tpl))
17744 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17746 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17747 (setq rpl (if (or (match-end 1) (not pkg))
17748 "" (org-latex-packages-to-string pkg snippets-p t))
17749 tpl (replace-match rpl t t tpl))
17752 (org-latex-packages-to-string pkg snippets-p)))))
17754 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17755 (setq rpl (if (or (match-end 1) (not extra))
17756 "" (concat extra "\n"))
17757 tpl (replace-match rpl t t tpl))
17758 (if (and extra (string-match "\\S-" extra))
17759 (setq end (concat end "\n" extra))))
17761 (if (string-match "\\S-" end)
17762 (concat tpl "\n" end)
17765 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17766 "Turn an alist of packages into a string with the \\usepackage macros."
17767 (setq pkg (mapconcat (lambda(p)
17770 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17771 (format "%% Package %s omitted" (cadr p)))
17772 ((equal "" (car p))
17773 (format "\\usepackage{%s}" (cadr p)))
17775 (format "\\usepackage[%s]{%s}"
17776 (car p) (cadr p)))))
17779 (if newline (concat pkg "\n") pkg))
17781 (defun org-dvipng-color (attr)
17782 "Return a RGB color specification for dvipng."
17783 (apply 'format "rgb %s %s %s"
17784 (mapcar 'org-normalize-color
17785 (if (featurep 'xemacs)
17786 (color-rgb-components
17787 (face-property 'default
17788 (cond ((eq attr :foreground) 'foreground)
17789 ((eq attr :background) 'background))))
17790 (color-values (face-attribute 'default attr nil))))))
17792 (defun org-latex-color (attr)
17793 "Return a RGB color for the LaTeX color package."
17794 (apply 'format "%s,%s,%s"
17795 (mapcar 'org-normalize-color
17796 (if (featurep 'xemacs)
17797 (color-rgb-components
17798 (face-property 'default
17799 (cond ((eq attr :foreground) 'foreground)
17800 ((eq attr :background) 'background))))
17801 (color-values (face-attribute 'default attr nil))))))
17803 (defun org-latex-color-format (color-name)
17804 "Convert COLOR-NAME to a RGB color value."
17805 (apply 'format "%s,%s,%s"
17806 (mapcar 'org-normalize-color
17807 (color-values color-name))))
17809 (defun org-normalize-color (value)
17810 "Return string to be used as color value for an RGB component."
17811 (format "%g" (/ value 65535.0)))
17816 (defvar org-inline-image-overlays nil)
17817 (make-variable-buffer-local 'org-inline-image-overlays)
17819 (defun org-toggle-inline-images (&optional include-linked)
17820 "Toggle the display of inline images.
17821 INCLUDE-LINKED is passed to `org-display-inline-images'."
17823 (if org-inline-image-overlays
17825 (org-remove-inline-images)
17826 (message "Inline image display turned off"))
17827 (org-display-inline-images include-linked)
17828 (if org-inline-image-overlays
17829 (message "%d images displayed inline"
17830 (length org-inline-image-overlays))
17831 (message "No images to display inline"))))
17833 (defun org-redisplay-inline-images ()
17834 "Refresh the display of inline images."
17836 (if (not org-inline-image-overlays)
17837 (org-toggle-inline-images)
17838 (org-toggle-inline-images)
17839 (org-toggle-inline-images)))
17841 (defun org-display-inline-images (&optional include-linked refresh beg end)
17842 "Display inline images.
17843 Normally only links without a description part are inlined, because this
17844 is how it will work for export. When INCLUDE-LINKED is set, also links
17845 with a description part will be inlined. This can be nice for a quick
17846 look at those images, but it does not reflect what exported files will look
17848 When REFRESH is set, refresh existing images between BEG and END.
17849 This will create new image displays only if necessary.
17850 BEG and END default to the buffer boundaries."
17853 (org-remove-inline-images)
17854 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17858 (setq beg (or beg (point-min)) end (or end (point-max)))
17860 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17861 (substring (org-image-file-name-regexp) 0 -2)
17862 "\\)\\]" (if include-linked "" "\\]")))
17864 (while (re-search-forward re end t)
17865 (setq old (get-char-property-and-overlay (match-beginning 1)
17866 'org-image-overlay))
17867 (setq file (expand-file-name
17868 (concat (or (match-string 3) "") (match-string 4))))
17869 (when (file-exists-p file)
17870 (if (and (car-safe old) refresh)
17871 (image-refresh (overlay-get (cdr old) 'display))
17872 (setq img (save-match-data (create-image file)))
17874 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17875 (overlay-put ov 'display img)
17876 (overlay-put ov 'face 'default)
17877 (overlay-put ov 'org-image-overlay t)
17878 (overlay-put ov 'modification-hooks
17879 (list 'org-display-inline-remove-overlay))
17880 (push ov org-inline-image-overlays)))))))))
17882 (define-obsolete-function-alias
17883 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
17885 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
17886 "Remove inline-display overlay if a corresponding region is modified."
17887 (let ((inhibit-modification-hooks t))
17888 (when (and ov after)
17889 (delete ov org-inline-image-overlays)
17890 (delete-overlay ov))))
17892 (defun org-remove-inline-images ()
17893 "Remove inline display of images."
17895 (mapc 'delete-overlay org-inline-image-overlays)
17896 (setq org-inline-image-overlays nil))
17900 ;; Outline functions from `outline-mode-prefix-map'
17901 ;; that can be remapped in Org:
17902 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17903 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17904 (define-key org-mode-map [remap outline-forward-same-level]
17905 'org-forward-heading-same-level)
17906 (define-key org-mode-map [remap outline-backward-same-level]
17907 'org-backward-heading-same-level)
17908 (define-key org-mode-map [remap show-branches]
17909 'org-kill-note-or-show-branches)
17910 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17911 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17912 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17914 ;; Outline functions from `outline-mode-prefix-map' that can not
17915 ;; be remapped in Org:
17917 ;; - the column "key binding" shows whether the Outline function is still
17918 ;; available in Org mode on the same key that it has been bound to in
17920 ;; - "overridden": key used for a different functionality in Org mode
17921 ;; - else: key still bound to the same Outline function in Org mode
17923 ;; | Outline function | key binding | Org replacement |
17924 ;; |------------------------------------+-------------+-----------------------|
17925 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17926 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17927 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17928 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17929 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17930 ;; | `show-entry' | overridden | no replacement |
17931 ;; | `show-children' | `C-c C-i' | visibility cycling |
17932 ;; | `show-branches' | `C-c C-k' | still same function |
17933 ;; | `show-subtree' | overridden | visibility cycling |
17934 ;; | `show-all' | overridden | no replacement |
17935 ;; | `hide-subtree' | overridden | visibility cycling |
17936 ;; | `hide-body' | overridden | no replacement |
17937 ;; | `hide-entry' | overridden | visibility cycling |
17938 ;; | `hide-leaves' | overridden | no replacement |
17939 ;; | `hide-sublevels' | overridden | no replacement |
17940 ;; | `hide-other' | overridden | no replacement |
17942 ;; Make `C-c C-x' a prefix key
17943 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17945 ;; TAB key with modifiers
17946 (org-defkey org-mode-map "\C-i" 'org-cycle)
17947 (org-defkey org-mode-map [(tab)] 'org-cycle)
17948 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17949 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17950 ;; The following line is necessary under Suse GNU/Linux
17951 (unless (featurep 'xemacs)
17952 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17953 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17954 (define-key org-mode-map [backtab] 'org-shifttab)
17956 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17957 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17958 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17960 ;; Cursor keys with modifiers
17961 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17962 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17963 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17964 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17966 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17967 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17968 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17969 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17971 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17972 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17973 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17974 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17976 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17977 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17978 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17979 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17982 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17983 (mapc (lambda (pair)
17984 (define-key org-babel-map (car pair) (cdr pair)))
17985 org-babel-key-bindings)
17987 ;;; Extra keys for tty access.
17988 ;; We only set them when really needed because otherwise the
17989 ;; menus don't show the simple keys
17991 (when (or org-use-extra-keys
17992 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17993 (not window-system))
17994 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17995 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17996 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17997 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17998 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17999 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18000 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18001 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18002 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18003 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18004 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18005 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18006 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18007 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18008 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18009 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18010 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18011 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18012 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18013 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18014 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18015 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18016 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18017 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18018 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18019 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18020 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18021 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18023 ;; All the other keys
18025 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18026 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18027 (if (boundp 'narrow-map)
18028 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18029 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18030 (if (boundp 'narrow-map)
18031 (org-defkey narrow-map "b" 'org-narrow-to-block)
18032 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18033 (if (boundp 'narrow-map)
18034 (org-defkey narrow-map "e" 'org-narrow-to-element)
18035 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18036 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18037 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18038 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18039 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18040 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18041 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18042 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18043 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18044 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18045 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18046 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18047 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18048 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18049 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18050 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18051 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18052 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18053 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18054 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18055 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18056 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18057 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18058 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18059 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18060 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18061 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18062 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18063 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18064 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18065 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18066 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18067 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18068 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18069 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18070 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18071 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18072 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18073 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18074 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18075 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18076 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18077 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18078 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18079 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18080 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18081 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18082 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18083 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18084 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18085 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18086 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18087 (org-defkey org-mode-map "\C-c^" 'org-sort)
18088 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18089 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18090 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18091 (org-defkey org-mode-map "\C-m" 'org-return)
18092 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18093 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18094 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18095 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18096 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18097 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18098 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18099 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18100 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18101 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18102 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18103 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18104 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18105 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18106 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18107 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18108 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18109 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18110 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18111 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18112 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18113 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18114 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18116 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
18117 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18118 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18119 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18121 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18122 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18123 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18124 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18125 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18126 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18127 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18128 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18129 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18130 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18131 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18132 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18133 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18134 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18135 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18136 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18137 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18138 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18139 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18140 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18141 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18142 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18144 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18145 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18146 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18147 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18148 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18150 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18152 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18154 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18155 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18157 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18160 (when (featurep 'xemacs)
18161 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18164 (defconst org-speed-commands-default
18166 ("Outline Navigation")
18167 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18168 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18169 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18170 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18171 ("u" . (org-speed-move-safe 'outline-up-heading))
18173 ("g" . (org-refile t))
18174 ("Outline Visibility")
18176 ("C" . org-shifttab)
18177 (" " . org-display-outline-path)
18178 (":" . org-columns)
18179 ("Outline Structure Editing")
18180 ("U" . org-shiftmetaup)
18181 ("D" . org-shiftmetadown)
18182 ("r" . org-metaright)
18183 ("l" . org-metaleft)
18184 ("R" . org-shiftmetaright)
18185 ("L" . org-shiftmetaleft)
18186 ("i" . (progn (forward-char 1) (call-interactively
18187 'org-insert-heading-respect-content)))
18190 ("a" . org-archive-subtree-default-with-confirmation)
18191 ("." . org-mark-subtree)
18192 ("#" . org-toggle-comment)
18194 ("I" . org-clock-in)
18195 ("O" . org-clock-out)
18196 ("Meta Data Editing")
18198 ("," . (org-priority))
18199 ("0" . (org-priority ?\ ))
18200 ("1" . (org-priority ?A))
18201 ("2" . (org-priority ?B))
18202 ("3" . (org-priority ?C))
18203 (";" . org-set-tags-command)
18204 ("e" . org-set-effort)
18205 ("E" . org-inc-effort)
18206 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18207 (org-entry-put (point) "APPT_WARNTIME" m)))
18208 ("Agenda Views etc")
18210 ("/" . org-sparse-tree)
18212 ("o" . org-open-at-point)
18213 ("?" . org-speed-command-help)
18214 ("<" . (org-agenda-set-restriction-lock 'subtree))
18215 (">" . (org-agenda-remove-restriction-lock))
18217 "The default speed commands.")
18219 (defun org-print-speed-command (e)
18220 (if (> (length (car e)) 1)
18225 (princ (make-string (length (car e)) ?-))
18229 (if (symbolp (cdr e))
18230 (princ (symbol-name (cdr e)))
18234 (defun org-speed-command-help ()
18235 "Show the available speed commands."
18237 (if (not org-use-speed-commands)
18238 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18239 (with-output-to-temp-buffer "*Help*"
18240 (princ "User-defined Speed commands\n===========================\n")
18241 (mapc 'org-print-speed-command org-speed-commands-user)
18243 (princ "Built-in Speed commands\n=======================\n")
18244 (mapc 'org-print-speed-command org-speed-commands-default))
18245 (with-current-buffer "*Help*"
18246 (setq truncate-lines t))))
18248 (defun org-speed-move-safe (cmd)
18249 "Execute CMD, but make sure that the cursor always ends up in a headline.
18250 If not, return to the original position and throw an error."
18252 (let ((pos (point)))
18253 (call-interactively cmd)
18254 (unless (and (bolp) (org-at-heading-p))
18256 (error "Boundary reached while executing %s" cmd))))
18258 (defvar org-self-insert-command-undo-counter 0)
18260 (defvar org-table-auto-blank-field) ; defined in org-table.el
18261 (defvar org-speed-command nil)
18263 (define-obsolete-function-alias
18264 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18266 (defun org-speed-command-activate (keys)
18267 "Hook for activating single-letter speed commands.
18268 `org-speed-commands-default' specifies a minimal command set.
18269 Use `org-speed-commands-user' for further customization."
18270 (when (or (and (bolp) (looking-at org-outline-regexp))
18271 (and (functionp org-use-speed-commands)
18272 (funcall org-use-speed-commands)))
18273 (cdr (assoc keys (append org-speed-commands-user
18274 org-speed-commands-default)))))
18276 (define-obsolete-function-alias
18277 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18279 (defun org-babel-speed-command-activate (keys)
18280 "Hook for activating single-letter code block commands."
18281 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18282 (cdr (assoc keys org-babel-key-bindings))))
18284 (defcustom org-speed-command-hook
18285 '(org-speed-command-default-hook org-babel-speed-command-hook)
18286 "Hook for activating speed commands at strategic locations.
18287 Hook functions are called in sequence until a valid handler is
18290 Each hook takes a single argument, a user-pressed command key
18291 which is also a `self-insert-command' from the global map.
18293 Within the hook, examine the cursor position and the command key
18294 and return nil or a valid handler as appropriate. Handler could
18295 be one of an interactive command, a function, or a form.
18297 Set `org-use-speed-commands' to non-nil value to enable this
18298 hook. The default setting is `org-speed-command-activate'."
18299 :group 'org-structure
18303 (defun org-self-insert-command (N)
18304 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18305 If the cursor is in a table looking at whitespace, the whitespace is
18306 overwritten, and the table is not marked as requiring realignment."
18308 (org-check-before-invisible-edit 'insert)
18310 ((and org-use-speed-commands
18311 (setq org-speed-command
18312 (run-hook-with-args-until-success
18313 'org-speed-command-hook (this-command-keys))))
18315 ((commandp org-speed-command)
18316 (setq this-command org-speed-command)
18317 (call-interactively org-speed-command))
18318 ((functionp org-speed-command)
18319 (funcall org-speed-command))
18320 ((and org-speed-command (listp org-speed-command))
18321 (eval org-speed-command))
18322 (t (let (org-use-speed-commands)
18323 (call-interactively 'org-self-insert-command)))))
18327 ;; check if we blank the field, and if that triggers align
18328 (and (featurep 'org-table) org-table-auto-blank-field
18329 (member last-command
18330 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18331 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18332 ;; got extra space, this field does not determine column width
18333 (let (org-table-may-need-update) (org-table-blank-field))
18334 ;; no extra space, this field may determine column width
18335 (org-table-blank-field)))
18338 (looking-at "[^|\n]* |"))
18339 (let (org-table-may-need-update)
18340 (goto-char (1- (match-end 0)))
18341 (backward-delete-char 1)
18342 (goto-char (match-beginning 0))
18343 (self-insert-command N)))
18345 (setq org-table-may-need-update t)
18346 (self-insert-command N)
18347 (org-fix-tags-on-the-fly)
18348 (if org-self-insert-cluster-for-undo
18349 (if (not (eq last-command 'org-self-insert-command))
18350 (setq org-self-insert-command-undo-counter 1)
18351 (if (>= org-self-insert-command-undo-counter 20)
18352 (setq org-self-insert-command-undo-counter 1)
18353 (and (> org-self-insert-command-undo-counter 0)
18354 buffer-undo-list (listp buffer-undo-list)
18355 (not (cadr buffer-undo-list)) ; remove nil entry
18356 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18357 (setq org-self-insert-command-undo-counter
18358 (1+ org-self-insert-command-undo-counter))))))))
18360 (defun org-check-before-invisible-edit (kind)
18361 "Check is editing if kind KIND would be dangerous with invisible text around.
18362 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18363 ;; First, try to get out of here as quickly as possible, to reduce overhead
18364 (if (and org-catch-invisible-edits
18365 (or (not (boundp 'visible-mode)) (not visible-mode))
18366 (or (get-char-property (point) 'invisible)
18367 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18368 ;; OK, we need to take a closer look
18369 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18370 (invisible-before-point (if (bobp) nil (get-char-property
18371 (1- (point)) 'invisible)))
18372 (border-and-ok-direction
18374 ;; Check if we are acting predictably before invisible text
18375 (and invisible-at-point (not invisible-before-point)
18376 (memq kind '(insert delete-backward)))
18377 ;; Check if we are acting predictably after invisible text
18378 ;; This works not well, and I have turned it off. It seems
18379 ;; better to always show and stop after invisible text.
18380 ;; (and (not invisible-at-point) invisible-before-point
18381 ;; (memq kind '(insert delete)))
18383 (when (or (memq invisible-at-point '(outline org-hide-block t))
18384 (memq invisible-before-point '(outline org-hide-block t)))
18385 (if (eq org-catch-invisible-edits 'error)
18386 (error "Editing in invisible areas is prohibited - make visible first"))
18387 (if (and org-custom-properties-overlays
18388 (y-or-n-p "Display invisible properties in this buffer? "))
18389 (org-toggle-custom-properties-visibility)
18390 ;; Make the area visible
18392 (if invisible-before-point
18393 (goto-char (previous-single-char-property-change
18394 (point) 'invisible)))
18397 ((eq org-catch-invisible-edits 'show)
18398 ;; That's it, we do the edit after showing
18400 "Unfolding invisible region around point before editing")
18402 ((and (eq org-catch-invisible-edits 'smart)
18403 border-and-ok-direction)
18404 (message "Unfolding invisible region around point before editing"))
18406 ;; Don't do the edit, make the user repeat it in full visibility
18407 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18409 (defun org-fix-tags-on-the-fly ()
18410 (when (and (equal (char-after (point-at-bol)) ?*)
18411 (org-at-heading-p))
18412 (org-align-tags-here org-tags-column)))
18414 (defun org-delete-backward-char (N)
18415 "Like `delete-backward-char', insert whitespace at field end in tables.
18416 When deleting backwards, in tables this function will insert whitespace in
18417 front of the next \"|\" separator, to keep the table aligned. The table will
18418 still be marked for re-alignment if the field did fill the entire column,
18419 because, in this case the deletion might narrow the column."
18421 (org-check-before-invisible-edit 'delete-backward)
18422 (if (and (org-table-p)
18424 (string-match "|" (buffer-substring (point-at-bol) (point)))
18425 (looking-at ".*?|"))
18426 (let ((pos (point))
18427 (noalign (looking-at "[^|\n\r]* |"))
18428 (c org-table-may-need-update))
18429 (backward-delete-char N)
18430 (if (not overwrite-mode)
18432 (skip-chars-forward "^|")
18434 (goto-char (1- pos))))
18435 ;; noalign: if there were two spaces at the end, this field
18436 ;; does not determine the width of the column.
18437 (if noalign (setq org-table-may-need-update c)))
18438 (backward-delete-char N)
18439 (org-fix-tags-on-the-fly)))
18441 (defun org-delete-char (N)
18442 "Like `delete-char', but insert whitespace at field end in tables.
18443 When deleting characters, in tables this function will insert whitespace in
18444 front of the next \"|\" separator, to keep the table aligned. The table will
18445 still be marked for re-alignment if the field did fill the entire column,
18446 because, in this case the deletion might narrow the column."
18448 (org-check-before-invisible-edit 'delete)
18449 (if (and (org-table-p)
18451 (not (= (char-after) ?|))
18453 (if (looking-at ".*?|")
18454 (let ((pos (point))
18455 (noalign (looking-at "[^|\n\r]* |"))
18456 (c org-table-may-need-update))
18457 (replace-match (concat
18458 (substring (match-string 0) 1 -1)
18461 ;; noalign: if there were two spaces at the end, this field
18462 ;; does not determine the width of the column.
18463 (if noalign (setq org-table-may-need-update c)))
18466 (org-fix-tags-on-the-fly)))
18468 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18469 (put 'org-self-insert-command 'delete-selection t)
18470 (put 'orgtbl-self-insert-command 'delete-selection t)
18471 (put 'org-delete-char 'delete-selection 'supersede)
18472 (put 'org-delete-backward-char 'delete-selection 'supersede)
18473 (put 'org-yank 'delete-selection 'yank)
18475 ;; Make `flyspell-mode' delay after some commands
18476 (put 'org-self-insert-command 'flyspell-delayed t)
18477 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18478 (put 'org-delete-char 'flyspell-delayed t)
18479 (put 'org-delete-backward-char 'flyspell-delayed t)
18481 ;; Make pabbrev-mode expand after org-mode commands
18482 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18483 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18485 ;; How to do this: Measure non-white length of current string
18486 ;; If equal to column width, we should realign.
18488 (defun org-remap (map &rest commands)
18489 "In MAP, remap the functions given in COMMANDS.
18490 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18493 (setq old (pop commands) new (pop commands))
18494 (if (fboundp 'command-remapping)
18495 (org-defkey map (vector 'remap old) new)
18496 (substitute-key-definition old new map global-map)))))
18498 (when (eq org-enable-table-editor 'optimized)
18499 ;; If the user wants maximum table support, we need to hijack
18500 ;; some standard editing functions
18501 (org-remap org-mode-map
18502 'self-insert-command 'org-self-insert-command
18503 'delete-char 'org-delete-char
18504 'delete-backward-char 'org-delete-backward-char)
18505 (org-defkey org-mode-map "|" 'org-force-self-insert))
18507 (defvar org-ctrl-c-ctrl-c-hook nil
18508 "Hook for functions attaching themselves to `C-c C-c'.
18510 This can be used to add additional functionality to the C-c C-c
18511 key which executes context-dependent commands. This hook is run
18512 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18513 run after the last test.
18515 Each function will be called with no arguments. The function
18516 must check if the context is appropriate for it to act. If yes,
18517 it should do its thing and then return a non-nil value. If the
18518 context is wrong, just do nothing and return nil.")
18520 (defvar org-ctrl-c-ctrl-c-final-hook nil
18521 "Hook for functions attaching themselves to `C-c C-c'.
18523 This can be used to add additional functionality to the C-c C-c
18524 key which executes context-dependent commands. This hook is run
18525 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18526 before the first test.
18528 Each function will be called with no arguments. The function
18529 must check if the context is appropriate for it to act. If yes,
18530 it should do its thing and then return a non-nil value. If the
18531 context is wrong, just do nothing and return nil.")
18533 (defvar org-tab-first-hook nil
18534 "Hook for functions to attach themselves to TAB.
18535 See `org-ctrl-c-ctrl-c-hook' for more information.
18536 This hook runs as the first action when TAB is pressed, even before
18537 `org-cycle' messes around with the `outline-regexp' to cater for
18538 inline tasks and plain list item folding.
18539 If any function in this hook returns t, any other actions that
18540 would have been caused by TAB (such as table field motion or visibility
18541 cycling) will not occur.")
18543 (defvar org-tab-after-check-for-table-hook nil
18544 "Hook for functions to attach themselves to TAB.
18545 See `org-ctrl-c-ctrl-c-hook' for more information.
18546 This hook runs after it has been established that the cursor is not in a
18547 table, but before checking if the cursor is in a headline or if global cycling
18549 If any function in this hook returns t, not other actions like visibility
18550 cycling will be done.")
18552 (defvar org-tab-after-check-for-cycling-hook nil
18553 "Hook for functions to attach themselves to TAB.
18554 See `org-ctrl-c-ctrl-c-hook' for more information.
18555 This hook runs after it has been established that not table field motion and
18556 not visibility should be done because of current context. This is probably
18557 the place where a package like yasnippets can hook in.")
18559 (defvar org-tab-before-tab-emulation-hook nil
18560 "Hook for functions to attach themselves to TAB.
18561 See `org-ctrl-c-ctrl-c-hook' for more information.
18562 This hook runs after every other options for TAB have been exhausted, but
18563 before indentation and \t insertion takes place.")
18565 (defvar org-metaleft-hook nil
18566 "Hook for functions attaching themselves to `M-left'.
18567 See `org-ctrl-c-ctrl-c-hook' for more information.")
18568 (defvar org-metaright-hook nil
18569 "Hook for functions attaching themselves to `M-right'.
18570 See `org-ctrl-c-ctrl-c-hook' for more information.")
18571 (defvar org-metaup-hook nil
18572 "Hook for functions attaching themselves to `M-up'.
18573 See `org-ctrl-c-ctrl-c-hook' for more information.")
18574 (defvar org-metadown-hook nil
18575 "Hook for functions attaching themselves to `M-down'.
18576 See `org-ctrl-c-ctrl-c-hook' for more information.")
18577 (defvar org-shiftmetaleft-hook nil
18578 "Hook for functions attaching themselves to `M-S-left'.
18579 See `org-ctrl-c-ctrl-c-hook' for more information.")
18580 (defvar org-shiftmetaright-hook nil
18581 "Hook for functions attaching themselves to `M-S-right'.
18582 See `org-ctrl-c-ctrl-c-hook' for more information.")
18583 (defvar org-shiftmetaup-hook nil
18584 "Hook for functions attaching themselves to `M-S-up'.
18585 See `org-ctrl-c-ctrl-c-hook' for more information.")
18586 (defvar org-shiftmetadown-hook nil
18587 "Hook for functions attaching themselves to `M-S-down'.
18588 See `org-ctrl-c-ctrl-c-hook' for more information.")
18589 (defvar org-metareturn-hook nil
18590 "Hook for functions attaching themselves to `M-RET'.
18591 See `org-ctrl-c-ctrl-c-hook' for more information.")
18592 (defvar org-shiftup-hook nil
18593 "Hook for functions attaching themselves to `S-up'.
18594 See `org-ctrl-c-ctrl-c-hook' for more information.")
18595 (defvar org-shiftup-final-hook nil
18596 "Hook for functions attaching themselves to `S-up'.
18597 This one runs after all other options except shift-select have been excluded.
18598 See `org-ctrl-c-ctrl-c-hook' for more information.")
18599 (defvar org-shiftdown-hook nil
18600 "Hook for functions attaching themselves to `S-down'.
18601 See `org-ctrl-c-ctrl-c-hook' for more information.")
18602 (defvar org-shiftdown-final-hook nil
18603 "Hook for functions attaching themselves to `S-down'.
18604 This one runs after all other options except shift-select have been excluded.
18605 See `org-ctrl-c-ctrl-c-hook' for more information.")
18606 (defvar org-shiftleft-hook nil
18607 "Hook for functions attaching themselves to `S-left'.
18608 See `org-ctrl-c-ctrl-c-hook' for more information.")
18609 (defvar org-shiftleft-final-hook nil
18610 "Hook for functions attaching themselves to `S-left'.
18611 This one runs after all other options except shift-select have been excluded.
18612 See `org-ctrl-c-ctrl-c-hook' for more information.")
18613 (defvar org-shiftright-hook nil
18614 "Hook for functions attaching themselves to `S-right'.
18615 See `org-ctrl-c-ctrl-c-hook' for more information.")
18616 (defvar org-shiftright-final-hook nil
18617 "Hook for functions attaching themselves to `S-right'.
18618 This one runs after all other options except shift-select have been excluded.
18619 See `org-ctrl-c-ctrl-c-hook' for more information.")
18621 (defun org-modifier-cursor-error ()
18622 "Throw an error, a modified cursor command was applied in wrong context."
18623 (error "This command is active in special context like tables, headlines or items"))
18625 (defun org-shiftselect-error ()
18626 "Throw an error because Shift-Cursor command was applied in wrong context."
18627 (if (and (boundp 'shift-select-mode) shift-select-mode)
18628 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18629 (error "This command works only in special context like headlines or timestamps")))
18631 (defun org-call-for-shift-select (cmd)
18632 (let ((this-command-keys-shift-translated t))
18633 (call-interactively cmd)))
18635 (defun org-shifttab (&optional arg)
18636 "Global visibility cycling or move to previous table field.
18637 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18639 See the individual commands for more information."
18642 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18644 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18645 (message "Content view to level: %d" arg)
18646 (org-content (prefix-numeric-value arg2))
18647 (setq org-cycle-global-status 'overview)))
18648 (t (call-interactively 'org-global-cycle))))
18650 (defun org-shiftmetaleft ()
18651 "Promote subtree or delete table column.
18652 Calls `org-promote-subtree', `org-outdent-item-tree', or
18653 `org-table-delete-column', depending on context. See the
18654 individual commands for more information."
18657 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18658 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18659 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18660 ((if (not (org-region-active-p)) (org-at-item-p)
18661 (save-excursion (goto-char (region-beginning))
18663 (call-interactively 'org-outdent-item-tree))
18664 (t (org-modifier-cursor-error))))
18666 (defun org-shiftmetaright ()
18667 "Demote subtree or insert table column.
18668 Calls `org-demote-subtree', `org-indent-item-tree', or
18669 `org-table-insert-column', depending on context. See the
18670 individual commands for more information."
18673 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18674 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18675 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18676 ((if (not (org-region-active-p)) (org-at-item-p)
18677 (save-excursion (goto-char (region-beginning))
18679 (call-interactively 'org-indent-item-tree))
18680 (t (org-modifier-cursor-error))))
18682 (defun org-shiftmetaup (&optional arg)
18683 "Move subtree up or kill table row.
18684 Calls `org-move-subtree-up' or `org-table-kill-row' or
18685 `org-move-item-up' or `org-timestamp-up', depending on context.
18686 See the individual commands for more information."
18689 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18690 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18691 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18692 ((org-at-item-p) (call-interactively 'org-move-item-up))
18693 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18694 (call-interactively 'org-timestamp-up)))
18695 (t (org-modifier-cursor-error))))
18697 (defun org-shiftmetadown (&optional arg)
18698 "Move subtree down or insert table row.
18699 Calls `org-move-subtree-down' or `org-table-insert-row' or
18700 `org-move-item-down' or `org-timestamp-up', depending on context.
18701 See the individual commands for more information."
18704 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18705 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18706 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18707 ((org-at-item-p) (call-interactively 'org-move-item-down))
18708 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18709 (call-interactively 'org-timestamp-down)))
18710 (t (org-modifier-cursor-error))))
18712 (defsubst org-hidden-tree-error ()
18714 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18716 (defun org-metaleft (&optional arg)
18717 "Promote heading or move table column to left.
18718 Calls `org-do-promote' or `org-table-move-column', depending on context.
18719 With no specific context, calls the Emacs default `backward-word'.
18720 See the individual commands for more information."
18723 ((run-hook-with-args-until-success 'org-metaleft-hook))
18724 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18725 ((org-with-limited-levels
18726 (or (org-at-heading-p)
18727 (and (org-region-active-p)
18729 (goto-char (region-beginning))
18730 (org-at-heading-p)))))
18731 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18732 (call-interactively 'org-do-promote))
18733 ;; At an inline task.
18734 ((org-at-heading-p)
18735 (call-interactively 'org-inlinetask-promote))
18736 ((or (org-at-item-p)
18737 (and (org-region-active-p)
18739 (goto-char (region-beginning))
18741 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18742 (call-interactively 'org-outdent-item))
18743 (t (call-interactively 'backward-word))))
18745 (defun org-metaright (&optional arg)
18746 "Demote a subtree, a list item or move table column to right.
18747 In front of a drawer or a block keyword, indent it correctly.
18748 With no specific context, calls the Emacs default `forward-word'.
18749 See the individual commands for more information."
18752 ((run-hook-with-args-until-success 'org-metaright-hook))
18753 ((org-at-table-p) (call-interactively 'org-table-move-column))
18754 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18755 ((org-at-block-p) (call-interactively 'org-indent-block))
18756 ((org-with-limited-levels
18757 (or (org-at-heading-p)
18758 (and (org-region-active-p)
18760 (goto-char (region-beginning))
18761 (org-at-heading-p)))))
18762 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18763 (call-interactively 'org-do-demote))
18764 ;; At an inline task.
18765 ((org-at-heading-p)
18766 (call-interactively 'org-inlinetask-demote))
18767 ((or (org-at-item-p)
18768 (and (org-region-active-p)
18770 (goto-char (region-beginning))
18772 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18773 (call-interactively 'org-indent-item))
18774 (t (call-interactively 'forward-word))))
18776 (defun org-check-for-hidden (what)
18777 "Check if there are hidden headlines/items in the current visual line.
18778 WHAT can be either `headlines' or `items'. If the current line is
18779 an outline or item heading and it has a folded subtree below it,
18780 this function returns t, nil otherwise."
18782 ((eq what 'headlines) org-outline-regexp-bol)
18783 ((eq what 'items) (org-item-beginning-re))
18784 (t (error "This should not happen"))))
18788 (unless (org-region-active-p)
18789 (setq beg (point-at-bol))
18790 (beginning-of-line 2)
18791 (while (and (not (eobp)) ;; this is like `next-line'
18792 (get-char-property (1- (point)) 'invisible))
18793 (beginning-of-line 2))
18796 (goto-char (point-at-eol))
18797 (setq end (max end (point)))
18798 (while (re-search-forward re end t)
18799 (if (get-char-property (match-beginning 0) 'invisible)
18803 (autoload 'org-element-at-point "org-element")
18805 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18806 (declare-function org-element-type "org-element" (element))
18807 (declare-function org-element-context "org-element" ())
18808 (declare-function org-element-contents "org-element" (element))
18809 (declare-function org-element-property "org-element" (property element))
18810 (declare-function org-element-paragraph-parser "org-element" (limit))
18811 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18812 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18813 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18814 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18815 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18817 (defun org-metaup (&optional arg)
18818 "Move subtree up or move table row up.
18819 Calls `org-move-subtree-up' or `org-table-move-row' or
18820 `org-move-item-up', depending on context. See the individual commands
18821 for more information."
18824 ((run-hook-with-args-until-success 'org-metaup-hook))
18825 ((org-region-active-p)
18826 (let* ((a (min (region-beginning) (region-end)))
18827 (b (1- (max (region-beginning) (region-end))))
18828 (c (save-excursion (goto-char a)
18829 (move-beginning-of-line 0)))
18830 (d (save-excursion (goto-char a)
18831 (move-end-of-line 0) (point))))
18832 (transpose-regions a b c d)
18834 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18835 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18836 ((org-at-item-p) (call-interactively 'org-move-item-up))
18837 (t (org-drag-element-backward))))
18839 (defun org-metadown (&optional arg)
18840 "Move subtree down or move table row down.
18841 Calls `org-move-subtree-down' or `org-table-move-row' or
18842 `org-move-item-down', depending on context. See the individual
18843 commands for more information."
18846 ((run-hook-with-args-until-success 'org-metadown-hook))
18847 ((org-region-active-p)
18848 (let* ((a (min (region-beginning) (region-end)))
18849 (b (max (region-beginning) (region-end)))
18850 (c (save-excursion (goto-char b)
18851 (move-beginning-of-line 1)))
18852 (d (save-excursion (goto-char b)
18853 (move-end-of-line 1) (1+ (point)))))
18854 (transpose-regions a b c d)
18856 ((org-at-table-p) (call-interactively 'org-table-move-row))
18857 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18858 ((org-at-item-p) (call-interactively 'org-move-item-down))
18859 (t (org-drag-element-forward))))
18861 (defun org-shiftup (&optional arg)
18862 "Increase item in timestamp or increase priority of current headline.
18863 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18864 depending on context. See the individual commands for more information."
18867 ((run-hook-with-args-until-success 'org-shiftup-hook))
18868 ((and org-support-shift-select (org-region-active-p))
18869 (org-call-for-shift-select 'previous-line))
18870 ((org-at-timestamp-p t)
18871 (call-interactively (if org-edit-timestamp-down-means-later
18872 'org-timestamp-down 'org-timestamp-up)))
18873 ((and (not (eq org-support-shift-select 'always))
18874 org-enable-priority-commands
18875 (org-at-heading-p))
18876 (call-interactively 'org-priority-up))
18877 ((and (not org-support-shift-select) (org-at-item-p))
18878 (call-interactively 'org-previous-item))
18879 ((org-clocktable-try-shift 'up arg))
18880 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18881 (org-support-shift-select
18882 (org-call-for-shift-select 'previous-line))
18883 (t (org-shiftselect-error))))
18885 (defun org-shiftdown (&optional arg)
18886 "Decrease item in timestamp or decrease priority of current headline.
18887 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18888 depending on context. See the individual commands for more information."
18891 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18892 ((and org-support-shift-select (org-region-active-p))
18893 (org-call-for-shift-select 'next-line))
18894 ((org-at-timestamp-p t)
18895 (call-interactively (if org-edit-timestamp-down-means-later
18896 'org-timestamp-up 'org-timestamp-down)))
18897 ((and (not (eq org-support-shift-select 'always))
18898 org-enable-priority-commands
18899 (org-at-heading-p))
18900 (call-interactively 'org-priority-down))
18901 ((and (not org-support-shift-select) (org-at-item-p))
18902 (call-interactively 'org-next-item))
18903 ((org-clocktable-try-shift 'down arg))
18904 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18905 (org-support-shift-select
18906 (org-call-for-shift-select 'next-line))
18907 (t (org-shiftselect-error))))
18909 (defun org-shiftright (&optional arg)
18910 "Cycle the thing at point or in the current line, depending on context.
18911 Depending on context, this does one of the following:
18913 - switch a timestamp at point one day into the future
18914 - on a headline, switch to the next TODO keyword.
18915 - on an item, switch entire list to the next bullet type
18916 - on a property line, switch to the next allowed value
18917 - on a clocktable definition line, move time block into the future"
18920 ((run-hook-with-args-until-success 'org-shiftright-hook))
18921 ((and org-support-shift-select (org-region-active-p))
18922 (org-call-for-shift-select 'forward-char))
18923 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18924 ((and (not (eq org-support-shift-select 'always))
18925 (org-at-heading-p))
18926 (let ((org-inhibit-logging
18927 (not org-treat-S-cursor-todo-selection-as-state-change))
18928 (org-inhibit-blocking
18929 (not org-treat-S-cursor-todo-selection-as-state-change)))
18930 (org-call-with-arg 'org-todo 'right)))
18931 ((or (and org-support-shift-select
18932 (not (eq org-support-shift-select 'always))
18933 (org-at-item-bullet-p))
18934 (and (not org-support-shift-select) (org-at-item-p)))
18935 (org-call-with-arg 'org-cycle-list-bullet nil))
18936 ((and (not (eq org-support-shift-select 'always))
18937 (org-at-property-p))
18938 (call-interactively 'org-property-next-allowed-value))
18939 ((org-clocktable-try-shift 'right arg))
18940 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18941 (org-support-shift-select
18942 (org-call-for-shift-select 'forward-char))
18943 (t (org-shiftselect-error))))
18945 (defun org-shiftleft (&optional arg)
18946 "Cycle the thing at point or in the current line, depending on context.
18947 Depending on context, this does one of the following:
18949 - switch a timestamp at point one day into the past
18950 - on a headline, switch to the previous TODO keyword.
18951 - on an item, switch entire list to the previous bullet type
18952 - on a property line, switch to the previous allowed value
18953 - on a clocktable definition line, move time block into the past"
18956 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18957 ((and org-support-shift-select (org-region-active-p))
18958 (org-call-for-shift-select 'backward-char))
18959 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18960 ((and (not (eq org-support-shift-select 'always))
18961 (org-at-heading-p))
18962 (let ((org-inhibit-logging
18963 (not org-treat-S-cursor-todo-selection-as-state-change))
18964 (org-inhibit-blocking
18965 (not org-treat-S-cursor-todo-selection-as-state-change)))
18966 (org-call-with-arg 'org-todo 'left)))
18967 ((or (and org-support-shift-select
18968 (not (eq org-support-shift-select 'always))
18969 (org-at-item-bullet-p))
18970 (and (not org-support-shift-select) (org-at-item-p)))
18971 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18972 ((and (not (eq org-support-shift-select 'always))
18973 (org-at-property-p))
18974 (call-interactively 'org-property-previous-allowed-value))
18975 ((org-clocktable-try-shift 'left arg))
18976 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18977 (org-support-shift-select
18978 (org-call-for-shift-select 'backward-char))
18979 (t (org-shiftselect-error))))
18981 (defun org-shiftcontrolright ()
18982 "Switch to next TODO set."
18985 ((and org-support-shift-select (org-region-active-p))
18986 (org-call-for-shift-select 'forward-word))
18987 ((and (not (eq org-support-shift-select 'always))
18988 (org-at-heading-p))
18989 (org-call-with-arg 'org-todo 'nextset))
18990 (org-support-shift-select
18991 (org-call-for-shift-select 'forward-word))
18992 (t (org-shiftselect-error))))
18994 (defun org-shiftcontrolleft ()
18995 "Switch to previous TODO set."
18998 ((and org-support-shift-select (org-region-active-p))
18999 (org-call-for-shift-select 'backward-word))
19000 ((and (not (eq org-support-shift-select 'always))
19001 (org-at-heading-p))
19002 (org-call-with-arg 'org-todo 'previousset))
19003 (org-support-shift-select
19004 (org-call-for-shift-select 'backward-word))
19005 (t (org-shiftselect-error))))
19007 (defun org-shiftcontrolup ()
19008 "Change timestamps synchronously up in CLOCK log lines."
19010 (cond ((and (not org-support-shift-select)
19011 (org-at-clock-log-p)
19012 (org-at-timestamp-p t))
19013 (org-clock-timestamps-up))
19014 (t (org-shiftselect-error))))
19016 (defun org-shiftcontroldown ()
19017 "Change timestamps synchronously down in CLOCK log lines."
19019 (cond ((and (not org-support-shift-select)
19020 (org-at-clock-log-p)
19021 (org-at-timestamp-p t))
19022 (org-clock-timestamps-down))
19023 (t (org-shiftselect-error))))
19025 (defun org-ctrl-c-ret ()
19026 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19029 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19030 (t (call-interactively 'org-insert-heading))))
19032 (defun org-find-visible ()
19034 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19035 (get-char-property s 'invisible)))
19037 (defun org-find-invisible ()
19039 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19040 (not (get-char-property s 'invisible))))
19043 (defun org-copy-visible (beg end)
19044 "Copy the visible parts of the region."
19049 (narrow-to-region beg end)
19050 (setq s (goto-char (point-min)))
19051 (while (not (= (point) (point-max)))
19052 (goto-char (org-find-invisible))
19053 (push (buffer-substring s (point)) snippets)
19054 (setq s (goto-char (org-find-visible))))))
19055 (kill-new (apply 'concat (nreverse snippets)))))
19057 (defun org-copy-special ()
19058 "Copy region in table or copy current subtree.
19059 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19060 See the individual commands for more information."
19062 (call-interactively
19063 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19065 (defun org-cut-special ()
19066 "Cut region in table or cut current subtree.
19067 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19068 See the individual commands for more information."
19070 (call-interactively
19071 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19073 (defun org-paste-special (arg)
19074 "Paste rectangular region into table, or past subtree relative to level.
19075 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19076 See the individual commands for more information."
19078 (if (org-at-table-p)
19079 (org-table-paste-rectangle)
19080 (org-paste-subtree arg)))
19082 (defun org-edit-special (&optional arg)
19083 "Call a special editor for the stuff at point.
19084 When at a table, call the formula editor with `org-table-edit-formulas'.
19085 When at the first line of an src example, call `org-edit-src-code'.
19086 When in an #+include line, visit the include file. Otherwise call
19087 `ffap' to visit the file at point."
19089 ;; possibly prep session before editing source
19091 (let* ((info (org-babel-get-src-block-info))
19092 (lang (nth 0 info))
19093 (params (nth 2 info))
19094 (session (cdr (assoc :session params))))
19095 (when (and info session) ;; we are in a source-code block with a session
19097 (intern (concat "org-babel-prep-session:" lang)) session params))))
19098 (cond ;; proceed with `org-edit-special'
19100 (beginning-of-line 1)
19101 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19102 (find-file (org-trim (match-string 1))))
19103 ((org-edit-src-code))
19104 ((org-edit-fixed-width-region))
19105 ((org-at-table.el-p)
19106 (org-edit-src-code))
19107 ((or (org-at-table-p)
19109 (beginning-of-line 1)
19110 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19111 (call-interactively 'org-table-edit-formulas))
19112 (t (call-interactively 'ffap))))
19114 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19115 (defun org-ctrl-c-ctrl-c (&optional arg)
19116 "Set tags in headline, or update according to changed information at point.
19118 This command does many different things, depending on context:
19120 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19121 this is what we do.
19123 - If the cursor is on a statistics cookie, update it.
19125 - If the cursor is in a headline, prompt for tags and insert them
19126 into the current line, aligned to `org-tags-column'. When called
19127 with prefix arg, realign all tags in the current buffer.
19129 - If the cursor is in one of the special #+KEYWORD lines, this
19130 triggers scanning the buffer for these lines and updating the
19133 - If the cursor is inside a table, realign the table. This command
19134 works even if the automatic table editor has been turned off.
19136 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19139 - If the cursor is at a footnote reference or definition, jump to
19140 the corresponding definition or references, respectively.
19142 - If the cursor is a the beginning of a dynamic block, update it.
19144 - If the current buffer is a capture buffer, close note and file it.
19146 - If the cursor is on a <<<target>>>, update radio targets and
19147 corresponding links in this buffer.
19149 - If the cursor is on a numbered item in a plain list, renumber the
19152 - If the cursor is on a checkbox, toggle it.
19154 - If the cursor is on a code block, evaluate it. The variable
19155 `org-confirm-babel-evaluate' can be used to control prompting
19156 before code block evaluation, by default every code block
19157 evaluation requires confirmation. Code block evaluation can be
19158 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19160 (let ((org-enable-table-editor t))
19162 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19163 org-occur-highlights
19164 org-latex-fragment-image-overlays)
19165 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19166 (org-remove-occur-highlights)
19167 (org-remove-latex-fragment-image-overlays)
19168 (message "Temporary highlights/overlays removed from current buffer"))
19169 ((and (local-variable-p 'org-finish-function (current-buffer))
19170 (fboundp org-finish-function))
19171 (funcall org-finish-function))
19172 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19173 ((org-in-regexp org-ts-regexp-both)
19174 (org-timestamp-change 0 'day))
19175 ((or (looking-at org-property-start-re)
19176 (org-at-property-p))
19177 (call-interactively 'org-property-action))
19178 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19179 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19180 (or (org-at-heading-p) (org-at-item-p)))
19181 (call-interactively 'org-update-statistics-cookies))
19182 ((org-at-heading-p) (call-interactively 'org-set-tags))
19183 ((org-at-table.el-p)
19184 (message "Use C-c ' to edit table.el tables"))
19186 (org-table-maybe-eval-formula)
19188 (call-interactively 'org-table-recalculate)
19189 (org-table-maybe-recalculate-line))
19190 (call-interactively 'org-table-align)
19191 (orgtbl-send-table 'maybe))
19192 ((or (org-footnote-at-reference-p)
19193 (org-footnote-at-definition-p))
19194 (call-interactively 'org-footnote-action))
19195 ((org-at-item-checkbox-p)
19196 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19197 ;; list only if at top item.
19198 (let* ((cbox (match-string 1))
19199 (struct (org-list-struct))
19200 (old-struct (copy-tree struct))
19201 (parents (org-list-parents-alist struct))
19202 (orderedp (org-entry-get nil "ORDERED"))
19203 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19205 ;; Use a light version of `org-toggle-checkbox' to avoid
19206 ;; computing list structure twice.
19207 (let ((new-box (cond
19208 ((equal arg '(16)) "[-]")
19209 ((equal arg '(4)) nil)
19210 ((equal "[X]" cbox) "[ ]")
19212 (if (and firstp arg)
19213 ;; If at first item of sub-list, remove check-box from
19214 ;; every item at the same level.
19216 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19217 (org-list-get-all-items
19218 (point-at-bol) struct (org-list-prevs-alist struct)))
19219 (org-list-set-checkbox (point-at-bol) struct new-box)))
19220 ;; Replicate `org-list-write-struct', while grabbing a return
19221 ;; value from `org-list-struct-fix-box'.
19222 (org-list-struct-fix-ind struct parents 2)
19223 (org-list-struct-fix-item-end struct)
19224 (let ((prevs (org-list-prevs-alist struct)))
19225 (org-list-struct-fix-bul struct prevs)
19226 (org-list-struct-fix-ind struct parents)
19228 (org-list-struct-fix-box struct parents prevs orderedp)))
19229 (org-list-struct-apply-struct struct old-struct)
19230 (org-update-checkbox-count-maybe)
19233 "Checkboxes were removed due to unchecked box at line %d"
19234 (org-current-line block-item)))
19235 (when firstp (org-list-send-list 'maybe))))
19237 ;; Cursor at an item: repair list. Do checkbox related actions
19238 ;; only if function was called with an argument. Send list only
19240 (let* ((struct (org-list-struct))
19241 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19244 (setq old-struct (copy-tree struct))
19246 ;; If at first item of sub-list, add check-box to every
19247 ;; item at the same level.
19250 (unless (org-list-get-checkbox pos struct)
19251 (org-list-set-checkbox pos struct "[ ]")))
19252 (org-list-get-all-items
19253 (point-at-bol) struct (org-list-prevs-alist struct)))
19254 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19255 (org-list-write-struct
19256 struct (org-list-parents-alist struct) old-struct)
19257 (when arg (org-update-checkbox-count-maybe))
19258 (when firstp (org-list-send-list 'maybe))))
19259 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19261 (beginning-of-line 1)
19262 (save-excursion (org-update-dblock)))
19264 (let ((case-fold-search t))
19265 (beginning-of-line 1)
19266 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19268 ((or (equal (match-string 1) "TBLFM")
19269 (equal (match-string 1) "tblfm"))
19270 ;; Recalculate the table before this line
19272 (beginning-of-line 1)
19273 (skip-chars-backward " \r\n\t")
19274 (if (org-at-table-p)
19275 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19277 (let ((org-inhibit-startup-visibility-stuff t)
19278 (org-startup-align-all-tables nil))
19279 (when (boundp 'org-table-coordinate-overlays)
19280 (mapc 'delete-overlay org-table-coordinate-overlays)
19281 (setq org-table-coordinate-overlays nil))
19282 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19283 (message "Local setup has been refreshed"))))
19284 ((org-clock-update-time-maybe))
19286 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19287 (error "C-c C-c can do nothing useful at this location"))))))
19289 (defun org-mode-restart ()
19290 "Restart Org-mode, to scan again for special lines.
19291 Also updates the keyword regular expressions."
19294 (message "Org-mode restarted"))
19296 (defun org-kill-note-or-show-branches ()
19297 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19299 (if (not org-finish-function)
19302 (call-interactively 'show-branches))
19303 (let ((org-note-abort t))
19304 (funcall org-finish-function))))
19306 (defun org-return (&optional indent)
19307 "Goto next table row or insert a newline.
19308 Calls `org-table-next-row' or `newline', depending on context.
19309 See the individual commands for more information."
19313 ((or (bobp) (org-in-src-block-p))
19314 (if indent (newline-and-indent) (newline)))
19316 (org-table-justify-field-maybe)
19317 (call-interactively 'org-table-next-row))
19318 ;; when `newline-and-indent' is called within a list, make sure
19319 ;; text moved stays inside the item.
19320 ((and (org-in-item-p) indent)
19321 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19323 (save-match-data (newline))
19324 (org-indent-line-to (length (match-string 0))))
19325 (let ((ind (org-get-indentation)))
19327 (if (org-looking-back org-list-end-re)
19329 (org-indent-line-to ind)))))
19330 ((and org-return-follows-link
19331 (org-at-timestamp-p t)
19332 (not (eq org-ts-what 'after)))
19333 (org-follow-timestamp-link))
19334 ((and org-return-follows-link
19335 (let ((tprop (get-text-property (point) 'face)))
19336 (or (eq tprop 'org-link)
19337 (and (listp tprop) (memq 'org-link tprop)))))
19338 (call-interactively 'org-open-at-point))
19339 ((and (org-at-heading-p)
19341 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19345 (t (if indent (newline-and-indent) (newline))))))
19347 (defun org-return-indent ()
19348 "Goto next table row or insert a newline and indent.
19349 Calls `org-table-next-row' or `newline-and-indent', depending on
19350 context. See the individual commands for more information."
19354 (defun org-ctrl-c-star ()
19355 "Compute table, or change heading status of lines.
19356 Calls `org-table-recalculate' or `org-toggle-heading',
19357 depending on context."
19361 (call-interactively 'org-table-recalculate))
19363 ;; Convert all lines in region to list items
19364 (call-interactively 'org-toggle-heading))))
19366 (defun org-ctrl-c-minus ()
19367 "Insert separator line in table or modify bullet status of line.
19368 Also turns a plain line or a region of lines into list items.
19369 Calls `org-table-insert-hline', `org-toggle-item', or
19370 `org-cycle-list-bullet', depending on context."
19374 (call-interactively 'org-table-insert-hline))
19375 ((org-region-active-p)
19376 (call-interactively 'org-toggle-item))
19378 (call-interactively 'org-cycle-list-bullet))
19380 (call-interactively 'org-toggle-item))))
19382 (defun org-toggle-item (arg)
19383 "Convert headings or normal lines to items, items to normal lines.
19384 If there is no active region, only the current line is considered.
19386 If the first non blank line in the region is an headline, convert
19387 all headlines to items, shifting text accordingly.
19389 If it is an item, convert all items to normal lines.
19391 If it is normal text, change region into an item. With a prefix
19392 argument ARG, change each line in region into an item."
19396 ;; Shift text in current section to IND, from point to END.
19397 ;; The function leaves point to END line.
19399 (let ((min-i 1000) (end (copy-marker end)))
19400 ;; First determine the minimum indentation (MIN-I) of
19404 (while (< (point) end)
19405 (let ((i (org-get-indentation)))
19407 ;; Skip blank lines and inline tasks.
19408 ((looking-at "^[ \t]*$"))
19409 ((looking-at org-outline-regexp-bol))
19410 ;; We can't find less than 0 indentation.
19411 ((zerop i) (throw 'exit (setq min-i 0)))
19412 ((< i min-i) (setq min-i i))))
19414 ;; Then indent each line so that a line indented to
19415 ;; MIN-I becomes indented to IND. Ignore blank lines
19416 ;; and inline tasks in the process.
19417 (let ((delta (- ind min-i)))
19418 (while (< (point) end)
19419 (unless (or (looking-at "^[ \t]*$")
19420 (looking-at org-outline-regexp-bol))
19421 (org-indent-line-to (+ (org-get-indentation) delta)))
19422 (forward-line)))))))
19425 ;; Return beginning of first non-blank line, starting from
19430 (skip-chars-forward " \r\t\n")
19433 ;; Determine boundaries of changes.
19434 (if (org-region-active-p)
19435 (setq beg (funcall skip-blanks (region-beginning))
19436 end (copy-marker (region-end)))
19437 (setq beg (funcall skip-blanks (point-at-bol))
19438 end (copy-marker (point-at-eol))))
19439 ;; Depending on the starting line, choose an action on the text
19440 ;; between BEG and END.
19441 (org-with-limited-levels
19445 ;; Case 1. Start at an item: de-itemize. Note that it only
19446 ;; happens when a region is active: `org-ctrl-c-minus'
19447 ;; would call `org-cycle-list-bullet' otherwise.
19449 (while (< (point) end)
19450 (when (org-at-item-p)
19451 (skip-chars-forward " \t")
19452 (delete-region (point) (match-end 0)))
19454 ;; Case 2. Start at an heading: convert to items.
19455 ((org-at-heading-p)
19456 (let* ((bul (org-list-bullet-string "-"))
19457 (bul-len (length bul))
19458 ;; Indentation of the first heading. It should be
19459 ;; relative to the indentation of its parent, if any.
19460 (start-ind (save-excursion
19462 ((not org-adapt-indentation) 0)
19463 ((not (outline-previous-heading)) 0)
19464 (t (length (match-string 0))))))
19465 ;; Level of first heading. Further headings will be
19466 ;; compared to it to determine hierarchy in the list.
19467 (ref-level (org-reduced-level (org-outline-level))))
19468 (while (< (point) end)
19469 (let* ((level (org-reduced-level (org-outline-level)))
19470 (delta (max 0 (- level ref-level))))
19471 ;; If current headline is less indented than the first
19472 ;; one, set it as reference, in order to preserve
19474 (when (< level ref-level) (setq ref-level level))
19475 (replace-match bul t t)
19476 (org-indent-line-to (+ start-ind (* delta bul-len)))
19477 ;; Ensure all text down to END (or SECTION-END) belongs
19478 ;; to the newly created item.
19479 (let ((section-end (save-excursion
19480 (or (outline-next-heading) (point)))))
19482 (funcall shift-text
19483 (+ start-ind (* (1+ delta) bul-len))
19484 (min end section-end)))))))
19485 ;; Case 3. Normal line with ARG: turn each non-item line into
19488 (while (< (point) end)
19489 (unless (or (org-at-heading-p) (org-at-item-p))
19490 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19492 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19494 ;; Case 4. Normal line without ARG: make the first line of
19495 ;; region an item, and shift indentation of others
19496 ;; lines to set them as item's body.
19497 (t (let* ((bul (org-list-bullet-string "-"))
19498 (bul-len (length bul))
19499 (ref-ind (org-get-indentation)))
19500 (skip-chars-forward " \t")
19503 (while (< (point) end)
19504 ;; Ensure that lines less indented than first one
19505 ;; still get included in item body.
19506 (funcall shift-text
19507 (+ ref-ind bul-len)
19508 (min end (save-excursion (or (outline-next-heading)
19510 (forward-line)))))))))
19512 (defun org-toggle-heading (&optional nstars)
19513 "Convert headings to normal text, or items or text to headings.
19514 If there is no active region, only the current line is considered.
19516 With a \\[universal-argument] prefix, convert the whole list at
19517 point into heading.
19521 - If the first non blank line is an headline, remove the stars
19522 from all headlines in the region.
19524 - If it is a normal line turn each and every normal line (i.e. not an
19525 heading or an item) in the region into a heading.
19527 - If it is a plain list item, turn all plain list items into headings.
19529 When converting a line into a heading, the number of stars is chosen
19530 such that the lines become children of the current entry. However,
19531 when a prefix argument is given, its value determines the number of
19536 ;; Return beginning of first non-blank line, starting from
19541 (while (org-at-comment-p) (forward-line))
19542 (skip-chars-forward " \r\t\n")
19545 ;; Determine boundaries of changes. If a universal prefix has
19546 ;; been given, put the list in a region. If region ends at a bol,
19547 ;; do not consider the last line to be in the region.
19549 (when (and current-prefix-arg (org-at-item-p))
19550 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19551 (org-mark-element))
19553 (if (org-region-active-p)
19554 (setq beg (funcall skip-blanks (region-beginning))
19555 end (copy-marker (save-excursion
19556 (goto-char (region-end))
19557 (if (bolp) (point) (point-at-eol)))))
19558 (setq beg (funcall skip-blanks (point-at-bol))
19559 end (copy-marker (point-at-eol))))
19560 ;; Ensure inline tasks don't count as headings.
19561 (org-with-limited-levels
19565 ;; Case 1. Started at an heading: de-star headings.
19566 ((org-at-heading-p)
19567 (while (< (point) end)
19568 (when (org-at-heading-p t)
19569 (looking-at org-outline-regexp) (replace-match "")
19572 ;; Case 2. Started at an item: change items into headlines.
19573 ;; One star will be added by `org-list-to-subtree'.
19575 (let* ((stars (make-string
19577 ;; subtract the star that will be added again by
19578 ;; `org-list-to-subtree'
19579 (1- (prefix-numeric-value current-prefix-arg))
19580 (or (org-current-level) 0))
19583 (cond (nstars "") ; stars from prefix only
19584 ((equal stars "") "") ; before first heading
19585 (org-odd-levels-only "*") ; inside heading, odd
19586 (t "")))) ; inside heading, oddeven
19587 (while (< (point) end)
19588 (when (org-at-item-p)
19589 ;; Pay attention to cases when region ends before list.
19590 (let* ((struct (org-list-struct))
19591 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19593 (narrow-to-region (point) list-end)
19595 (org-list-to-subtree
19596 (org-list-parse-list t)
19597 '(:istart (concat stars add-stars (funcall get-stars depth))
19598 :icount (concat stars add-stars (funcall get-stars depth)))))))
19601 ;; Case 3. Started at normal text: make every line an heading,
19602 ;; skipping headlines and items.
19603 (t (let* ((stars (make-string
19605 (prefix-numeric-value current-prefix-arg)
19606 (or (org-current-level) 0))
19609 (cond (nstars "") ; stars from prefix only
19610 ((equal stars "") "*") ; before first heading
19611 (org-odd-levels-only "**") ; inside heading, odd
19612 (t "*"))) ; inside heading, oddeven
19613 (rpl (concat stars add-stars " ")))
19614 (while (< (point) end)
19615 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19616 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19617 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19618 (forward-line)))))))
19619 (unless toggled (message "Cannot toggle heading from here"))))
19621 (defun org-meta-return (&optional arg)
19622 "Insert a new heading or wrap a region in a table.
19623 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19624 See the individual commands for more information."
19627 ((run-hook-with-args-until-success 'org-metareturn-hook))
19628 ((or (org-at-drawer-p) (org-at-property-p))
19629 (newline-and-indent))
19631 (call-interactively 'org-table-wrap-region))
19632 (t (call-interactively 'org-insert-heading))))
19636 (defsubst org-in-subtree-not-table-p ()
19637 "Are we in a subtree and not in a table?"
19638 (and (not (org-before-first-heading-p))
19639 (not (org-at-table-p))))
19641 ;; Define the Org-mode menus
19642 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19644 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19645 ["Next Field" org-cycle (org-at-table-p)]
19646 ["Previous Field" org-shifttab (org-at-table-p)]
19647 ["Next Row" org-return (org-at-table-p)]
19649 ["Blank Field" org-table-blank-field (org-at-table-p)]
19650 ["Edit Field" org-table-edit-field (org-at-table-p)]
19651 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19654 ["Move Column Left" org-metaleft (org-at-table-p)]
19655 ["Move Column Right" org-metaright (org-at-table-p)]
19656 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19657 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19659 ["Move Row Up" org-metaup (org-at-table-p)]
19660 ["Move Row Down" org-metadown (org-at-table-p)]
19661 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19662 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19663 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19665 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19667 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19668 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19669 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19670 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19673 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19674 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19675 ["Edit Formulas" org-edit-special (org-at-table-p)]
19677 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19678 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19679 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19681 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19683 ["Sum Column/Rectangle" org-table-sum
19684 (or (org-at-table-p) (org-region-active-p))]
19685 ["Which Column?" org-table-current-column (org-at-table-p)])
19687 org-table-toggle-formula-debugger
19688 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19689 ["Show Col/Row Numbers"
19690 org-table-toggle-coordinate-overlays
19692 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19694 ["Create" org-table-create (and (not (org-at-table-p))
19695 org-enable-table-editor)]
19696 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19697 ["Import from File" org-table-import (not (org-at-table-p))]
19698 ["Export to File" org-table-export (org-at-table-p)]
19700 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19702 (easy-menu-define org-org-menu org-mode-map "Org menu"
19705 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19706 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19707 ["Sparse Tree..." org-sparse-tree t]
19708 ["Reveal Context" org-reveal t]
19709 ["Show All" show-all t]
19711 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19713 ["New Heading" org-insert-heading t]
19714 ("Navigate Headings"
19715 ["Up" outline-up-heading t]
19716 ["Next" outline-next-visible-heading t]
19717 ["Previous" outline-previous-visible-heading t]
19718 ["Next Same Level" outline-forward-same-level t]
19719 ["Previous Same Level" outline-backward-same-level t]
19721 ["Jump" org-goto t])
19723 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19725 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19726 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19728 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19729 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19730 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19732 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19734 ["Copy visible text" org-copy-visible t]
19736 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19737 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19738 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19739 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19741 ["Sort Region/Children" org-sort t]
19743 ["Convert to odd levels" org-convert-to-odd-levels t]
19744 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19746 ["Emphasis..." org-emphasize t]
19747 ["Edit Source Example" org-edit-special t]
19749 ["Footnote new/jump" org-footnote-action t]
19750 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19752 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19754 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19755 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19756 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19760 ["Store Link (Global)" org-store-link t]
19761 ["Find existing link to here" org-occur-link-in-agenda-files t]
19762 ["Insert Link" org-insert-link t]
19763 ["Follow Link" org-open-at-point t]
19765 ["Next link" org-next-link t]
19766 ["Previous link" org-previous-link t]
19768 ["Descriptive Links"
19769 org-toggle-link-display
19771 :selected org-descriptive-links
19774 org-toggle-link-display
19776 :selected (not org-descriptive-links)])
19779 ["TODO/DONE/-" org-todo t]
19781 ["Next keyword" org-shiftright (org-at-heading-p)]
19782 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19783 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19784 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19785 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19786 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19787 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19789 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19790 :selected org-enforce-todo-dependencies :style toggle :active t]
19791 "Settings for tree at point"
19792 ["Do Children sequentially" org-toggle-ordered-property :style radio
19793 :selected (org-entry-get nil "ORDERED")
19794 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19795 ["Do Children parallel" org-toggle-ordered-property :style radio
19796 :selected (not (org-entry-get nil "ORDERED"))
19797 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19799 ["Set Priority" org-priority t]
19800 ["Priority Up" org-shiftup t]
19801 ["Priority Down" org-shiftdown t]
19803 ["Get news from all feeds" org-feed-update-all t]
19804 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19805 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19806 ("TAGS and Properties"
19807 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19808 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19810 ["Set property" org-set-property (not (org-before-first-heading-p))]
19811 ["Column view of properties" org-columns t]
19812 ["Insert Column View DBlock" org-insert-columns-dblock t])
19813 ("Dates and Scheduling"
19814 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19815 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19817 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19818 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19819 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19820 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19821 ["Compute Time Range" org-evaluate-time-range t]
19822 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19823 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19825 ["Custom time format" org-toggle-time-stamp-overlays
19826 :style radio :selected org-display-custom-times]
19828 ["Goto Calendar" org-goto-calendar t]
19829 ["Date from Calendar" org-date-from-calendar t]
19831 ["Start/Restart Timer" org-timer-start t]
19832 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19833 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19834 ["Insert Timer String" org-timer t]
19835 ["Insert Timer Item" org-timer-item t])
19837 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19838 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19839 ["Clock out" org-clock-out t]
19840 ["Clock cancel" org-clock-cancel t]
19842 ["Mark as default task" org-clock-mark-default-task t]
19843 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19844 ["Goto running clock" org-clock-goto t]
19846 ["Display times" org-clock-display t]
19847 ["Create clock table" org-clock-report t]
19849 ["Record DONE time"
19850 (progn (setq org-log-done (not org-log-done))
19851 (message "Switching to %s will %s record a timestamp"
19852 (car org-done-keywords)
19853 (if org-log-done "automatically" "not")))
19854 :style toggle :selected org-log-done])
19856 ["Agenda Command..." org-agenda t]
19857 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19858 ("File List for Agenda")
19859 ("Special views current file"
19860 ["TODO Tree" org-show-todo-tree t]
19861 ["Check Deadlines" org-check-deadlines t]
19862 ["Timeline" org-timeline t]
19863 ["Tags/Property tree" org-match-sparse-tree t])
19865 ["Export/Publish..." org-export t]
19867 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19868 :selected org-cdlatex-mode]
19869 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19870 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19871 ["Modify math symbol" org-cdlatex-math-modify
19872 (org-inside-LaTeX-fragment-p)]
19873 ["Insert citation" org-reftex-citation t]
19875 ["Template for BEAMER" (progn (require 'org-beamer)
19876 (org-insert-beamer-options-template)) t])
19879 ["Push Files and Views" org-mobile-push t]
19880 ["Get Captured and Flagged" org-mobile-pull t]
19881 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19883 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19886 ["Show Version" org-version t]
19887 ["Info Documentation" org-info t])
19889 ["Browse Org Group" org-customize t]
19891 ["Expand This Menu" org-create-customize-menu
19892 (fboundp 'customize-menu-create)])
19893 ["Send bug report" org-submit-bug-report t]
19896 ["Refresh setup current buffer" org-mode-restart t]
19897 ["Reload Org (after update)" org-reload t]
19898 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19901 (defun org-info (&optional node)
19902 "Read documentation for Org-mode in the info system.
19903 With optional NODE, go directly to that node."
19905 (info (format "(org)%s" (or node ""))))
19908 (defun org-submit-bug-report ()
19909 "Submit a bug report on Org-mode via mail.
19911 Don't hesitate to report any problems or inaccurate documentation.
19913 If you don't have setup sending mail from (X)Emacs, please copy the
19914 output buffer into your mail program, as it gives us important
19915 information about your Org-mode version and configuration."
19917 (require 'reporter)
19918 (org-load-modules-maybe)
19919 (org-require-autoloaded-modules)
19920 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19921 (reporter-submit-bug-report
19922 "emacs-orgmode@gnu.org"
19923 (org-version nil 'full)
19925 (save-window-excursion
19926 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19927 (delete-other-windows)
19929 (insert "You are about to submit a bug report to the Org-mode mailing list.
19931 We would like to add your full Org-mode and Outline configuration to the
19932 bug report. This greatly simplifies the work of the maintainer and
19933 other experts on the mailing list.
19935 HOWEVER, some variables you have customized may contain private
19936 information. The names of customers, colleagues, or friends, might
19937 appear in the form of file names, tags, todo states, or search strings.
19938 If you answer yes to the prompt, you might want to check and remove
19939 such private information before sending the email.")
19940 (add-text-properties (point-min) (point-max) '(face org-warning))
19941 (when (yes-or-no-p "Include your Org-mode configuration ")
19945 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19946 (or (and (symbol-value v)
19947 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19949 (get v 'custom-type) (get v 'standard-value)
19950 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19952 (kill-buffer (get-buffer "*Warn about privacy*"))
19955 "Remember to cover the basics, that is, what you expected to happen and
19956 what in fact did happen. You don't know how to make a good report? See
19958 http://orgmode.org/manual/Feedback.html#Feedback
19960 Your bug report will be posted to the Org-mode mailing list.
19961 ------------------------------------------------------------------------")
19963 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19964 (replace-match "\\1Bug: \\3 [\\2]")))))
19967 (defun org-install-agenda-files-menu ()
19968 (let ((bl (buffer-list)))
19971 (set-buffer (pop bl))
19972 (if (derived-mode-p 'org-mode) (setq bl nil)))
19973 (when (derived-mode-p 'org-mode)
19975 '("Org") "File List for Agenda"
19978 ["Edit File List" (org-edit-agenda-file-list) t]
19979 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19980 ["Remove Current File from List" org-remove-file t]
19981 ["Cycle through agenda files" org-cycle-agenda-files t]
19982 ["Occur in all agenda files" org-occur-in-agenda-files t]
19984 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19989 (defun org-require-autoloaded-modules ()
19992 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19993 org-docbook org-exp org-html org-icalendar
19995 org-publish org-remember org-table
19996 org-timer org-xoxo)))
19999 (defun org-reload (&optional uncompiled)
20000 "Reload all org lisp files.
20001 With prefix arg UNCOMPILED, load the uncompiled versions."
20003 (require 'find-func)
20004 (let* ((file-re "^org\\(-.*\\)?\\.el")
20005 (dir-org (file-name-directory (org-find-library-dir "org")))
20006 (dir-org-contrib (ignore-errors
20007 (file-name-directory
20008 (org-find-library-dir "org-contribdir"))))
20010 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
20011 (append (list nil "comint" "eval" "exp" "keys"
20012 "lob" "ref" "table" "tangle")
20016 (when (cdr lang) (symbol-name (car lang))))
20017 org-babel-load-languages)))))
20019 (append babel-files
20020 (and dir-org-contrib
20021 (directory-files dir-org-contrib t file-re))
20022 (directory-files dir-org t file-re)))
20023 (remove-re (concat (if (featurep 'xemacs)
20024 "org-colview" "org-colview-xemacs")
20026 (setq files (mapcar 'file-name-sans-extension files))
20027 (setq files (mapcar
20028 (lambda (x) (if (string-match remove-re x) nil x))
20030 (setq files (delq nil files))
20033 (when (featurep (intern (file-name-nondirectory f)))
20034 (if (and (not uncompiled)
20035 (file-exists-p (concat f ".elc")))
20036 (load (concat f ".elc") nil nil 'nosuffix)
20037 (load (concat f ".el") nil nil 'nosuffix))))
20039 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
20040 (org-version nil 'full 'message))
20043 (defun org-customize ()
20044 "Call the customize function with org as argument."
20046 (org-load-modules-maybe)
20047 (org-require-autoloaded-modules)
20048 (customize-browse 'org))
20050 (defun org-create-customize-menu ()
20051 "Create a full customization menu for Org-mode, insert it into the menu."
20053 (org-load-modules-maybe)
20054 (org-require-autoloaded-modules)
20055 (if (fboundp 'customize-menu-create)
20058 '("Org") "Customize"
20059 `(["Browse Org group" org-customize t]
20061 ,(customize-menu-create 'org)
20062 ["Set" Custom-set t]
20063 ["Save" Custom-save t]
20064 ["Reset to Current" Custom-reset-current t]
20065 ["Reset to Saved" Custom-reset-saved t]
20066 ["Reset to Standard Settings" Custom-reset-standard t]))
20067 (message "\"Org\"-menu now contains full customization menu"))
20068 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20070 ;;;; Miscellaneous stuff
20072 ;;; Generally useful functions
20074 (defun org-get-at-bol (property)
20075 "Get text property PROPERTY at beginning of line."
20076 (get-text-property (point-at-bol) property))
20078 (defun org-find-text-property-in-string (prop s)
20079 "Return the first non-nil value of property PROP in string S."
20080 (or (get-text-property 0 prop s)
20081 (get-text-property (or (next-single-property-change 0 prop s) 0)
20084 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20085 "Display the given MESSAGE as a warning."
20086 (if (fboundp 'display-warning)
20087 (display-warning 'org message
20088 (if (featurep 'xemacs) 'warning :warning))
20089 (let ((buf (get-buffer-create "*Org warnings*")))
20090 (with-current-buffer buf
20091 (goto-char (point-max))
20092 (insert "Warning (Org): " message)
20095 (display-buffer buf)
20098 (defun org-eval (form)
20099 "Eval FORM and return result."
20100 (condition-case error
20102 (error (format "%%![Error: %s]" error))))
20104 (defun org-in-clocktable-p ()
20105 "Check if the cursor is in a clocktable."
20106 (let ((pos (point)) start)
20109 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20110 (setq start (match-beginning 0))
20111 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20112 (>= (match-end 0) pos)
20115 (defun org-in-commented-line ()
20116 "Is point in a line starting with `#'?"
20117 (equal (char-after (point-at-bol)) ?#))
20119 (defun org-in-indented-comment-line ()
20120 "Is point in a line starting with `#' after some white space?"
20123 (goto-char (point-at-bol))
20124 (looking-at "[ \t]*#"))))
20126 (defun org-in-verbatim-emphasis ()
20128 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20130 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20131 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20132 (if (and marker (marker-buffer marker)
20133 (buffer-live-p (marker-buffer marker)))
20135 (org-pop-to-buffer-same-window (marker-buffer marker))
20136 (if (or (> marker (point-max)) (< marker (point-min)))
20139 (org-show-context 'org-goto))
20141 (bookmark-jump bookmark)
20142 (error "Cannot find location"))))
20144 (defun org-quote-csv-field (s)
20145 "Quote field for inclusion in CSV material."
20146 (if (string-match "[\",]" s)
20147 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20150 (defun org-force-self-insert (N)
20151 "Needed to enforce self-insert under remapping."
20153 (self-insert-command N))
20155 (defun org-string-width (s)
20156 "Compute width of string, ignoring invisible characters.
20157 This ignores character with invisibility property `org-link', and also
20158 characters with property `org-cwidth', because these will become invisible
20159 upon the next fontification round."
20161 (when (or (eq t buffer-invisibility-spec)
20162 (assq 'org-link buffer-invisibility-spec))
20163 (while (setq b (text-property-any 0 (length s)
20164 'invisible 'org-link s))
20165 (setq s (concat (substring s 0 b)
20166 (substring s (or (next-single-property-change
20167 b 'invisible s) (length s)))))))
20168 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20169 (setq s (concat (substring s 0 b)
20170 (substring s (or (next-single-property-change
20171 b 'org-cwidth s) (length s))))))
20172 (setq l (string-width s) b -1)
20173 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20174 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20177 (defun org-shorten-string (s maxlength)
20178 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20179 If the string is shorter or has length MAXLENGTH, just return the
20180 original string. If it is longer, the functions finds a space in the
20181 string, breaks this string off at that locations and adds three dots
20182 as ellipsis. Including the ellipsis, the string will not be longer
20183 than MAXLENGTH. If finding a good breaking point in the string does
20184 not work, the string is just chopped off in the middle of a word
20186 (if (<= (length s) maxlength)
20188 (let* ((n (max (- maxlength 4) 1))
20189 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20190 (if (string-match re s)
20191 (concat (match-string 1 s) "...")
20192 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20194 (defun org-get-indentation (&optional line)
20195 "Get the indentation of the current line, interpreting tabs.
20196 When LINE is given, assume it represents a line and compute its indentation."
20198 (if (string-match "^ *" (org-remove-tabs line))
20201 (beginning-of-line 1)
20202 (skip-chars-forward " \t")
20203 (current-column))))
20205 (defun org-get-string-indentation (s)
20206 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20207 (let ((n -1) (i 0) (w tab-width) c)
20209 (while (< (setq n (1+ n)) (length s))
20210 (setq c (aref s n))
20211 (cond ((= c ?\ ) (setq i (1+ i)))
20212 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20213 (t (throw 'exit t)))))
20216 (defun org-remove-tabs (s &optional width)
20217 "Replace tabulators in S with spaces.
20218 Assumes that s is a single line, starting in column 0."
20219 (setq width (or width tab-width))
20220 (while (string-match "\t" s)
20221 (setq s (replace-match
20223 (- (* width (/ (+ (match-beginning 0) width) width))
20224 (match-beginning 0)) ?\ )
20228 (defun org-fix-indentation (line ind)
20229 "Fix indentation in LINE.
20230 IND is a cons cell with target and minimum indentation.
20231 If the current indentation in LINE is smaller than the minimum,
20232 leave it alone. If it is larger than ind, set it to the target."
20233 (let* ((l (org-remove-tabs line))
20234 (i (org-get-indentation l))
20235 (i1 (car ind)) (i2 (cdr ind)))
20236 (if (>= i i2) (setq l (substring line i2)))
20238 (concat (make-string i1 ?\ ) l)
20241 (defun org-remove-indentation (code &optional n)
20242 "Remove the maximum common indentation from the lines in CODE.
20243 N may optionally be the number of spaces to remove."
20246 (org-do-remove-indentation n)
20249 (defun org-do-remove-indentation (&optional n)
20250 "Remove the maximum common indentation from the buffer."
20251 (untabify (point-min) (point-max))
20252 (let ((min 10000) re)
20255 (goto-char (point-min))
20256 (while (re-search-forward "^ *[^ \n]" nil t)
20257 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20258 (unless (or (= min 0) (= min 10000))
20259 (setq re (format "^ \\{%d\\}" min))
20260 (goto-char (point-min))
20261 (while (re-search-forward re nil t)
20266 (defun org-fill-template (template alist)
20267 "Find each %key of ALIST in TEMPLATE and replace it."
20268 (let ((case-fold-search nil)
20270 (setq alist (sort (copy-sequence alist)
20271 (lambda (a b) (< (length (car a)) (length (car b))))))
20272 (while (setq entry (pop alist))
20274 (replace-regexp-in-string
20275 (concat "%" (regexp-quote (car entry)))
20276 (or (cdr entry) "") template t t)))
20279 (defun org-base-buffer (buffer)
20280 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20283 (or (buffer-base-buffer buffer)
20286 (defun org-trim (s)
20287 "Remove whitespace at beginning and end of string."
20288 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20289 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20292 (defun org-wrap (string &optional width lines)
20293 "Wrap string to either a number of lines, or a width in characters.
20294 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20295 that costs. If there is a word longer than WIDTH, the text is actually
20296 wrapped to the length of that word.
20297 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20298 many lines, whatever width that takes.
20299 The return value is a list of lines, without newlines at the end."
20300 (let* ((words (org-split-string string "[ \t\n]+"))
20301 (maxword (apply 'max (mapcar 'org-string-width words)))
20304 (org-do-wrap words (max maxword width)))
20307 (setq ll (org-do-wrap words maxword))
20308 (if (<= (length ll) lines)
20311 (while (> (length ll) lines)
20313 (setq ll (org-do-wrap words w)))
20315 (t (error "Cannot wrap this")))))
20317 (defun org-do-wrap (words width)
20318 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20321 (setq line (pop words))
20322 (while (and words (< (+ (length line) (length (car words))) width))
20323 (setq line (concat line " " (pop words))))
20324 (setq lines (push line lines)))
20327 (defun org-split-string (string &optional separators)
20328 "Splits STRING into substrings at SEPARATORS.
20329 No empty strings are returned if there are matches at the beginning
20330 and end of string."
20331 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20335 (while (and (string-match rexp string
20337 (= start (match-beginning 0))
20338 (< start (length string)))
20340 (< (match-beginning 0) (length string)))
20342 (or (eq (match-beginning 0) 0)
20343 (and (eq (match-beginning 0) (match-end 0))
20344 (eq (match-beginning 0) start))
20346 (cons (substring string start (match-beginning 0))
20348 (setq start (match-end 0)))
20349 (or (eq start (length string))
20351 (cons (substring string start)
20355 (defun org-quote-vert (s)
20356 "Replace \"|\" with \"\\vert\"."
20357 (while (string-match "|" s)
20358 (setq s (replace-match "\\vert" t t s)))
20361 (defun org-uuidgen-p (s)
20362 "Is S an ID created by UUIDGEN?"
20363 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20365 (defun org-in-src-block-p nil
20366 "Whether point is in a code source block."
20368 (when (setq ov (overlays-at (point)))
20369 (memq 'org-block-background
20370 (overlay-properties
20373 (defun org-context ()
20374 "Return a list of contexts of the current cursor position.
20375 If several contexts apply, all are returned.
20376 Each context entry is a list with a symbol naming the context, and
20377 two positions indicating start and end of the context. Possible
20380 :headline anywhere in a headline
20381 :headline-stars on the leading stars in a headline
20382 :todo-keyword on a TODO keyword (including DONE) in a headline
20383 :tags on the TAGS in a headline
20384 :priority on the priority cookie in a headline
20385 :item on the first line of a plain list item
20386 :item-bullet on the bullet/number of a plain list item
20387 :checkbox on the checkbox in a plain list item
20388 :table in an org-mode table
20389 :table-special on a special filed in a table
20390 :table-table in a table.el table
20391 :clocktable in a clocktable
20392 :src-block in a source block
20393 :link on a hyperlink
20394 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20395 :target on a <<target>>
20396 :radio-target on a <<<radio-target>>>
20397 :latex-fragment on a LaTeX fragment
20398 :latex-preview on a LaTeX fragment with overlaid preview image
20400 This function expects the position to be visible because it uses font-lock
20401 faces as a help to recognize the following contexts: :table-special, :link,
20403 (let* ((f (get-text-property (point) 'face))
20404 (faces (if (listp f) f (list f)))
20405 (case-fold-search t)
20406 (p (point)) clist o)
20407 ;; First the large context
20409 ((org-at-heading-p t)
20410 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20412 (beginning-of-line 1)
20413 (looking-at org-todo-line-tags-regexp))
20414 (push (org-point-in-group p 1 :headline-stars) clist)
20415 (push (org-point-in-group p 2 :todo-keyword) clist)
20416 (push (org-point-in-group p 4 :tags) clist))
20418 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20419 (if (looking-at "\\[#[A-Z0-9]\\]")
20420 (push (org-point-in-group p 0 :priority) clist)))
20423 (push (org-point-in-group p 2 :item-bullet) clist)
20424 (push (list :item (point-at-bol)
20425 (save-excursion (org-end-of-item) (point)))
20427 (and (org-at-item-checkbox-p)
20428 (push (org-point-in-group p 0 :checkbox) clist)))
20431 (push (list :table (org-table-begin) (org-table-end)) clist)
20432 (if (memq 'org-formula faces)
20433 (push (list :table-special
20434 (previous-single-property-change p 'face)
20435 (next-single-property-change p 'face)) clist)))
20436 ((org-at-table-p 'any)
20437 (push (list :table-table) clist)))
20440 (let ((case-fold-search t))
20441 ;; New the "medium" contexts: clocktables, source blocks
20442 (cond ((org-in-clocktable-p)
20443 (push (list :clocktable
20444 (and (or (looking-at "#\\+BEGIN: clocktable")
20445 (search-backward "#+BEGIN: clocktable" nil t))
20446 (match-beginning 0))
20447 (and (re-search-forward "#\\+END:?" nil t)
20448 (match-end 0))) clist))
20449 ((org-in-src-block-p)
20450 (push (list :src-block
20451 (and (or (looking-at "#\\+BEGIN_SRC")
20452 (search-backward "#+BEGIN_SRC" nil t))
20453 (match-beginning 0))
20454 (and (search-forward "#+END_SRC" nil t)
20455 (match-beginning 0))) clist))))
20458 ;; Now the small context
20460 ((org-at-timestamp-p)
20461 (push (org-point-in-group p 0 :timestamp) clist))
20462 ((memq 'org-link faces)
20464 (previous-single-property-change p 'face)
20465 (next-single-property-change p 'face)) clist))
20466 ((memq 'org-special-keyword faces)
20467 (push (list :keyword
20468 (previous-single-property-change p 'face)
20469 (next-single-property-change p 'face)) clist))
20471 (push (org-point-in-group p 0 :target) clist)
20472 (goto-char (1- (match-beginning 0)))
20473 (if (looking-at org-radio-target-regexp)
20474 (push (org-point-in-group p 0 :radio-target) clist))
20476 ((setq o (car (delq nil
20479 (if (memq x org-latex-fragment-image-overlays) x))
20480 (overlays-at (point))))))
20481 (push (list :latex-fragment
20482 (overlay-start o) (overlay-end o)) clist)
20483 (push (list :latex-preview
20484 (overlay-start o) (overlay-end o)) clist))
20485 ((org-inside-LaTeX-fragment-p)
20486 ;; FIXME: positions wrong.
20487 (push (list :latex-fragment (point) (point)) clist)))
20489 (setq clist (nreverse (delq nil clist)))
20492 ;; FIXME: Compare with at-regexp-p Do we need both?
20493 (defun org-in-regexp (re &optional nlines visually)
20494 "Check if point is inside a match of regexp.
20495 Normally only the current line is checked, but you can include NLINES extra
20496 lines both before and after point into the search.
20497 If VISUALLY is set, require that the cursor is not after the match but
20498 really on, so that the block visually is on the match."
20500 (let ((pos (point))
20501 (eol (point-at-eol (+ 1 (or nlines 0))))
20502 (inc (if visually 1 0)))
20504 (beginning-of-line (- 1 (or nlines 0)))
20505 (while (re-search-forward re eol t)
20506 (if (and (<= (match-beginning 0) pos)
20507 (>= (+ inc (match-end 0)) pos))
20508 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20510 (defun org-at-regexp-p (regexp)
20511 "Is point inside a match of REGEXP in the current line?"
20514 (let ((pos (point)) (end (point-at-eol)))
20515 (beginning-of-line 1)
20516 (while (re-search-forward regexp end t)
20517 (if (and (<= (match-beginning 0) pos)
20518 (>= (match-end 0) pos))
20522 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20523 "Non-nil when point is between matches of START-RE and END-RE.
20525 Also return a non-nil value when point is on one of the matches.
20527 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20528 buffer positions. Default values are the positions of headlines
20529 surrounding the point.
20531 The functions returns a cons cell whose car (resp. cdr) is the
20532 position before START-RE (resp. after END-RE)."
20534 (let ((pos (point))
20535 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20536 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20539 ;; Point is on a block when on START-RE or if START-RE can be
20540 ;; found before it...
20541 (and (or (org-at-regexp-p start-re)
20542 (re-search-backward start-re limit-up t))
20543 (setq beg (match-beginning 0))
20544 ;; ... and END-RE after it...
20545 (goto-char (match-end 0))
20546 (re-search-forward end-re limit-down t)
20547 (> (setq end (match-end 0)) pos)
20548 ;; ... without another START-RE in-between.
20549 (goto-char (match-beginning 0))
20550 (not (re-search-backward start-re (1+ beg) t))
20552 (cons beg end))))))
20554 (defun org-in-block-p (names)
20555 "Non-nil when point belongs to a block whose name belongs to NAMES.
20557 NAMES is a list of strings containing names of blocks.
20559 Return first block name matched, or nil. Beware that in case of
20560 nested blocks, the returned name may not belong to the closest
20564 (let ((case-fold-search t)
20565 (lim-up (save-excursion (outline-previous-heading)))
20566 (lim-down (save-excursion (outline-next-heading))))
20567 (mapc (lambda (name)
20568 (let ((n (regexp-quote name)))
20569 (when (org-between-regexps-p
20570 (concat "^[ \t]*#\\+begin_" n)
20571 (concat "^[ \t]*#\\+end_" n)
20577 (defun org-occur-in-agenda-files (regexp &optional nlines)
20578 "Call `multi-occur' with buffers for all agenda files."
20579 (interactive "sOrg-files matching: \np")
20580 (let* ((files (org-agenda-files))
20581 (tnames (mapcar 'file-truename files))
20582 (extra org-agenda-text-search-extra-files)
20584 (when (eq (car extra) 'agenda-archives)
20585 (setq extra (cdr extra))
20586 (setq files (org-add-archive-files files)))
20587 (while (setq f (pop extra))
20588 (unless (member (file-truename f) tnames)
20589 (add-to-list 'files f 'append)
20590 (add-to-list 'tnames (file-truename f) 'append)))
20592 (mapcar (lambda (x)
20593 (with-current-buffer
20594 (or (get-file-buffer x) (find-file-noselect x))
20600 (if (boundp 'occur-mode-find-occurrence-hook)
20602 (add-hook 'occur-mode-find-occurrence-hook
20604 (when (derived-mode-p 'org-mode)
20607 (defadvice occur-mode-goto-occurrence
20608 (after org-occur-reveal activate)
20609 (and (derived-mode-p 'org-mode) (org-reveal)))
20610 (defadvice occur-mode-goto-occurrence-other-window
20611 (after org-occur-reveal activate)
20612 (and (derived-mode-p 'org-mode) (org-reveal)))
20613 (defadvice occur-mode-display-occurrence
20614 (after org-occur-reveal activate)
20615 (when (derived-mode-p 'org-mode)
20616 (let ((pos (occur-mode-find-occurrence)))
20617 (with-current-buffer (marker-buffer pos)
20622 (defun org-occur-link-in-agenda-files ()
20623 "Create a link and search for it in the agendas.
20624 The link is not stored in `org-stored-links', it is just created
20625 for the search purpose."
20627 (let ((link (condition-case nil
20628 (org-store-link nil)
20629 (error "Unable to create a link to here"))))
20630 (org-occur-in-agenda-files (regexp-quote link))))
20632 (defun org-uniquify (list)
20633 "Remove duplicate elements from LIST."
20635 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20638 (defun org-delete-all (elts list)
20639 "Remove all elements in ELTS from LIST."
20641 (setq list (delete (pop elts) list)))
20644 (defun org-count (cl-item cl-seq)
20645 "Count the number of occurrences of ITEM in SEQ.
20646 Taken from `count' in cl-seq.el with all keyword arguments removed."
20647 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20648 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20649 (while (< cl-start cl-end)
20650 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20651 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20652 (setq cl-start (1+ cl-start)))
20655 (defun org-remove-if (predicate seq)
20656 "Remove everything from SEQ that fulfills PREDICATE."
20660 (if (not (funcall predicate e)) (push e res)))
20663 (defun org-remove-if-not (predicate seq)
20664 "Remove everything from SEQ that does not fulfill PREDICATE."
20668 (if (funcall predicate e) (push e res)))
20671 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20672 "Reduce two-argument FUNCTION across SEQ.
20673 Taken from `reduce' in cl-seq.el with all keyword arguments but
20674 \":initial-value\" removed."
20675 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20676 (cadr (memq :initial-value cl-keys)))
20677 (cl-seq (pop cl-seq))
20678 (t (funcall cl-func)))))
20680 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20683 (defun org-back-over-empty-lines ()
20684 "Move backwards over whitespace, to the beginning of the first empty line.
20685 Returns the number of empty lines passed."
20686 (let ((pos (point)))
20687 (if (cdr (assoc 'heading org-blank-before-new-entry))
20688 (skip-chars-backward " \t\n\r")
20690 (forward-line -1)))
20691 (beginning-of-line 2)
20692 (goto-char (min (point) pos))
20693 (count-lines (point) pos)))
20695 (defun org-skip-whitespace ()
20696 (skip-chars-forward " \t\n\r"))
20698 (defun org-point-in-group (point group &optional context)
20699 "Check if POINT is in match-group GROUP.
20700 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20701 match. If the match group does not exist or point is not inside it,
20703 (and (match-beginning group)
20704 (>= point (match-beginning group))
20705 (<= point (match-end group))
20707 (list context (match-beginning group) (match-end group))
20710 (defun org-switch-to-buffer-other-window (&rest args)
20711 "Switch to buffer in a second window on the current frame.
20712 In particular, do not allow pop-up frames.
20713 Returns the newly created buffer."
20714 (let (pop-up-frames special-display-buffer-names special-display-regexps
20715 special-display-function)
20716 (apply 'switch-to-buffer-other-window args)))
20718 (defun org-combine-plists (&rest plists)
20719 "Create a single property list from all plists in PLISTS.
20720 The process starts by copying the first list, and then setting properties
20721 from the other lists. Settings in the last list are the most significant
20722 ones and overrule settings in the other lists."
20723 (let ((rtn (copy-sequence (pop plists)))
20726 (setq ls (pop plists))
20728 (setq p (pop ls) v (pop ls))
20729 (setq rtn (plist-put rtn p v))))
20732 (defun org-replace-escapes (string table)
20733 "Replace %-escapes in STRING with values in TABLE.
20734 TABLE is an association list with keys like \"%a\" and string values.
20735 The sequences in STRING may contain normal field width and padding information,
20736 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20737 so values can contain further %-escapes if they are define later in TABLE."
20738 (let ((tbl (copy-alist table))
20739 (case-fold-search nil)
20742 (while (setq e (pop tbl))
20743 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20744 (when (and (cdr e) (string-match re (cdr e)))
20745 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20747 (add-text-properties 0 3 (list 'sref sref) safe)
20748 (setcdr e (replace-match safe t t (cdr e)))))
20749 (while (string-match re string)
20750 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20752 (setq string (replace-match rpl t t string))))
20753 (while (setq pchg (next-property-change pchg string))
20754 (let ((sref (get-text-property pchg 'sref string)))
20755 (when (and sref (string-match "SREF" string pchg))
20756 (setq string (replace-match sref t t string)))))
20759 (defun org-sublist (list start end)
20760 "Return a section of LIST, from START to END.
20761 Counting starts at 1."
20762 (let (rtn (c start))
20763 (setq list (nthcdr (1- start) list))
20764 (while (and list (<= c end))
20765 (push (pop list) rtn)
20769 (defun org-find-base-buffer-visiting (file)
20770 "Like `find-buffer-visiting' but always return the base buffer and
20771 not an indirect buffer."
20772 (let ((buf (or (get-file-buffer file)
20773 (find-buffer-visiting file))))
20775 (or (buffer-base-buffer buf) buf)
20778 (defun org-image-file-name-regexp (&optional extensions)
20779 "Return regexp matching the file names of images.
20780 If EXTENSIONS is given, only match these."
20781 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20782 (image-file-name-regexp)
20783 (let ((image-file-name-extensions
20785 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20786 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20788 (regexp-opt (nconc (mapcar 'upcase
20789 image-file-name-extensions)
20790 image-file-name-extensions)
20794 (defun org-file-image-p (file &optional extensions)
20795 "Return non-nil if FILE is an image."
20797 (string-match (org-image-file-name-regexp extensions) file)))
20799 (defun org-get-cursor-date ()
20800 "Return the date at cursor in as a time.
20801 This works in the calendar and in the agenda, anywhere else it just
20802 returns the current time."
20803 (let (date day defd)
20805 ((eq major-mode 'calendar-mode)
20806 (setq date (calendar-cursor-to-date)
20807 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20808 ((eq major-mode 'org-agenda-mode)
20809 (setq day (get-text-property (point) 'day))
20811 (setq date (calendar-gregorian-from-absolute day)
20812 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20814 (or defd (current-time))))
20816 (defvar org-agenda-action-marker (make-marker)
20817 "Marker pointing to the entry for the next agenda action.")
20819 (defun org-mark-entry-for-agenda-action ()
20820 "Mark the current entry as target of an agenda action.
20821 Agenda actions are actions executed from the agenda with the key `k',
20822 which make use of the date at the cursor."
20824 (move-marker org-agenda-action-marker
20825 (save-excursion (org-back-to-heading t) (point))
20828 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20830 (defun org-mark-subtree (&optional up)
20831 "Mark the current subtree.
20832 This puts point at the start of the current subtree, and mark at
20833 the end. If a numeric prefix UP is given, move up into the
20834 hierarchy of headlines by UP levels before marking the subtree."
20836 (org-with-limited-levels
20837 (cond ((org-at-heading-p) (beginning-of-line))
20838 ((org-before-first-heading-p) (error "Not in a subtree"))
20839 (t (outline-previous-visible-heading 1))))
20840 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20841 (if (org-called-interactively-p 'any)
20842 (call-interactively 'org-mark-element)
20843 (org-mark-element)))
20847 (defun org-indent-line ()
20848 "Indent line depending on context."
20850 (let* ((pos (point))
20851 (itemp (org-at-item-p))
20852 (case-fold-search t)
20853 (org-drawer-regexp (or org-drawer-regexp "\000"))
20854 (inline-task-p (and (featurep 'org-inlinetask)
20855 (org-inlinetask-in-task-p)))
20856 (inline-re (and inline-task-p
20857 (org-inlinetask-outline-regexp)))
20859 (if (and orgstruct-is-++ (eq pos (point)))
20860 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20861 (indent-according-to-mode))
20862 (beginning-of-line 1)
20865 ((looking-at org-outline-regexp) (setq column 0))
20867 ((looking-at "#\\+include:") (setq column 0))
20868 ;; Footnote definition
20869 ((looking-at org-footnote-definition-re) (setq column 0))
20870 ;; Literal examples
20871 ((looking-at "[ \t]*:\\( \\|$\\)")
20872 (setq column (org-get-indentation))) ; do nothing
20874 ((ignore-errors (goto-char (org-in-item-p)))
20875 (setq column (if itemp
20876 (org-get-indentation)
20877 (org-list-item-body-column (point))))
20880 ((and (looking-at "[ \t]*:END:")
20881 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20883 (goto-char (1- (match-beginning 1)))
20884 (setq column (current-column))))
20886 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20888 (re-search-backward
20889 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20890 (setq column (org-get-indentation (match-string 0))))
20891 ((and (not (looking-at "[ \t]*#\\+begin_"))
20892 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20894 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20896 (cond ((equal (downcase (match-string 1)) "src")
20897 ;; src blocks: let `org-edit-src-exit' handle them
20898 (org-get-indentation))
20899 ((equal (downcase (match-string 1)) "example")
20900 (max (org-get-indentation)
20901 (org-get-indentation (match-string 0))))
20903 (org-get-indentation (match-string 0))))))
20904 ;; This line has nothing special, look at the previous relevant
20905 ;; line to compute indentation
20907 (beginning-of-line 0)
20908 (while (and (not (bobp))
20909 (not (looking-at org-drawer-regexp))
20910 ;; When point started in an inline task, do not move
20911 ;; above task starting line.
20912 (not (and inline-task-p (looking-at inline-re)))
20913 ;; Skip drawers, blocks, empty lines, verbatim,
20914 ;; comments, tables, footnotes definitions, lists,
20916 (or (and (looking-at "[ \t]*:END:")
20917 (re-search-backward org-drawer-regexp nil t))
20918 (and (looking-at "[ \t]*#\\+end_")
20919 (re-search-backward "[ \t]*#\\+begin_"nil t))
20920 (looking-at "[ \t]*[\n:#|]")
20921 (looking-at org-footnote-definition-re)
20922 (and (ignore-errors (goto-char (org-in-item-p)))
20924 (org-list-get-top-point (org-list-struct))))
20925 (and (not inline-task-p)
20926 (featurep 'org-inlinetask)
20927 (org-inlinetask-in-task-p)
20928 (or (org-inlinetask-goto-beginning) t))))
20929 (beginning-of-line 0))
20931 ;; There was an heading above.
20932 ((looking-at "\\*+[ \t]+")
20933 (if (not org-adapt-indentation)
20935 (goto-char (match-end 0))
20936 (setq column (current-column))))
20937 ;; A drawer had started and is unfinished
20938 ((looking-at org-drawer-regexp)
20939 (goto-char (1- (match-beginning 1)))
20940 (setq column (current-column)))
20941 ;; Else, nothing noticeable found: get indentation and go on.
20942 (t (setq column (org-get-indentation))))))
20943 ;; Now apply indentation and move cursor accordingly
20945 (if (<= (current-column) (current-indentation))
20946 (org-indent-line-to column)
20947 (save-excursion (org-indent-line-to column)))
20948 ;; Special polishing for properties, see `org-property-format'
20949 (setq column (current-column))
20950 (beginning-of-line 1)
20952 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20953 (replace-match (concat (match-string 1)
20954 (format org-property-format
20955 (match-string 2) (match-string 3)))
20957 (org-move-to-column column))))
20959 (defun org-indent-drawer ()
20960 "Indent the drawer at point."
20963 (e (and (save-excursion (re-search-forward ":END:" nil t))
20968 (when (overlays-at (point))
20969 (member 'invisible (overlay-properties
20970 (car (overlays-at (point)))))))))
20971 (when folded (org-cycle))
20972 (indent-for-tab-command)
20973 (while (and (move-beginning-of-line 2) (< (point) e))
20974 (indent-for-tab-command))
20976 (when folded (org-cycle)))
20977 (message "Drawer at point indented"))
20979 (defun org-indent-block ()
20980 "Indent the block at point."
20983 (case-fold-search t)
20984 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20989 (when (overlays-at (point))
20990 (member 'invisible (overlay-properties
20991 (car (overlays-at (point)))))))))
20992 (when folded (org-cycle))
20993 (indent-for-tab-command)
20994 (while (and (move-beginning-of-line 2) (< (point) e))
20995 (indent-for-tab-command))
20997 (when folded (org-cycle)))
20998 (message "Block at point indented"))
21000 (defun org-indent-region (start end)
21004 (let ((line-end (org-current-line end)))
21006 (while (< (org-current-line) line-end)
21007 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21008 (t (call-interactively 'org-indent-line)))
21009 (move-beginning-of-line 2)))))
21014 ;; We use our own fill-paragraph and auto-fill functions.
21016 ;; `org-fill-paragraph' relies on adaptive filling and context
21017 ;; checking. Appropriate `fill-prefix' is computed with
21018 ;; `org-adaptive-fill-function'.
21020 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21021 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21022 ;; `org-adaptive-fill-function' value. Internally,
21023 ;; `org-comment-line-break-function' breaks the line.
21025 ;; `org-setup-filling' installs filling and auto-filling related
21026 ;; variables during `org-mode' initialization.
21028 (defun org-setup-filling ()
21030 ;; Prevent auto-fill from inserting unwanted new items.
21031 (when (boundp 'fill-nobreak-predicate)
21033 'fill-nobreak-predicate
21035 (append fill-nobreak-predicate
21036 '(org-fill-paragraph-separate-nobreak-p
21037 org-fill-line-break-nobreak-p)))))
21038 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21039 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21040 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21041 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21043 (defvar org-element-paragraph-separate) ; org-element.el
21044 (defun org-fill-paragraph-separate-nobreak-p ()
21045 "Non-nil when a line break at point would insert a new item."
21046 (looking-at (substring org-element-paragraph-separate 1)))
21048 (defun org-fill-line-break-nobreak-p ()
21049 "Non-nil when a line break at point would create an Org line break."
21051 (skip-chars-backward "[ \t]")
21052 (skip-chars-backward "\\\\")
21053 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21055 (declare-function message-in-body-p "message" ())
21056 (defvar org-element--affiliated-re) ; From org-element.el
21057 (defun org-adaptive-fill-function ()
21058 "Compute a fill prefix for the current line.
21059 Return fill prefix, as a string, or nil if current line isn't
21060 meant to be filled."
21061 (org-with-wide-buffer
21062 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21063 ;; FIXME: This is really the job of orgstruct++-mode
21064 (let* ((p (line-beginning-position))
21065 (element (save-excursion (beginning-of-line)
21066 (org-element-at-point)))
21067 (type (org-element-type element))
21070 (goto-char (org-element-property :begin element))
21071 (while (looking-at org-element--affiliated-re) (forward-line))
21073 (unless (< p post-affiliated)
21075 (comment (looking-at "[ \t]*# ?") (match-string 0))
21076 (footnote-definition "")
21078 (make-string (org-list-item-body-column post-affiliated) ? ))
21080 ;; Fill prefix is usually the same as the current line,
21081 ;; except if the paragraph is at the beginning of an item.
21082 (let ((parent (org-element-property :parent element)))
21083 (cond ((eq (org-element-type parent) 'item)
21084 (make-string (org-list-item-body-column
21085 (org-element-property :begin parent))
21087 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21091 ;; Only fill contents if P is within block boundaries.
21092 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21095 (cend (save-excursion
21096 (goto-char (org-element-property :end element))
21097 (skip-chars-backward " \r\t\n")
21098 (line-beginning-position))))
21099 (when (and (>= p cbeg) (< p cend))
21100 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21104 (declare-function message-goto-body "message" ())
21105 (defvar message-cite-prefix-regexp) ; From message.el
21106 (defvar org-element-all-objects) ; From org-element.el
21107 (defun org-fill-paragraph (&optional justify)
21108 "Fill element at point, when applicable.
21110 This function only applies to comment blocks, comments, example
21111 blocks and paragraphs. Also, as a special case, re-align table
21112 when point is at one.
21114 If JUSTIFY is non-nil (interactively, with prefix argument),
21115 justify as well. If `sentence-end-double-space' is non-nil, then
21116 period followed by one space does not end a sentence, so don't
21117 break a line there. The variable `fill-column' controls the
21120 For convenience, when point is at a plain list, an item or
21121 a footnote definition, try to fill the first paragraph within."
21122 ;; Falls back on message-fill-paragraph when necessary
21124 (if (and (derived-mode-p 'message-mode)
21125 (or (not (message-in-body-p))
21126 (save-excursion (move-beginning-of-line 1)
21127 (looking-at message-cite-prefix-regexp))))
21128 (let ((fill-paragraph-function
21129 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21130 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21131 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21132 (paragraph-separate
21133 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21134 (fill-paragraph nil))
21136 ;; Move to end of line in order to get the first paragraph
21137 ;; within a plain list or a footnote definition.
21139 (let ((element (org-element-at-point)))
21140 ;; First check if point is in a blank line at the beginning of
21141 ;; the buffer. In that case, ignore filling.
21142 (if (< (point) (org-element-property :begin element)) t
21143 (case (org-element-type element)
21144 ;; Align Org tables, leave table.el tables as-is.
21145 (table-row (org-table-align) t)
21147 (when (eq (org-element-property :type element) 'org)
21151 ;; Paragraphs may contain `line-break' type objects.
21152 (let ((beg (max (point-min)
21153 (org-element-property :contents-begin element)))
21154 (end (min (point-max)
21155 (org-element-property :contents-end element))))
21156 ;; Do nothing if point is at an affiliated keyword.
21157 (if (< (point) beg) t
21158 (when (derived-mode-p 'message-mode)
21159 ;; In `message-mode', do not fill following
21160 ;; citation in current paragraph nor text before
21162 (let ((body-start (save-excursion (message-goto-body))))
21163 (when body-start (setq beg (max body-start beg))))
21164 (when (save-excursion
21166 (concat "^" message-cite-prefix-regexp) end t))
21167 (setq end (match-beginning 0))))
21168 ;; Fill paragraph, taking line breaks into
21169 ;; consideration. For that, slice the paragraph
21170 ;; using line breaks as separators, and fill the
21171 ;; parts in reverse order to avoid messing with
21177 (fill-region-as-paragraph pos (point) justify)
21179 ;; Find the list of ending positions for line
21180 ;; breaks in the current paragraph. Add paragraph
21181 ;; beginning to include first slice.
21186 (org-element--parse-objects
21187 beg end nil org-element-all-objects)
21189 (lambda (lb) (org-element-property :end lb)))))))
21191 ;; Contents of `comment-block' type elements should be
21192 ;; filled as plain text, but only if point is within block
21195 (let* ((case-fold-search t)
21196 (beg (save-excursion
21197 (goto-char (org-element-property :begin element))
21198 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21201 (end (save-excursion
21202 (goto-char (org-element-property :end element))
21203 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21204 (line-beginning-position))))
21205 (when (and (>= (point) beg) (< (point) end))
21206 (fill-region-as-paragraph
21209 (re-search-backward "^[ \t]*$" beg 'move)
21210 (line-beginning-position))
21212 (beginning-of-line)
21213 (re-search-forward "^[ \t]*$" end 'move)
21214 (line-beginning-position))
21218 (comment (fill-comment-paragraph justify))
21219 ;; Ignore every other element.
21220 (otherwise t)))))))
21222 (defun org-auto-fill-function ()
21223 "Auto-fill function."
21224 ;; Check if auto-filling is meaningful.
21225 (let ((fc (current-fill-column)))
21226 (when (and fc (> (current-column) fc))
21227 (let ((fill-prefix (org-adaptive-fill-function)))
21228 (when fill-prefix (do-auto-fill))))))
21230 (defun org-comment-line-break-function (&optional soft)
21231 "Break line at point and indent, continuing comment if within one.
21232 The inserted newline is marked hard if variable
21233 `use-hard-newlines' is true, unless optional argument SOFT is
21235 (if soft (insert-and-inherit ?\n) (newline 1))
21236 (save-excursion (forward-char -1) (delete-horizontal-space))
21237 (delete-horizontal-space)
21238 (indent-to-left-margin)
21239 (insert-before-markers-and-inherit fill-prefix))
21244 ;; Org comments syntax is quite complex. It requires the entire line
21245 ;; to be just a comment. Also, even with the right syntax at the
21246 ;; beginning of line, some some elements (i.e. verse-block or
21247 ;; example-block) don't accept comments. Usual Emacs comment commands
21248 ;; cannot cope with those requirements. Therefore, Org replaces them.
21250 ;; Org still relies on `comment-dwim', but cannot trust
21251 ;; `comment-only-p'. So, `comment-region-function' and
21252 ;; `uncomment-region-function' both point
21253 ;; to`org-comment-or-uncomment-region'. Eventually,
21254 ;; `org-insert-comment' takes care of insertion of comments at the
21255 ;; beginning of line.
21257 ;; `org-setup-comments-handling' install comments related variables
21258 ;; during `org-mode' initialization.
21260 (defun org-setup-comments-handling ()
21262 (org-set-local 'comment-use-syntax nil)
21263 (org-set-local 'comment-start "# ")
21264 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21265 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21266 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21267 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21269 (defun org-insert-comment ()
21270 "Insert an empty comment above current line.
21271 If the line is empty, insert comment at its beginning."
21272 (beginning-of-line)
21273 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21277 (defvar comment-empty-lines) ; From newcomment.el.
21278 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21279 "Comment or uncomment each non-blank line in the region.
21280 Uncomment each non-blank line between BEG and END if it only
21281 contains commented lines. Otherwise, comment them."
21284 (narrow-to-region (save-excursion (goto-char beg)
21285 (skip-chars-forward " \r\t\n" end)
21286 (line-beginning-position))
21287 (save-excursion (goto-char end)
21288 (skip-chars-backward " \r\t\n" beg)
21289 (line-end-position)))
21291 ;; UNCOMMENTP is non-nil when every non blank line between
21292 ;; BEG and END is a comment.
21294 (goto-char (point-min))
21295 (while (and (not (eobp))
21296 (let ((element (org-element-at-point)))
21297 (and (eq (org-element-type element) 'comment)
21298 (goto-char (min (point-max)
21299 (org-element-property
21300 :end element)))))))
21303 ;; Only blank lines and comments in region: uncomment it.
21305 (goto-char (point-min))
21306 (while (not (eobp))
21307 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21308 (replace-match "" nil nil nil 1))
21310 ;; Comment each line in region.
21311 (let ((min-indent (point-max)))
21312 ;; First find the minimum indentation across all lines.
21314 (goto-char (point-min))
21315 (while (and (not (eobp)) (not (zerop min-indent)))
21316 (unless (looking-at "[ \t]*$")
21317 (setq min-indent (min min-indent (current-indentation))))
21319 ;; Then loop over all lines.
21321 (goto-char (point-min))
21322 (while (not (eobp))
21323 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21324 (org-move-to-column min-indent t)
21325 (insert comment-start))
21326 (forward-line))))))))
21331 (defun org-toggle-fixed-width-section (arg)
21332 "Toggle the fixed-width export.
21333 If there is no active region, the QUOTE keyword at the current headline is
21334 inserted or removed. When present, it causes the text between this headline
21335 and the next to be exported as fixed-width text, and unmodified.
21336 If there is an active region, this command adds or removes a colon as the
21337 first character of this line. If the first character of a line is a colon,
21338 this line is also exported in fixed-width font."
21341 (regionp (org-region-active-p))
21342 (beg (if regionp (region-beginning) (point)))
21343 (end (if regionp (region-end)))
21344 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21345 (case-fold-search nil)
21346 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21351 (setq cc (current-column))
21352 (beginning-of-line 1)
21353 (setq off (looking-at re))
21354 (while (> nlines 0)
21355 (setq nlines (1- nlines))
21356 (beginning-of-line 1)
21359 (org-move-to-column cc t)
21362 ((and off (looking-at re))
21363 (replace-match "" t t nil 1))
21364 ((not off) (org-move-to-column cc t) (insert ": ")))
21367 (org-back-to-heading)
21369 ((looking-at (format org-heading-keyword-regexp-format
21371 (goto-char (match-end 1))
21372 (looking-at (concat " +" org-quote-string))
21373 (replace-match "" t t)
21374 (when (eolp) (insert " ")))
21375 ((looking-at org-outline-regexp)
21376 (goto-char (match-end 0))
21377 (insert org-quote-string " ")))))))
21379 (defun org-reftex-citation ()
21380 "Use reftex-citation to insert a citation into the buffer.
21381 This looks for a line like
21383 #+BIBLIOGRAPHY: foo plain option:-d
21385 and derives from it that foo.bib is the bibliography file relevant
21386 for this document. It then installs the necessary environment for RefTeX
21387 to work in this buffer and calls `reftex-citation' to insert a citation
21390 Export of such citations to both LaTeX and HTML is handled by the contributed
21391 package org-exp-bibtex by Taru Karttunen."
21393 (let ((reftex-docstruct-symbol 'rds)
21394 (reftex-cite-format "\\cite{%l}")
21399 (let ((case-fold-search t)
21400 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21401 (if (not (save-excursion
21402 (or (re-search-forward re nil t)
21403 (re-search-backward re nil t))))
21404 (error "No bibliography defined in file")
21405 (setq bib (concat (match-string 1) ".bib")
21406 rds (list (list 'bib bib)))))))
21407 (call-interactively 'reftex-citation)))
21409 ;;;; Functions extending outline functionality
21411 (defun org-beginning-of-line (&optional arg)
21412 "Go to the beginning of the current line. If that is invisible, continue
21413 to a visible line beginning. This makes the function of C-a more intuitive.
21414 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21415 first attempt, and only move to after the tags when the cursor is already
21416 beyond the end of the headline."
21418 (let ((pos (point))
21419 (special (if (consp org-special-ctrl-a/e)
21420 (car org-special-ctrl-a/e)
21421 org-special-ctrl-a/e))
21423 (if (org-bound-and-true-p line-move-visual)
21424 (beginning-of-visual-line 1)
21425 (beginning-of-line 1))
21426 (if (and arg (fboundp 'move-beginning-of-line))
21427 (call-interactively 'move-beginning-of-line)
21431 (if (org-truely-invisible-p)
21432 (while (and (not (bobp)) (org-truely-invisible-p))
21434 (beginning-of-line 1))
21435 (forward-char 1))))
21438 ((and (looking-at org-complex-heading-regexp)
21439 (= (char-after (match-end 1)) ?\ ))
21440 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21444 (cond ((> pos refpos) refpos)
21445 ((= pos (point)) refpos)
21447 (cond ((> pos (point)) (point))
21448 ((not (eq last-command this-command)) (point))
21451 ;; Being at an item and not looking at an the item means point
21452 ;; was previously moved to beginning of a visual line, which
21453 ;; doesn't contain the item. Therefore, do nothing special,
21455 (when (looking-at org-list-full-item-re)
21456 ;; Set special position at first white space character after
21457 ;; bullet, and check-box, if any.
21458 (let ((after-bullet
21459 (let ((box (match-end 3)))
21460 (if (not box) (match-end 1)
21461 (let ((after (char-after box)))
21462 (if (and after (= after ? )) (1+ box) box))))))
21463 ;; Special case: Move point to special position when
21464 ;; currently after it or at beginning of line.
21466 (when (or (> pos after-bullet) (= (point) pos))
21467 (goto-char after-bullet))
21468 ;; Reversed case: Move point to special position when
21469 ;; point was already at beginning of line and command is
21471 (when (and (= (point) pos) (eq last-command this-command))
21472 (goto-char after-bullet))))))))
21474 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21476 (defun org-end-of-line (&optional arg)
21477 "Go to the end of the line.
21478 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21479 first attempt, and only move to after the tags when the cursor is already
21480 beyond the end of the headline."
21482 (let ((special (if (consp org-special-ctrl-a/e)
21483 (cdr org-special-ctrl-a/e)
21484 org-special-ctrl-a/e)))
21486 ((or (not special) arg
21487 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21488 (call-interactively
21489 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21490 ((fboundp 'move-end-of-line) 'move-end-of-line)
21491 (t 'end-of-line))))
21492 ((org-at-heading-p)
21493 (let ((pos (point)))
21494 (beginning-of-line 1)
21495 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21497 (if (or (< pos (match-beginning 1))
21498 (= pos (match-end 0)))
21499 (goto-char (match-beginning 1))
21500 (goto-char (match-end 0)))
21501 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21502 (goto-char (match-end 0))
21503 (goto-char (match-beginning 1))))
21504 (call-interactively (if (fboundp 'move-end-of-line)
21508 (move-end-of-line 1)
21509 (when (overlays-at (1- (point))) (backward-char 1)))
21510 ;; At an item: Move before any hidden text.
21511 (t (call-interactively
21512 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21513 ((fboundp 'move-end-of-line) 'move-end-of-line)
21514 (t 'end-of-line)))))
21516 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21518 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21519 (define-key org-mode-map "\C-e" 'org-end-of-line)
21521 (defun org-backward-sentence (&optional arg)
21522 "Go to beginning of sentence, or beginning of table field.
21523 This will call `backward-sentence' or `org-table-beginning-of-field',
21524 depending on context."
21527 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21528 (t (call-interactively 'backward-sentence))))
21530 (defun org-forward-sentence (&optional arg)
21531 "Go to end of sentence, or end of table field.
21532 This will call `forward-sentence' or `org-table-end-of-field',
21533 depending on context."
21536 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21537 (t (call-interactively 'forward-sentence))))
21539 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21540 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21542 (defun org-kill-line (&optional arg)
21543 "Kill line, to tags or end of line."
21546 ((or (not org-special-ctrl-k)
21548 (not (org-at-heading-p)))
21549 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21550 org-ctrl-k-protect-subtree)
21551 (if (or (eq org-ctrl-k-protect-subtree 'error)
21552 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21553 (error "C-k aborted - would kill hidden subtree")))
21554 (call-interactively
21555 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21556 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21557 (kill-region (point) (match-beginning 1))
21558 (org-set-tags nil t))
21559 (t (kill-region (point) (point-at-eol)))))
21561 (define-key org-mode-map "\C-k" 'org-kill-line)
21563 (defun org-yank (&optional arg)
21564 "Yank. If the kill is a subtree, treat it specially.
21565 This command will look at the current kill and check if is a single
21566 subtree, or a series of subtrees[1]. If it passes the test, and if the
21567 cursor is at the beginning of a line or after the stars of a currently
21568 empty headline, then the yank is handled specially. How exactly depends
21569 on the value of the following variables, both set by default.
21571 org-yank-folded-subtrees
21572 When set, the subtree(s) will be folded after insertion, but only
21573 if doing so would now swallow text after the yanked text.
21575 org-yank-adjusted-subtrees
21576 When set, the subtree will be promoted or demoted in order to
21577 fit into the local outline tree structure, which means that the level
21578 will be adjusted so that it becomes the smaller one of the two
21579 *visible* surrounding headings.
21581 Any prefix to this command will cause `yank' to be called directly with
21582 no special treatment. In particular, a simple \\[universal-argument] prefix \
21584 plainly yank the text as it is.
21586 \[1] The test checks if the first non-white line is a heading
21587 and if there are no other headings with fewer stars."
21589 (org-yank-generic 'yank arg))
21591 (defun org-yank-generic (command arg)
21592 "Perform some yank-like command.
21594 This function implements the behavior described in the `org-yank'
21595 documentation. However, it has been generalized to work for any
21596 interactive command with similar behavior."
21598 ;; pretend to be command COMMAND
21599 (setq this-command command)
21602 (call-interactively command)
21604 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21605 (and (org-kill-is-subtree-p)
21607 (and (looking-at "[ \t]*$")
21610 (buffer-substring (point-at-bol) (point)))))))
21613 ((and subtreep org-yank-folded-subtrees)
21614 (let ((beg (point))
21616 (if (and subtreep org-yank-adjusted-subtrees)
21617 (org-paste-subtree nil nil 'for-yank)
21618 (call-interactively command))
21622 (when (and (bolp) subtreep
21623 (not (setq swallowp
21624 (org-yank-folding-would-swallow-text beg end))))
21625 (org-with-limited-levels
21626 (or (looking-at org-outline-regexp)
21627 (re-search-forward org-outline-regexp-bol end t))
21628 (while (and (< (point) end) (looking-at org-outline-regexp))
21630 (org-cycle-show-empty-lines 'folded)
21631 (condition-case nil
21632 (outline-forward-same-level 1)
21633 (error (goto-char end))))))
21636 "Inserted text not folded because that would swallow text"))
21639 (skip-chars-forward " \t\n\r")
21640 (beginning-of-line 1)
21641 (push-mark beg 'nomsg)))
21642 ((and subtreep org-yank-adjusted-subtrees)
21643 (let ((beg (point-at-bol)))
21644 (org-paste-subtree nil nil 'for-yank)
21645 (push-mark beg 'nomsg)))
21647 (call-interactively command))))))
21649 (defun org-yank-folding-would-swallow-text (beg end)
21650 "Would hide-subtree at BEG swallow any text after END?"
21652 (org-with-limited-levels
21655 (when (or (looking-at org-outline-regexp)
21656 (re-search-forward org-outline-regexp-bol end t))
21657 (setq level (org-outline-level)))
21659 (skip-chars-forward " \t\r\n\v\f")
21661 (and (bolp) (looking-at org-outline-regexp)
21662 (<= (org-outline-level) level)))
21663 nil ; Nothing would be swallowed
21664 t))))) ; something would swallow
21666 (define-key org-mode-map "\C-y" 'org-yank)
21668 (defun org-truely-invisible-p ()
21669 "Check if point is at a character currently not visible.
21670 This version does not only check the character property, but also
21672 ;; Early versions of noutline don't have `outline-invisible-p'.
21673 (if (org-bound-and-true-p visible-mode)
21675 (outline-invisible-p)))
21677 (defun org-invisible-p2 ()
21678 "Check if point is at a character currently not visible."
21680 (if (and (eolp) (not (bobp))) (backward-char 1))
21681 ;; Early versions of noutline don't have `outline-invisible-p'.
21682 (outline-invisible-p)))
21684 (defun org-back-to-heading (&optional invisible-ok)
21685 "Call `outline-back-to-heading', but provide a better error message."
21686 (condition-case nil
21687 (outline-back-to-heading invisible-ok)
21688 (error (error "Before first headline at position %d in buffer %s"
21689 (point) (current-buffer)))))
21691 (defun org-before-first-heading-p ()
21692 "Before first heading?"
21695 (null (re-search-backward org-outline-regexp-bol nil t))))
21697 (defun org-at-heading-p (&optional ignored)
21698 (outline-on-heading-p t))
21699 ;; Compatibility alias with Org versions < 7.8.03
21700 (defalias 'org-on-heading-p 'org-at-heading-p)
21702 (defun org-at-comment-p nil
21703 "Is cursor in a line starting with a # character?"
21705 (beginning-of-line)
21706 (looking-at "^#")))
21708 (defun org-at-drawer-p nil
21709 "Is cursor at a drawer keyword?"
21711 (move-beginning-of-line 1)
21712 (looking-at org-drawer-regexp)))
21714 (defun org-at-block-p nil
21715 "Is cursor at a block keyword?"
21717 (move-beginning-of-line 1)
21718 (looking-at org-block-regexp)))
21720 (defun org-point-at-end-of-empty-headline ()
21721 "If point is at the end of an empty headline, return t, else nil.
21722 If the heading only contains a TODO keyword, it is still still considered
21724 (and (looking-at "[ \t]*$")
21725 (when org-todo-line-regexp
21727 (beginning-of-line 1)
21728 (let ((case-fold-search nil))
21729 (looking-at org-todo-line-regexp)
21730 (string= (match-string 3) ""))))))
21732 (defun org-at-heading-or-item-p ()
21733 (or (org-at-heading-p) (org-at-item-p)))
21735 (defun org-at-target-p ()
21736 (or (org-in-regexp org-radio-target-regexp)
21737 (org-in-regexp org-target-regexp)))
21738 ;; Compatibility alias with Org versions < 7.8.03
21739 (defalias 'org-on-target-p 'org-at-target-p)
21741 (defun org-up-heading-all (arg)
21742 "Move to the heading line of which the present line is a subheading.
21743 This function considers both visible and invisible heading lines.
21744 With argument, move up ARG levels."
21745 (if (fboundp 'outline-up-heading-all)
21746 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21747 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21749 (defun org-up-heading-safe ()
21750 "Move to the heading line of which the present line is a subheading.
21751 This version will not throw an error. It will return the level of the
21752 headline found, or nil if no higher level is found.
21754 Also, this function will be a lot faster than `outline-up-heading',
21755 because it relies on stars being the outline starters. This can really
21756 make a significant difference in outlines with very many siblings."
21757 (let (start-level re)
21758 (org-back-to-heading t)
21759 (setq start-level (funcall outline-level))
21760 (if (equal start-level 1)
21762 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21763 (if (re-search-backward re nil t)
21764 (funcall outline-level)))))
21766 (defun org-first-sibling-p ()
21767 "Is this heading the first child of its parents?"
21769 (let ((re org-outline-regexp-bol)
21771 (unless (org-at-heading-p t)
21772 (error "Not at a heading"))
21773 (setq level (funcall outline-level))
21775 (if (not (re-search-backward re nil t))
21777 (setq l (funcall outline-level))
21780 (defun org-goto-sibling (&optional previous)
21781 "Goto the next sibling, even if it is invisible.
21782 When PREVIOUS is set, go to the previous sibling instead. Returns t
21783 when a sibling was found. When none is found, return nil and don't
21785 (let ((fun (if previous 're-search-backward 're-search-forward))
21787 (re org-outline-regexp-bol)
21789 (when (condition-case nil (org-back-to-heading t) (error nil))
21790 (setq level (funcall outline-level))
21792 (or previous (forward-char 1))
21793 (while (funcall fun re nil t)
21794 (setq l (funcall outline-level))
21795 (when (< l level) (goto-char pos) (throw 'exit nil))
21796 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21800 (defun org-show-siblings ()
21801 "Show all siblings of the current headline."
21803 (while (org-goto-sibling) (org-flag-heading nil)))
21805 (while (org-goto-sibling 'previous)
21806 (org-flag-heading nil))))
21808 (defun org-goto-first-child ()
21809 "Goto the first child, even if it is invisible.
21810 Return t when a child was found. Otherwise don't move point and
21812 (let (level (pos (point)) (re org-outline-regexp-bol))
21813 (when (condition-case nil (org-back-to-heading t) (error nil))
21814 (setq level (outline-level))
21816 (if (and (re-search-forward re nil t) (> (outline-level) level))
21817 (progn (goto-char (match-beginning 0)) t)
21818 (goto-char pos) nil))))
21820 (defun org-show-hidden-entry ()
21821 "Show an entry where even the heading is hidden."
21825 (defun org-flag-heading (flag &optional entry)
21826 "Flag the current heading. FLAG non-nil means make invisible.
21827 When ENTRY is non-nil, show the entire entry."
21829 (org-back-to-heading t)
21830 ;; Check if we should show the entire entry
21835 (and (outline-next-heading)
21836 (org-flag-heading nil))))
21837 (outline-flag-region (max (point-min) (1- (point)))
21838 (save-excursion (outline-end-of-heading) (point))
21841 (defun org-get-next-sibling ()
21842 "Move to next heading of the same level, and return point.
21843 If there is no such heading, return nil.
21844 This is like outline-next-sibling, but invisible headings are ok."
21845 (let ((level (funcall outline-level)))
21846 (outline-next-heading)
21847 (while (and (not (eobp)) (> (funcall outline-level) level))
21848 (outline-next-heading))
21849 (if (or (eobp) (< (funcall outline-level) level))
21853 (defun org-get-last-sibling ()
21854 "Move to previous heading of the same level, and return point.
21855 If there is no such heading, return nil."
21856 (let ((opoint (point))
21857 (level (funcall outline-level)))
21858 (outline-previous-heading)
21859 (when (and (/= (point) opoint) (outline-on-heading-p t))
21860 (while (and (> (funcall outline-level) level)
21862 (outline-previous-heading))
21863 (if (< (funcall outline-level) level)
21867 (defun org-end-of-subtree (&optional invisible-ok to-heading)
21868 "Goto to the end of a subtree."
21869 ;; This contains an exact copy of the original function, but it uses
21870 ;; `org-back-to-heading', to make it work also in invisible
21871 ;; trees. And is uses an invisible-ok argument.
21872 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21873 ;; Furthermore, when used inside Org, finding the end of a large subtree
21874 ;; with many children and grandchildren etc, this can be much faster
21875 ;; than the outline version.
21876 (org-back-to-heading invisible-ok)
21878 (level (funcall outline-level)))
21879 (if (and (derived-mode-p 'org-mode) (< level 1000))
21880 ;; A true heading (not a plain list item), in Org-mode
21881 ;; This means we can easily find the end by looking
21882 ;; only for the right number of stars. Using a regexp to do
21883 ;; this is so much faster than using a Lisp loop.
21884 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21886 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21887 ;; something else, do it the slow way
21888 (while (and (not (eobp))
21889 (or first (> (funcall outline-level) level)))
21891 (outline-next-heading)))
21893 (if (memq (preceding-char) '(?\n ?\^M))
21895 ;; Go to end of line before heading
21897 (if (memq (preceding-char) '(?\n ?\^M))
21898 ;; leave blank line before heading
21899 (forward-char -1))))))
21902 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21903 "Use Org version in org-mode, for dramatic speed-up."
21904 (if (derived-mode-p 'org-mode)
21906 (org-end-of-subtree nil t)
21907 (unless (eobp) (backward-char 1)))
21910 (defun org-end-of-meta-data-and-drawers ()
21911 "Jump to the first text after meta data and drawers in the current entry.
21912 This will move over empty lines, lines with planning time stamps,
21913 clocking lines, and drawers."
21914 (org-back-to-heading t)
21915 (let ((end (save-excursion (outline-next-heading) (point)))
21916 (re (concat "\\(" org-drawer-regexp "\\)"
21917 "\\|" "[ \t]*" org-keyword-time-regexp)))
21919 (while (re-search-forward re end t)
21920 (if (not (match-end 1))
21921 ;; empty or planning line
21923 ;; a drawer, find the end
21924 (re-search-forward "^[ \t]*:END:" end 'move)
21926 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21929 (defun org-forward-heading-same-level (arg &optional invisible-ok)
21930 "Move forward to the arg'th subheading at same level as this one.
21931 Stop at the first and last subheadings of a superior heading.
21932 Normally this only looks at visible headings, but when INVISIBLE-OK is
21933 non-nil it will also look at invisible ones."
21935 (org-back-to-heading invisible-ok)
21937 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21938 (re (format "^\\*\\{1,%d\\} " level))
21942 (while (and (re-search-forward re nil 'move)
21943 (setq l (- (match-end 0) (match-beginning 0) 1))
21946 (progn (backward-char 1) (outline-invisible-p)))
21947 (if (< l level) (setq arg 1)))
21948 (setq arg (1- arg)))
21949 (beginning-of-line 1)))
21951 (defun org-backward-heading-same-level (arg &optional invisible-ok)
21952 "Move backward to the arg'th subheading at same level as this one.
21953 Stop at the first and last subheadings of a superior heading."
21955 (org-back-to-heading)
21957 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21958 (re (format "^\\*\\{1,%d\\} " level))
21961 (while (and (re-search-backward re nil 'move)
21962 (setq l (- (match-end 0) (match-beginning 0) 1))
21965 (outline-invisible-p))
21966 (if (< l level) (setq arg 1)))
21967 (setq arg (1- arg)))))
21970 (defun org-forward-element ()
21971 "Move forward by one element.
21972 Move to the next element at the same level, when possible."
21974 (cond ((eobp) (error "Cannot move further down"))
21975 ((org-with-limited-levels (org-at-heading-p))
21976 (let ((origin (point)))
21977 (org-forward-heading-same-level 1)
21978 (unless (org-with-limited-levels (org-at-heading-p))
21980 (error "Cannot move further down"))))
21982 (let* ((elem (org-element-at-point))
21983 (end (org-element-property :end elem))
21984 (parent (org-element-property :parent elem)))
21985 (if (and parent (= (org-element-property :contents-end parent) end))
21986 (goto-char (org-element-property :end parent))
21987 (goto-char end))))))
21990 (defun org-backward-element ()
21991 "Move backward by one element.
21992 Move to the previous element at the same level, when possible."
21994 (cond ((bobp) (error "Cannot move further up"))
21995 ((org-with-limited-levels (org-at-heading-p))
21996 ;; At an headline, move to the previous one, if any, or stay
21998 (let ((origin (point)))
21999 (org-backward-heading-same-level 1)
22000 (unless (org-with-limited-levels (org-at-heading-p))
22002 (error "Cannot move further up"))))
22004 (let* ((trail (org-element-at-point 'keep-trail))
22006 (prev-elem (nth 1 trail))
22007 (beg (org-element-property :begin elem)))
22009 ;; Move to beginning of current element if point isn't
22011 ((/= (point) beg) (goto-char beg))
22012 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22013 ((org-before-first-heading-p) (goto-char (point-min)))
22014 (t (org-back-to-heading)))))))
22017 (defun org-up-element ()
22018 "Move to upper element."
22020 (if (org-with-limited-levels (org-at-heading-p))
22021 (unless (org-up-heading-safe) (error "No surrounding element"))
22022 (let* ((elem (org-element-at-point))
22023 (parent (org-element-property :parent elem)))
22024 (if parent (goto-char (org-element-property :begin parent))
22025 (if (org-with-limited-levels (org-before-first-heading-p))
22026 (error "No surrounding element")
22027 (org-with-limited-levels (org-back-to-heading)))))))
22030 (defvar org-element-greater-elements)
22031 (defun org-down-element ()
22032 "Move to inner element."
22034 (let ((element (org-element-at-point)))
22036 ((memq (org-element-type element) '(plain-list table))
22037 (goto-char (org-element-property :contents-begin element))
22039 ((memq (org-element-type element) org-element-greater-elements)
22040 ;; If contents are hidden, first disclose them.
22041 (when (org-element-property :hiddenp element) (org-cycle))
22042 (goto-char (or (org-element-property :contents-begin element)
22043 (error "No content for this element"))))
22044 (t (error "No inner element")))))
22047 (defun org-drag-element-backward ()
22048 "Move backward element at point."
22050 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22051 (let* ((trail (org-element-at-point 'keep-trail))
22053 (prev-elem (nth 1 trail)))
22054 ;; Error out if no previous element or previous element is
22055 ;; a parent of the current one.
22056 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22057 (error "Cannot drag element backward")
22058 (let ((pos (point)))
22059 (org-element-swap-A-B prev-elem elem)
22060 (goto-char (+ (org-element-property :begin prev-elem)
22061 (- pos (org-element-property :begin elem)))))))))
22064 (defun org-drag-element-forward ()
22065 "Move forward element at point."
22067 (let* ((pos (point))
22068 (elem (org-element-at-point)))
22069 (when (= (point-max) (org-element-property :end elem))
22070 (error "Cannot drag element forward"))
22071 (goto-char (org-element-property :end elem))
22072 (let ((next-elem (org-element-at-point)))
22073 (when (or (org-element-nested-p elem next-elem)
22074 (and (eq (org-element-type next-elem) 'headline)
22075 (not (eq (org-element-type elem) 'headline))))
22077 (error "Cannot drag element forward"))
22078 ;; Compute new position of point: it's shifted by NEXT-ELEM
22079 ;; body's length (without final blanks) and by the length of
22080 ;; blanks between ELEM and NEXT-ELEM.
22081 (let ((size-next (- (save-excursion
22082 (goto-char (org-element-property :end next-elem))
22083 (skip-chars-backward " \r\t\n")
22085 ;; Small correction if buffer doesn't end
22086 ;; with a newline character.
22087 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22088 (org-element-property :begin next-elem)))
22089 (size-blank (- (org-element-property :end elem)
22091 (goto-char (org-element-property :end elem))
22092 (skip-chars-backward " \r\t\n")
22095 (org-element-swap-A-B elem next-elem)
22096 (goto-char (+ pos size-next size-blank))))))
22099 (defun org-mark-element ()
22100 "Put point at beginning of this element, mark at end.
22102 Interactively, if this command is repeated or (in Transient Mark
22103 mode) if the mark is active, it marks the next element after the
22104 ones already marked."
22106 (let (deactivate-mark)
22107 (if (and (org-called-interactively-p 'any)
22108 (or (and (eq last-command this-command) (mark t))
22109 (and transient-mark-mode mark-active)))
22113 (goto-char (org-element-property :end (org-element-at-point)))))
22114 (let ((element (org-element-at-point)))
22116 (push-mark (org-element-property :end element) t t)
22117 (goto-char (org-element-property :begin element))))))
22120 (defun org-narrow-to-element ()
22121 "Narrow buffer to current element."
22123 (let ((elem (org-element-at-point)))
22125 ((eq (car elem) 'headline)
22127 (org-element-property :begin elem)
22128 (org-element-property :end elem)))
22129 ((memq (car elem) org-element-greater-elements)
22131 (org-element-property :contents-begin elem)
22132 (org-element-property :contents-end elem)))
22135 (org-element-property :begin elem)
22136 (org-element-property :end elem))))))
22139 (defun org-transpose-element ()
22140 "Transpose current and previous elements, keeping blank lines between.
22141 Point is moved after both elements."
22143 (org-skip-whitespace)
22144 (let ((end (org-element-property :end (org-element-at-point))))
22145 (org-drag-element-backward)
22149 (defun org-unindent-buffer ()
22150 "Un-indent the visible part of the buffer.
22151 Relative indentation (between items, inside blocks, etc.) isn't
22154 (unless (eq major-mode 'org-mode)
22155 (error "Cannot un-indent a buffer not in Org mode"))
22156 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22157 unindent-tree ; For byte-compiler.
22163 (if (memq (org-element-type element) '(headline section))
22164 (funcall unindent-tree (org-element-contents element))
22168 (org-element-property :begin element)
22169 (org-element-property :end element))
22170 (org-do-remove-indentation)))))
22171 (reverse contents))))))
22172 (funcall unindent-tree (org-element-contents parse-tree))))
22174 (defun org-show-subtree ()
22175 "Show everything after this heading at deeper levels."
22177 (outline-flag-region
22180 (org-end-of-subtree t t))
22183 (defun org-show-entry ()
22184 "Show the body directly following this heading.
22185 Show the heading too, if it is currently invisible."
22188 (condition-case nil
22190 (org-back-to-heading t)
22191 (outline-flag-region
22192 (max (point-min) (1- (point)))
22194 (if (re-search-forward
22195 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22196 (match-beginning 1)
22199 (org-cycle-hide-drawers 'children))
22202 (defun org-make-options-regexp (kwds &optional extra)
22203 "Make a regular expression for keyword lines."
22206 (mapconcat 'regexp-quote kwds "\\|")
22207 (if extra (concat "\\|" extra))
22208 "\\):[ \t]*\\(.*\\)"))
22210 ;; Make isearch reveal the necessary context
22211 (defun org-isearch-end ()
22212 "Reveal context after isearch exits."
22213 (when isearch-success ; only if search was successful
22214 (if (featurep 'xemacs)
22215 ;; Under XEmacs, the hook is run in the correct place,
22216 ;; we directly show the context.
22217 (org-show-context 'isearch)
22218 ;; In Emacs the hook runs *before* restoring the overlays.
22219 ;; So we have to use a one-time post-command-hook to do this.
22220 ;; (Emacs 22 has a special variable, see function `org-mode')
22221 (unless (and (boundp 'isearch-mode-end-hook-quit)
22222 isearch-mode-end-hook-quit)
22223 ;; Only when the isearch was not quitted.
22224 (org-add-hook 'post-command-hook 'org-isearch-post-command
22225 'append 'local)))))
22227 (defun org-isearch-post-command ()
22228 "Remove self from hook, and show context."
22229 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22230 (org-show-context 'isearch))
22233 ;;;; Integration with and fixes for other packages
22237 (defvar org-imenu-markers nil
22238 "All markers currently used by Imenu.")
22239 (make-variable-buffer-local 'org-imenu-markers)
22241 (defun org-imenu-new-marker (&optional pos)
22242 "Return a new marker for use by Imenu, and remember the marker."
22243 (let ((m (make-marker)))
22244 (move-marker m (or pos (point)))
22245 (push m org-imenu-markers)
22248 (defun org-imenu-get-tree ()
22249 "Produce the index for Imenu."
22250 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22251 (setq org-imenu-markers nil)
22252 (let* ((n org-imenu-depth)
22253 (re (concat "^" (org-get-limited-outline-regexp)))
22254 (subs (make-vector (1+ n) nil))
22260 (goto-char (point-max))
22261 (while (re-search-backward re nil t)
22262 (setq level (org-reduced-level (funcall outline-level)))
22263 (when (and (<= level n)
22264 (looking-at org-complex-heading-regexp))
22265 (setq head (org-link-display-format
22266 (org-match-string-no-properties 4))
22267 m (org-imenu-new-marker))
22268 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22269 (if (>= level last-level)
22270 (push (cons head m) (aref subs level))
22271 (push (cons head (aref subs (1+ level))) (aref subs level))
22272 (loop for i from (1+ level) to n do (aset subs i nil)))
22273 (setq last-level level)))))
22276 (eval-after-load "imenu"
22278 (add-hook 'imenu-after-jump-hook
22280 (if (derived-mode-p 'org-mode)
22281 (org-show-context 'org-goto))))))
22283 (defun org-link-display-format (link)
22284 "Replace a link with either the description, or the link target
22285 if no description is present"
22287 (if (string-match org-bracket-link-analytic-regexp link)
22288 (replace-match (if (match-end 5)
22289 (match-string 5 link)
22290 (concat (match-string 1 link)
22291 (match-string 3 link)))
22295 (defun org-toggle-link-display ()
22296 "Toggle the literal or descriptive display of links."
22298 (if org-descriptive-links
22299 (progn (org-remove-from-invisibility-spec '(org-link))
22300 (org-restart-font-lock)
22301 (setq org-descriptive-links nil))
22302 (progn (add-to-invisibility-spec '(org-link))
22303 (org-restart-font-lock)
22304 (setq org-descriptive-links t))))
22306 ;; Speedbar support
22308 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22309 "Overlay marking the agenda restriction line in speedbar.")
22310 (overlay-put org-speedbar-restriction-lock-overlay
22311 'face 'org-agenda-restriction-lock)
22312 (overlay-put org-speedbar-restriction-lock-overlay
22313 'help-echo "Agendas are currently limited to this item.")
22314 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22316 (defun org-speedbar-set-agenda-restriction ()
22317 "Restrict future agenda commands to the location at point in speedbar.
22318 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22320 (require 'org-agenda)
22321 (let (p m tp np dir txt)
22323 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22325 (setq m (get-text-property p 'org-imenu-marker))
22326 (with-current-buffer (marker-buffer m)
22328 (org-agenda-set-restriction-lock 'subtree)))
22329 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22330 'speedbar-function 'speedbar-find-file))
22331 (setq tp (previous-single-property-change
22332 (1+ p) 'speedbar-function)
22333 np (next-single-property-change
22334 tp 'speedbar-function)
22335 dir (speedbar-line-directory)
22336 txt (buffer-substring-no-properties (or tp (point-min))
22337 (or np (point-max))))
22338 (with-current-buffer (find-file-noselect
22339 (let ((default-directory dir))
22340 (expand-file-name txt)))
22341 (unless (derived-mode-p 'org-mode)
22342 (error "Cannot restrict to non-Org-mode file"))
22343 (org-agenda-set-restriction-lock 'file)))
22344 (t (error "Don't know how to restrict Org-mode's agenda")))
22345 (move-overlay org-speedbar-restriction-lock-overlay
22346 (point-at-bol) (point-at-eol))
22347 (setq current-prefix-arg nil)
22348 (org-agenda-maybe-redo)))
22350 (eval-after-load "speedbar"
22352 (speedbar-add-supported-extension ".org")
22353 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22354 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22355 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22356 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22357 (add-hook 'speedbar-visiting-tag-hook
22358 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22360 ;;; Fixes and Hacks for problems with other packages
22362 ;; Make flyspell not check words in links, to not mess up our keymap
22363 (defun org-mode-flyspell-verify ()
22364 "Don't let flyspell put overlays at active buttons, or on
22365 {todo,all-time,additional-option-like}-keywords."
22366 (let ((pos (max (1- (point)) (point-min)))
22367 (word (thing-at-point 'word)))
22368 (and (not (get-text-property pos 'keymap))
22369 (not (get-text-property pos 'org-no-flyspell))
22370 (not (member word org-todo-keywords-1))
22371 (not (member word org-all-time-keywords))
22372 (not (member word org-options-keywords))
22373 (not (member word (mapcar 'car org-startup-options)))
22374 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22376 (defun org-remove-flyspell-overlays-in (beg end)
22377 "Remove flyspell overlays in region."
22378 (and (org-bound-and-true-p flyspell-mode)
22379 (fboundp 'flyspell-delete-region-overlays)
22380 (flyspell-delete-region-overlays beg end))
22381 (add-text-properties beg end '(org-no-flyspell t)))
22383 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22384 (eval-after-load "bookmark"
22385 '(if (boundp 'bookmark-after-jump-hook)
22386 ;; We can use the hook
22387 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22388 ;; Hook not available, use advice
22389 (defadvice bookmark-jump (after org-make-visible activate)
22390 "Make the position visible."
22391 (org-bookmark-jump-unhide))))
22393 ;; Make sure saveplace shows the location if it was hidden
22394 (eval-after-load "saveplace"
22395 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22396 "Make the position visible."
22397 (org-bookmark-jump-unhide)))
22399 ;; Make sure ecb shows the location if it was hidden
22400 (eval-after-load "ecb"
22401 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22402 "Make hierarchy visible when jumping into location from ECB tree buffer."
22403 (if (derived-mode-p 'org-mode)
22404 (org-show-context))))
22406 (defun org-bookmark-jump-unhide ()
22407 "Unhide the current position, to show the bookmark location."
22408 (and (derived-mode-p 'org-mode)
22409 (or (outline-invisible-p)
22410 (save-excursion (goto-char (max (point-min) (1- (point))))
22411 (outline-invisible-p)))
22412 (org-show-context 'bookmark-jump)))
22414 ;; Make session.el ignore our circular variable
22415 (eval-after-load "session"
22416 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22418 ;;;; Experimental code
22420 (defun org-closed-in-range ()
22421 "Sparse tree of items closed in a certain time range.
22422 Still experimental, may disappear in the future."
22424 ;; Get the time interval from the user.
22425 (let* ((time1 (org-float-time
22426 (org-read-date nil 'to-time nil "Starting date: ")))
22427 (time2 (org-float-time
22428 (org-read-date nil 'to-time nil "End date:")))
22429 ;; callback function
22430 (callback (lambda ()
22433 (apply 'encode-time
22434 (org-parse-time-string
22435 (match-string 1))))))
22436 ;; check if time in interval
22437 (and (>= time time1) (<= time time2))))))
22438 ;; make tree, check each match with the callback
22439 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22445 (run-hooks 'org-load-hook)
22447 ;;; org.el ends here