Interpret relative file names in remember templates.
[org-mode/org-tableheadings.git] / org.el
blob7b6acde9a02e1022efb5a17a94f33ece8b99f474
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 5.23a++
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
15 ;; any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around NOTES files that contain
34 ;; information about projects as plain text. Org-mode is implemented on
35 ;; top of outline-mode, which makes it possible to keep the content of
36 ;; large files well structured. Visibility cycling and structure editing
37 ;; help to work with the tree. Tables are easily created with a built-in
38 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
39 ;; and scheduling. It dynamically compiles entries into an agenda that
40 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
41 ;; Plain text URL-like links connect to websites, emails, Usenet
42 ;; messages, BBDB entries, and any files related to the projects. For
43 ;; printing and sharing of notes, an Org-mode file can be exported as a
44 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
45 ;; iCalendar file. It can also serve as a publishing tool for a set of
46 ;; linked webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://orgmode.org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org-mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org-mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the etc/ directory of Emacs 22.
62 ;; A list of recent changes can be found at
63 ;; http://orgmode.org/Changes.html
65 ;;; Code:
67 ;;;; Require other packages
69 (eval-when-compile
70 (require 'cl)
71 (require 'gnus-sum)
72 (require 'calendar))
73 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
74 ;; the file noutline.el being loaded.
75 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
76 ;; We require noutline, which might be provided in outline.el
77 (require 'outline) (require 'noutline)
78 ;; Other stuff we need.
79 (require 'time-date)
80 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
81 (require 'easymenu)
83 ;;;; Customization variables
85 ;;; Version
87 (defconst org-version "5.23a++"
88 "The version number of the file org.el.")
90 (defun org-version (&optional here)
91 "Show the org-mode version in the echo area.
92 With prefix arg HERE, insert it at point."
93 (interactive "P")
94 (let ((version (format "Org-mode version %s" org-version)))
95 (message version)
96 (if here
97 (insert version))))
99 ;;; Compatibility constants
100 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
101 (defconst org-format-transports-properties-p
102 (let ((x "a"))
103 (add-text-properties 0 1 '(test t) x)
104 (get-text-property 0 'test (format "%s" x)))
105 "Does format transport text properties?")
107 (defmacro org-bound-and-true-p (var)
108 "Return the value of symbol VAR if it is bound, else nil."
109 `(and (boundp (quote ,var)) ,var))
111 (defmacro org-unmodified (&rest body)
112 "Execute body without changing `buffer-modified-p'."
113 `(set-buffer-modified-p
114 (prog1 (buffer-modified-p) ,@body)))
116 (defmacro org-re (s)
117 "Replace posix classes in regular expression."
118 (if (featurep 'xemacs)
119 (let ((ss s))
120 (save-match-data
121 (while (string-match "\\[:alnum:\\]" ss)
122 (setq ss (replace-match "a-zA-Z0-9" t t ss)))
123 (while (string-match "\\[:alpha:\\]" ss)
124 (setq ss (replace-match "a-zA-Z" t t ss)))
125 ss))
128 (defmacro org-preserve-lc (&rest body)
129 `(let ((_line (org-current-line))
130 (_col (current-column)))
131 (unwind-protect
132 (progn ,@body)
133 (goto-line _line)
134 (move-to-column _col))))
136 (defmacro org-without-partial-completion (&rest body)
137 `(let ((pc-mode (and (boundp 'partial-completion-mode)
138 partial-completion-mode)))
139 (unwind-protect
140 (progn
141 (if pc-mode (partial-completion-mode -1))
142 ,@body)
143 (if pc-mode (partial-completion-mode 1)))))
145 ;;; The custom variables
147 (defgroup org nil
148 "Outline-based notes management and organizer."
149 :tag "Org"
150 :group 'outlines
151 :group 'hypermedia
152 :group 'calendar)
154 (defcustom org-load-hook nil
155 "Hook that is run after org.el has been loaded."
156 :group 'org
157 :type 'hook)
159 (defvar org-modules) ; defined below
160 (defvar org-modules-loaded nil
161 "Have the modules been loaded already?")
163 (defun org-load-modules-maybe (&optional force)
164 "Load all extensions listed in `org-default-extensions'."
165 (when (or force (not org-modules-loaded))
166 (mapc (lambda (ext)
167 (condition-case nil (require ext)
168 (error (message "Problems while trying to load feature `%s'" ext))))
169 org-modules)
170 (setq org-modules-loaded t)))
172 (defun org-set-modules (var value)
173 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
174 (set var value)
175 (when (featurep 'org)
176 (org-load-modules-maybe 'force)))
178 (defcustom org-modules '(org-bbdb org-gnus org-info org-irc org-mhe org-rmail org-vm org-wl)
179 "Modules that should always be loaded together with org.el.
180 If the description starts with <A>, this means the extension
181 will be autoloaded when needed, preloading is not necessary.
182 If a description starts with <C>, the file is not part of emacs
183 and loading it will require that you have downloaded and properly installed
184 the org-mode distribution."
185 :group 'org
186 :set 'org-set-modules
187 :type
188 '(set :greedy t
189 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
190 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
191 (const :tag " info: Links to Info nodes" org-info)
192 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
193 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
194 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
195 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
196 (const :tag " vm: Links to VM folders/messages" org-vm)
197 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
198 (const :tag " mouse: Additional mouse support" org-mouse)
199 ; (const :tag "A export-latex: LaTeX export" org-export-latex)
200 ; (const :tag "A publish: Publishing" org-publish)
202 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
203 (const :tag "C bibtex: Org links to BibTeX entries" org-bibtex)
204 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
205 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
206 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
207 (const :tag "C id: Global id's for identifying entries" org-id)
208 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
209 (const :tag "C iswitchb: Use iswitchb to select Org buffer" org-iswitchb)
210 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
211 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
212 (const :tag "C mew: Support for links to messages in Mew" org-mew)
213 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
214 (const :tag "C registry: A registry for Org links" org-registry)
215 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
216 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
217 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)))
219 ;; FIXME: Needs a separate group...
220 (defcustom org-completion-fallback-command 'hippie-expand
221 "The expansion command called by \\[org-complete] in normal context.
222 Normal means, no org-mode-specific context."
223 :group 'org
224 :type 'function)
226 (defgroup org-startup nil
227 "Options concerning startup of Org-mode."
228 :tag "Org Startup"
229 :group 'org)
231 (defcustom org-startup-folded t
232 "Non-nil means, entering Org-mode will switch to OVERVIEW.
233 This can also be configured on a per-file basis by adding one of
234 the following lines anywhere in the buffer:
236 #+STARTUP: fold
237 #+STARTUP: nofold
238 #+STARTUP: content"
239 :group 'org-startup
240 :type '(choice
241 (const :tag "nofold: show all" nil)
242 (const :tag "fold: overview" t)
243 (const :tag "content: all headlines" content)))
245 (defcustom org-startup-truncated t
246 "Non-nil means, entering Org-mode will set `truncate-lines'.
247 This is useful since some lines containing links can be very long and
248 uninteresting. Also tables look terrible when wrapped."
249 :group 'org-startup
250 :type 'boolean)
252 (defcustom org-startup-align-all-tables nil
253 "Non-nil means, align all tables when visiting a file.
254 This is useful when the column width in tables is forced with <N> cookies
255 in table fields. Such tables will look correct only after the first re-align.
256 This can also be configured on a per-file basis by adding one of
257 the following lines anywhere in the buffer:
258 #+STARTUP: align
259 #+STARTUP: noalign"
260 :group 'org-startup
261 :type 'boolean)
263 (defcustom org-insert-mode-line-in-empty-file nil
264 "Non-nil means insert the first line setting Org-mode in empty files.
265 When the function `org-mode' is called interactively in an empty file, this
266 normally means that the file name does not automatically trigger Org-mode.
267 To ensure that the file will always be in Org-mode in the future, a
268 line enforcing Org-mode will be inserted into the buffer, if this option
269 has been set."
270 :group 'org-startup
271 :type 'boolean)
273 (defcustom org-replace-disputed-keys nil
274 "Non-nil means use alternative key bindings for some keys.
275 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
276 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
277 If you want to use Org-mode together with one of these other modes,
278 or more generally if you would like to move some Org-mode commands to
279 other keys, set this variable and configure the keys with the variable
280 `org-disputed-keys'.
282 This option is only relevant at load-time of Org-mode, and must be set
283 *before* org.el is loaded. Changing it requires a restart of Emacs to
284 become effective."
285 :group 'org-startup
286 :type 'boolean)
288 (if (fboundp 'defvaralias)
289 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
291 (defcustom org-disputed-keys
292 '(([(shift up)] . [(meta p)])
293 ([(shift down)] . [(meta n)])
294 ([(shift left)] . [(meta -)])
295 ([(shift right)] . [(meta +)])
296 ([(control shift right)] . [(meta shift +)])
297 ([(control shift left)] . [(meta shift -)]))
298 "Keys for which Org-mode and other modes compete.
299 This is an alist, cars are the default keys, second element specifies
300 the alternative to use when `org-replace-disputed-keys' is t.
302 Keys can be specified in any syntax supported by `define-key'.
303 The value of this option takes effect only at Org-mode's startup,
304 therefore you'll have to restart Emacs to apply it after changing."
305 :group 'org-startup
306 :type 'alist)
308 (defun org-key (key)
309 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
310 Or return the original if not disputed."
311 (if org-replace-disputed-keys
312 (let* ((nkey (key-description key))
313 (x (org-find-if (lambda (x)
314 (equal (key-description (car x)) nkey))
315 org-disputed-keys)))
316 (if x (cdr x) key))
317 key))
319 (defun org-find-if (predicate seq)
320 (catch 'exit
321 (while seq
322 (if (funcall predicate (car seq))
323 (throw 'exit (car seq))
324 (pop seq)))))
326 (defun org-defkey (keymap key def)
327 "Define a key, possibly translated, as returned by `org-key'."
328 (define-key keymap (org-key key) def))
330 (defcustom org-ellipsis nil
331 "The ellipsis to use in the Org-mode outline.
332 When nil, just use the standard three dots. When a string, use that instead,
333 When a face, use the standart 3 dots, but with the specified face.
334 The change affects only Org-mode (which will then use its own display table).
335 Changing this requires executing `M-x org-mode' in a buffer to become
336 effective."
337 :group 'org-startup
338 :type '(choice (const :tag "Default" nil)
339 (face :tag "Face" :value org-warning)
340 (string :tag "String" :value "...#")))
342 (defvar org-display-table nil
343 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
345 (defgroup org-keywords nil
346 "Keywords in Org-mode."
347 :tag "Org Keywords"
348 :group 'org)
350 (defcustom org-deadline-string "DEADLINE:"
351 "String to mark deadline entries.
352 A deadline is this string, followed by a time stamp. Should be a word,
353 terminated by a colon. You can insert a schedule keyword and
354 a timestamp with \\[org-deadline].
355 Changes become only effective after restarting Emacs."
356 :group 'org-keywords
357 :type 'string)
359 (defcustom org-scheduled-string "SCHEDULED:"
360 "String to mark scheduled TODO entries.
361 A schedule is this string, followed by a time stamp. Should be a word,
362 terminated by a colon. You can insert a schedule keyword and
363 a timestamp with \\[org-schedule].
364 Changes become only effective after restarting Emacs."
365 :group 'org-keywords
366 :type 'string)
368 (defcustom org-closed-string "CLOSED:"
369 "String used as the prefix for timestamps logging closing a TODO entry."
370 :group 'org-keywords
371 :type 'string)
373 (defcustom org-clock-string "CLOCK:"
374 "String used as prefix for timestamps clocking work hours on an item."
375 :group 'org-keywords
376 :type 'string)
378 (defcustom org-comment-string "COMMENT"
379 "Entries starting with this keyword will never be exported.
380 An entry can be toggled between COMMENT and normal with
381 \\[org-toggle-comment].
382 Changes become only effective after restarting Emacs."
383 :group 'org-keywords
384 :type 'string)
386 (defcustom org-quote-string "QUOTE"
387 "Entries starting with this keyword will be exported in fixed-width font.
388 Quoting applies only to the text in the entry following the headline, and does
389 not extend beyond the next headline, even if that is lower level.
390 An entry can be toggled between QUOTE and normal with
391 \\[org-toggle-fixed-width-section]."
392 :group 'org-keywords
393 :type 'string)
395 (defconst org-repeat-re
396 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
397 "Regular expression for specifying repeated events.
398 After a match, group 1 contains the repeat expression.")
400 (defgroup org-structure nil
401 "Options concerning the general structure of Org-mode files."
402 :tag "Org Structure"
403 :group 'org)
405 (defgroup org-reveal-location nil
406 "Options about how to make context of a location visible."
407 :tag "Org Reveal Location"
408 :group 'org-structure)
410 (defconst org-context-choice
411 '(choice
412 (const :tag "Always" t)
413 (const :tag "Never" nil)
414 (repeat :greedy t :tag "Individual contexts"
415 (cons
416 (choice :tag "Context"
417 (const agenda)
418 (const org-goto)
419 (const occur-tree)
420 (const tags-tree)
421 (const link-search)
422 (const mark-goto)
423 (const bookmark-jump)
424 (const isearch)
425 (const default))
426 (boolean))))
427 "Contexts for the reveal options.")
429 (defcustom org-show-hierarchy-above '((default . t))
430 "Non-nil means, show full hierarchy when revealing a location.
431 Org-mode often shows locations in an org-mode file which might have
432 been invisible before. When this is set, the hierarchy of headings
433 above the exposed location is shown.
434 Turning this off for example for sparse trees makes them very compact.
435 Instead of t, this can also be an alist specifying this option for different
436 contexts. Valid contexts are
437 agenda when exposing an entry from the agenda
438 org-goto when using the command `org-goto' on key C-c C-j
439 occur-tree when using the command `org-occur' on key C-c /
440 tags-tree when constructing a sparse tree based on tags matches
441 link-search when exposing search matches associated with a link
442 mark-goto when exposing the jump goal of a mark
443 bookmark-jump when exposing a bookmark location
444 isearch when exiting from an incremental search
445 default default for all contexts not set explicitly"
446 :group 'org-reveal-location
447 :type org-context-choice)
449 (defcustom org-show-following-heading '((default . nil))
450 "Non-nil means, show following heading when revealing a location.
451 Org-mode often shows locations in an org-mode file which might have
452 been invisible before. When this is set, the heading following the
453 match is shown.
454 Turning this off for example for sparse trees makes them very compact,
455 but makes it harder to edit the location of the match. In such a case,
456 use the command \\[org-reveal] to show more context.
457 Instead of t, this can also be an alist specifying this option for different
458 contexts. See `org-show-hierarchy-above' for valid contexts."
459 :group 'org-reveal-location
460 :type org-context-choice)
462 (defcustom org-show-siblings '((default . nil) (isearch t))
463 "Non-nil means, show all sibling heading when revealing a location.
464 Org-mode often shows locations in an org-mode file which might have
465 been invisible before. When this is set, the sibling of the current entry
466 heading are all made visible. If `org-show-hierarchy-above' is t,
467 the same happens on each level of the hierarchy above the current entry.
469 By default this is on for the isearch context, off for all other contexts.
470 Turning this off for example for sparse trees makes them very compact,
471 but makes it harder to edit the location of the match. In such a case,
472 use the command \\[org-reveal] to show more context.
473 Instead of t, this can also be an alist specifying this option for different
474 contexts. See `org-show-hierarchy-above' for valid contexts."
475 :group 'org-reveal-location
476 :type org-context-choice)
478 (defcustom org-show-entry-below '((default . nil))
479 "Non-nil means, show the entry below a headline when revealing a location.
480 Org-mode often shows locations in an org-mode file which might have
481 been invisible before. When this is set, the text below the headline that is
482 exposed is also shown.
484 By default this is off for all contexts.
485 Instead of t, this can also be an alist specifying this option for different
486 contexts. See `org-show-hierarchy-above' for valid contexts."
487 :group 'org-reveal-location
488 :type org-context-choice)
490 (defgroup org-cycle nil
491 "Options concerning visibility cycling in Org-mode."
492 :tag "Org Cycle"
493 :group 'org-structure)
495 (defcustom org-drawers '("PROPERTIES" "CLOCK")
496 "Names of drawers. Drawers are not opened by cycling on the headline above.
497 Drawers only open with a TAB on the drawer line itself. A drawer looks like
498 this:
499 :DRAWERNAME:
500 .....
501 :END:
502 The drawer \"PROPERTIES\" is special for capturing properties through
503 the property API.
505 Drawers can be defined on the per-file basis with a line like:
507 #+DRAWERS: HIDDEN STATE PROPERTIES"
508 :group 'org-structure
509 :type '(repeat (string :tag "Drawer Name")))
511 (defcustom org-cycle-global-at-bob nil
512 "Cycle globally if cursor is at beginning of buffer and not at a headline.
513 This makes it possible to do global cycling without having to use S-TAB or
514 C-u TAB. For this special case to work, the first line of the buffer
515 must not be a headline - it may be empty ot some other text. When used in
516 this way, `org-cycle-hook' is disables temporarily, to make sure the
517 cursor stays at the beginning of the buffer.
518 When this option is nil, don't do anything special at the beginning
519 of the buffer."
520 :group 'org-cycle
521 :type 'boolean)
523 (defcustom org-cycle-emulate-tab t
524 "Where should `org-cycle' emulate TAB.
525 nil Never
526 white Only in completely white lines
527 whitestart Only at the beginning of lines, before the first non-white char
528 t Everywhere except in headlines
529 exc-hl-bol Everywhere except at the start of a headline
530 If TAB is used in a place where it does not emulate TAB, the current subtree
531 visibility is cycled."
532 :group 'org-cycle
533 :type '(choice (const :tag "Never" nil)
534 (const :tag "Only in completely white lines" white)
535 (const :tag "Before first char in a line" whitestart)
536 (const :tag "Everywhere except in headlines" t)
537 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
540 (defcustom org-cycle-separator-lines 2
541 "Number of empty lines needed to keep an empty line between collapsed trees.
542 If you leave an empty line between the end of a subtree and the following
543 headline, this empty line is hidden when the subtree is folded.
544 Org-mode will leave (exactly) one empty line visible if the number of
545 empty lines is equal or larger to the number given in this variable.
546 So the default 2 means, at least 2 empty lines after the end of a subtree
547 are needed to produce free space between a collapsed subtree and the
548 following headline.
550 Special case: when 0, never leave empty lines in collapsed view."
551 :group 'org-cycle
552 :type 'integer)
554 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
555 org-cycle-hide-drawers
556 org-cycle-show-empty-lines
557 org-optimize-window-after-visibility-change)
558 "Hook that is run after `org-cycle' has changed the buffer visibility.
559 The function(s) in this hook must accept a single argument which indicates
560 the new state that was set by the most recent `org-cycle' command. The
561 argument is a symbol. After a global state change, it can have the values
562 `overview', `content', or `all'. After a local state change, it can have
563 the values `folded', `children', or `subtree'."
564 :group 'org-cycle
565 :type 'hook)
567 (defgroup org-edit-structure nil
568 "Options concerning structure editing in Org-mode."
569 :tag "Org Edit Structure"
570 :group 'org-structure)
572 (defcustom org-odd-levels-only nil
573 "Non-nil means, skip even levels and only use odd levels for the outline.
574 This has the effect that two stars are being added/taken away in
575 promotion/demotion commands. It also influences how levels are
576 handled by the exporters.
577 Changing it requires restart of `font-lock-mode' to become effective
578 for fontification also in regions already fontified.
579 You may also set this on a per-file basis by adding one of the following
580 lines to the buffer:
582 #+STARTUP: odd
583 #+STARTUP: oddeven"
584 :group 'org-edit-structure
585 :group 'org-font-lock
586 :type 'boolean)
588 (defcustom org-adapt-indentation t
589 "Non-nil means, adapt indentation when promoting and demoting.
590 When this is set and the *entire* text in an entry is indented, the
591 indentation is increased by one space in a demotion command, and
592 decreased by one in a promotion command. If any line in the entry
593 body starts at column 0, indentation is not changed at all."
594 :group 'org-edit-structure
595 :type 'boolean)
597 (defcustom org-special-ctrl-a/e nil
598 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
599 When t, `C-a' will bring back the cursor to the beginning of the
600 headline text, i.e. after the stars and after a possible TODO keyword.
601 In an item, this will be the position after the bullet.
602 When the cursor is already at that position, another `C-a' will bring
603 it to the beginning of the line.
604 `C-e' will jump to the end of the headline, ignoring the presence of tags
605 in the headline. A second `C-e' will then jump to the true end of the
606 line, after any tags.
607 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
608 and only a directly following, identical keypress will bring the cursor
609 to the special positions."
610 :group 'org-edit-structure
611 :type '(choice
612 (const :tag "off" nil)
613 (const :tag "after bullet first" t)
614 (const :tag "border first" reversed)))
616 (if (fboundp 'defvaralias)
617 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
619 (defcustom org-special-ctrl-k nil
620 "Non-nil means `C-k' will behave specially in headlines.
621 When nil, `C-k' will call the default `kill-line' command.
622 When t, the following will happen while the cursor is in the headline:
624 - When the cursor is at the beginning of a headline, kill the entire
625 line and possible the folded subtree below the line.
626 - When in the middle of the headline text, kill the headline up to the tags.
627 - When after the headline text, kill the tags."
628 :group 'org-edit-structure
629 :type 'boolean)
631 (defcustom org-M-RET-may-split-line '((default . t))
632 "Non-nil means, M-RET will split the line at the cursor position.
633 When nil, it will go to the end of the line before making a
634 new line.
635 You may also set this option in a different way for different
636 contexts. Valid contexts are:
638 headline when creating a new headline
639 item when creating a new item
640 table in a table field
641 default the value to be used for all contexts not explicitly
642 customized"
643 :group 'org-structure
644 :group 'org-table
645 :type '(choice
646 (const :tag "Always" t)
647 (const :tag "Never" nil)
648 (repeat :greedy t :tag "Individual contexts"
649 (cons
650 (choice :tag "Context"
651 (const headline)
652 (const item)
653 (const table)
654 (const default))
655 (boolean)))))
658 (defcustom org-blank-before-new-entry '((heading . nil)
659 (plain-list-item . nil))
660 "Should `org-insert-heading' leave a blank line before new heading/item?
661 The value is an alist, with `heading' and `plain-list-item' as car,
662 and a boolean flag as cdr."
663 :group 'org-edit-structure
664 :type '(list
665 (cons (const heading) (boolean))
666 (cons (const plain-list-item) (boolean))))
668 (defcustom org-insert-heading-hook nil
669 "Hook being run after inserting a new heading."
670 :group 'org-edit-structure
671 :type 'hook)
673 (defcustom org-enable-fixed-width-editor t
674 "Non-nil means, lines starting with \":\" are treated as fixed-width.
675 This currently only means, they are never auto-wrapped.
676 When nil, such lines will be treated like ordinary lines.
677 See also the QUOTE keyword."
678 :group 'org-edit-structure
679 :type 'boolean)
681 (defcustom org-goto-auto-isearch t
682 "Non-nil means, typing characters in org-goto starts incremental search."
683 :group 'org-edit-structure
684 :type 'boolean)
686 (defgroup org-sparse-trees nil
687 "Options concerning sparse trees in Org-mode."
688 :tag "Org Sparse Trees"
689 :group 'org-structure)
691 (defcustom org-highlight-sparse-tree-matches t
692 "Non-nil means, highlight all matches that define a sparse tree.
693 The highlights will automatically disappear the next time the buffer is
694 changed by an edit command."
695 :group 'org-sparse-trees
696 :type 'boolean)
698 (defcustom org-remove-highlights-with-change t
699 "Non-nil means, any change to the buffer will remove temporary highlights.
700 Such highlights are created by `org-occur' and `org-clock-display'.
701 When nil, `C-c C-c needs to be used to get rid of the highlights.
702 The highlights created by `org-preview-latex-fragment' always need
703 `C-c C-c' to be removed."
704 :group 'org-sparse-trees
705 :group 'org-time
706 :type 'boolean)
709 (defcustom org-occur-hook '(org-first-headline-recenter)
710 "Hook that is run after `org-occur' has constructed a sparse tree.
711 This can be used to recenter the window to show as much of the structure
712 as possible."
713 :group 'org-sparse-trees
714 :type 'hook)
716 (defgroup org-plain-lists nil
717 "Options concerning plain lists in Org-mode."
718 :tag "Org Plain lists"
719 :group 'org-structure)
721 (defcustom org-cycle-include-plain-lists nil
722 "Non-nil means, include plain lists into visibility cycling.
723 This means that during cycling, plain list items will *temporarily* be
724 interpreted as outline headlines with a level given by 1000+i where i is the
725 indentation of the bullet. In all other operations, plain list items are
726 not seen as headlines. For example, you cannot assign a TODO keyword to
727 such an item."
728 :group 'org-plain-lists
729 :type 'boolean)
731 (defcustom org-plain-list-ordered-item-terminator t
732 "The character that makes a line with leading number an ordered list item.
733 Valid values are ?. and ?\). To get both terminators, use t. While
734 ?. may look nicer, it creates the danger that a line with leading
735 number may be incorrectly interpreted as an item. ?\) therefore is
736 the safe choice."
737 :group 'org-plain-lists
738 :type '(choice (const :tag "dot like in \"2.\"" ?.)
739 (const :tag "paren like in \"2)\"" ?\))
740 (const :tab "both" t)))
742 (defcustom org-auto-renumber-ordered-lists t
743 "Non-nil means, automatically renumber ordered plain lists.
744 Renumbering happens when the sequence have been changed with
745 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
746 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
747 :group 'org-plain-lists
748 :type 'boolean)
750 (defcustom org-provide-checkbox-statistics t
751 "Non-nil means, update checkbox statistics after insert and toggle.
752 When this is set, checkbox statistics is updated each time you either insert
753 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
754 with \\[org-ctrl-c-ctrl-c\\]."
755 :group 'org-plain-lists
756 :type 'boolean)
758 (defgroup org-archive nil
759 "Options concerning archiving in Org-mode."
760 :tag "Org Archive"
761 :group 'org-structure)
763 (defcustom org-archive-tag "ARCHIVE"
764 "The tag that marks a subtree as archived.
765 An archived subtree does not open during visibility cycling, and does
766 not contribute to the agenda listings.
767 After changing this, font-lock must be restarted in the relevant buffers to
768 get the proper fontification."
769 :group 'org-archive
770 :group 'org-keywords
771 :type 'string)
773 (defcustom org-agenda-skip-archived-trees t
774 "Non-nil means, the agenda will skip any items located in archived trees.
775 An archived tree is a tree marked with the tag ARCHIVE."
776 :group 'org-archive
777 :group 'org-agenda-skip
778 :type 'boolean)
780 (defcustom org-cycle-open-archived-trees nil
781 "Non-nil means, `org-cycle' will open archived trees.
782 An archived tree is a tree marked with the tag ARCHIVE.
783 When nil, archived trees will stay folded. You can still open them with
784 normal outline commands like `show-all', but not with the cycling commands."
785 :group 'org-archive
786 :group 'org-cycle
787 :type 'boolean)
789 (defcustom org-sparse-tree-open-archived-trees nil
790 "Non-nil means sparse tree construction shows matches in archived trees.
791 When nil, matches in these trees are highlighted, but the trees are kept in
792 collapsed state."
793 :group 'org-archive
794 :group 'org-sparse-trees
795 :type 'boolean)
797 (defcustom org-archive-location "%s_archive::"
798 "The location where subtrees should be archived.
799 This string consists of two parts, separated by a double-colon.
801 The first part is a file name - when omitted, archiving happens in the same
802 file. %s will be replaced by the current file name (without directory part).
803 Archiving to a different file is useful to keep archived entries from
804 contributing to the Org-mode Agenda.
806 The part after the double colon is a headline. The archived entries will be
807 filed under that headline. When omitted, the subtrees are simply filed away
808 at the end of the file, as top-level entries.
810 Here are a few examples:
811 \"%s_archive::\"
812 If the current file is Projects.org, archive in file
813 Projects.org_archive, as top-level trees. This is the default.
815 \"::* Archived Tasks\"
816 Archive in the current file, under the top-level headline
817 \"* Archived Tasks\".
819 \"~/org/archive.org::\"
820 Archive in file ~/org/archive.org (absolute path), as top-level trees.
822 \"basement::** Finished Tasks\"
823 Archive in file ./basement (relative path), as level 3 trees
824 below the level 2 heading \"** Finished Tasks\".
826 You may set this option on a per-file basis by adding to the buffer a
827 line like
829 #+ARCHIVE: basement::** Finished Tasks"
830 :group 'org-archive
831 :type 'string)
833 (defcustom org-archive-mark-done t
834 "Non-nil means, mark entries as DONE when they are moved to the archive file.
835 This can be a string to set the keyword to use. When t, Org-mode will
836 use the first keyword in its list that means done."
837 :group 'org-archive
838 :type '(choice
839 (const :tag "No" nil)
840 (const :tag "Yes" t)
841 (string :tag "Use this keyword")))
843 (defcustom org-archive-stamp-time t
844 "Non-nil means, add a time stamp to entries moved to an archive file.
845 This variable is obsolete and has no effect anymore, instead add ot remove
846 `time' from the variablle `org-archive-save-context-info'."
847 :group 'org-archive
848 :type 'boolean)
850 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
851 "Parts of context info that should be stored as properties when archiving.
852 When a subtree is moved to an archive file, it looses information given by
853 context, like inherited tags, the category, and possibly also the TODO
854 state (depending on the variable `org-archive-mark-done').
855 This variable can be a list of any of the following symbols:
857 time The time of archiving.
858 file The file where the entry originates.
859 itags The local tags, in the headline of the subtree.
860 ltags The tags the subtree inherits from further up the hierarchy.
861 todo The pre-archive TODO state.
862 category The category, taken from file name or #+CATEGORY lines.
863 olpath The outline path to the item. These are all headlines above
864 the current item, separated by /, like a file path.
866 For each symbol present in the list, a property will be created in
867 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
868 information."
869 :group 'org-archive
870 :type '(set :greedy t
871 (const :tag "Time" time)
872 (const :tag "File" file)
873 (const :tag "Category" category)
874 (const :tag "TODO state" todo)
875 (const :tag "TODO state" priority)
876 (const :tag "Inherited tags" itags)
877 (const :tag "Outline path" olpath)
878 (const :tag "Local tags" ltags)))
880 (defgroup org-imenu-and-speedbar nil
881 "Options concerning imenu and speedbar in Org-mode."
882 :tag "Org Imenu and Speedbar"
883 :group 'org-structure)
885 (defcustom org-imenu-depth 2
886 "The maximum level for Imenu access to Org-mode headlines.
887 This also applied for speedbar access."
888 :group 'org-imenu-and-speedbar
889 :type 'number)
891 (defgroup org-table nil
892 "Options concerning tables in Org-mode."
893 :tag "Org Table"
894 :group 'org)
896 (defcustom org-enable-table-editor 'optimized
897 "Non-nil means, lines starting with \"|\" are handled by the table editor.
898 When nil, such lines will be treated like ordinary lines.
900 When equal to the symbol `optimized', the table editor will be optimized to
901 do the following:
902 - Automatic overwrite mode in front of whitespace in table fields.
903 This makes the structure of the table stay in tact as long as the edited
904 field does not exceed the column width.
905 - Minimize the number of realigns. Normally, the table is aligned each time
906 TAB or RET are pressed to move to another field. With optimization this
907 happens only if changes to a field might have changed the column width.
908 Optimization requires replacing the functions `self-insert-command',
909 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
910 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
911 very good at guessing when a re-align will be necessary, but you can always
912 force one with \\[org-ctrl-c-ctrl-c].
914 If you would like to use the optimized version in Org-mode, but the
915 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
917 This variable can be used to turn on and off the table editor during a session,
918 but in order to toggle optimization, a restart is required.
920 See also the variable `org-table-auto-blank-field'."
921 :group 'org-table
922 :type '(choice
923 (const :tag "off" nil)
924 (const :tag "on" t)
925 (const :tag "on, optimized" optimized)))
927 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
928 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
929 In the optimized version, the table editor takes over all simple keys that
930 normally just insert a character. In tables, the characters are inserted
931 in a way to minimize disturbing the table structure (i.e. in overwrite mode
932 for empty fields). Outside tables, the correct binding of the keys is
933 restored.
935 The default for this option is t if the optimized version is also used in
936 Org-mode. See the variable `org-enable-table-editor' for details. Changing
937 this variable requires a restart of Emacs to become effective."
938 :group 'org-table
939 :type 'boolean)
941 (defcustom orgtbl-radio-table-templates
942 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
943 % END RECEIVE ORGTBL %n
944 \\begin{comment}
945 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
946 | | |
947 \\end{comment}\n")
948 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
949 @c END RECEIVE ORGTBL %n
950 @ignore
951 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
952 | | |
953 @end ignore\n")
954 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
955 <!-- END RECEIVE ORGTBL %n -->
956 <!--
957 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
958 | | |
959 -->\n"))
960 "Templates for radio tables in different major modes.
961 All occurrences of %n in a template will be replaced with the name of the
962 table, obtained by prompting the user."
963 :group 'org-table
964 :type '(repeat
965 (list (symbol :tag "Major mode")
966 (string :tag "Format"))))
968 (defgroup org-table-settings nil
969 "Settings for tables in Org-mode."
970 :tag "Org Table Settings"
971 :group 'org-table)
973 (defcustom org-table-default-size "5x2"
974 "The default size for newly created tables, Columns x Rows."
975 :group 'org-table-settings
976 :type 'string)
978 (defcustom org-table-number-regexp
979 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
980 "Regular expression for recognizing numbers in table columns.
981 If a table column contains mostly numbers, it will be aligned to the
982 right. If not, it will be aligned to the left.
984 The default value of this option is a regular expression which allows
985 anything which looks remotely like a number as used in scientific
986 context. For example, all of the following will be considered a
987 number:
988 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
990 Other options offered by the customize interface are more restrictive."
991 :group 'org-table-settings
992 :type '(choice
993 (const :tag "Positive Integers"
994 "^[0-9]+$")
995 (const :tag "Integers"
996 "^[-+]?[0-9]+$")
997 (const :tag "Floating Point Numbers"
998 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
999 (const :tag "Floating Point Number or Integer"
1000 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1001 (const :tag "Exponential, Floating point, Integer"
1002 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1003 (const :tag "Very General Number-Like, including hex"
1004 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
1005 (string :tag "Regexp:")))
1007 (defcustom org-table-number-fraction 0.5
1008 "Fraction of numbers in a column required to make the column align right.
1009 In a column all non-white fields are considered. If at least this
1010 fraction of fields is matched by `org-table-number-fraction',
1011 alignment to the right border applies."
1012 :group 'org-table-settings
1013 :type 'number)
1015 (defgroup org-table-editing nil
1016 "Behavior of tables during editing in Org-mode."
1017 :tag "Org Table Editing"
1018 :group 'org-table)
1020 (defcustom org-table-automatic-realign t
1021 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1022 When nil, aligning is only done with \\[org-table-align], or after column
1023 removal/insertion."
1024 :group 'org-table-editing
1025 :type 'boolean)
1027 (defcustom org-table-auto-blank-field t
1028 "Non-nil means, automatically blank table field when starting to type into it.
1029 This only happens when typing immediately after a field motion
1030 command (TAB, S-TAB or RET).
1031 Only relevant when `org-enable-table-editor' is equal to `optimized'."
1032 :group 'org-table-editing
1033 :type 'boolean)
1035 (defcustom org-table-tab-jumps-over-hlines t
1036 "Non-nil means, tab in the last column of a table with jump over a hline.
1037 If a horizontal separator line is following the current line,
1038 `org-table-next-field' can either create a new row before that line, or jump
1039 over the line. When this option is nil, a new line will be created before
1040 this line."
1041 :group 'org-table-editing
1042 :type 'boolean)
1044 (defcustom org-table-tab-recognizes-table.el t
1045 "Non-nil means, TAB will automatically notice a table.el table.
1046 When it sees such a table, it moves point into it and - if necessary -
1047 calls `table-recognize-table'."
1048 :group 'org-table-editing
1049 :type 'boolean)
1051 (defgroup org-table-calculation nil
1052 "Options concerning tables in Org-mode."
1053 :tag "Org Table Calculation"
1054 :group 'org-table)
1056 (defcustom org-table-use-standard-references t
1057 "Should org-mode work with table refrences like B3 instead of @3$2?
1058 Possible values are:
1059 nil never use them
1060 from accept as input, do not present for editing
1061 t: accept as input and present for editing"
1062 :group 'org-table-calculation
1063 :type '(choice
1064 (const :tag "Never, don't even check unser input for them" nil)
1065 (const :tag "Always, both as user input, and when editing" t)
1066 (const :tag "Convert user input, don't offer during editing" 'from)))
1068 (defcustom org-table-copy-increment t
1069 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1070 :group 'org-table-calculation
1071 :type 'boolean)
1073 (defcustom org-calc-default-modes
1074 '(calc-internal-prec 12
1075 calc-float-format (float 5)
1076 calc-angle-mode deg
1077 calc-prefer-frac nil
1078 calc-symbolic-mode nil
1079 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1080 calc-display-working-message t
1082 "List with Calc mode settings for use in calc-eval for table formulas.
1083 The list must contain alternating symbols (Calc modes variables and values).
1084 Don't remove any of the default settings, just change the values. Org-mode
1085 relies on the variables to be present in the list."
1086 :group 'org-table-calculation
1087 :type 'plist)
1089 (defcustom org-table-formula-evaluate-inline t
1090 "Non-nil means, TAB and RET evaluate a formula in current table field.
1091 If the current field starts with an equal sign, it is assumed to be a formula
1092 which should be evaluated as described in the manual and in the documentation
1093 string of the command `org-table-eval-formula'. This feature requires the
1094 Emacs calc package.
1095 When this variable is nil, formula calculation is only available through
1096 the command \\[org-table-eval-formula]."
1097 :group 'org-table-calculation
1098 :type 'boolean)
1100 (defcustom org-table-formula-use-constants t
1101 "Non-nil means, interpret constants in formulas in tables.
1102 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1103 by the value given in `org-table-formula-constants', or by a value obtained
1104 from the `constants.el' package."
1105 :group 'org-table-calculation
1106 :type 'boolean)
1108 (defcustom org-table-formula-constants nil
1109 "Alist with constant names and values, for use in table formulas.
1110 The car of each element is a name of a constant, without the `$' before it.
1111 The cdr is the value as a string. For example, if you'd like to use the
1112 speed of light in a formula, you would configure
1114 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1116 and then use it in an equation like `$1*$c'.
1118 Constants can also be defined on a per-file basis using a line like
1120 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1121 :group 'org-table-calculation
1122 :type '(repeat
1123 (cons (string :tag "name")
1124 (string :tag "value"))))
1126 (defvar org-table-formula-constants-local nil
1127 "Local version of `org-table-formula-constants'.")
1128 (make-variable-buffer-local 'org-table-formula-constants-local)
1130 (defcustom org-table-allow-automatic-line-recalculation t
1131 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1132 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1133 :group 'org-table-calculation
1134 :type 'boolean)
1136 (defgroup org-link nil
1137 "Options concerning links in Org-mode."
1138 :tag "Org Link"
1139 :group 'org)
1141 (defvar org-link-abbrev-alist-local nil
1142 "Buffer-local version of `org-link-abbrev-alist', which see.
1143 The value of this is taken from the #+LINK lines.")
1144 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1146 (defcustom org-link-abbrev-alist nil
1147 "Alist of link abbreviations.
1148 The car of each element is a string, to be replaced at the start of a link.
1149 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1150 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1152 [[linkkey:tag][description]]
1154 If REPLACE is a string, the tag will simply be appended to create the link.
1155 If the string contains \"%s\", the tag will be inserted there.
1157 REPLACE may also be a function that will be called with the tag as the
1158 only argument to create the link, which should be returned as a string.
1160 See the manual for examples."
1161 :group 'org-link
1162 :type 'alist)
1164 (defcustom org-descriptive-links t
1165 "Non-nil means, hide link part and only show description of bracket links.
1166 Bracket links are like [[link][descritpion]]. This variable sets the initial
1167 state in new org-mode buffers. The setting can then be toggled on a
1168 per-buffer basis from the Org->Hyperlinks menu."
1169 :group 'org-link
1170 :type 'boolean)
1172 (defcustom org-link-file-path-type 'adaptive
1173 "How the path name in file links should be stored.
1174 Valid values are:
1176 relative Relative to the current directory, i.e. the directory of the file
1177 into which the link is being inserted.
1178 absolute Absolute path, if possible with ~ for home directory.
1179 noabbrev Absolute path, no abbreviation of home directory.
1180 adaptive Use relative path for files in the current directory and sub-
1181 directories of it. For other files, use an absolute path."
1182 :group 'org-link
1183 :type '(choice
1184 (const relative)
1185 (const absolute)
1186 (const noabbrev)
1187 (const adaptive)))
1189 (defcustom org-activate-links '(bracket angle plain radio tag date)
1190 "Types of links that should be activated in Org-mode files.
1191 This is a list of symbols, each leading to the activation of a certain link
1192 type. In principle, it does not hurt to turn on most link types - there may
1193 be a small gain when turning off unused link types. The types are:
1195 bracket The recommended [[link][description]] or [[link]] links with hiding.
1196 angular Links in angular brackes that may contain whitespace like
1197 <bbdb:Carsten Dominik>.
1198 plain Plain links in normal text, no whitespace, like http://google.com.
1199 radio Text that is matched by a radio target, see manual for details.
1200 tag Tag settings in a headline (link to tag search).
1201 date Time stamps (link to calendar).
1203 Changing this variable requires a restart of Emacs to become effective."
1204 :group 'org-link
1205 :type '(set (const :tag "Double bracket links (new style)" bracket)
1206 (const :tag "Angular bracket links (old style)" angular)
1207 (const :tag "Plain text links" plain)
1208 (const :tag "Radio target matches" radio)
1209 (const :tag "Tags" tag)
1210 (const :tag "Timestamps" date)))
1212 (defgroup org-link-store nil
1213 "Options concerning storing links in Org-mode."
1214 :tag "Org Store Link"
1215 :group 'org-link)
1217 (defcustom org-email-link-description-format "Email %c: %.30s"
1218 "Format of the description part of a link to an email or usenet message.
1219 The following %-excapes will be replaced by corresponding information:
1221 %F full \"From\" field
1222 %f name, taken from \"From\" field, address if no name
1223 %T full \"To\" field
1224 %t first name in \"To\" field, address if no name
1225 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1226 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1227 %s subject
1228 %m message-id.
1230 You may use normal field width specification between the % and the letter.
1231 This is for example useful to limit the length of the subject.
1233 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1234 :group 'org-link-store
1235 :type 'string)
1237 (defcustom org-from-is-user-regexp
1238 (let (r1 r2)
1239 (when (and user-mail-address (not (string= user-mail-address "")))
1240 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1241 (when (and user-full-name (not (string= user-full-name "")))
1242 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1243 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1244 "Regexp mached against the \"From:\" header of an email or usenet message.
1245 It should match if the message is from the user him/herself."
1246 :group 'org-link-store
1247 :type 'regexp)
1249 (defcustom org-context-in-file-links t
1250 "Non-nil means, file links from `org-store-link' contain context.
1251 A search string will be added to the file name with :: as separator and
1252 used to find the context when the link is activated by the command
1253 `org-open-at-point'.
1254 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1255 negates this setting for the duration of the command."
1256 :group 'org-link-store
1257 :type 'boolean)
1259 (defcustom org-keep-stored-link-after-insertion nil
1260 "Non-nil means, keep link in list for entire session.
1262 The command `org-store-link' adds a link pointing to the current
1263 location to an internal list. These links accumulate during a session.
1264 The command `org-insert-link' can be used to insert links into any
1265 Org-mode file (offering completion for all stored links). When this
1266 option is nil, every link which has been inserted once using \\[org-insert-link]
1267 will be removed from the list, to make completing the unused links
1268 more efficient."
1269 :group 'org-link-store
1270 :type 'boolean)
1272 (defgroup org-link-follow nil
1273 "Options concerning following links in Org-mode."
1274 :tag "Org Follow Link"
1275 :group 'org-link)
1277 (defcustom org-follow-link-hook nil
1278 "Hook that is run after a link has been followed."
1279 :group 'org-link-follow
1280 :type 'hook)
1282 (defcustom org-tab-follows-link nil
1283 "Non-nil means, on links TAB will follow the link.
1284 Needs to be set before org.el is loaded."
1285 :group 'org-link-follow
1286 :type 'boolean)
1288 (defcustom org-return-follows-link nil
1289 "Non-nil means, on links RET will follow the link.
1290 Needs to be set before org.el is loaded."
1291 :group 'org-link-follow
1292 :type 'boolean)
1294 (defcustom org-mouse-1-follows-link
1295 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1296 "Non-nil means, mouse-1 on a link will follow the link.
1297 A longer mouse click will still set point. Does not work on XEmacs.
1298 Needs to be set before org.el is loaded."
1299 :group 'org-link-follow
1300 :type 'boolean)
1302 (defcustom org-mark-ring-length 4
1303 "Number of different positions to be recorded in the ring
1304 Changing this requires a restart of Emacs to work correctly."
1305 :group 'org-link-follow
1306 :type 'interger)
1308 (defcustom org-link-frame-setup
1309 '((vm . vm-visit-folder-other-frame)
1310 (gnus . gnus-other-frame)
1311 (file . find-file-other-window))
1312 "Setup the frame configuration for following links.
1313 When following a link with Emacs, it may often be useful to display
1314 this link in another window or frame. This variable can be used to
1315 set this up for the different types of links.
1316 For VM, use any of
1317 `vm-visit-folder'
1318 `vm-visit-folder-other-frame'
1319 For Gnus, use any of
1320 `gnus'
1321 `gnus-other-frame'
1322 For FILE, use any of
1323 `find-file'
1324 `find-file-other-window'
1325 `find-file-other-frame'
1326 For the calendar, use the variable `calendar-setup'.
1327 For BBDB, it is currently only possible to display the matches in
1328 another window."
1329 :group 'org-link-follow
1330 :type '(list
1331 (cons (const vm)
1332 (choice
1333 (const vm-visit-folder)
1334 (const vm-visit-folder-other-window)
1335 (const vm-visit-folder-other-frame)))
1336 (cons (const gnus)
1337 (choice
1338 (const gnus)
1339 (const gnus-other-frame)))
1340 (cons (const file)
1341 (choice
1342 (const find-file)
1343 (const find-file-other-window)
1344 (const find-file-other-frame)))))
1346 (defcustom org-display-internal-link-with-indirect-buffer nil
1347 "Non-nil means, use indirect buffer to display infile links.
1348 Activating internal links (from one location in a file to another location
1349 in the same file) normally just jumps to the location. When the link is
1350 activated with a C-u prefix (or with mouse-3), the link is displayed in
1351 another window. When this option is set, the other window actually displays
1352 an indirect buffer clone of the current buffer, to avoid any visibility
1353 changes to the current buffer."
1354 :group 'org-link-follow
1355 :type 'boolean)
1357 (defcustom org-open-non-existing-files nil
1358 "Non-nil means, `org-open-file' will open non-existing files.
1359 When nil, an error will be generated."
1360 :group 'org-link-follow
1361 :type 'boolean)
1363 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1364 "Function and arguments to call for following mailto links.
1365 This is a list with the first element being a lisp function, and the
1366 remaining elements being arguments to the function. In string arguments,
1367 %a will be replaced by the address, and %s will be replaced by the subject
1368 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1369 :group 'org-link-follow
1370 :type '(choice
1371 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1372 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1373 (const :tag "message-mail" (message-mail "%a" "%s"))
1374 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1376 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1377 "Non-nil means, ask for confirmation before executing shell links.
1378 Shell links can be dangerous: just think about a link
1380 [[shell:rm -rf ~/*][Google Search]]
1382 This link would show up in your Org-mode document as \"Google Search\",
1383 but really it would remove your entire home directory.
1384 Therefore we advise against setting this variable to nil.
1385 Just change it to `y-or-n-p' of you want to confirm with a
1386 single keystroke rather than having to type \"yes\"."
1387 :group 'org-link-follow
1388 :type '(choice
1389 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1390 (const :tag "with y-or-n (faster)" y-or-n-p)
1391 (const :tag "no confirmation (dangerous)" nil)))
1393 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1394 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1395 Elisp links can be dangerous: just think about a link
1397 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1399 This link would show up in your Org-mode document as \"Google Search\",
1400 but really it would remove your entire home directory.
1401 Therefore we advise against setting this variable to nil.
1402 Just change it to `y-or-n-p' of you want to confirm with a
1403 single keystroke rather than having to type \"yes\"."
1404 :group 'org-link-follow
1405 :type '(choice
1406 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1407 (const :tag "with y-or-n (faster)" y-or-n-p)
1408 (const :tag "no confirmation (dangerous)" nil)))
1410 (defconst org-file-apps-defaults-gnu
1411 '((remote . emacs)
1412 (t . mailcap))
1413 "Default file applications on a UNIX or GNU/Linux system.
1414 See `org-file-apps'.")
1416 (defconst org-file-apps-defaults-macosx
1417 '((remote . emacs)
1418 (t . "open %s")
1419 ("ps" . "gv %s")
1420 ("ps.gz" . "gv %s")
1421 ("eps" . "gv %s")
1422 ("eps.gz" . "gv %s")
1423 ("dvi" . "xdvi %s")
1424 ("fig" . "xfig %s"))
1425 "Default file applications on a MacOS X system.
1426 The system \"open\" is known as a default, but we use X11 applications
1427 for some files for which the OS does not have a good default.
1428 See `org-file-apps'.")
1430 (defconst org-file-apps-defaults-windowsnt
1431 (list
1432 '(remote . emacs)
1433 (cons t
1434 (list (if (featurep 'xemacs)
1435 'mswindows-shell-execute
1436 'w32-shell-execute)
1437 "open" 'file)))
1438 "Default file applications on a Windows NT system.
1439 The system \"open\" is used for most files.
1440 See `org-file-apps'.")
1442 (defcustom org-file-apps
1444 ("txt" . emacs)
1445 ("tex" . emacs)
1446 ("ltx" . emacs)
1447 ("org" . emacs)
1448 ("el" . emacs)
1449 ("bib" . emacs)
1451 "External applications for opening `file:path' items in a document.
1452 Org-mode uses system defaults for different file types, but
1453 you can use this variable to set the application for a given file
1454 extension. The entries in this list are cons cells where the car identifies
1455 files and the cdr the corresponding command. Possible values for the
1456 file identifier are
1457 \"ext\" A string identifying an extension
1458 `directory' Matches a directory
1459 `remote' Matches a remote file, accessible through tramp or efs.
1460 Remote files most likely should be visited through Emacs
1461 because external applications cannot handle such paths.
1462 t Default for all remaining files
1464 Possible values for the command are:
1465 `emacs' The file will be visited by the current Emacs process.
1466 `default' Use the default application for this file type.
1467 string A command to be executed by a shell; %s will be replaced
1468 by the path to the file.
1469 sexp A Lisp form which will be evaluated. The file path will
1470 be available in the Lisp variable `file'.
1471 For more examples, see the system specific constants
1472 `org-file-apps-defaults-macosx'
1473 `org-file-apps-defaults-windowsnt'
1474 `org-file-apps-defaults-gnu'."
1475 :group 'org-link-follow
1476 :type '(repeat
1477 (cons (choice :value ""
1478 (string :tag "Extension")
1479 (const :tag "Default for unrecognized files" t)
1480 (const :tag "Remote file" remote)
1481 (const :tag "Links to a directory" directory))
1482 (choice :value ""
1483 (const :tag "Visit with Emacs" emacs)
1484 (const :tag "Use system default" default)
1485 (string :tag "Command")
1486 (sexp :tag "Lisp form")))))
1488 (defgroup org-remember nil
1489 "Options concerning interaction with remember.el."
1490 :tag "Org Remember"
1491 :group 'org)
1493 (defcustom org-directory "~/org"
1494 "Directory with org files.
1495 This directory will be used as default to prompt for org files.
1496 Used by the hooks for remember.el."
1497 :group 'org-remember
1498 :type 'directory)
1500 (defcustom org-default-notes-file "~/.notes"
1501 "Default target for storing notes.
1502 Used by the hooks for remember.el. This can be a string, or nil to mean
1503 the value of `remember-data-file'.
1504 You can set this on a per-template basis with the variable
1505 `org-remember-templates'."
1506 :group 'org-remember
1507 :type '(choice
1508 (const :tag "Default from remember-data-file" nil)
1509 file))
1511 (defcustom org-remember-store-without-prompt t
1512 "Non-nil means, `C-c C-c' stores remember note without further promts.
1513 In this case, you need `C-u C-c C-c' to get the prompts for
1514 note file and headline.
1515 When this variable is nil, `C-c C-c' give you the prompts, and
1516 `C-u C-c C-c' trigger the fasttrack."
1517 :group 'org-remember
1518 :type 'boolean)
1520 (defcustom org-remember-interactive-interface 'refile
1521 "The interface to be used for interactive filing of remember notes.
1522 This is only used when the interactive mode for selecting a filing
1523 location is used (see the variable `org-remember-store-without-prompt').
1524 Allowed vaues are:
1525 outline The interface shows an outline of the relevant file
1526 and the correct heading is found by moving through
1527 the outline or by searching with incremental search.
1528 outline-path-completion Headlines in the current buffer are offered via
1529 completion.
1530 refile Use the refile interface, and offer headlines,
1531 possibly from different buffers."
1532 :group 'org-remember
1533 :type '(choice
1534 (const :tag "Refile" refile)
1535 (const :tag "Outline" outline)
1536 (const :tag "Outline-path-completion" outline-path-completion)))
1538 (defcustom org-goto-interface 'outline
1539 "The default interface to be used for `org-goto'.
1540 Allowed vaues are:
1541 outline The interface shows an outline of the relevant file
1542 and the correct heading is found by moving through
1543 the outline or by searching with incremental search.
1544 outline-path-completion Headlines in the current buffer are offered via
1545 completion."
1546 :group 'org-remember ; FIXME: different group for org-goto and org-refile
1547 :type '(choice
1548 (const :tag "Outline" outline)
1549 (const :tag "Outline-path-completion" outline-path-completion)))
1551 (defcustom org-remember-default-headline ""
1552 "The headline that should be the default location in the notes file.
1553 When filing remember notes, the cursor will start at that position.
1554 You can set this on a per-template basis with the variable
1555 `org-remember-templates'."
1556 :group 'org-remember
1557 :type 'string)
1559 (defcustom org-remember-templates nil
1560 "Templates for the creation of remember buffers.
1561 When nil, just let remember make the buffer.
1562 When not nil, this is a list of 5-element lists. In each entry, the first
1563 element is the name of the template, which should be a single short word.
1564 The second element is a character, a unique key to select this template.
1565 The third element is the template.
1567 The fourth element is optional and can specify a destination file for
1568 remember items created with this template. The default file is given
1569 by `org-default-notes-file'. If the file name is not an absolute path,
1570 it will be interpreted relative to `org-directory'.
1572 An optional fifth element can specify the headline in that file that should
1573 be offered first when the user is asked to file the entry. The default
1574 headline is given in the variable `org-remember-default-headline'.
1576 An optional sixth element specifies the contexts in which the user can
1577 select the template. This element can be either a list of major modes
1578 or a function. `org-remember' will first check whether the function
1579 returns `t' or if we are in any of the listed major modes, and select
1580 the template accordingly.
1582 The template specifies the structure of the remember buffer. It should have
1583 a first line starting with a star, to act as the org-mode headline.
1584 Furthermore, the following %-escapes will be replaced with content:
1586 %^{prompt} Prompt the user for a string and replace this sequence with it.
1587 A default value and a completion table ca be specified like this:
1588 %^{prompt|default|completion2|completion3|...}
1589 %t time stamp, date only
1590 %T time stamp with date and time
1591 %u, %U like the above, but inactive time stamps
1592 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1593 You may define a prompt like %^{Please specify birthday}t
1594 %n user name (taken from `user-full-name')
1595 %a annotation, normally the link created with org-store-link
1596 %i initial content, the region active. If %i is indented,
1597 the entire inserted text will be indented as well.
1598 %c content of the clipboard, or current kill ring head
1599 %^g prompt for tags, with completion on tags in target file
1600 %^G prompt for tags, with completion all tags in all agenda files
1601 %:keyword specific information for certain link types, see below
1602 %[pathname] insert the contents of the file given by `pathname'
1603 %(sexp) evaluate elisp `(sexp)' and replace with the result
1604 %! Store this note immediately after filling the template
1606 %? After completing the template, position cursor here.
1608 Apart from these general escapes, you can access information specific to the
1609 link type that is created. For example, calling `remember' in emails or gnus
1610 will record the author and the subject of the message, which you can access
1611 with %:author and %:subject, respectively. Here is a complete list of what
1612 is recorded for each link type.
1614 Link type | Available information
1615 -------------------+------------------------------------------------------
1616 bbdb | %:type %:name %:company
1617 vm, wl, mh, rmail | %:type %:subject %:message-id
1618 | %:from %:fromname %:fromaddress
1619 | %:to %:toname %:toaddress
1620 | %:fromto (either \"to NAME\" or \"from NAME\")
1621 gnus | %:group, for messages also all email fields
1622 w3, w3m | %:type %:url
1623 info | %:type %:file %:node
1624 calendar | %:type %:date"
1625 :group 'org-remember
1626 :get (lambda (var) ; Make sure all entries have at least 5 elements
1627 (mapcar (lambda (x)
1628 (if (not (stringp (car x))) (setq x (cons "" x)))
1629 (cond ((= (length x) 4) (append x '("")))
1630 ((= (length x) 3) (append x '("" "")))
1631 (t x)))
1632 (default-value var)))
1633 :type '(repeat
1634 :tag "enabled"
1635 (list :value ("" ?a "\n" nil nil nil)
1636 (string :tag "Name")
1637 (character :tag "Selection Key")
1638 (string :tag "Template")
1639 (choice
1640 (file :tag "Destination file")
1641 (const :tag "Prompt for file" nil))
1642 (choice
1643 (string :tag "Destination headline")
1644 (const :tag "Selection interface for heading"))
1645 (choice
1646 (const :tag "Use by default" nil)
1647 (const :tag "Use in all contexts" t)
1648 (repeat :tag "Use only if in major mode"
1649 (symbol :tag "Major mode"))
1650 (function :tag "Perform a check against function")))))
1652 (defcustom org-reverse-note-order nil
1653 "Non-nil means, store new notes at the beginning of a file or entry.
1654 When nil, new notes will be filed to the end of a file or entry.
1655 This can also be a list with cons cells of regular expressions that
1656 are matched against file names, and values."
1657 :group 'org-remember
1658 :type '(choice
1659 (const :tag "Reverse always" t)
1660 (const :tag "Reverse never" nil)
1661 (repeat :tag "By file name regexp"
1662 (cons regexp boolean))))
1664 (defcustom org-refile-targets nil
1665 "Targets for refiling entries with \\[org-refile].
1666 This is list of cons cells. Each cell contains:
1667 - a specification of the files to be considered, either a list of files,
1668 or a symbol whose function or value fields will be used to retrieve
1669 a file name or a list of file names. Nil means, refile to a different
1670 heading in the current buffer.
1671 - A specification of how to find candidate refile targets. This may be
1672 any of
1673 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1674 This tag has to be present in all target headlines, inheritance will
1675 not be considered.
1676 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1677 todo keyword.
1678 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1679 headlines that are refiling targets.
1680 - a cons cell (:level . N). Any headline of level N is considered a target.
1681 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1682 ;; FIXME: what if there are a var and func with same name???
1683 :group 'org-remember
1684 :type '(repeat
1685 (cons
1686 (choice :value org-agenda-files
1687 (const :tag "All agenda files" org-agenda-files)
1688 (const :tag "Current buffer" nil)
1689 (function) (variable) (file))
1690 (choice :tag "Identify target headline by"
1691 (cons :tag "Specific tag" (const :tag) (string))
1692 (cons :tag "TODO keyword" (const :todo) (string))
1693 (cons :tag "Regular expression" (const :regexp) (regexp))
1694 (cons :tag "Level number" (const :level) (integer))
1695 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1697 (defcustom org-refile-use-outline-path nil
1698 "Non-nil means, provide refile targets as paths.
1699 So a level 3 headline will be available as level1/level2/level3.
1700 When the value is `file', also include the file name (without directory)
1701 into the path. When `full-file-path', include the full file path."
1702 :group 'org-remember
1703 :type '(choice
1704 (const :tag "Not" nil)
1705 (const :tag "Yes" t)
1706 (const :tag "Start with file name" file)
1707 (const :tag "Start with full file path" full-file-path)))
1709 (defgroup org-todo nil
1710 "Options concerning TODO items in Org-mode."
1711 :tag "Org TODO"
1712 :group 'org)
1714 (defgroup org-progress nil
1715 "Options concerning Progress logging in Org-mode."
1716 :tag "Org Progress"
1717 :group 'org-time)
1719 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1720 "List of TODO entry keyword sequences and their interpretation.
1721 \\<org-mode-map>This is a list of sequences.
1723 Each sequence starts with a symbol, either `sequence' or `type',
1724 indicating if the keywords should be interpreted as a sequence of
1725 action steps, or as different types of TODO items. The first
1726 keywords are states requiring action - these states will select a headline
1727 for inclusion into the global TODO list Org-mode produces. If one of
1728 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1729 signify that no further action is necessary. If \"|\" is not found,
1730 the last keyword is treated as the only DONE state of the sequence.
1732 The command \\[org-todo] cycles an entry through these states, and one
1733 additional state where no keyword is present. For details about this
1734 cycling, see the manual.
1736 TODO keywords and interpretation can also be set on a per-file basis with
1737 the special #+SEQ_TODO and #+TYP_TODO lines.
1739 Each keyword can optionally specify a character for fast state selection
1740 \(in combination with the variable `org-use-fast-todo-selection')
1741 and specifiers for state change logging, using the same syntax
1742 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1743 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1744 indicates to record a time stamp each time this state is selected.
1746 Each keyword may also specify if a timestamp or a note should be
1747 recorded when entering or leaving the state, by adding additional
1748 characters in the parenthesis after the keyword. This looks like this:
1749 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1750 record only the time of the state change. With X and Y being either
1751 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1752 Y when leaving the state if and only if the *target* state does not
1753 define X. You may omit any of the fast-selection key or X or /Y,
1754 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1756 For backward compatibility, this variable may also be just a list
1757 of keywords - in this case the interptetation (sequence or type) will be
1758 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1759 :group 'org-todo
1760 :group 'org-keywords
1761 :type '(choice
1762 (repeat :tag "Old syntax, just keywords"
1763 (string :tag "Keyword"))
1764 (repeat :tag "New syntax"
1765 (cons
1766 (choice
1767 :tag "Interpretation"
1768 (const :tag "Sequence (cycling hits every state)" sequence)
1769 (const :tag "Type (cycling directly to DONE)" type))
1770 (repeat
1771 (string :tag "Keyword"))))))
1773 (defvar org-todo-keywords-1 nil
1774 "All TODO and DONE keywords active in a buffer.")
1775 (make-variable-buffer-local 'org-todo-keywords-1)
1776 (defvar org-todo-keywords-for-agenda nil)
1777 (defvar org-done-keywords-for-agenda nil)
1778 (defvar org-not-done-keywords nil)
1779 (make-variable-buffer-local 'org-not-done-keywords)
1780 (defvar org-done-keywords nil)
1781 (make-variable-buffer-local 'org-done-keywords)
1782 (defvar org-todo-heads nil)
1783 (make-variable-buffer-local 'org-todo-heads)
1784 (defvar org-todo-sets nil)
1785 (make-variable-buffer-local 'org-todo-sets)
1786 (defvar org-todo-log-states nil)
1787 (make-variable-buffer-local 'org-todo-log-states)
1788 (defvar org-todo-kwd-alist nil)
1789 (make-variable-buffer-local 'org-todo-kwd-alist)
1790 (defvar org-todo-key-alist nil)
1791 (make-variable-buffer-local 'org-todo-key-alist)
1792 (defvar org-todo-key-trigger nil)
1793 (make-variable-buffer-local 'org-todo-key-trigger)
1795 (defcustom org-todo-interpretation 'sequence
1796 "Controls how TODO keywords are interpreted.
1797 This variable is in principle obsolete and is only used for
1798 backward compatibility, if the interpretation of todo keywords is
1799 not given already in `org-todo-keywords'. See that variable for
1800 more information."
1801 :group 'org-todo
1802 :group 'org-keywords
1803 :type '(choice (const sequence)
1804 (const type)))
1806 (defcustom org-use-fast-todo-selection 'prefix
1807 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1808 This variable describes if and under what circumstances the cycling
1809 mechanism for TODO keywords will be replaced by a single-key, direct
1810 selection scheme.
1812 When nil, fast selection is never used.
1814 When the symbol `prefix', it will be used when `org-todo' is called with
1815 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1816 in an agenda buffer.
1818 When t, fast selection is used by default. In this case, the prefix
1819 argument forces cycling instead.
1821 In all cases, the special interface is only used if access keys have actually
1822 been assigned by the user, i.e. if keywords in the configuration are followed
1823 by a letter in parenthesis, like TODO(t)."
1824 :group 'org-todo
1825 :type '(choice
1826 (const :tag "Never" nil)
1827 (const :tag "By default" t)
1828 (const :tag "Only with C-u C-c C-t" prefix)))
1830 (defcustom org-after-todo-state-change-hook nil
1831 "Hook which is run after the state of a TODO item was changed.
1832 The new state (a string with a TODO keyword, or nil) is available in the
1833 Lisp variable `state'."
1834 :group 'org-todo
1835 :type 'hook)
1837 (defcustom org-log-done nil
1838 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1839 When equal to the list (done), also prompt for a closing note.
1840 This can also be configured on a per-file basis by adding one of
1841 the following lines anywhere in the buffer:
1843 #+STARTUP: logdone
1844 #+STARTUP: lognotedone
1845 #+STARTUP: nologdone"
1846 :group 'org-todo
1847 :group 'org-progress
1848 :type '(choice
1849 (const :tag "No logging" nil)
1850 (const :tag "Record CLOSED timestamp" time)
1851 (const :tag "Record CLOSED timestamp with closing note." note)))
1853 ;; Normalize old uses of org-log-done.
1854 (cond
1855 ((eq org-log-done t) (setq org-log-done 'time))
1856 ((and (listp org-log-done) (memq 'done org-log-done))
1857 (setq org-log-done 'note)))
1859 ;; FIXME: document
1860 (defcustom org-log-note-clock-out nil
1861 "Non-nil means, recored a note when clocking out of an item.
1862 This can also be configured on a per-file basis by adding one of
1863 the following lines anywhere in the buffer:
1865 #+STARTUP: lognoteclock-out
1866 #+STARTUP: nolognoteclock-out"
1867 :group 'org-todo
1868 :group 'org-progress
1869 :type 'boolean)
1871 (defcustom org-log-done-with-time t
1872 "Non-nil means, the CLOSED time stamp will contain date and time.
1873 When nil, only the date will be recorded."
1874 :group 'org-progress
1875 :type 'boolean)
1877 (defcustom org-log-note-headings
1878 '((done . "CLOSING NOTE %t")
1879 (state . "State %-12s %t")
1880 (clock-out . ""))
1881 "Headings for notes added when clocking out or closing TODO items.
1882 The value is an alist, with the car being a symbol indicating the note
1883 context, and the cdr is the heading to be used. The heading may also be the
1884 empty string.
1885 %t in the heading will be replaced by a time stamp.
1886 %s will be replaced by the new TODO state, in double quotes.
1887 %u will be replaced by the user name.
1888 %U will be replaced by the full user name."
1889 :group 'org-todo
1890 :group 'org-progress
1891 :type '(list :greedy t
1892 (cons (const :tag "Heading when closing an item" done) string)
1893 (cons (const :tag
1894 "Heading when changing todo state (todo sequence only)"
1895 state) string)
1896 (cons (const :tag "Heading when clocking out" clock-out) string)))
1898 (defcustom org-log-states-order-reversed t
1899 "Non-nil means, the latest state change note will be directly after heading.
1900 When nil, the notes will be orderer according to time."
1901 :group 'org-todo
1902 :group 'org-progress
1903 :type 'boolean)
1905 (defcustom org-log-repeat 'time
1906 "Non-nil means, record moving through the DONE state when triggering repeat.
1907 An auto-repeating tasks is immediately switched back to TODO when marked
1908 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1909 the TODO keyword definition, or recording a cloing note by setting
1910 `org-log-done', there will be no record of the task moving trhough DONE.
1911 This variable forces taking a note anyway. Possible values are:
1913 nil Don't force a record
1914 time Record a time stamp
1915 note Record a note
1917 This option can also be set with on a per-file-basis with
1919 #+STARTUP: logrepeat
1920 #+STARTUP: lognoterepeat
1921 #+STARTUP: nologrepeat
1923 You can have local logging settings for a subtree by setting the LOGGING
1924 property to one or more of these keywords."
1925 :group 'org-todo
1926 :group 'org-progress
1927 :type '(choice
1928 (const :tag "Don't force a record" nil)
1929 (const :tag "Force recording the DONE state" time)
1930 (const :tag "Force recording a note with the DONE state" note)))
1932 (defcustom org-clock-into-drawer 2
1933 "Should clocking info be wrapped into a drawer?
1934 When t, clocking info will always be inserted into a :CLOCK: drawer.
1935 If necessary, the drawer will be created.
1936 When nil, the drawer will not be created, but used when present.
1937 When an integer and the number of clocking entries in an item
1938 reaches or exceeds this number, a drawer will be created."
1939 :group 'org-todo
1940 :group 'org-progress
1941 :type '(choice
1942 (const :tag "Always" t)
1943 (const :tag "Only when drawer exists" nil)
1944 (integer :tag "When at least N clock entries")))
1946 (defcustom org-clock-out-when-done t
1947 "When t, the clock will be stopped when the relevant entry is marked DONE.
1948 Nil means, clock will keep running until stopped explicitly with
1949 `C-c C-x C-o', or until the clock is started in a different item."
1950 :group 'org-progress
1951 :type 'boolean)
1953 (defcustom org-clock-in-switch-to-state nil
1954 "Set task to a special todo state while clocking it.
1955 The value should be the state to which the entry should be switched."
1956 :group 'org-progress
1957 :group 'org-todo
1958 :type '(choice
1959 (const :tag "Don't force a state" nil)
1960 (string :tag "State")))
1962 (defgroup org-priorities nil
1963 "Priorities in Org-mode."
1964 :tag "Org Priorities"
1965 :group 'org-todo)
1967 (defcustom org-highest-priority ?A
1968 "The highest priority of TODO items. A character like ?A, ?B etc.
1969 Must have a smaller ASCII number than `org-lowest-priority'."
1970 :group 'org-priorities
1971 :type 'character)
1973 (defcustom org-lowest-priority ?C
1974 "The lowest priority of TODO items. A character like ?A, ?B etc.
1975 Must have a larger ASCII number than `org-highest-priority'."
1976 :group 'org-priorities
1977 :type 'character)
1979 (defcustom org-default-priority ?B
1980 "The default priority of TODO items.
1981 This is the priority an item get if no explicit priority is given."
1982 :group 'org-priorities
1983 :type 'character)
1985 (defcustom org-priority-start-cycle-with-default t
1986 "Non-nil means, start with default priority when starting to cycle.
1987 When this is nil, the first step in the cycle will be (depending on the
1988 command used) one higher or lower that the default priority."
1989 :group 'org-priorities
1990 :type 'boolean)
1992 (defgroup org-time nil
1993 "Options concerning time stamps and deadlines in Org-mode."
1994 :tag "Org Time"
1995 :group 'org)
1997 (defcustom org-insert-labeled-timestamps-at-point nil
1998 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1999 When nil, these labeled time stamps are forces into the second line of an
2000 entry, just after the headline. When scheduling from the global TODO list,
2001 the time stamp will always be forced into the second line."
2002 :group 'org-time
2003 :type 'boolean)
2005 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2006 "Formats for `format-time-string' which are used for time stamps.
2007 It is not recommended to change this constant.")
2009 (defcustom org-time-stamp-rounding-minutes '(0 5)
2010 "Number of minutes to round time stamps to.
2011 These are two values, the first applies when first creating a time stamp.
2012 The second applies when changing it with the commands `S-up' and `S-down'.
2013 When changing the time stamp, this means that it will change in steps
2014 of N minutes, as given by the second value.
2016 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2017 numbers should be factors of 60, so for example 5, 10, 15.
2019 When this is larger than 1, you can still force an exact time-stamp by using
2020 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2021 and by using a prefix arg to `S-up/down' to specify the exact number
2022 of minutes to shift."
2023 :group 'org-time
2024 :get '(lambda (var) ; Make sure all entries have 5 elements
2025 (if (integerp (default-value var))
2026 (list (default-value var) 5)
2027 (default-value var)))
2028 :type '(list
2029 (integer :tag "when inserting times")
2030 (integer :tag "when modifying times")))
2032 ;; Make sure old customizations of this variable don't lead to problems.
2033 (when (integerp org-time-stamp-rounding-minutes)
2034 (setq org-time-stamp-rounding-minutes
2035 (list org-time-stamp-rounding-minutes
2036 org-time-stamp-rounding-minutes)))
2038 (defcustom org-display-custom-times nil
2039 "Non-nil means, overlay custom formats over all time stamps.
2040 The formats are defined through the variable `org-time-stamp-custom-formats'.
2041 To turn this on on a per-file basis, insert anywhere in the file:
2042 #+STARTUP: customtime"
2043 :group 'org-time
2044 :set 'set-default
2045 :type 'sexp)
2046 (make-variable-buffer-local 'org-display-custom-times)
2048 (defcustom org-time-stamp-custom-formats
2049 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2050 "Custom formats for time stamps. See `format-time-string' for the syntax.
2051 These are overlayed over the default ISO format if the variable
2052 `org-display-custom-times' is set. Time like %H:%M should be at the
2053 end of the second format."
2054 :group 'org-time
2055 :type 'sexp)
2057 (defun org-time-stamp-format (&optional long inactive)
2058 "Get the right format for a time string."
2059 (let ((f (if long (cdr org-time-stamp-formats)
2060 (car org-time-stamp-formats))))
2061 (if inactive
2062 (concat "[" (substring f 1 -1) "]")
2063 f)))
2065 (defcustom org-read-date-prefer-future t
2066 "Non-nil means, assume future for incomplete date input from user.
2067 This affects the following situations:
2068 1. The user gives a day, but no month.
2069 For example, if today is the 15th, and you enter \"3\", Org-mode will
2070 read this as the third of *next* month. However, if you enter \"17\",
2071 it will be considered as *this* month.
2072 2. The user gives a month but not a year.
2073 For example, if it is april and you enter \"feb 2\", this will be read
2074 as feb 2, *next* year. \"May 5\", however, will be this year.
2076 Currently this does not work for ISO week specifications.
2078 When this option is nil, the current month and year will always be used
2079 as defaults."
2080 :group 'org-time
2081 :type 'boolean)
2083 (defcustom org-read-date-display-live t
2084 "Non-nil means, display current interpretation of date prompt live.
2085 This display will be in an overlay, in the minibuffer."
2086 :group 'org-time
2087 :type 'boolean)
2089 (defcustom org-read-date-popup-calendar t
2090 "Non-nil means, pop up a calendar when prompting for a date.
2091 In the calendar, the date can be selected with mouse-1. However, the
2092 minibuffer will also be active, and you can simply enter the date as well.
2093 When nil, only the minibuffer will be available."
2094 :group 'org-time
2095 :type 'boolean)
2096 (if (fboundp 'defvaralias)
2097 (defvaralias 'org-popup-calendar-for-date-prompt
2098 'org-read-date-popup-calendar))
2100 (defcustom org-extend-today-until 0
2101 "The hour when your day really ends.
2102 This has influence for the following applications:
2103 - When switching the agenda to \"today\". It it is still earlier than
2104 the time given here, the day recognized as TODAY is actually yesterday.
2105 - When a date is read from the user and it is still before the time given
2106 here, the current date and time will be assumed to be yesterday, 23:59.
2108 FIXME:
2109 IMPORTANT: This is still a very experimental feature, it may disappear
2110 again or it may be extended to mean more things."
2111 :group 'org-time
2112 :type 'number)
2114 (defcustom org-edit-timestamp-down-means-later nil
2115 "Non-nil means, S-down will increase the time in a time stamp.
2116 When nil, S-up will increase."
2117 :group 'org-time
2118 :type 'boolean)
2120 (defcustom org-calendar-follow-timestamp-change t
2121 "Non-nil means, make the calendar window follow timestamp changes.
2122 When a timestamp is modified and the calendar window is visible, it will be
2123 moved to the new date."
2124 :group 'org-time
2125 :type 'boolean)
2127 (defcustom org-clock-heading-function nil
2128 "When non-nil, should be a function to create `org-clock-heading'.
2129 This is the string shown in the mode line when a clock is running.
2130 The function is called with point at the beginning of the headline."
2131 :group 'org-time ; FIXME: Should we have a separate group????
2132 :type 'function)
2134 (defgroup org-tags nil
2135 "Options concerning tags in Org-mode."
2136 :tag "Org Tags"
2137 :group 'org)
2139 (defcustom org-tag-alist nil
2140 "List of tags allowed in Org-mode files.
2141 When this list is nil, Org-mode will base TAG input on what is already in the
2142 buffer.
2143 The value of this variable is an alist, the car of each entry must be a
2144 keyword as a string, the cdr may be a character that is used to select
2145 that tag through the fast-tag-selection interface.
2146 See the manual for details."
2147 :group 'org-tags
2148 :type '(repeat
2149 (choice
2150 (cons (string :tag "Tag name")
2151 (character :tag "Access char"))
2152 (const :tag "Start radio group" (:startgroup))
2153 (const :tag "End radio group" (:endgroup)))))
2155 (defcustom org-use-fast-tag-selection 'auto
2156 "Non-nil means, use fast tag selection scheme.
2157 This is a special interface to select and deselect tags with single keys.
2158 When nil, fast selection is never used.
2159 When the symbol `auto', fast selection is used if and only if selection
2160 characters for tags have been configured, either through the variable
2161 `org-tag-alist' or through a #+TAGS line in the buffer.
2162 When t, fast selection is always used and selection keys are assigned
2163 automatically if necessary."
2164 :group 'org-tags
2165 :type '(choice
2166 (const :tag "Always" t)
2167 (const :tag "Never" nil)
2168 (const :tag "When selection characters are configured" 'auto)))
2170 (defcustom org-fast-tag-selection-single-key nil
2171 "Non-nil means, fast tag selection exits after first change.
2172 When nil, you have to press RET to exit it.
2173 During fast tag selection, you can toggle this flag with `C-c'.
2174 This variable can also have the value `expert'. In this case, the window
2175 displaying the tags menu is not even shown, until you press C-c again."
2176 :group 'org-tags
2177 :type '(choice
2178 (const :tag "No" nil)
2179 (const :tag "Yes" t)
2180 (const :tag "Expert" expert)))
2182 (defvar org-fast-tag-selection-include-todo nil
2183 "Non-nil means, fast tags selection interface will also offer TODO states.
2184 This is an undocumented feature, you should not rely on it.")
2186 (defcustom org-tags-column -80
2187 "The column to which tags should be indented in a headline.
2188 If this number is positive, it specifies the column. If it is negative,
2189 it means that the tags should be flushright to that column. For example,
2190 -80 works well for a normal 80 character screen."
2191 :group 'org-tags
2192 :type 'integer)
2194 (defcustom org-auto-align-tags t
2195 "Non-nil means, realign tags after pro/demotion of TODO state change.
2196 These operations change the length of a headline and therefore shift
2197 the tags around. With this options turned on, after each such operation
2198 the tags are again aligned to `org-tags-column'."
2199 :group 'org-tags
2200 :type 'boolean)
2202 (defcustom org-use-tag-inheritance t
2203 "Non-nil means, tags in levels apply also for sublevels.
2204 When nil, only the tags directly given in a specific line apply there.
2205 If you turn off this option, you very likely want to turn on the
2206 companion option `org-tags-match-list-sublevels'."
2207 :group 'org-tags
2208 :type 'boolean)
2210 (defcustom org-tags-match-list-sublevels nil
2211 "Non-nil means list also sublevels of headlines matching tag search.
2212 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2213 the sublevels of a headline matching a tag search often also match
2214 the same search. Listing all of them can create very long lists.
2215 Setting this variable to nil causes subtrees of a match to be skipped.
2216 This option is off by default, because inheritance in on. If you turn
2217 inheritance off, you very likely want to turn this option on.
2219 As a special case, if the tag search is restricted to TODO items, the
2220 value of this variable is ignored and sublevels are always checked, to
2221 make sure all corresponding TODO items find their way into the list."
2222 :group 'org-tags
2223 :type 'boolean)
2225 (defvar org-tags-history nil
2226 "History of minibuffer reads for tags.")
2227 (defvar org-last-tags-completion-table nil
2228 "The last used completion table for tags.")
2229 (defvar org-after-tags-change-hook nil
2230 "Hook that is run after the tags in a line have changed.")
2232 (defgroup org-properties nil
2233 "Options concerning properties in Org-mode."
2234 :tag "Org Properties"
2235 :group 'org)
2237 (defcustom org-property-format "%-10s %s"
2238 "How property key/value pairs should be formatted by `indent-line'.
2239 When `indent-line' hits a property definition, it will format the line
2240 according to this format, mainly to make sure that the values are
2241 lined-up with respect to each other."
2242 :group 'org-properties
2243 :type 'string)
2245 (defcustom org-use-property-inheritance nil
2246 "Non-nil means, properties apply also for sublevels.
2247 This setting is only relevant during property searches, not when querying
2248 an entry with `org-entry-get'. To retrieve a property with inheritance,
2249 you need to call `org-entry-get' with the inheritance flag.
2250 Turning this on can cause significant overhead when doing a search, so
2251 this is turned off by default.
2252 When nil, only the properties directly given in the current entry count.
2253 The value may also be a list of properties that shouldhave inheritance.
2255 However, note that some special properties use inheritance under special
2256 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2257 and the properties ending in \"_ALL\" when they are used as descriptor
2258 for valid values of a property."
2259 :group 'org-properties
2260 :type '(choice
2261 (const :tag "Not" nil)
2262 (const :tag "Always" nil)
2263 (repeat :tag "Specific properties" (string :tag "Property"))))
2265 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2266 "The default column format, if no other format has been defined.
2267 This variable can be set on the per-file basis by inserting a line
2269 #+COLUMNS: %25ITEM ....."
2270 :group 'org-properties
2271 :type 'string)
2273 (defcustom org-global-properties nil
2274 "List of property/value pairs that can be inherited by any entry.
2275 You can set buffer-local values for this by adding lines like
2277 #+PROPERTY: NAME VALUE"
2278 :group 'org-properties
2279 :type '(repeat
2280 (cons (string :tag "Property")
2281 (string :tag "Value"))))
2283 (defvar org-local-properties nil
2284 "List of property/value pairs that can be inherited by any entry.
2285 Valid for the current buffer.
2286 This variable is populated from #+PROPERTY lines.")
2288 (defgroup org-agenda nil
2289 "Options concerning agenda views in Org-mode."
2290 :tag "Org Agenda"
2291 :group 'org)
2293 (defvar org-category nil
2294 "Variable used by org files to set a category for agenda display.
2295 Such files should use a file variable to set it, for example
2297 # -*- mode: org; org-category: \"ELisp\"
2299 or contain a special line
2301 #+CATEGORY: ELisp
2303 If the file does not specify a category, then file's base name
2304 is used instead.")
2305 (make-variable-buffer-local 'org-category)
2307 (defcustom org-agenda-files nil
2308 "The files to be used for agenda display.
2309 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2310 \\[org-remove-file]. You can also use customize to edit the list.
2312 If an entry is a directory, all files in that directory that are matched by
2313 `org-agenda-file-regexp' will be part of the file list.
2315 If the value of the variable is not a list but a single file name, then
2316 the list of agenda files is actually stored and maintained in that file, one
2317 agenda file per line."
2318 :group 'org-agenda
2319 :type '(choice
2320 (repeat :tag "List of files and directories" file)
2321 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2323 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2324 "Regular expression to match files for `org-agenda-files'.
2325 If any element in the list in that variable contains a directory instead
2326 of a normal file, all files in that directory that are matched by this
2327 regular expression will be included."
2328 :group 'org-agenda
2329 :type 'regexp)
2331 (defcustom org-agenda-skip-unavailable-files nil
2332 "t means to just skip non-reachable files in `org-agenda-files'.
2333 Nil means to remove them, after a query, from the list."
2334 :group 'org-agenda
2335 :type 'boolean)
2337 (defcustom org-agenda-text-search-extra-files nil
2338 "List of extra files to be searched by text search commands.
2339 These files will be search in addition to the agenda files bu the
2340 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2341 Note that these files will only be searched for text search commands,
2342 not for the other agenda views like todo lists, tag earches or the weekly
2343 agenda. This variable is intended to list notes and possibly archive files
2344 that should also be searched by these two commands."
2345 :group 'org-agenda
2346 :type '(repeat file))
2348 (if (fboundp 'defvaralias)
2349 (defvaralias 'org-agenda-multi-occur-extra-files
2350 'org-agenda-text-search-extra-files))
2352 (defcustom org-agenda-confirm-kill 1
2353 "When set, remote killing from the agenda buffer needs confirmation.
2354 When t, a confirmation is always needed. When a number N, confirmation is
2355 only needed when the text to be killed contains more than N non-white lines."
2356 :group 'org-agenda
2357 :type '(choice
2358 (const :tag "Never" nil)
2359 (const :tag "Always" t)
2360 (number :tag "When more than N lines")))
2362 (defcustom org-calendar-to-agenda-key [?c]
2363 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2364 The command `org-calendar-goto-agenda' will be bound to this key. The
2365 default is the character `c' because then `c' can be used to switch back and
2366 forth between agenda and calendar."
2367 :group 'org-agenda
2368 :type 'sexp)
2370 (defcustom org-agenda-compact-blocks nil
2371 "Non-nil means, make the block agenda more compact.
2372 This is done by leaving out unnecessary lines."
2373 :group 'org-agenda
2374 :type nil)
2376 (defgroup org-agenda-export nil
2377 "Options concerning exporting agenda views in Org-mode."
2378 :tag "Org Agenda Export"
2379 :group 'org-agenda)
2381 (defcustom org-agenda-with-colors t
2382 "Non-nil means, use colors in agenda views."
2383 :group 'org-agenda-export
2384 :type 'boolean)
2386 (defcustom org-agenda-exporter-settings nil
2387 "Alist of variable/value pairs that should be active during agenda export.
2388 This is a good place to set uptions for ps-print and for htmlize."
2389 :group 'org-agenda-export
2390 :type '(repeat
2391 (list
2392 (variable)
2393 (sexp :tag "Value"))))
2395 (defcustom org-agenda-export-html-style ""
2396 "The style specification for exported HTML Agenda files.
2397 If this variable contains a string, it will replace the default <style>
2398 section as produced by `htmlize'.
2399 Since there are different ways of setting style information, this variable
2400 needs to contain the full HTML structure to provide a style, including the
2401 surrounding HTML tags. The style specifications should include definitions
2402 the fonts used by the agenda, here is an example:
2404 <style type=\"text/css\">
2405 p { font-weight: normal; color: gray; }
2406 .org-agenda-structure {
2407 font-size: 110%;
2408 color: #003399;
2409 font-weight: 600;
2411 .org-todo {
2412 color: #cc6666;
2413 font-weight: bold;
2415 .org-done {
2416 color: #339933;
2418 .title { text-align: center; }
2419 .todo, .deadline { color: red; }
2420 .done { color: green; }
2421 </style>
2423 or, if you want to keep the style in a file,
2425 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2427 As the value of this option simply gets inserted into the HTML <head> header,
2428 you can \"misuse\" it to also add other text to the header. However,
2429 <style>...</style> is required, if not present the variable will be ignored."
2430 :group 'org-agenda-export
2431 :group 'org-export-html
2432 :type 'string)
2434 (defgroup org-agenda-custom-commands nil
2435 "Options concerning agenda views in Org-mode."
2436 :tag "Org Agenda Custom Commands"
2437 :group 'org-agenda)
2439 (defconst org-sorting-choice
2440 '(choice
2441 (const time-up) (const time-down)
2442 (const category-keep) (const category-up) (const category-down)
2443 (const tag-down) (const tag-up)
2444 (const priority-up) (const priority-down))
2445 "Sorting choices.")
2447 (defconst org-agenda-custom-commands-local-options
2448 `(repeat :tag "Local settings for this command. Remember to quote values"
2449 (choice :tag "Setting"
2450 (list :tag "Any variable"
2451 (variable :tag "Variable")
2452 (sexp :tag "Value"))
2453 (list :tag "Files to be searched"
2454 (const org-agenda-files)
2455 (list
2456 (const :format "" quote)
2457 (repeat
2458 (file))))
2459 (list :tag "Sorting strategy"
2460 (const org-agenda-sorting-strategy)
2461 (list
2462 (const :format "" quote)
2463 (repeat
2464 ,org-sorting-choice)))
2465 (list :tag "Prefix format"
2466 (const org-agenda-prefix-format :value " %-12:c%?-12t% s")
2467 (string))
2468 (list :tag "Number of days in agenda"
2469 (const org-agenda-ndays)
2470 (integer :value 1))
2471 (list :tag "Fixed starting date"
2472 (const org-agenda-start-day)
2473 (string :value "2007-11-01"))
2474 (list :tag "Start on day of week"
2475 (const org-agenda-start-on-weekday)
2476 (choice :value 1
2477 (const :tag "Today" nil)
2478 (number :tag "Weekday No.")))
2479 (list :tag "Include data from diary"
2480 (const org-agenda-include-diary)
2481 (boolean))
2482 (list :tag "Deadline Warning days"
2483 (const org-deadline-warning-days)
2484 (integer :value 1))
2485 (list :tag "Standard skipping condition"
2486 :value (org-agenda-skip-function '(org-agenda-skip-entry-if))
2487 (const org-agenda-skip-function)
2488 (list
2489 (const :format "" quote)
2490 (list
2491 (choice
2492 :tag "Skiping range"
2493 (const :tag "Skip entry" org-agenda-skip-entry-if)
2494 (const :tag "Skip subtree" org-agenda-skip-subtree-if))
2495 (repeat :inline t :tag "Conditions for skipping"
2496 (choice
2497 :tag "Condition type"
2498 (list :tag "Regexp matches" :inline t (const :format "" 'regexp) (regexp))
2499 (list :tag "Regexp does not match" :inline t (const :format "" 'notregexp) (regexp))
2500 (const :tag "scheduled" 'scheduled)
2501 (const :tag "not scheduled" 'notscheduled)
2502 (const :tag "deadline" 'deadline)
2503 (const :tag "no deadline" 'notdeadline))))))
2504 (list :tag "Non-standard skipping condition"
2505 :value (org-agenda-skip-function)
2506 (list
2507 (const org-agenda-skip-function)
2508 (sexp :tag "Function or form (quoted!)")))))
2509 "Selection of examples for agenda command settings.
2510 This will be spliced into the custom type of
2511 `org-agenda-custom-commands'.")
2514 (defcustom org-agenda-custom-commands nil
2515 "Custom commands for the agenda.
2516 These commands will be offered on the splash screen displayed by the
2517 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2519 (key desc type match settings files)
2521 key The key (one or more characters as a string) to be associated
2522 with the command.
2523 desc A description of the command, when omitted or nil, a default
2524 description is built using MATCH.
2525 type The command type, any of the following symbols:
2526 agenda The daily/weekly agenda.
2527 todo Entries with a specific TODO keyword, in all agenda files.
2528 search Entries containing search words entry or headline.
2529 tags Tags/Property/TODO match in all agenda files.
2530 tags-todo Tags/P/T match in all agenda files, TODO entries only.
2531 todo-tree Sparse tree of specific TODO keyword in *current* file.
2532 tags-tree Sparse tree with all tags matches in *current* file.
2533 occur-tree Occur sparse tree for *current* file.
2534 ... A user-defined function.
2535 match What to search for:
2536 - a single keyword for TODO keyword searches
2537 - a tags match expression for tags searches
2538 - a word search expression for text searches.
2539 - a regular expression for occur searches
2540 For all other commands, this should be the empty string.
2541 settings A list of option settings, similar to that in a let form, so like
2542 this: ((opt1 val1) (opt2 val2) ...). The values will be
2543 evaluated at the moment of execution, so quote them when needed.
2544 files A list of files file to write the produced agenda buffer to
2545 with the command `org-store-agenda-views'.
2546 If a file name ends in \".html\", an HTML version of the buffer
2547 is written out. If it ends in \".ps\", a postscript version is
2548 produced. Otherwide, only the plain text is written to the file.
2550 You can also define a set of commands, to create a composite agenda buffer.
2551 In this case, an entry looks like this:
2553 (key desc (cmd1 cmd2 ...) general-settings-for-whole-set files)
2555 where
2557 desc A description string to be displayed in the dispatcher menu.
2558 cmd An agenda command, similar to the above. However, tree commands
2559 are no allowed, but instead you can get agenda and global todo list.
2560 So valid commands for a set are:
2561 (agenda \"\" settings)
2562 (alltodo \"\" settings)
2563 (stuck \"\" settings)
2564 (todo \"match\" settings files)
2565 (search \"match\" settings files)
2566 (tags \"match\" settings files)
2567 (tags-todo \"match\" settings files)
2569 Each command can carry a list of options, and another set of options can be
2570 given for the whole set of commands. Individual command options take
2571 precedence over the general options.
2573 When using several characters as key to a command, the first characters
2574 are prefix commands. For the dispatcher to display useful information, you
2575 should provide a description for the prefix, like
2577 (setq org-agenda-custom-commands
2578 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2579 (\"hl\" tags \"+HOME+Lisa\")
2580 (\"hp\" tags \"+HOME+Peter\")
2581 (\"hk\" tags \"+HOME+Kim\")))"
2582 :group 'org-agenda-custom-commands
2583 :type `(repeat
2584 (choice :value ("x" "Describe command here" tags "" nil)
2585 (list :tag "Single command"
2586 (string :tag "Access Key(s) ")
2587 (option (string :tag "Description"))
2588 (choice
2589 (const :tag "Agenda" agenda)
2590 (const :tag "TODO list" alltodo)
2591 (const :tag "Search words" search)
2592 (const :tag "Stuck projects" stuck)
2593 (const :tag "Tags search (all agenda files)" tags)
2594 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2595 (const :tag "TODO keyword search (all agenda files)" todo)
2596 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2597 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2598 (const :tag "Occur tree (current buffer)" occur-tree)
2599 (sexp :tag "Other, user-defined function"))
2600 (string :tag "Match (only for some commands)")
2601 ,org-agenda-custom-commands-local-options
2602 (option (repeat :tag "Export" (file :tag "Export to"))))
2603 (list :tag "Command series, all agenda files"
2604 (string :tag "Access Key(s)")
2605 (string :tag "Description ")
2606 (repeat :tag "Component"
2607 (choice
2608 (list :tag "Agenda"
2609 (const :format "" agenda)
2610 (const :tag "" :format "" "")
2611 ,org-agenda-custom-commands-local-options)
2612 (list :tag "TODO list (all keywords)"
2613 (const :format "" alltodo)
2614 (const :tag "" :format "" "")
2615 ,org-agenda-custom-commands-local-options)
2616 (list :tag "Search words"
2617 (const :format "" search)
2618 (string :tag "Match")
2619 ,org-agenda-custom-commands-local-options)
2620 (list :tag "Stuck projects"
2621 (const :format "" stuck)
2622 (const :tag "" :format "" "")
2623 ,org-agenda-custom-commands-local-options)
2624 (list :tag "Tags search"
2625 (const :format "" tags)
2626 (string :tag "Match")
2627 ,org-agenda-custom-commands-local-options)
2628 (list :tag "Tags search, TODO entries only"
2629 (const :format "" tags-todo)
2630 (string :tag "Match")
2631 ,org-agenda-custom-commands-local-options)
2632 (list :tag "TODO keyword search"
2633 (const :format "" todo)
2634 (string :tag "Match")
2635 ,org-agenda-custom-commands-local-options)
2636 (list :tag "Other, user-defined function"
2637 (symbol :tag "function")
2638 (string :tag "Match")
2639 ,org-agenda-custom-commands-local-options)))
2641 (repeat :tag "Settings for entire command set"
2642 (list (variable :tag "Any variable")
2643 (sexp :tag "Value")))
2644 (option (repeat :tag "Export" (file :tag "Export to"))))
2645 (cons :tag "Prefix key documentation"
2646 (string :tag "Access Key(s)")
2647 (string :tag "Description ")))))
2649 (defcustom org-agenda-query-register ?o
2650 "The register holding the current query string.
2651 The prupose of this is that if you construct a query string interactively,
2652 you can then use it to define a custom command."
2653 :group 'org-agenda-custom-commands
2654 :type 'character)
2656 (defcustom org-stuck-projects
2657 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2658 "How to identify stuck projects.
2659 This is a list of four items:
2660 1. A tags/todo matcher string that is used to identify a project.
2661 The entire tree below a headline matched by this is considered one project.
2662 2. A list of TODO keywords identifying non-stuck projects.
2663 If the project subtree contains any headline with one of these todo
2664 keywords, the project is considered to be not stuck. If you specify
2665 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2666 3. A list of tags identifying non-stuck projects.
2667 If the project subtree contains any headline with one of these tags,
2668 the project is considered to be not stuck. If you specify \"*\" as
2669 a tag, any tag will mark the project unstuck.
2670 4. An arbitrary regular expression matching non-stuck projects.
2672 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2673 or `C-c a #' to produce the list."
2674 :group 'org-agenda-custom-commands
2675 :type '(list
2676 (string :tag "Tags/TODO match to identify a project")
2677 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2678 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2679 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2682 (defgroup org-agenda-skip nil
2683 "Options concerning skipping parts of agenda files."
2684 :tag "Org Agenda Skip"
2685 :group 'org-agenda)
2687 (defcustom org-agenda-todo-list-sublevels t
2688 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2689 When nil, the sublevels of a TODO entry are not checked, resulting in
2690 potentially much shorter TODO lists."
2691 :group 'org-agenda-skip
2692 :group 'org-todo
2693 :type 'boolean)
2695 (defcustom org-agenda-todo-ignore-with-date nil
2696 "Non-nil means, don't show entries with a date in the global todo list.
2697 You can use this if you prefer to mark mere appointments with a TODO keyword,
2698 but don't want them to show up in the TODO list.
2699 When this is set, it also covers deadlines and scheduled items, the settings
2700 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2701 will be ignored."
2702 :group 'org-agenda-skip
2703 :group 'org-todo
2704 :type 'boolean)
2706 (defcustom org-agenda-todo-ignore-scheduled nil
2707 "Non-nil means, don't show scheduled entries in the global todo list.
2708 The idea behind this is that by scheduling it, you have already taken care
2709 of this item.
2710 See also `org-agenda-todo-ignore-with-date'."
2711 :group 'org-agenda-skip
2712 :group 'org-todo
2713 :type 'boolean)
2715 (defcustom org-agenda-todo-ignore-deadlines nil
2716 "Non-nil means, don't show near deadline entries in the global todo list.
2717 Near means closer than `org-deadline-warning-days' days.
2718 The idea behind this is that such items will appear in the agenda anyway.
2719 See also `org-agenda-todo-ignore-with-date'."
2720 :group 'org-agenda-skip
2721 :group 'org-todo
2722 :type 'boolean)
2724 (defcustom org-agenda-skip-scheduled-if-done nil
2725 "Non-nil means don't show scheduled items in agenda when they are done.
2726 This is relevant for the daily/weekly agenda, not for the TODO list. And
2727 it applies only to the actual date of the scheduling. Warnings about
2728 an item with a past scheduling dates are always turned off when the item
2729 is DONE."
2730 :group 'org-agenda-skip
2731 :type 'boolean)
2733 (defcustom org-agenda-skip-deadline-if-done nil
2734 "Non-nil means don't show deadines when the corresponding item is done.
2735 When nil, the deadline is still shown and should give you a happy feeling.
2736 This is relevant for the daily/weekly agenda. And it applied only to the
2737 actualy date of the deadline. Warnings about approching and past-due
2738 deadlines are always turned off when the item is DONE."
2739 :group 'org-agenda-skip
2740 :type 'boolean)
2742 (defcustom org-agenda-skip-timestamp-if-done nil
2743 "Non-nil means don't select item by timestamp or -range if it is DONE."
2744 :group 'org-agenda-skip
2745 :type 'boolean)
2747 (defcustom org-timeline-show-empty-dates 3
2748 "Non-nil means, `org-timeline' also shows dates without an entry.
2749 When nil, only the days which actually have entries are shown.
2750 When t, all days between the first and the last date are shown.
2751 When an integer, show also empty dates, but if there is a gap of more than
2752 N days, just insert a special line indicating the size of the gap."
2753 :group 'org-agenda-skip
2754 :type '(choice
2755 (const :tag "None" nil)
2756 (const :tag "All" t)
2757 (number :tag "at most")))
2760 (defgroup org-agenda-startup nil
2761 "Options concerning initial settings in the Agenda in Org Mode."
2762 :tag "Org Agenda Startup"
2763 :group 'org-agenda)
2765 (defcustom org-finalize-agenda-hook nil
2766 "Hook run just before displaying an agenda buffer."
2767 :group 'org-agenda-startup
2768 :type 'hook)
2770 (defcustom org-agenda-mouse-1-follows-link nil
2771 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2772 A longer mouse click will still set point. Does not work on XEmacs.
2773 Needs to be set before org.el is loaded."
2774 :group 'org-agenda-startup
2775 :type 'boolean)
2777 (defcustom org-agenda-start-with-follow-mode nil
2778 "The initial value of follow-mode in a newly created agenda window."
2779 :group 'org-agenda-startup
2780 :type 'boolean)
2782 (defgroup org-agenda-windows nil
2783 "Options concerning the windows used by the Agenda in Org Mode."
2784 :tag "Org Agenda Windows"
2785 :group 'org-agenda)
2787 (defcustom org-agenda-window-setup 'reorganize-frame
2788 "How the agenda buffer should be displayed.
2789 Possible values for this option are:
2791 current-window Show agenda in the current window, keeping all other windows.
2792 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2793 other-window Use `switch-to-buffer-other-window' to display agenda.
2794 reorganize-frame Show only two windows on the current frame, the current
2795 window and the agenda.
2796 See also the variable `org-agenda-restore-windows-after-quit'."
2797 :group 'org-agenda-windows
2798 :type '(choice
2799 (const current-window)
2800 (const other-frame)
2801 (const other-window)
2802 (const reorganize-frame)))
2804 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2805 "The min and max height of the agenda window as a fraction of frame height.
2806 The value of the variable is a cons cell with two numbers between 0 and 1.
2807 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2808 :group 'org-agenda-windows
2809 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2811 (defcustom org-agenda-restore-windows-after-quit nil
2812 "Non-nil means, restore window configuration open exiting agenda.
2813 Before the window configuration is changed for displaying the agenda,
2814 the current status is recorded. When the agenda is exited with
2815 `q' or `x' and this option is set, the old state is restored. If
2816 `org-agenda-window-setup' is `other-frame', the value of this
2817 option will be ignored.."
2818 :group 'org-agenda-windows
2819 :type 'boolean)
2821 (defcustom org-indirect-buffer-display 'other-window
2822 "How should indirect tree buffers be displayed?
2823 This applies to indirect buffers created with the commands
2824 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2825 Valid values are:
2826 current-window Display in the current window
2827 other-window Just display in another window.
2828 dedicated-frame Create one new frame, and re-use it each time.
2829 new-frame Make a new frame each time. Note that in this case
2830 previously-made indirect buffers are kept, and you need to
2831 kill these buffers yourself."
2832 :group 'org-structure
2833 :group 'org-agenda-windows
2834 :type '(choice
2835 (const :tag "In current window" current-window)
2836 (const :tag "In current frame, other window" other-window)
2837 (const :tag "Each time a new frame" new-frame)
2838 (const :tag "One dedicated frame" dedicated-frame)))
2840 (defgroup org-agenda-daily/weekly nil
2841 "Options concerning the daily/weekly agenda."
2842 :tag "Org Agenda Daily/Weekly"
2843 :group 'org-agenda)
2845 (defcustom org-agenda-ndays 7
2846 "Number of days to include in overview display.
2847 Should be 1 or 7."
2848 :group 'org-agenda-daily/weekly
2849 :type 'number)
2851 (defcustom org-agenda-start-on-weekday 1
2852 "Non-nil means, start the overview always on the specified weekday.
2853 0 denotes Sunday, 1 denotes Monday etc.
2854 When nil, always start on the current day."
2855 :group 'org-agenda-daily/weekly
2856 :type '(choice (const :tag "Today" nil)
2857 (number :tag "Weekday No.")))
2859 (defcustom org-agenda-show-all-dates t
2860 "Non-nil means, `org-agenda' shows every day in the selected range.
2861 When nil, only the days which actually have entries are shown."
2862 :group 'org-agenda-daily/weekly
2863 :type 'boolean)
2865 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2866 "Format string for displaying dates in the agenda.
2867 Used by the daily/weekly agenda and by the timeline. This should be
2868 a format string understood by `format-time-string', or a function returning
2869 the formatted date as a string. The function must take a single argument,
2870 a calendar-style date list like (month day year)."
2871 :group 'org-agenda-daily/weekly
2872 :type '(choice
2873 (string :tag "Format string")
2874 (function :tag "Function")))
2876 (defun org-agenda-format-date-aligned (date)
2877 "Format a date string for display in the daily/weekly agenda, or timeline.
2878 This function makes sure that dates are aligned for easy reading."
2879 (require 'cal-iso)
2880 (let* ((dayname (calendar-day-name date))
2881 (day (extract-calendar-day date))
2882 (day-of-week (calendar-day-of-week date))
2883 (month (extract-calendar-month date))
2884 (monthname (calendar-month-name month))
2885 (year (extract-calendar-year date))
2886 (iso-week (org-days-to-iso-week
2887 (calendar-absolute-from-gregorian date)))
2888 (weekyear (cond ((and (= month 1) (>= iso-week 52))
2889 (1- year))
2890 ((and (= month 12) (<= iso-week 1))
2891 (1+ year))
2892 (t year)))
2893 (weekstring (if (= day-of-week 1)
2894 (format " W%02d" iso-week)
2895 "")))
2896 (format "%-9s %2d %s %4d%s"
2897 dayname day monthname year weekstring)))
2899 (defcustom org-agenda-include-diary nil
2900 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2901 :group 'org-agenda-daily/weekly
2902 :type 'boolean)
2904 (defcustom org-agenda-include-all-todo nil
2905 "Set means weekly/daily agenda will always contain all TODO entries.
2906 The TODO entries will be listed at the top of the agenda, before
2907 the entries for specific days."
2908 :group 'org-agenda-daily/weekly
2909 :type 'boolean)
2911 (defcustom org-agenda-repeating-timestamp-show-all t
2912 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2913 When nil, only one occurence is shown, either today or the
2914 nearest into the future."
2915 :group 'org-agenda-daily/weekly
2916 :type 'boolean)
2918 (defcustom org-deadline-warning-days 14
2919 "No. of days before expiration during which a deadline becomes active.
2920 This variable governs the display in sparse trees and in the agenda.
2921 When 0 or negative, it means use this number (the absolute value of it)
2922 even if a deadline has a different individual lead time specified."
2923 :group 'org-time
2924 :group 'org-agenda-daily/weekly
2925 :type 'number)
2927 (defcustom org-scheduled-past-days 10000
2928 "No. of days to continue listing scheduled items that are not marked DONE.
2929 When an item is scheduled on a date, it shows up in the agenda on this
2930 day and will be listed until it is marked done for the number of days
2931 given here."
2932 :group 'org-agenda-daily/weekly
2933 :type 'number)
2935 (defgroup org-agenda-time-grid nil
2936 "Options concerning the time grid in the Org-mode Agenda."
2937 :tag "Org Agenda Time Grid"
2938 :group 'org-agenda)
2940 (defcustom org-agenda-use-time-grid t
2941 "Non-nil means, show a time grid in the agenda schedule.
2942 A time grid is a set of lines for specific times (like every two hours between
2943 8:00 and 20:00). The items scheduled for a day at specific times are
2944 sorted in between these lines.
2945 For details about when the grid will be shown, and what it will look like, see
2946 the variable `org-agenda-time-grid'."
2947 :group 'org-agenda-time-grid
2948 :type 'boolean)
2950 (defcustom org-agenda-time-grid
2951 '((daily today require-timed)
2952 "----------------"
2953 (800 1000 1200 1400 1600 1800 2000))
2955 "The settings for time grid for agenda display.
2956 This is a list of three items. The first item is again a list. It contains
2957 symbols specifying conditions when the grid should be displayed:
2959 daily if the agenda shows a single day
2960 weekly if the agenda shows an entire week
2961 today show grid on current date, independent of daily/weekly display
2962 require-timed show grid only if at least one item has a time specification
2964 The second item is a string which will be places behing the grid time.
2966 The third item is a list of integers, indicating the times that should have
2967 a grid line."
2968 :group 'org-agenda-time-grid
2969 :type
2970 '(list
2971 (set :greedy t :tag "Grid Display Options"
2972 (const :tag "Show grid in single day agenda display" daily)
2973 (const :tag "Show grid in weekly agenda display" weekly)
2974 (const :tag "Always show grid for today" today)
2975 (const :tag "Show grid only if any timed entries are present"
2976 require-timed)
2977 (const :tag "Skip grid times already present in an entry"
2978 remove-match))
2979 (string :tag "Grid String")
2980 (repeat :tag "Grid Times" (integer :tag "Time"))))
2982 (defgroup org-agenda-sorting nil
2983 "Options concerning sorting in the Org-mode Agenda."
2984 :tag "Org Agenda Sorting"
2985 :group 'org-agenda)
2987 (defcustom org-agenda-sorting-strategy
2988 '((agenda time-up category-keep priority-down)
2989 (todo category-keep priority-down)
2990 (tags category-keep priority-down)
2991 (search category-keep))
2992 "Sorting structure for the agenda items of a single day.
2993 This is a list of symbols which will be used in sequence to determine
2994 if an entry should be listed before another entry. The following
2995 symbols are recognized:
2997 time-up Put entries with time-of-day indications first, early first
2998 time-down Put entries with time-of-day indications first, late first
2999 category-keep Keep the default order of categories, corresponding to the
3000 sequence in `org-agenda-files'.
3001 category-up Sort alphabetically by category, A-Z.
3002 category-down Sort alphabetically by category, Z-A.
3003 tag-up Sort alphabetically by last tag, A-Z.
3004 tag-down Sort alphabetically by last tag, Z-A.
3005 priority-up Sort numerically by priority, high priority last.
3006 priority-down Sort numerically by priority, high priority first.
3008 The different possibilities will be tried in sequence, and testing stops
3009 if one comparison returns a \"not-equal\". For example, the default
3010 '(time-up category-keep priority-down)
3011 means: Pull out all entries having a specified time of day and sort them,
3012 in order to make a time schedule for the current day the first thing in the
3013 agenda listing for the day. Of the entries without a time indication, keep
3014 the grouped in categories, don't sort the categories, but keep them in
3015 the sequence given in `org-agenda-files'. Within each category sort by
3016 priority.
3018 Leaving out `category-keep' would mean that items will be sorted across
3019 categories by priority.
3021 Instead of a single list, this can also be a set of list for specific
3022 contents, with a context symbol in the car of the list, any of
3023 `agenda', `todo', `tags' for the corresponding agenda views."
3024 :group 'org-agenda-sorting
3025 :type `(choice
3026 (repeat :tag "General" ,org-sorting-choice)
3027 (list :tag "Individually"
3028 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
3029 (repeat ,org-sorting-choice))
3030 (cons (const :tag "Strategy for TODO lists" todo)
3031 (repeat ,org-sorting-choice))
3032 (cons (const :tag "Strategy for Tags matches" tags)
3033 (repeat ,org-sorting-choice)))))
3035 (defcustom org-sort-agenda-notime-is-late t
3036 "Non-nil means, items without time are considered late.
3037 This is only relevant for sorting. When t, items which have no explicit
3038 time like 15:30 will be considered as 99:01, i.e. later than any items which
3039 do have a time. When nil, the default time is before 0:00. You can use this
3040 option to decide if the schedule for today should come before or after timeless
3041 agenda entries."
3042 :group 'org-agenda-sorting
3043 :type 'boolean)
3045 (defgroup org-agenda-line-format nil
3046 "Options concerning the entry prefix in the Org-mode agenda display."
3047 :tag "Org Agenda Line Format"
3048 :group 'org-agenda)
3050 (defcustom org-agenda-prefix-format
3051 '((agenda . " %-12:c%?-12t% s")
3052 (timeline . " % s")
3053 (todo . " %-12:c")
3054 (tags . " %-12:c")
3055 (search . " %-12:c"))
3056 "Format specifications for the prefix of items in the agenda views.
3057 An alist with four entries, for the different agenda types. The keys to the
3058 sublists are `agenda', `timeline', `todo', and `tags'. The values
3059 are format strings.
3060 This format works similar to a printf format, with the following meaning:
3062 %c the category of the item, \"Diary\" for entries from the diary, or
3063 as given by the CATEGORY keyword or derived from the file name.
3064 %T the *last* tag of the item. Last because inherited tags come
3065 first in the list.
3066 %t the time-of-day specification if one applies to the entry, in the
3067 format HH:MM
3068 %s Scheduling/Deadline information, a short string
3070 All specifiers work basically like the standard `%s' of printf, but may
3071 contain two additional characters: A question mark just after the `%' and
3072 a whitespace/punctuation character just before the final letter.
3074 If the first character after `%' is a question mark, the entire field
3075 will only be included if the corresponding value applies to the
3076 current entry. This is useful for fields which should have fixed
3077 width when present, but zero width when absent. For example,
3078 \"%?-12t\" will result in a 12 character time field if a time of the
3079 day is specified, but will completely disappear in entries which do
3080 not contain a time.
3082 If there is punctuation or whitespace character just before the final
3083 format letter, this character will be appended to the field value if
3084 the value is not empty. For example, the format \"%-12:c\" leads to
3085 \"Diary: \" if the category is \"Diary\". If the category were be
3086 empty, no additional colon would be interted.
3088 The default value of this option is \" %-12:c%?-12t% s\", meaning:
3089 - Indent the line with two space characters
3090 - Give the category in a 12 chars wide field, padded with whitespace on
3091 the right (because of `-'). Append a colon if there is a category
3092 (because of `:').
3093 - If there is a time-of-day, put it into a 12 chars wide field. If no
3094 time, don't put in an empty field, just skip it (because of '?').
3095 - Finally, put the scheduling information and append a whitespace.
3097 As another example, if you don't want the time-of-day of entries in
3098 the prefix, you could use:
3100 (setq org-agenda-prefix-format \" %-11:c% s\")
3102 See also the variables `org-agenda-remove-times-when-in-prefix' and
3103 `org-agenda-remove-tags'."
3104 :type '(choice
3105 (string :tag "General format")
3106 (list :greedy t :tag "View dependent"
3107 (cons (const agenda) (string :tag "Format"))
3108 (cons (const timeline) (string :tag "Format"))
3109 (cons (const todo) (string :tag "Format"))
3110 (cons (const tags) (string :tag "Format"))
3111 (cons (const search) (string :tag "Format"))))
3112 :group 'org-agenda-line-format)
3114 (defvar org-prefix-format-compiled nil
3115 "The compiled version of the most recently used prefix format.
3116 See the variable `org-agenda-prefix-format'.")
3118 (defcustom org-agenda-todo-keyword-format "%-1s"
3119 "Format for the TODO keyword in agenda lines.
3120 Set this to something like \"%-12s\" if you want all TODO keywords
3121 to occupy a fixed space in the agenda display."
3122 :group 'org-agenda-line-format
3123 :type 'string)
3125 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
3126 "Text preceeding scheduled items in the agenda view.
3127 This is a list with two strings. The first applies when the item is
3128 scheduled on the current day. The second applies when it has been scheduled
3129 previously, it may contain a %d to capture how many days ago the item was
3130 scheduled."
3131 :group 'org-agenda-line-format
3132 :type '(list
3133 (string :tag "Scheduled today ")
3134 (string :tag "Scheduled previously")))
3136 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
3137 "Text preceeding deadline items in the agenda view.
3138 This is a list with two strings. The first applies when the item has its
3139 deadline on the current day. The second applies when it is in the past or
3140 in the future, it may contain %d to capture how many days away the deadline
3141 is (was)."
3142 :group 'org-agenda-line-format
3143 :type '(list
3144 (string :tag "Deadline today ")
3145 (string :tag "Deadline relative")))
3147 (defcustom org-agenda-remove-times-when-in-prefix t
3148 "Non-nil means, remove duplicate time specifications in agenda items.
3149 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
3150 time-of-day specification in a headline or diary entry is extracted and
3151 placed into the prefix. If this option is non-nil, the original specification
3152 \(a timestamp or -range, or just a plain time(range) specification like
3153 11:30-4pm) will be removed for agenda display. This makes the agenda less
3154 cluttered.
3155 The option can be t or nil. It may also be the symbol `beg', indicating
3156 that the time should only be removed what it is located at the beginning of
3157 the headline/diary entry."
3158 :group 'org-agenda-line-format
3159 :type '(choice
3160 (const :tag "Always" t)
3161 (const :tag "Never" nil)
3162 (const :tag "When at beginning of entry" beg)))
3165 (defcustom org-agenda-default-appointment-duration nil
3166 "Default duration for appointments that only have a starting time.
3167 When nil, no duration is specified in such cases.
3168 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
3169 :group 'org-agenda-line-format
3170 :type '(choice
3171 (integer :tag "Minutes")
3172 (const :tag "No default duration")))
3175 (defcustom org-agenda-remove-tags nil
3176 "Non-nil means, remove the tags from the headline copy in the agenda.
3177 When this is the symbol `prefix', only remove tags when
3178 `org-agenda-prefix-format' contains a `%T' specifier."
3179 :group 'org-agenda-line-format
3180 :type '(choice
3181 (const :tag "Always" t)
3182 (const :tag "Never" nil)
3183 (const :tag "When prefix format contains %T" prefix)))
3185 (if (fboundp 'defvaralias)
3186 (defvaralias 'org-agenda-remove-tags-when-in-prefix
3187 'org-agenda-remove-tags))
3189 (defcustom org-agenda-tags-column -80
3190 "Shift tags in agenda items to this column.
3191 If this number is positive, it specifies the column. If it is negative,
3192 it means that the tags should be flushright to that column. For example,
3193 -80 works well for a normal 80 character screen."
3194 :group 'org-agenda-line-format
3195 :type 'integer)
3197 (if (fboundp 'defvaralias)
3198 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
3200 (defcustom org-agenda-fontify-priorities t
3201 "Non-nil means, highlight low and high priorities in agenda.
3202 When t, the highest priority entries are bold, lowest priority italic.
3203 This may also be an association list of priority faces. The face may be
3204 a names face, or a list like `(:background \"Red\")'."
3205 :group 'org-agenda-line-format
3206 :type '(choice
3207 (const :tag "Never" nil)
3208 (const :tag "Defaults" t)
3209 (repeat :tag "Specify"
3210 (list (character :tag "Priority" :value ?A)
3211 (sexp :tag "face")))))
3213 (defgroup org-latex nil
3214 "Options for embedding LaTeX code into Org-mode."
3215 :tag "Org LaTeX"
3216 :group 'org)
3218 (defcustom org-format-latex-options
3219 '(:foreground default :background default :scale 1.0
3220 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
3221 :matchers ("begin" "$" "$$" "\\(" "\\["))
3222 "Options for creating images from LaTeX fragments.
3223 This is a property list with the following properties:
3224 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
3225 `default' means use the forground of the default face.
3226 :background the background color, or \"Transparent\".
3227 `default' means use the background of the default face.
3228 :scale a scaling factor for the size of the images
3229 :html-foreground, :html-background, :html-scale
3230 The same numbers for HTML export.
3231 :matchers a list indicating which matchers should be used to
3232 find LaTeX fragments. Valid members of this list are:
3233 \"begin\" find environments
3234 \"$\" find math expressions surrounded by $...$
3235 \"$$\" find math expressions surrounded by $$....$$
3236 \"\\(\" find math expressions surrounded by \\(...\\)
3237 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3238 :group 'org-latex
3239 :type 'plist)
3241 (defcustom org-format-latex-header "\\documentclass{article}
3242 \\usepackage{fullpage} % do not remove
3243 \\usepackage{amssymb}
3244 \\usepackage[usenames]{color}
3245 \\usepackage{amsmath}
3246 \\usepackage{latexsym}
3247 \\usepackage[mathscr]{eucal}
3248 \\pagestyle{empty} % do not remove"
3249 "The document header used for processing LaTeX fragments."
3250 :group 'org-latex
3251 :type 'string)
3253 (defgroup org-export nil
3254 "Options for exporting org-listings."
3255 :tag "Org Export"
3256 :group 'org)
3258 (defgroup org-export-general nil
3259 "General options for exporting Org-mode files."
3260 :tag "Org Export General"
3261 :group 'org-export)
3263 ;; FIXME
3264 (defvar org-export-publishing-directory nil)
3266 (defcustom org-export-with-special-strings t
3267 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3268 When this option is turned on, these strings will be exported as:
3270 Org HTML LaTeX
3271 -----+----------+--------
3272 \\- &shy; \\-
3273 -- &ndash; --
3274 --- &mdash; ---
3275 ... &hellip; \ldots
3277 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3278 :group 'org-export-translation
3279 :type 'boolean)
3281 (defcustom org-export-language-setup
3282 '(("en" "Author" "Date" "Table of Contents")
3283 ("cs" "Autor" "Datum" "Obsah")
3284 ("da" "Ophavsmand" "Dato" "Indhold")
3285 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3286 ("es" "Autor" "Fecha" "\xcdndice")
3287 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3288 ("it" "Autore" "Data" "Indice")
3289 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3290 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3291 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3292 "Terms used in export text, translated to different languages.
3293 Use the variable `org-export-default-language' to set the language,
3294 or use the +OPTION lines for a per-file setting."
3295 :group 'org-export-general
3296 :type '(repeat
3297 (list
3298 (string :tag "HTML language tag")
3299 (string :tag "Author")
3300 (string :tag "Date")
3301 (string :tag "Table of Contents"))))
3303 (defcustom org-export-default-language "en"
3304 "The default language of HTML export, as a string.
3305 This should have an association in `org-export-language-setup'."
3306 :group 'org-export-general
3307 :type 'string)
3309 (defcustom org-export-skip-text-before-1st-heading t
3310 "Non-nil means, skip all text before the first headline when exporting.
3311 When nil, that text is exported as well."
3312 :group 'org-export-general
3313 :type 'boolean)
3315 (defcustom org-export-headline-levels 3
3316 "The last level which is still exported as a headline.
3317 Inferior levels will produce itemize lists when exported.
3318 Note that a numeric prefix argument to an exporter function overrides
3319 this setting.
3321 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3322 :group 'org-export-general
3323 :type 'number)
3325 (defcustom org-export-with-section-numbers t
3326 "Non-nil means, add section numbers to headlines when exporting.
3328 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3329 :group 'org-export-general
3330 :type 'boolean)
3332 (defcustom org-export-with-toc t
3333 "Non-nil means, create a table of contents in exported files.
3334 The TOC contains headlines with levels up to`org-export-headline-levels'.
3335 When an integer, include levels up to N in the toc, this may then be
3336 different from `org-export-headline-levels', but it will not be allowed
3337 to be larger than the number of headline levels.
3338 When nil, no table of contents is made.
3340 Headlines which contain any TODO items will be marked with \"(*)\" in
3341 ASCII export, and with red color in HTML output, if the option
3342 `org-export-mark-todo-in-toc' is set.
3344 In HTML output, the TOC will be clickable.
3346 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3347 or \"toc:3\"."
3348 :group 'org-export-general
3349 :type '(choice
3350 (const :tag "No Table of Contents" nil)
3351 (const :tag "Full Table of Contents" t)
3352 (integer :tag "TOC to level")))
3354 (defcustom org-export-mark-todo-in-toc nil
3355 "Non-nil means, mark TOC lines that contain any open TODO items."
3356 :group 'org-export-general
3357 :type 'boolean)
3359 (defcustom org-export-preserve-breaks nil
3360 "Non-nil means, preserve all line breaks when exporting.
3361 Normally, in HTML output paragraphs will be reformatted. In ASCII
3362 export, line breaks will always be preserved, regardless of this variable.
3364 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3365 :group 'org-export-general
3366 :type 'boolean)
3368 (defcustom org-export-with-archived-trees 'headline
3369 "Whether subtrees with the ARCHIVE tag should be exported.
3370 This can have three different values
3371 nil Do not export, pretend this tree is not present
3372 t Do export the entire tree
3373 headline Only export the headline, but skip the tree below it."
3374 :group 'org-export-general
3375 :group 'org-archive
3376 :type '(choice
3377 (const :tag "not at all" nil)
3378 (const :tag "headline only" 'headline)
3379 (const :tag "entirely" t)))
3381 (defcustom org-export-author-info t
3382 "Non-nil means, insert author name and email into the exported file.
3384 This option can also be set with the +OPTIONS line,
3385 e.g. \"author-info:nil\"."
3386 :group 'org-export-general
3387 :type 'boolean)
3389 (defcustom org-export-time-stamp-file t
3390 "Non-nil means, insert a time stamp into the exported file.
3391 The time stamp shows when the file was created.
3393 This option can also be set with the +OPTIONS line,
3394 e.g. \"timestamp:nil\"."
3395 :group 'org-export-general
3396 :type 'boolean)
3398 (defcustom org-export-with-timestamps t
3399 "If nil, do not export time stamps and associated keywords."
3400 :group 'org-export-general
3401 :type 'boolean)
3403 (defcustom org-export-remove-timestamps-from-toc t
3404 "If nil, remove timestamps from the table of contents entries."
3405 :group 'org-export-general
3406 :type 'boolean)
3408 (defcustom org-export-with-tags 'not-in-toc
3409 "If nil, do not export tags, just remove them from headlines.
3410 If this is the symbol `not-in-toc', tags will be removed from table of
3411 contents entries, but still be shown in the headlines of the document.
3413 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3414 :group 'org-export-general
3415 :type '(choice
3416 (const :tag "Off" nil)
3417 (const :tag "Not in TOC" not-in-toc)
3418 (const :tag "On" t)))
3420 (defcustom org-export-with-drawers nil
3421 "Non-nil means, export with drawers like the property drawer.
3422 When t, all drawers are exported. This may also be a list of
3423 drawer names to export."
3424 :group 'org-export-general
3425 :type '(choice
3426 (const :tag "All drawers" t)
3427 (const :tag "None" nil)
3428 (repeat :tag "Selected drawers"
3429 (string :tag "Drawer name"))))
3431 (defgroup org-export-translation nil
3432 "Options for translating special ascii sequences for the export backends."
3433 :tag "Org Export Translation"
3434 :group 'org-export)
3436 (defcustom org-export-with-emphasize t
3437 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3438 If the export target supports emphasizing text, the word will be
3439 typeset in bold, italic, or underlined, respectively. Works only for
3440 single words, but you can say: I *really* *mean* *this*.
3441 Not all export backends support this.
3443 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3444 :group 'org-export-translation
3445 :type 'boolean)
3447 (defcustom org-export-with-footnotes t
3448 "If nil, export [1] as a footnote marker.
3449 Lines starting with [1] will be formatted as footnotes.
3451 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3452 :group 'org-export-translation
3453 :type 'boolean)
3455 (defcustom org-export-with-sub-superscripts t
3456 "Non-nil means, interpret \"_\" and \"^\" for export.
3457 When this option is turned on, you can use TeX-like syntax for sub- and
3458 superscripts. Several characters after \"_\" or \"^\" will be
3459 considered as a single item - so grouping with {} is normally not
3460 needed. For example, the following things will be parsed as single
3461 sub- or superscripts.
3463 10^24 or 10^tau several digits will be considered 1 item.
3464 10^-12 or 10^-tau a leading sign with digits or a word
3465 x^2-y^3 will be read as x^2 - y^3, because items are
3466 terminated by almost any nonword/nondigit char.
3467 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3469 Still, ambiguity is possible - so when in doubt use {} to enclose the
3470 sub/superscript. If you set this variable to the symbol `{}',
3471 the braces are *required* in order to trigger interpretations as
3472 sub/superscript. This can be helpful in documents that need \"_\"
3473 frequently in plain text.
3475 Not all export backends support this, but HTML does.
3477 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3478 :group 'org-export-translation
3479 :type '(choice
3480 (const :tag "Always interpret" t)
3481 (const :tag "Only with braces" {})
3482 (const :tag "Never interpret" nil)))
3484 (defcustom org-export-with-special-strings t
3485 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3486 When this option is turned on, these strings will be exported as:
3488 \\- : &shy;
3489 -- : &ndash;
3490 --- : &mdash;
3492 Not all export backends support this, but HTML does.
3494 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3495 :group 'org-export-translation
3496 :type 'boolean)
3498 (defcustom org-export-with-TeX-macros t
3499 "Non-nil means, interpret simple TeX-like macros when exporting.
3500 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3501 No only real TeX macros will work here, but the standard HTML entities
3502 for math can be used as macro names as well. For a list of supported
3503 names in HTML export, see the constant `org-html-entities'.
3504 Not all export backends support this.
3506 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3507 :group 'org-export-translation
3508 :group 'org-export-latex
3509 :type 'boolean)
3511 (defcustom org-export-with-LaTeX-fragments nil
3512 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3513 When set, the exporter will find LaTeX environments if the \\begin line is
3514 the first non-white thing on a line. It will also find the math delimiters
3515 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3516 display math.
3518 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3519 :group 'org-export-translation
3520 :group 'org-export-latex
3521 :type 'boolean)
3523 (defcustom org-export-with-fixed-width t
3524 "Non-nil means, lines starting with \":\" will be in fixed width font.
3525 This can be used to have pre-formatted text, fragments of code etc. For
3526 example:
3527 : ;; Some Lisp examples
3528 : (while (defc cnt)
3529 : (ding))
3530 will be looking just like this in also HTML. See also the QUOTE keyword.
3531 Not all export backends support this.
3533 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3534 :group 'org-export-translation
3535 :type 'boolean)
3537 (defcustom org-match-sexp-depth 3
3538 "Number of stacked braces for sub/superscript matching.
3539 This has to be set before loading org.el to be effective."
3540 :group 'org-export-translation
3541 :type 'integer)
3543 (defgroup org-export-tables nil
3544 "Options for exporting tables in Org-mode."
3545 :tag "Org Export Tables"
3546 :group 'org-export)
3548 (defcustom org-export-with-tables t
3549 "If non-nil, lines starting with \"|\" define a table.
3550 For example:
3552 | Name | Address | Birthday |
3553 |-------------+----------+-----------|
3554 | Arthur Dent | England | 29.2.2100 |
3556 Not all export backends support this.
3558 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3559 :group 'org-export-tables
3560 :type 'boolean)
3562 (defcustom org-export-highlight-first-table-line t
3563 "Non-nil means, highlight the first table line.
3564 In HTML export, this means use <th> instead of <td>.
3565 In tables created with table.el, this applies to the first table line.
3566 In Org-mode tables, all lines before the first horizontal separator
3567 line will be formatted with <th> tags."
3568 :group 'org-export-tables
3569 :type 'boolean)
3571 (defcustom org-export-table-remove-special-lines t
3572 "Remove special lines and marking characters in calculating tables.
3573 This removes the special marking character column from tables that are set
3574 up for spreadsheet calculations. It also removes the entire lines
3575 marked with `!', `_', or `^'. The lines with `$' are kept, because
3576 the values of constants may be useful to have."
3577 :group 'org-export-tables
3578 :type 'boolean)
3580 (defcustom org-export-prefer-native-exporter-for-tables nil
3581 "Non-nil means, always export tables created with table.el natively.
3582 Natively means, use the HTML code generator in table.el.
3583 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3584 the table does not use row- or column-spanning). This has the
3585 advantage, that the automatic HTML conversions for math symbols and
3586 sub/superscripts can be applied. Org-mode's HTML generator is also
3587 much faster."
3588 :group 'org-export-tables
3589 :type 'boolean)
3591 (defgroup org-export-ascii nil
3592 "Options specific for ASCII export of Org-mode files."
3593 :tag "Org Export ASCII"
3594 :group 'org-export)
3596 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3597 "Characters for underlining headings in ASCII export.
3598 In the given sequence, these characters will be used for level 1, 2, ..."
3599 :group 'org-export-ascii
3600 :type '(repeat character))
3602 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3603 "Bullet characters for headlines converted to lists in ASCII export.
3604 The first character is used for the first lest level generated in this
3605 way, and so on. If there are more levels than characters given here,
3606 the list will be repeated.
3607 Note that plain lists will keep the same bullets as the have in the
3608 Org-mode file."
3609 :group 'org-export-ascii
3610 :type '(repeat character))
3612 (defgroup org-export-xml nil
3613 "Options specific for XML export of Org-mode files."
3614 :tag "Org Export XML"
3615 :group 'org-export)
3617 (defgroup org-export-html nil
3618 "Options specific for HTML export of Org-mode files."
3619 :tag "Org Export HTML"
3620 :group 'org-export)
3622 (defcustom org-export-html-coding-system nil
3624 :group 'org-export-html
3625 :type 'coding-system)
3627 (defcustom org-export-html-extension "html"
3628 "The extension for exported HTML files."
3629 :group 'org-export-html
3630 :type 'string)
3632 (defcustom org-export-html-style
3633 "<style type=\"text/css\">
3634 html {
3635 font-family: Times, serif;
3636 font-size: 12pt;
3638 .title { text-align: center; }
3639 .todo { color: red; }
3640 .done { color: green; }
3641 .timestamp { color: grey }
3642 .timestamp-kwd { color: CadetBlue }
3643 .tag { background-color:lightblue; font-weight:normal }
3644 .target { background-color: lavender; }
3645 pre {
3646 border: 1pt solid #AEBDCC;
3647 background-color: #F3F5F7;
3648 padding: 5pt;
3649 font-family: courier, monospace;
3651 table { border-collapse: collapse; }
3652 td, th {
3653 vertical-align: top;
3654 <!--border: 1pt solid #ADB9CC;-->
3656 </style>"
3657 "The default style specification for exported HTML files.
3658 Since there are different ways of setting style information, this variable
3659 needs to contain the full HTML structure to provide a style, including the
3660 surrounding HTML tags. The style specifications should include definitions
3661 for new classes todo, done, title, and deadline. For example, valid values
3662 would be:
3664 <style type=\"text/css\">
3665 p { font-weight: normal; color: gray; }
3666 h1 { color: black; }
3667 .title { text-align: center; }
3668 .todo, .deadline { color: red; }
3669 .done { color: green; }
3670 </style>
3672 or, if you want to keep the style in a file,
3674 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3676 As the value of this option simply gets inserted into the HTML <head> header,
3677 you can \"misuse\" it to add arbitrary text to the header."
3678 :group 'org-export-html
3679 :type 'string)
3682 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3683 "Format for typesetting the document title in HTML export."
3684 :group 'org-export-html
3685 :type 'string)
3687 (defcustom org-export-html-toplevel-hlevel 2
3688 "The <H> level for level 1 headings in HTML export."
3689 :group 'org-export-html
3690 :type 'string)
3692 (defcustom org-export-html-link-org-files-as-html t
3693 "Non-nil means, make file links to `file.org' point to `file.html'.
3694 When org-mode is exporting an org-mode file to HTML, links to
3695 non-html files are directly put into a href tag in HTML.
3696 However, links to other Org-mode files (recognized by the
3697 extension `.org.) should become links to the corresponding html
3698 file, assuming that the linked org-mode file will also be
3699 converted to HTML.
3700 When nil, the links still point to the plain `.org' file."
3701 :group 'org-export-html
3702 :type 'boolean)
3704 (defcustom org-export-html-inline-images 'maybe
3705 "Non-nil means, inline images into exported HTML pages.
3706 This is done using an <img> tag. When nil, an anchor with href is used to
3707 link to the image. If this option is `maybe', then images in links with
3708 an empty description will be inlined, while images with a description will
3709 be linked only."
3710 :group 'org-export-html
3711 :type '(choice (const :tag "Never" nil)
3712 (const :tag "Always" t)
3713 (const :tag "When there is no description" maybe)))
3715 ;; FIXME: rename
3716 (defcustom org-export-html-expand t
3717 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3718 When nil, these tags will be exported as plain text and therefore
3719 not be interpreted by a browser.
3721 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3722 :group 'org-export-html
3723 :type 'boolean)
3725 (defcustom org-export-html-table-tag
3726 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3727 "The HTML tag that is used to start a table.
3728 This must be a <table> tag, but you may change the options like
3729 borders and spacing."
3730 :group 'org-export-html
3731 :type 'string)
3733 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3734 "The opening tag for table header fields.
3735 This is customizable so that alignment options can be specified."
3736 :group 'org-export-tables
3737 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3739 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3740 "The opening tag for table data fields.
3741 This is customizable so that alignment options can be specified."
3742 :group 'org-export-tables
3743 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3745 (defcustom org-export-html-with-timestamp nil
3746 "If non-nil, write `org-export-html-html-helper-timestamp'
3747 into the exported HTML text. Otherwise, the buffer will just be saved
3748 to a file."
3749 :group 'org-export-html
3750 :type 'boolean)
3752 (defcustom org-export-html-html-helper-timestamp
3753 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3754 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3755 :group 'org-export-html
3756 :type 'string)
3758 (defgroup org-export-icalendar nil
3759 "Options specific for iCalendar export of Org-mode files."
3760 :tag "Org Export iCalendar"
3761 :group 'org-export)
3763 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3764 "The file name for the iCalendar file covering all agenda files.
3765 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3766 The file name should be absolute, the file will be overwritten without warning."
3767 :group 'org-export-icalendar
3768 :type 'file)
3770 (defcustom org-icalendar-include-todo nil
3771 "Non-nil means, export to iCalendar files should also cover TODO items."
3772 :group 'org-export-icalendar
3773 :type '(choice
3774 (const :tag "None" nil)
3775 (const :tag "Unfinished" t)
3776 (const :tag "All" all)))
3778 (defcustom org-icalendar-include-sexps t
3779 "Non-nil means, export to iCalendar files should also cover sexp entries.
3780 These are entries like in the diary, but directly in an Org-mode file."
3781 :group 'org-export-icalendar
3782 :type 'boolean)
3784 (defcustom org-icalendar-include-body 100
3785 "Amount of text below headline to be included in iCalendar export.
3786 This is a number of characters that should maximally be included.
3787 Properties, scheduling and clocking lines will always be removed.
3788 The text will be inserted into the DESCRIPTION field."
3789 :group 'org-export-icalendar
3790 :type '(choice
3791 (const :tag "Nothing" nil)
3792 (const :tag "Everything" t)
3793 (integer :tag "Max characters")))
3795 (defcustom org-icalendar-combined-name "OrgMode"
3796 "Calendar name for the combined iCalendar representing all agenda files."
3797 :group 'org-export-icalendar
3798 :type 'string)
3800 (defgroup org-font-lock nil
3801 "Font-lock settings for highlighting in Org-mode."
3802 :tag "Org Font Lock"
3803 :group 'org)
3805 (defcustom org-level-color-stars-only nil
3806 "Non-nil means fontify only the stars in each headline.
3807 When nil, the entire headline is fontified.
3808 Changing it requires restart of `font-lock-mode' to become effective
3809 also in regions already fontified."
3810 :group 'org-font-lock
3811 :type 'boolean)
3813 (defcustom org-hide-leading-stars nil
3814 "Non-nil means, hide the first N-1 stars in a headline.
3815 This works by using the face `org-hide' for these stars. This
3816 face is white for a light background, and black for a dark
3817 background. You may have to customize the face `org-hide' to
3818 make this work.
3819 Changing it requires restart of `font-lock-mode' to become effective
3820 also in regions already fontified.
3821 You may also set this on a per-file basis by adding one of the following
3822 lines to the buffer:
3824 #+STARTUP: hidestars
3825 #+STARTUP: showstars"
3826 :group 'org-font-lock
3827 :type 'boolean)
3829 (defcustom org-fontify-done-headline nil
3830 "Non-nil means, change the face of a headline if it is marked DONE.
3831 Normally, only the TODO/DONE keyword indicates the state of a headline.
3832 When this is non-nil, the headline after the keyword is set to the
3833 `org-headline-done' as an additional indication."
3834 :group 'org-font-lock
3835 :type 'boolean)
3837 (defcustom org-fontify-emphasized-text t
3838 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3839 Changing this variable requires a restart of Emacs to take effect."
3840 :group 'org-font-lock
3841 :type 'boolean)
3843 (defcustom org-highlight-latex-fragments-and-specials nil
3844 "Non-nil means, fontify what is treated specially by the exporters."
3845 :group 'org-font-lock
3846 :type 'boolean)
3848 (defcustom org-hide-emphasis-markers nil
3849 "Non-nil mean font-lock should hide the emphasis marker characters."
3850 :group 'org-font-lock
3851 :type 'boolean)
3853 (defvar org-emph-re nil
3854 "Regular expression for matching emphasis.")
3855 (defvar org-verbatim-re nil
3856 "Regular expression for matching verbatim text.")
3857 (defvar org-emphasis-regexp-components) ; defined just below
3858 (defvar org-emphasis-alist) ; defined just below
3859 (defun org-set-emph-re (var val)
3860 "Set variable and compute the emphasis regular expression."
3861 (set var val)
3862 (when (and (boundp 'org-emphasis-alist)
3863 (boundp 'org-emphasis-regexp-components)
3864 org-emphasis-alist org-emphasis-regexp-components)
3865 (let* ((e org-emphasis-regexp-components)
3866 (pre (car e))
3867 (post (nth 1 e))
3868 (border (nth 2 e))
3869 (body (nth 3 e))
3870 (nl (nth 4 e))
3871 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3872 (body1 (concat body "*?"))
3873 (markers (mapconcat 'car org-emphasis-alist ""))
3874 (vmarkers (mapconcat
3875 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3876 org-emphasis-alist "")))
3877 ;; make sure special characters appear at the right position in the class
3878 (if (string-match "\\^" markers)
3879 (setq markers (concat (replace-match "" t t markers) "^")))
3880 (if (string-match "-" markers)
3881 (setq markers (concat (replace-match "" t t markers) "-")))
3882 (if (string-match "\\^" vmarkers)
3883 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3884 (if (string-match "-" vmarkers)
3885 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3886 (if (> nl 0)
3887 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3888 (int-to-string nl) "\\}")))
3889 ;; Make the regexp
3890 (setq org-emph-re
3891 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3892 "\\("
3893 "\\([" markers "]\\)"
3894 "\\("
3895 "[^" border "]\\|"
3896 "[^" border (if (and nil stacked) markers) "]"
3897 body1
3898 "[^" border (if (and nil stacked) markers) "]"
3899 "\\)"
3900 "\\3\\)"
3901 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3902 (setq org-verbatim-re
3903 (concat "\\([" pre "]\\|^\\)"
3904 "\\("
3905 "\\([" vmarkers "]\\)"
3906 "\\("
3907 "[^" border "]\\|"
3908 "[^" border "]"
3909 body1
3910 "[^" border "]"
3911 "\\)"
3912 "\\3\\)"
3913 "\\([" post "]\\|$\\)")))))
3915 (defcustom org-emphasis-regexp-components
3916 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3917 "Components used to build the regular expression for emphasis.
3918 This is a list with 6 entries. Terminology: In an emphasis string
3919 like \" *strong word* \", we call the initial space PREMATCH, the final
3920 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3921 and \"trong wor\" is the body. The different components in this variable
3922 specify what is allowed/forbidden in each part:
3924 pre Chars allowed as prematch. Beginning of line will be allowed too.
3925 post Chars allowed as postmatch. End of line will be allowed too.
3926 border The chars *forbidden* as border characters.
3927 body-regexp A regexp like \".\" to match a body character. Don't use
3928 non-shy groups here, and don't allow newline here.
3929 newline The maximum number of newlines allowed in an emphasis exp.
3931 Use customize to modify this, or restart Emacs after changing it."
3932 :group 'org-font-lock
3933 :set 'org-set-emph-re
3934 :type '(list
3935 (sexp :tag "Allowed chars in pre ")
3936 (sexp :tag "Allowed chars in post ")
3937 (sexp :tag "Forbidden chars in border ")
3938 (sexp :tag "Regexp for body ")
3939 (integer :tag "number of newlines allowed")
3940 (option (boolean :tag "Stacking (DISABLED) "))))
3942 (defcustom org-emphasis-alist
3943 '(("*" bold "<b>" "</b>")
3944 ("/" italic "<i>" "</i>")
3945 ("_" underline "<u>" "</u>")
3946 ("=" org-code "<code>" "</code>" verbatim)
3947 ("~" org-verbatim "" "" verbatim)
3948 ("+" (:strike-through t) "<del>" "</del>")
3950 "Special syntax for emphasized text.
3951 Text starting and ending with a special character will be emphasized, for
3952 example *bold*, _underlined_ and /italic/. This variable sets the marker
3953 characters, the face to be used by font-lock for highlighting in Org-mode
3954 Emacs buffers, and the HTML tags to be used for this.
3955 Use customize to modify this, or restart Emacs after changing it."
3956 :group 'org-font-lock
3957 :set 'org-set-emph-re
3958 :type '(repeat
3959 (list
3960 (string :tag "Marker character")
3961 (choice
3962 (face :tag "Font-lock-face")
3963 (plist :tag "Face property list"))
3964 (string :tag "HTML start tag")
3965 (string :tag "HTML end tag")
3966 (option (const verbatim)))))
3968 ;;; The faces
3970 (defgroup org-faces nil
3971 "Faces in Org-mode."
3972 :tag "Org Faces"
3973 :group 'org-font-lock)
3975 (defun org-compatible-face (inherits specs)
3976 "Make a compatible face specification.
3977 If INHERITS is an existing face and if the Emacs version supports it,
3978 just inherit the face. If not, use SPECS to define the face.
3979 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3980 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3981 to the top of the list. The `min-colors' attribute will be removed from
3982 any other entries, and any resulting duplicates will be removed entirely."
3983 (cond
3984 ((and inherits (facep inherits)
3985 (not (featurep 'xemacs)) (> emacs-major-version 22))
3986 ;; In Emacs 23, we use inheritance where possible.
3987 ;; We only do this in Emacs 23, because only there the outline
3988 ;; faces have been changed to the original org-mode-level-faces.
3989 (list (list t :inherit inherits)))
3990 ((or (featurep 'xemacs) (< emacs-major-version 22))
3991 ;; These do not understand the `min-colors' attribute.
3992 (let (r e a)
3993 (while (setq e (pop specs))
3994 (cond
3995 ((memq (car e) '(t default)) (push e r))
3996 ((setq a (member '(min-colors 8) (car e)))
3997 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3998 (cdr e)))))
3999 ((setq a (assq 'min-colors (car e)))
4000 (setq e (cons (delq a (car e)) (cdr e)))
4001 (or (assoc (car e) r) (push e r)))
4002 (t (or (assoc (car e) r) (push e r)))))
4003 (nreverse r)))
4004 (t specs)))
4005 (put 'org-compatible-face 'lisp-indent-function 1)
4007 (defface org-hide
4008 '((((background light)) (:foreground "white"))
4009 (((background dark)) (:foreground "black")))
4010 "Face used to hide leading stars in headlines.
4011 The forground color of this face should be equal to the background
4012 color of the frame."
4013 :group 'org-faces)
4015 (defface org-level-1 ;; font-lock-function-name-face
4016 (org-compatible-face 'outline-1
4017 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4018 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4019 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4020 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4021 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4022 (t (:bold t))))
4023 "Face used for level 1 headlines."
4024 :group 'org-faces)
4026 (defface org-level-2 ;; font-lock-variable-name-face
4027 (org-compatible-face 'outline-2
4028 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4029 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4030 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
4031 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
4032 (t (:bold t))))
4033 "Face used for level 2 headlines."
4034 :group 'org-faces)
4036 (defface org-level-3 ;; font-lock-keyword-face
4037 (org-compatible-face 'outline-3
4038 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
4039 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
4040 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
4041 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
4042 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
4043 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
4044 (t (:bold t))))
4045 "Face used for level 3 headlines."
4046 :group 'org-faces)
4048 (defface org-level-4 ;; font-lock-comment-face
4049 (org-compatible-face 'outline-4
4050 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4051 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4052 (((class color) (min-colors 16) (background light)) (:foreground "red"))
4053 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
4054 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4055 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4056 (t (:bold t))))
4057 "Face used for level 4 headlines."
4058 :group 'org-faces)
4060 (defface org-level-5 ;; font-lock-type-face
4061 (org-compatible-face 'outline-5
4062 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
4063 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
4064 (((class color) (min-colors 8)) (:foreground "green"))))
4065 "Face used for level 5 headlines."
4066 :group 'org-faces)
4068 (defface org-level-6 ;; font-lock-constant-face
4069 (org-compatible-face 'outline-6
4070 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
4071 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
4072 (((class color) (min-colors 8)) (:foreground "magenta"))))
4073 "Face used for level 6 headlines."
4074 :group 'org-faces)
4076 (defface org-level-7 ;; font-lock-builtin-face
4077 (org-compatible-face 'outline-7
4078 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
4079 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
4080 (((class color) (min-colors 8)) (:foreground "blue"))))
4081 "Face used for level 7 headlines."
4082 :group 'org-faces)
4084 (defface org-level-8 ;; font-lock-string-face
4085 (org-compatible-face 'outline-8
4086 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4087 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4088 (((class color) (min-colors 8)) (:foreground "green"))))
4089 "Face used for level 8 headlines."
4090 :group 'org-faces)
4092 (defface org-special-keyword ;; font-lock-string-face
4093 (org-compatible-face nil
4094 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4095 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4096 (t (:italic t))))
4097 "Face used for special keywords."
4098 :group 'org-faces)
4100 (defface org-drawer ;; font-lock-function-name-face
4101 (org-compatible-face nil
4102 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4103 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4104 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4105 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4106 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4107 (t (:bold t))))
4108 "Face used for drawers."
4109 :group 'org-faces)
4111 (defface org-property-value nil
4112 "Face used for the value of a property."
4113 :group 'org-faces)
4115 (defface org-column
4116 (org-compatible-face nil
4117 '((((class color) (min-colors 16) (background light))
4118 (:background "grey90"))
4119 (((class color) (min-colors 16) (background dark))
4120 (:background "grey30"))
4121 (((class color) (min-colors 8))
4122 (:background "cyan" :foreground "black"))
4123 (t (:inverse-video t))))
4124 "Face for column display of entry properties."
4125 :group 'org-faces)
4127 (when (fboundp 'set-face-attribute)
4128 ;; Make sure that a fixed-width face is used when we have a column table.
4129 (set-face-attribute 'org-column nil
4130 :height (face-attribute 'default :height)
4131 :family (face-attribute 'default :family)))
4133 (defface org-warning
4134 (org-compatible-face 'font-lock-warning-face
4135 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4136 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4137 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4138 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4139 (t (:bold t))))
4140 "Face for deadlines and TODO keywords."
4141 :group 'org-faces)
4143 (defface org-archived ; similar to shadow
4144 (org-compatible-face 'shadow
4145 '((((class color grayscale) (min-colors 88) (background light))
4146 (:foreground "grey50"))
4147 (((class color grayscale) (min-colors 88) (background dark))
4148 (:foreground "grey70"))
4149 (((class color) (min-colors 8) (background light))
4150 (:foreground "green"))
4151 (((class color) (min-colors 8) (background dark))
4152 (:foreground "yellow"))))
4153 "Face for headline with the ARCHIVE tag."
4154 :group 'org-faces)
4156 (defface org-link
4157 '((((class color) (background light)) (:foreground "Purple" :underline t))
4158 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4159 (t (:underline t)))
4160 "Face for links."
4161 :group 'org-faces)
4163 (defface org-ellipsis
4164 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
4165 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
4166 (t (:strike-through t)))
4167 "Face for the ellipsis in folded text."
4168 :group 'org-faces)
4170 (defface org-target
4171 '((((class color) (background light)) (:underline t))
4172 (((class color) (background dark)) (:underline t))
4173 (t (:underline t)))
4174 "Face for links."
4175 :group 'org-faces)
4177 (defface org-date
4178 '((((class color) (background light)) (:foreground "Purple" :underline t))
4179 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4180 (t (:underline t)))
4181 "Face for links."
4182 :group 'org-faces)
4184 (defface org-sexp-date
4185 '((((class color) (background light)) (:foreground "Purple"))
4186 (((class color) (background dark)) (:foreground "Cyan"))
4187 (t (:underline t)))
4188 "Face for links."
4189 :group 'org-faces)
4191 (defface org-tag
4192 '((t (:bold t)))
4193 "Face for tags."
4194 :group 'org-faces)
4196 (defface org-todo ; font-lock-warning-face
4197 (org-compatible-face nil
4198 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4199 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4200 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4201 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4202 (t (:inverse-video t :bold t))))
4203 "Face for TODO keywords."
4204 :group 'org-faces)
4206 (defface org-done ;; font-lock-type-face
4207 (org-compatible-face nil
4208 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
4209 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
4210 (((class color) (min-colors 8)) (:foreground "green"))
4211 (t (:bold t))))
4212 "Face used for todo keywords that indicate DONE items."
4213 :group 'org-faces)
4215 (defface org-headline-done ;; font-lock-string-face
4216 (org-compatible-face nil
4217 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4218 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4219 (((class color) (min-colors 8) (background light)) (:bold nil))))
4220 "Face used to indicate that a headline is DONE.
4221 This face is only used if `org-fontify-done-headline' is set. If applies
4222 to the part of the headline after the DONE keyword."
4223 :group 'org-faces)
4225 (defcustom org-todo-keyword-faces nil
4226 "Faces for specific TODO keywords.
4227 This is a list of cons cells, with TODO keywords in the car
4228 and faces in the cdr. The face can be a symbol, or a property
4229 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
4230 :group 'org-faces
4231 :group 'org-todo
4232 :type '(repeat
4233 (cons
4234 (string :tag "keyword")
4235 (sexp :tag "face"))))
4237 (defface org-table ;; font-lock-function-name-face
4238 (org-compatible-face nil
4239 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4240 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4241 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4242 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4243 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
4244 (((class color) (min-colors 8) (background dark)))))
4245 "Face used for tables."
4246 :group 'org-faces)
4248 (defface org-formula
4249 (org-compatible-face nil
4250 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4251 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4252 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4253 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4254 (t (:bold t :italic t))))
4255 "Face for formulas."
4256 :group 'org-faces)
4258 (defface org-code
4259 (org-compatible-face nil
4260 '((((class color grayscale) (min-colors 88) (background light))
4261 (:foreground "grey50"))
4262 (((class color grayscale) (min-colors 88) (background dark))
4263 (:foreground "grey70"))
4264 (((class color) (min-colors 8) (background light))
4265 (:foreground "green"))
4266 (((class color) (min-colors 8) (background dark))
4267 (:foreground "yellow"))))
4268 "Face for fixed-with text like code snippets."
4269 :group 'org-faces
4270 :version "22.1")
4272 (defface org-verbatim
4273 (org-compatible-face nil
4274 '((((class color grayscale) (min-colors 88) (background light))
4275 (:foreground "grey50" :underline t))
4276 (((class color grayscale) (min-colors 88) (background dark))
4277 (:foreground "grey70" :underline t))
4278 (((class color) (min-colors 8) (background light))
4279 (:foreground "green" :underline t))
4280 (((class color) (min-colors 8) (background dark))
4281 (:foreground "yellow" :underline t))))
4282 "Face for fixed-with text like code snippets."
4283 :group 'org-faces
4284 :version "22.1")
4286 (defface org-agenda-structure ;; font-lock-function-name-face
4287 (org-compatible-face nil
4288 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4289 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4290 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4291 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4292 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4293 (t (:bold t))))
4294 "Face used in agenda for captions and dates."
4295 :group 'org-faces)
4297 (defface org-scheduled-today
4298 (org-compatible-face nil
4299 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4300 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4301 (((class color) (min-colors 8)) (:foreground "green"))
4302 (t (:bold t :italic t))))
4303 "Face for items scheduled for a certain day."
4304 :group 'org-faces)
4306 (defface org-scheduled-previously
4307 (org-compatible-face nil
4308 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4309 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4310 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4311 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4312 (t (:bold t))))
4313 "Face for items scheduled previously, and not yet done."
4314 :group 'org-faces)
4316 (defface org-upcoming-deadline
4317 (org-compatible-face nil
4318 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4319 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4320 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4321 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4322 (t (:bold t))))
4323 "Face for items scheduled previously, and not yet done."
4324 :group 'org-faces)
4326 (defcustom org-agenda-deadline-faces
4327 '((1.0 . org-warning)
4328 (0.5 . org-upcoming-deadline)
4329 (0.0 . default))
4330 "Faces for showing deadlines in the agenda.
4331 This is a list of cons cells. The cdr of each cell is a face to be used,
4332 and it can also just be like '(:foreground \"yellow\").
4333 Each car is a fraction of the head-warning time that must have passed for
4334 this the face in the cdr to be used for display. The numbers must be
4335 given in descending order. The head-warning time is normally taken
4336 from `org-deadline-warning-days', but can also be specified in the deadline
4337 timestamp itself, like this:
4339 DEADLINE: <2007-08-13 Mon -8d>
4341 You may use d for days, w for weeks, m for months and y for years. Months
4342 and years will only be treated in an approximate fashion (30.4 days for a
4343 month and 365.24 days for a year)."
4344 :group 'org-faces
4345 :group 'org-agenda-daily/weekly
4346 :type '(repeat
4347 (cons
4348 (number :tag "Fraction of head-warning time passed")
4349 (sexp :tag "Face"))))
4351 ;; FIXME: this is not a good face yet.
4352 (defface org-agenda-restriction-lock
4353 (org-compatible-face nil
4354 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4355 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4356 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4357 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4358 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4359 (t (:inverse-video t))))
4360 "Face for showing the agenda restriction lock."
4361 :group 'org-faces)
4363 (defface org-time-grid ;; font-lock-variable-name-face
4364 (org-compatible-face nil
4365 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4366 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4367 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4368 "Face used for time grids."
4369 :group 'org-faces)
4371 (defconst org-level-faces
4372 '(org-level-1 org-level-2 org-level-3 org-level-4
4373 org-level-5 org-level-6 org-level-7 org-level-8
4376 (defcustom org-n-level-faces (length org-level-faces)
4377 "The number of different faces to be used for headlines.
4378 Org-mode defines 8 different headline faces, so this can be at most 8.
4379 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4380 :type 'number
4381 :group 'org-faces)
4383 ;;; Functions and variables from ther packages
4384 ;; Declared here to avoid compiler warnings
4386 (eval-and-compile
4387 (unless (fboundp 'declare-function)
4388 (defmacro declare-function (fn file &optional arglist fileonly))))
4390 ;; XEmacs only
4391 (defvar outline-mode-menu-heading)
4392 (defvar outline-mode-menu-show)
4393 (defvar outline-mode-menu-hide)
4394 (defvar zmacs-regions) ; XEmacs regions
4396 ;; Emacs only
4397 (defvar mark-active)
4399 ;; Various packages
4400 ;; FIXME: get the argument lists for the UNKNOWN stuff
4401 (declare-function add-to-diary-list "diary-lib"
4402 (date string specifier &optional marker globcolor literal))
4403 (declare-function table--at-cell-p "table" (position &optional object at-column))
4404 (declare-function bibtex-beginning-of-entry "bibtex" ())
4405 (declare-function bibtex-generate-autokey "bibtex" ())
4406 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4407 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4408 (defvar calc-embedded-close-formula)
4409 (defvar calc-embedded-open-formula)
4410 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4411 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4412 (declare-function calendar-check-holidays "holidays" (date))
4413 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4414 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4415 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4416 (declare-function calendar-forward-day "cal-move" (arg))
4417 (declare-function calendar-french-date-string "cal-french" (&optional date))
4418 (declare-function calendar-goto-date "cal-move" (date))
4419 (declare-function calendar-goto-today "cal-move" ())
4420 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4421 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4422 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4423 (declare-function calendar-iso-from-absolute "cal-iso" (&optional date))
4424 (declare-function calendar-absolute-from-iso "cal-iso" (&optional date))
4425 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4426 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4427 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4428 (defvar calendar-mode-map)
4429 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4430 (declare-function cdlatex-tab "ext:cdlatex" ())
4431 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4432 (defvar font-lock-unfontify-region-function)
4433 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4434 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4435 (declare-function parse-time-string "parse-time" (string))
4436 (declare-function remember "remember" (&optional initial))
4437 (declare-function remember-buffer-desc "remember" ())
4438 (declare-function remember-finalize "remember" ())
4439 (defvar remember-save-after-remembering)
4440 (defvar remember-data-file)
4441 (defvar remember-register)
4442 (defvar remember-buffer)
4443 (defvar remember-handler-functions)
4444 (defvar remember-annotation-functions)
4445 (defvar texmathp-why)
4446 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4448 (defvar w3m-current-url)
4449 (defvar w3m-current-title)
4451 (defvar org-latex-regexps)
4452 (defvar constants-unit-system)
4454 ;;; Variables for pre-computed regular expressions, all buffer local
4456 (defvar org-drawer-regexp nil
4457 "Matches first line of a hidden block.")
4458 (make-variable-buffer-local 'org-drawer-regexp)
4459 (defvar org-todo-regexp nil
4460 "Matches any of the TODO state keywords.")
4461 (make-variable-buffer-local 'org-todo-regexp)
4462 (defvar org-not-done-regexp nil
4463 "Matches any of the TODO state keywords except the last one.")
4464 (make-variable-buffer-local 'org-not-done-regexp)
4465 (defvar org-todo-line-regexp nil
4466 "Matches a headline and puts TODO state into group 2 if present.")
4467 (make-variable-buffer-local 'org-todo-line-regexp)
4468 (defvar org-complex-heading-regexp nil
4469 "Matches a headline and puts everything into groups:
4470 group 1: the stars
4471 group 2: The todo keyword, maybe
4472 group 3: Priority cookie
4473 group 4: True headline
4474 group 5: Tags")
4475 (make-variable-buffer-local 'org-complex-heading-regexp)
4476 (defvar org-todo-line-tags-regexp nil
4477 "Matches a headline and puts TODO state into group 2 if present.
4478 Also put tags into group 4 if tags are present.")
4479 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4480 (defvar org-nl-done-regexp nil
4481 "Matches newline followed by a headline with the DONE keyword.")
4482 (make-variable-buffer-local 'org-nl-done-regexp)
4483 (defvar org-looking-at-done-regexp nil
4484 "Matches the DONE keyword a point.")
4485 (make-variable-buffer-local 'org-looking-at-done-regexp)
4486 (defvar org-ds-keyword-length 12
4487 "Maximum length of the Deadline and SCHEDULED keywords.")
4488 (make-variable-buffer-local 'org-ds-keyword-length)
4489 (defvar org-deadline-regexp nil
4490 "Matches the DEADLINE keyword.")
4491 (make-variable-buffer-local 'org-deadline-regexp)
4492 (defvar org-deadline-time-regexp nil
4493 "Matches the DEADLINE keyword together with a time stamp.")
4494 (make-variable-buffer-local 'org-deadline-time-regexp)
4495 (defvar org-deadline-line-regexp nil
4496 "Matches the DEADLINE keyword and the rest of the line.")
4497 (make-variable-buffer-local 'org-deadline-line-regexp)
4498 (defvar org-scheduled-regexp nil
4499 "Matches the SCHEDULED keyword.")
4500 (make-variable-buffer-local 'org-scheduled-regexp)
4501 (defvar org-scheduled-time-regexp nil
4502 "Matches the SCHEDULED keyword together with a time stamp.")
4503 (make-variable-buffer-local 'org-scheduled-time-regexp)
4504 (defvar org-closed-time-regexp nil
4505 "Matches the CLOSED keyword together with a time stamp.")
4506 (make-variable-buffer-local 'org-closed-time-regexp)
4508 (defvar org-keyword-time-regexp nil
4509 "Matches any of the 4 keywords, together with the time stamp.")
4510 (make-variable-buffer-local 'org-keyword-time-regexp)
4511 (defvar org-keyword-time-not-clock-regexp nil
4512 "Matches any of the 3 keywords, together with the time stamp.")
4513 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4514 (defvar org-maybe-keyword-time-regexp nil
4515 "Matches a timestamp, possibly preceeded by a keyword.")
4516 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4517 (defvar org-planning-or-clock-line-re nil
4518 "Matches a line with planning or clock info.")
4519 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4521 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4522 rear-nonsticky t mouse-map t fontified t)
4523 "Properties to remove when a string without properties is wanted.")
4525 (defsubst org-match-string-no-properties (num &optional string)
4526 (if (featurep 'xemacs)
4527 (let ((s (match-string num string)))
4528 (remove-text-properties 0 (length s) org-rm-props s)
4530 (match-string-no-properties num string)))
4532 (defsubst org-no-properties (s)
4533 (if (fboundp 'set-text-properties)
4534 (set-text-properties 0 (length s) nil s)
4535 (remove-text-properties 0 (length s) org-rm-props s))
4538 (defsubst org-get-alist-option (option key)
4539 (cond ((eq key t) t)
4540 ((eq option t) t)
4541 ((assoc key option) (cdr (assoc key option)))
4542 (t (cdr (assq 'default option)))))
4544 (defsubst org-inhibit-invisibility ()
4545 "Modified `buffer-invisibility-spec' for Emacs 21.
4546 Some ops with invisible text do not work correctly on Emacs 21. For these
4547 we turn off invisibility temporarily. Use this in a `let' form."
4548 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4550 (defsubst org-set-local (var value)
4551 "Make VAR local in current buffer and set it to VALUE."
4552 (set (make-variable-buffer-local var) value))
4554 (defsubst org-mode-p ()
4555 "Check if the current buffer is in Org-mode."
4556 (eq major-mode 'org-mode))
4558 (defsubst org-last (list)
4559 "Return the last element of LIST."
4560 (car (last list)))
4562 (defun org-let (list &rest body)
4563 (eval (cons 'let (cons list body))))
4564 (put 'org-let 'lisp-indent-function 1)
4566 (defun org-let2 (list1 list2 &rest body)
4567 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4568 (put 'org-let2 'lisp-indent-function 2)
4569 (defconst org-startup-options
4570 '(("fold" org-startup-folded t)
4571 ("overview" org-startup-folded t)
4572 ("nofold" org-startup-folded nil)
4573 ("showall" org-startup-folded nil)
4574 ("content" org-startup-folded content)
4575 ("hidestars" org-hide-leading-stars t)
4576 ("showstars" org-hide-leading-stars nil)
4577 ("odd" org-odd-levels-only t)
4578 ("oddeven" org-odd-levels-only nil)
4579 ("align" org-startup-align-all-tables t)
4580 ("noalign" org-startup-align-all-tables nil)
4581 ("customtime" org-display-custom-times t)
4582 ("logdone" org-log-done time)
4583 ("lognotedone" org-log-done note)
4584 ("nologdone" org-log-done nil)
4585 ("lognoteclock-out" org-log-note-clock-out t)
4586 ("nolognoteclock-out" org-log-note-clock-out nil)
4587 ("logrepeat" org-log-repeat state)
4588 ("lognoterepeat" org-log-repeat note)
4589 ("nologrepeat" org-log-repeat nil)
4590 ("constcgs" constants-unit-system cgs)
4591 ("constSI" constants-unit-system SI))
4592 "Variable associated with STARTUP options for org-mode.
4593 Each element is a list of three items: The startup options as written
4594 in the #+STARTUP line, the corresponding variable, and the value to
4595 set this variable to if the option is found. An optional forth element PUSH
4596 means to push this value onto the list in the variable.")
4598 (defun org-set-regexps-and-options ()
4599 "Precompute regular expressions for current buffer."
4600 (when (org-mode-p)
4601 (org-set-local 'org-todo-kwd-alist nil)
4602 (org-set-local 'org-todo-key-alist nil)
4603 (org-set-local 'org-todo-key-trigger nil)
4604 (org-set-local 'org-todo-keywords-1 nil)
4605 (org-set-local 'org-done-keywords nil)
4606 (org-set-local 'org-todo-heads nil)
4607 (org-set-local 'org-todo-sets nil)
4608 (org-set-local 'org-todo-log-states nil)
4609 (let ((re (org-make-options-regexp
4610 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4611 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4612 "CONSTANTS" "PROPERTY" "DRAWERS")))
4613 (splitre "[ \t]+")
4614 kwds kws0 kwsa key log value cat arch tags const links hw dws
4615 tail sep kws1 prio props drawers)
4616 (save-excursion
4617 (save-restriction
4618 (widen)
4619 (goto-char (point-min))
4620 (while (re-search-forward re nil t)
4621 (setq key (match-string 1) value (org-match-string-no-properties 2))
4622 (cond
4623 ((equal key "CATEGORY")
4624 (if (string-match "[ \t]+$" value)
4625 (setq value (replace-match "" t t value)))
4626 (setq cat value))
4627 ((member key '("SEQ_TODO" "TODO"))
4628 (push (cons 'sequence (org-split-string value splitre)) kwds))
4629 ((equal key "TYP_TODO")
4630 (push (cons 'type (org-split-string value splitre)) kwds))
4631 ((equal key "TAGS")
4632 (setq tags (append tags (org-split-string value splitre))))
4633 ((equal key "COLUMNS")
4634 (org-set-local 'org-columns-default-format value))
4635 ((equal key "LINK")
4636 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4637 (push (cons (match-string 1 value)
4638 (org-trim (match-string 2 value)))
4639 links)))
4640 ((equal key "PRIORITIES")
4641 (setq prio (org-split-string value " +")))
4642 ((equal key "PROPERTY")
4643 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4644 (push (cons (match-string 1 value) (match-string 2 value))
4645 props)))
4646 ((equal key "DRAWERS")
4647 (setq drawers (org-split-string value splitre)))
4648 ((equal key "CONSTANTS")
4649 (setq const (append const (org-split-string value splitre))))
4650 ((equal key "STARTUP")
4651 (let ((opts (org-split-string value splitre))
4652 l var val)
4653 (while (setq l (pop opts))
4654 (when (setq l (assoc l org-startup-options))
4655 (setq var (nth 1 l) val (nth 2 l))
4656 (if (not (nth 3 l))
4657 (set (make-local-variable var) val)
4658 (if (not (listp (symbol-value var)))
4659 (set (make-local-variable var) nil))
4660 (set (make-local-variable var) (symbol-value var))
4661 (add-to-list var val))))))
4662 ((equal key "ARCHIVE")
4663 (string-match " *$" value)
4664 (setq arch (replace-match "" t t value))
4665 (remove-text-properties 0 (length arch)
4666 '(face t fontified t) arch)))
4668 (when cat
4669 (org-set-local 'org-category (intern cat))
4670 (push (cons "CATEGORY" cat) props))
4671 (when prio
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-local-properties (nreverse props)))
4678 (and drawers (org-set-local 'org-drawers drawers))
4679 (and arch (org-set-local 'org-archive-location arch))
4680 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4681 ;; Process the TODO keywords
4682 (unless kwds
4683 ;; Use the global values as if they had been given locally.
4684 (setq kwds (default-value 'org-todo-keywords))
4685 (if (stringp (car kwds))
4686 (setq kwds (list (cons org-todo-interpretation
4687 (default-value 'org-todo-keywords)))))
4688 (setq kwds (reverse kwds)))
4689 (setq kwds (nreverse kwds))
4690 (let (inter kws kw)
4691 (while (setq kws (pop kwds))
4692 (setq inter (pop kws) sep (member "|" kws)
4693 kws0 (delete "|" (copy-sequence kws))
4694 kwsa nil
4695 kws1 (mapcar
4696 (lambda (x)
4697 ;; 1 2
4698 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4699 (progn
4700 (setq kw (match-string 1 x)
4701 key (and (match-end 2) (match-string 2 x))
4702 log (org-extract-log-state-settings x))
4703 (push (cons kw (and key (string-to-char key))) kwsa)
4704 (and log (push log org-todo-log-states))
4706 (error "Invalid TODO keyword %s" x)))
4707 kws0)
4708 kwsa (if kwsa (append '((:startgroup))
4709 (nreverse kwsa)
4710 '((:endgroup))))
4711 hw (car kws1)
4712 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4713 tail (list inter hw (car dws) (org-last dws)))
4714 (add-to-list 'org-todo-heads hw 'append)
4715 (push kws1 org-todo-sets)
4716 (setq org-done-keywords (append org-done-keywords dws nil))
4717 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4718 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4719 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4720 (setq org-todo-sets (nreverse org-todo-sets)
4721 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4722 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4723 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4724 ;; Process the constants
4725 (when const
4726 (let (e cst)
4727 (while (setq e (pop const))
4728 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4729 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4730 (setq org-table-formula-constants-local cst)))
4732 ;; Process the tags.
4733 (when tags
4734 (let (e tgs)
4735 (while (setq e (pop tags))
4736 (cond
4737 ((equal e "{") (push '(:startgroup) tgs))
4738 ((equal e "}") (push '(:endgroup) tgs))
4739 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4740 (push (cons (match-string 1 e)
4741 (string-to-char (match-string 2 e)))
4742 tgs))
4743 (t (push (list e) tgs))))
4744 (org-set-local 'org-tag-alist nil)
4745 (while (setq e (pop tgs))
4746 (or (and (stringp (car e))
4747 (assoc (car e) org-tag-alist))
4748 (push e org-tag-alist))))))
4750 ;; Compute the regular expressions and other local variables
4751 (if (not org-done-keywords)
4752 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4753 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4754 (length org-scheduled-string)))
4755 org-drawer-regexp
4756 (concat "^[ \t]*:\\("
4757 (mapconcat 'regexp-quote org-drawers "\\|")
4758 "\\):[ \t]*$")
4759 org-not-done-keywords
4760 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4761 org-todo-regexp
4762 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4763 "\\|") "\\)\\>")
4764 org-not-done-regexp
4765 (concat "\\<\\("
4766 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4767 "\\)\\>")
4768 org-todo-line-regexp
4769 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4770 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4771 "\\)\\>\\)?[ \t]*\\(.*\\)")
4772 org-complex-heading-regexp
4773 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4774 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4775 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4776 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4777 org-nl-done-regexp
4778 (concat "\n\\*+[ \t]+"
4779 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4780 "\\)" "\\>")
4781 org-todo-line-tags-regexp
4782 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4783 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4784 (org-re
4785 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4786 org-looking-at-done-regexp
4787 (concat "^" "\\(?:"
4788 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4789 "\\>")
4790 org-deadline-regexp (concat "\\<" org-deadline-string)
4791 org-deadline-time-regexp
4792 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4793 org-deadline-line-regexp
4794 (concat "\\<\\(" org-deadline-string "\\).*")
4795 org-scheduled-regexp
4796 (concat "\\<" org-scheduled-string)
4797 org-scheduled-time-regexp
4798 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4799 org-closed-time-regexp
4800 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4801 org-keyword-time-regexp
4802 (concat "\\<\\(" org-scheduled-string
4803 "\\|" org-deadline-string
4804 "\\|" org-closed-string
4805 "\\|" org-clock-string "\\)"
4806 " *[[<]\\([^]>]+\\)[]>]")
4807 org-keyword-time-not-clock-regexp
4808 (concat "\\<\\(" org-scheduled-string
4809 "\\|" org-deadline-string
4810 "\\|" org-closed-string
4811 "\\)"
4812 " *[[<]\\([^]>]+\\)[]>]")
4813 org-maybe-keyword-time-regexp
4814 (concat "\\(\\<\\(" org-scheduled-string
4815 "\\|" org-deadline-string
4816 "\\|" org-closed-string
4817 "\\|" org-clock-string "\\)\\)?"
4818 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4819 org-planning-or-clock-line-re
4820 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4821 "\\|" org-deadline-string
4822 "\\|" org-closed-string "\\|" org-clock-string
4823 "\\)\\>\\)")
4825 (org-compute-latex-and-specials-regexp)
4826 (org-set-font-lock-defaults)))
4828 (defun org-extract-log-state-settings (x)
4829 "Extract the log state setting from a TODO keyword string.
4830 This will extract info from a string like \"WAIT(w@/!)\"."
4831 (let (kw key log1 log2)
4832 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4833 (setq kw (match-string 1 x)
4834 key (and (match-end 2) (match-string 2 x))
4835 log1 (and (match-end 3) (match-string 3 x))
4836 log2 (and (match-end 4) (match-string 4 x)))
4837 (and (or log1 log2)
4838 (list kw
4839 (and log1 (if (equal log1 "!") 'time 'note))
4840 (and log2 (if (equal log2 "!") 'time 'note)))))))
4842 (defun org-remove-keyword-keys (list)
4843 "Remove a pair of parenthesis at the end of each string in LIST."
4844 (mapcar (lambda (x)
4845 (if (string-match "(.*)$" x)
4846 (substring x 0 (match-beginning 0))
4848 list))
4850 ;; FIXME: this could be done much better, using second characters etc.
4851 (defun org-assign-fast-keys (alist)
4852 "Assign fast keys to a keyword-key alist.
4853 Respect keys that are already there."
4854 (let (new e k c c1 c2 (char ?a))
4855 (while (setq e (pop alist))
4856 (cond
4857 ((equal e '(:startgroup)) (push e new))
4858 ((equal e '(:endgroup)) (push e new))
4860 (setq k (car e) c2 nil)
4861 (if (cdr e)
4862 (setq c (cdr e))
4863 ;; automatically assign a character.
4864 (setq c1 (string-to-char
4865 (downcase (substring
4866 k (if (= (string-to-char k) ?@) 1 0)))))
4867 (if (or (rassoc c1 new) (rassoc c1 alist))
4868 (while (or (rassoc char new) (rassoc char alist))
4869 (setq char (1+ char)))
4870 (setq c2 c1))
4871 (setq c (or c2 char)))
4872 (push (cons k c) new))))
4873 (nreverse new)))
4875 ;;; Some variables ujsed in various places
4877 (defvar org-window-configuration nil
4878 "Used in various places to store a window configuration.")
4879 (defvar org-finish-function nil
4880 "Function to be called when `C-c C-c' is used.
4881 This is for getting out of special buffers like remember.")
4884 ;; FIXME: Occasionally check by commenting these, to make sure
4885 ;; no other functions uses these, forgetting to let-bind them.
4886 (defvar entry)
4887 (defvar state)
4888 (defvar last-state)
4889 (defvar date)
4890 (defvar description)
4892 ;; Defined somewhere in this file, but used before definition.
4893 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4894 (defvar org-agenda-buffer-name)
4895 (defvar org-agenda-undo-list)
4896 (defvar org-agenda-pending-undo-list)
4897 (defvar org-agenda-overriding-header)
4898 (defvar orgtbl-mode)
4899 (defvar org-html-entities)
4900 (defvar org-struct-menu)
4901 (defvar org-org-menu)
4902 (defvar org-tbl-menu)
4903 (defvar org-agenda-keymap)
4905 ;;;; Emacs/XEmacs compatibility
4907 ;; Overlay compatibility functions
4908 (defun org-make-overlay (beg end &optional buffer)
4909 (if (featurep 'xemacs)
4910 (make-extent beg end buffer)
4911 (make-overlay beg end buffer)))
4912 (defun org-delete-overlay (ovl)
4913 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4914 (defun org-detach-overlay (ovl)
4915 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4916 (defun org-move-overlay (ovl beg end &optional buffer)
4917 (if (featurep 'xemacs)
4918 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4919 (move-overlay ovl beg end buffer)))
4920 (defun org-overlay-put (ovl prop value)
4921 (if (featurep 'xemacs)
4922 (set-extent-property ovl prop value)
4923 (overlay-put ovl prop value)))
4924 (defun org-overlay-display (ovl text &optional face evap)
4925 "Make overlay OVL display TEXT with face FACE."
4926 (if (featurep 'xemacs)
4927 (let ((gl (make-glyph text)))
4928 (and face (set-glyph-face gl face))
4929 (set-extent-property ovl 'invisible t)
4930 (set-extent-property ovl 'end-glyph gl))
4931 (overlay-put ovl 'display text)
4932 (if face (overlay-put ovl 'face face))
4933 (if evap (overlay-put ovl 'evaporate t))))
4934 (defun org-overlay-before-string (ovl text &optional face evap)
4935 "Make overlay OVL display TEXT with face FACE."
4936 (if (featurep 'xemacs)
4937 (let ((gl (make-glyph text)))
4938 (and face (set-glyph-face gl face))
4939 (set-extent-property ovl 'begin-glyph gl))
4940 (if face (org-add-props text nil 'face face))
4941 (overlay-put ovl 'before-string text)
4942 (if evap (overlay-put ovl 'evaporate t))))
4943 (defun org-overlay-get (ovl prop)
4944 (if (featurep 'xemacs)
4945 (extent-property ovl prop)
4946 (overlay-get ovl prop)))
4947 (defun org-overlays-at (pos)
4948 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4949 (defun org-overlays-in (&optional start end)
4950 (if (featurep 'xemacs)
4951 (extent-list nil start end)
4952 (overlays-in start end)))
4953 (defun org-overlay-start (o)
4954 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4955 (defun org-overlay-end (o)
4956 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4957 (defun org-find-overlays (prop &optional pos delete)
4958 "Find all overlays specifying PROP at POS or point.
4959 If DELETE is non-nil, delete all those overlays."
4960 (let ((overlays (org-overlays-at (or pos (point))))
4961 ov found)
4962 (while (setq ov (pop overlays))
4963 (if (org-overlay-get ov prop)
4964 (if delete (org-delete-overlay ov) (push ov found))))
4965 found))
4967 ;; Region compatibility
4969 (defun org-add-hook (hook function &optional append local)
4970 "Add-hook, compatible with both Emacsen."
4971 (if (and local (featurep 'xemacs))
4972 (add-local-hook hook function append)
4973 (add-hook hook function append local)))
4975 (defvar org-ignore-region nil
4976 "To temporarily disable the active region.")
4978 (defun org-region-active-p ()
4979 "Is `transient-mark-mode' on and the region active?
4980 Works on both Emacs and XEmacs."
4981 (if org-ignore-region
4983 (if (featurep 'xemacs)
4984 (and zmacs-regions (region-active-p))
4985 (if (fboundp 'use-region-p)
4986 (use-region-p)
4987 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4989 ;; Invisibility compatibility
4991 (defun org-add-to-invisibility-spec (arg)
4992 "Add elements to `buffer-invisibility-spec'.
4993 See documentation for `buffer-invisibility-spec' for the kind of elements
4994 that can be added."
4995 (cond
4996 ((fboundp 'add-to-invisibility-spec)
4997 (add-to-invisibility-spec arg))
4998 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4999 (setq buffer-invisibility-spec (list arg)))
5001 (setq buffer-invisibility-spec
5002 (cons arg buffer-invisibility-spec)))))
5004 (defun org-remove-from-invisibility-spec (arg)
5005 "Remove elements from `buffer-invisibility-spec'."
5006 (if (fboundp 'remove-from-invisibility-spec)
5007 (remove-from-invisibility-spec arg)
5008 (if (consp buffer-invisibility-spec)
5009 (setq buffer-invisibility-spec
5010 (delete arg buffer-invisibility-spec)))))
5012 (defun org-in-invisibility-spec-p (arg)
5013 "Is ARG a member of `buffer-invisibility-spec'?"
5014 (if (consp buffer-invisibility-spec)
5015 (member arg buffer-invisibility-spec)
5016 nil))
5018 ;;;; Define the Org-mode
5020 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5021 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or ugrade to newer allout, for example by switching to Emacs 22."))
5024 ;; We use a before-change function to check if a table might need
5025 ;; an update.
5026 (defvar org-table-may-need-update t
5027 "Indicates that a table might need an update.
5028 This variable is set by `org-before-change-function'.
5029 `org-table-align' sets it back to nil.")
5030 (defvar org-mode-map)
5031 (defvar org-mode-hook nil)
5032 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5033 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5034 (defvar org-table-buffer-is-an nil)
5035 (defconst org-outline-regexp "\\*+ ")
5037 ;;;###autoload
5038 (define-derived-mode org-mode outline-mode "Org"
5039 "Outline-based notes management and organizer, alias
5040 \"Carsten's outline-mode for keeping track of everything.\"
5042 Org-mode develops organizational tasks around a NOTES file which
5043 contains information about projects as plain text. Org-mode is
5044 implemented on top of outline-mode, which is ideal to keep the content
5045 of large files well structured. It supports ToDo items, deadlines and
5046 time stamps, which magically appear in the diary listing of the Emacs
5047 calendar. Tables are easily created with a built-in table editor.
5048 Plain text URL-like links connect to websites, emails (VM), Usenet
5049 messages (Gnus), BBDB entries, and any files related to the project.
5050 For printing and sharing of notes, an Org-mode file (or a part of it)
5051 can be exported as a structured ASCII or HTML file.
5053 The following commands are available:
5055 \\{org-mode-map}"
5057 ;; Get rid of Outline menus, they are not needed
5058 ;; Need to do this here because define-derived-mode sets up
5059 ;; the keymap so late. Still, it is a waste to call this each time
5060 ;; we switch another buffer into org-mode.
5061 (if (featurep 'xemacs)
5062 (when (boundp 'outline-mode-menu-heading)
5063 ;; Assume this is Greg's port, it used easymenu
5064 (easy-menu-remove outline-mode-menu-heading)
5065 (easy-menu-remove outline-mode-menu-show)
5066 (easy-menu-remove outline-mode-menu-hide))
5067 (define-key org-mode-map [menu-bar headings] 'undefined)
5068 (define-key org-mode-map [menu-bar hide] 'undefined)
5069 (define-key org-mode-map [menu-bar show] 'undefined))
5071 (org-load-modules-maybe)
5072 (easy-menu-add org-org-menu)
5073 (easy-menu-add org-tbl-menu)
5074 (org-install-agenda-files-menu)
5075 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
5076 (org-add-to-invisibility-spec '(org-cwidth))
5077 (when (featurep 'xemacs)
5078 (org-set-local 'line-move-ignore-invisible t))
5079 (org-set-local 'outline-regexp org-outline-regexp)
5080 (org-set-local 'outline-level 'org-outline-level)
5081 (when (and org-ellipsis
5082 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5083 (fboundp 'make-glyph-code))
5084 (unless org-display-table
5085 (setq org-display-table (make-display-table)))
5086 (set-display-table-slot
5087 org-display-table 4
5088 (vconcat (mapcar
5089 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5090 org-ellipsis)))
5091 (if (stringp org-ellipsis) org-ellipsis "..."))))
5092 (setq buffer-display-table org-display-table))
5093 (org-set-regexps-and-options)
5094 ;; Calc embedded
5095 (org-set-local 'calc-embedded-open-mode "# ")
5096 (modify-syntax-entry ?# "<")
5097 (modify-syntax-entry ?@ "w")
5098 (if org-startup-truncated (setq truncate-lines t))
5099 (org-set-local 'font-lock-unfontify-region-function
5100 'org-unfontify-region)
5101 ;; Activate before-change-function
5102 (org-set-local 'org-table-may-need-update t)
5103 (org-add-hook 'before-change-functions 'org-before-change-function nil
5104 'local)
5105 ;; Check for running clock before killing a buffer
5106 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5107 ;; Paragraphs and auto-filling
5108 (org-set-autofill-regexps)
5109 (setq indent-line-function 'org-indent-line-function)
5110 (org-update-radio-target-regexp)
5112 ;; Comment characters
5113 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
5114 (org-set-local 'comment-padding " ")
5116 ;; Align options lines
5117 (org-set-local
5118 'align-mode-rules-list
5119 '((org-in-buffer-settings
5120 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5121 (modes . '(org-mode)))))
5123 ;; Imenu
5124 (org-set-local 'imenu-create-index-function
5125 'org-imenu-get-tree)
5127 ;; Make isearch reveal context
5128 (if (or (featurep 'xemacs)
5129 (not (boundp 'outline-isearch-open-invisible-function)))
5130 ;; Emacs 21 and XEmacs make use of the hook
5131 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5132 ;; Emacs 22 deals with this through a special variable
5133 (org-set-local 'outline-isearch-open-invisible-function
5134 (lambda (&rest ignore) (org-show-context 'isearch))))
5136 ;; If empty file that did not turn on org-mode automatically, make it to.
5137 (if (and org-insert-mode-line-in-empty-file
5138 (interactive-p)
5139 (= (point-min) (point-max)))
5140 (insert "# -*- mode: org -*-\n\n"))
5142 (unless org-inhibit-startup
5143 (when org-startup-align-all-tables
5144 (let ((bmp (buffer-modified-p)))
5145 (org-table-map-tables 'org-table-align)
5146 (set-buffer-modified-p bmp)))
5147 (org-cycle-hide-drawers 'all)
5148 (cond
5149 ((eq org-startup-folded t)
5150 (org-cycle '(4)))
5151 ((eq org-startup-folded 'content)
5152 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5153 (org-cycle '(4)) (org-cycle '(4)))))))
5155 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5157 (defsubst org-call-with-arg (command arg)
5158 "Call COMMAND interactively, but pretend prefix are was ARG."
5159 (let ((current-prefix-arg arg)) (call-interactively command)))
5161 (defsubst org-current-line (&optional pos)
5162 (save-excursion
5163 (and pos (goto-char pos))
5164 ;; works also in narrowed buffer, because we start at 1, not point-min
5165 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
5167 (defun org-current-time ()
5168 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5169 (if (> (car org-time-stamp-rounding-minutes) 1)
5170 (let ((r (car org-time-stamp-rounding-minutes))
5171 (time (decode-time)))
5172 (apply 'encode-time
5173 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5174 (nthcdr 2 time))))
5175 (current-time)))
5177 (defun org-add-props (string plist &rest props)
5178 "Add text properties to entire string, from beginning to end.
5179 PLIST may be a list of properties, PROPS are individual properties and values
5180 that will be added to PLIST. Returns the string that was modified."
5181 (add-text-properties
5182 0 (length string) (if props (append plist props) plist) string)
5183 string)
5184 (put 'org-add-props 'lisp-indent-function 2)
5187 ;;;; Font-Lock stuff, including the activators
5189 (defvar org-mouse-map (make-sparse-keymap))
5190 (org-defkey org-mouse-map
5191 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
5192 (org-defkey org-mouse-map
5193 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
5194 (when org-mouse-1-follows-link
5195 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5196 (when org-tab-follows-link
5197 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5198 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5199 (when org-return-follows-link
5200 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
5201 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5203 (require 'font-lock)
5205 (defconst org-non-link-chars "]\t\n\r<>")
5206 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5207 "shell" "elisp"))
5208 (defvar org-link-re-with-space nil
5209 "Matches a link with spaces, optional angular brackets around it.")
5210 (defvar org-link-re-with-space2 nil
5211 "Matches a link with spaces, optional angular brackets around it.")
5212 (defvar org-angle-link-re nil
5213 "Matches link with angular brackets, spaces are allowed.")
5214 (defvar org-plain-link-re nil
5215 "Matches plain link, without spaces.")
5216 (defvar org-bracket-link-regexp nil
5217 "Matches a link in double brackets.")
5218 (defvar org-bracket-link-analytic-regexp nil
5219 "Regular expression used to analyze links.
5220 Here is what the match groups contain after a match:
5221 1: http:
5222 2: http
5223 3: path
5224 4: [desc]
5225 5: desc")
5226 (defvar org-any-link-re nil
5227 "Regular expression matching any link.")
5229 (defun org-make-link-regexps ()
5230 "Update the link regular expressions.
5231 This should be called after the variable `org-link-types' has changed."
5232 (setq org-link-re-with-space
5233 (concat
5234 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5235 "\\([^" org-non-link-chars " ]"
5236 "[^" org-non-link-chars "]*"
5237 "[^" org-non-link-chars " ]\\)>?")
5238 org-link-re-with-space2
5239 (concat
5240 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5241 "\\([^" org-non-link-chars " ]"
5242 "[^]\t\n\r]*"
5243 "[^" org-non-link-chars " ]\\)>?")
5244 org-angle-link-re
5245 (concat
5246 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5247 "\\([^" org-non-link-chars " ]"
5248 "[^" org-non-link-chars "]*"
5249 "\\)>")
5250 org-plain-link-re
5251 (concat
5252 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5253 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5254 org-bracket-link-regexp
5255 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5256 org-bracket-link-analytic-regexp
5257 (concat
5258 "\\[\\["
5259 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5260 "\\([^]]+\\)"
5261 "\\]"
5262 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5263 "\\]")
5264 org-any-link-re
5265 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5266 org-angle-link-re "\\)\\|\\("
5267 org-plain-link-re "\\)")))
5269 (org-make-link-regexps)
5271 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5272 "Regular expression for fast time stamp matching.")
5273 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5274 "Regular expression for fast time stamp matching.")
5275 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5276 "Regular expression matching time strings for analysis.
5277 This one does not require the space after the date, so it can be used
5278 on a string that terminates immediately after the date.")
5279 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5280 "Regular expression matching time strings for analysis.")
5281 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5282 "Regular expression matching time stamps, with groups.")
5283 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5284 "Regular expression matching time stamps (also [..]), with groups.")
5285 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5286 "Regular expression matching a time stamp range.")
5287 (defconst org-tr-regexp-both
5288 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5289 "Regular expression matching a time stamp range.")
5290 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5291 org-ts-regexp "\\)?")
5292 "Regular expression matching a time stamp or time stamp range.")
5293 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5294 org-ts-regexp-both "\\)?")
5295 "Regular expression matching a time stamp or time stamp range.
5296 The time stamps may be either active or inactive.")
5298 (defvar org-emph-face nil)
5300 (defun org-do-emphasis-faces (limit)
5301 "Run through the buffer and add overlays to links."
5302 (let (rtn)
5303 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5304 (if (not (= (char-after (match-beginning 3))
5305 (char-after (match-beginning 4))))
5306 (progn
5307 (setq rtn t)
5308 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5309 'face
5310 (nth 1 (assoc (match-string 3)
5311 org-emphasis-alist)))
5312 (add-text-properties (match-beginning 2) (match-end 2)
5313 '(font-lock-multiline t))
5314 (when org-hide-emphasis-markers
5315 (add-text-properties (match-end 4) (match-beginning 5)
5316 '(invisible org-link))
5317 (add-text-properties (match-beginning 3) (match-end 3)
5318 '(invisible org-link)))))
5319 (backward-char 1))
5320 rtn))
5322 (defun org-emphasize (&optional char)
5323 "Insert or change an emphasis, i.e. a font like bold or italic.
5324 If there is an active region, change that region to a new emphasis.
5325 If there is no region, just insert the marker characters and position
5326 the cursor between them.
5327 CHAR should be either the marker character, or the first character of the
5328 HTML tag associated with that emphasis. If CHAR is a space, the means
5329 to remove the emphasis of the selected region.
5330 If char is not given (for example in an interactive call) it
5331 will be prompted for."
5332 (interactive)
5333 (let ((eal org-emphasis-alist) e det
5334 (erc org-emphasis-regexp-components)
5335 (prompt "")
5336 (string "") beg end move tag c s)
5337 (if (org-region-active-p)
5338 (setq beg (region-beginning) end (region-end)
5339 string (buffer-substring beg end))
5340 (setq move t))
5342 (while (setq e (pop eal))
5343 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5344 c (aref tag 0))
5345 (push (cons c (string-to-char (car e))) det)
5346 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5347 (substring tag 1)))))
5348 (unless char
5349 (message "%s" (concat "Emphasis marker or tag:" prompt))
5350 (setq char (read-char-exclusive)))
5351 (setq char (or (cdr (assoc char det)) char))
5352 (if (equal char ?\ )
5353 (setq s "" move nil)
5354 (unless (assoc (char-to-string char) org-emphasis-alist)
5355 (error "No such emphasis marker: \"%c\"" char))
5356 (setq s (char-to-string char)))
5357 (while (and (> (length string) 1)
5358 (equal (substring string 0 1) (substring string -1))
5359 (assoc (substring string 0 1) org-emphasis-alist))
5360 (setq string (substring string 1 -1)))
5361 (setq string (concat s string s))
5362 (if beg (delete-region beg end))
5363 (unless (or (bolp)
5364 (string-match (concat "[" (nth 0 erc) "\n]")
5365 (char-to-string (char-before (point)))))
5366 (insert " "))
5367 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5368 (char-to-string (char-after (point))))
5369 (insert " ") (backward-char 1))
5370 (insert string)
5371 (and move (backward-char 1))))
5373 (defconst org-nonsticky-props
5374 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5377 (defun org-activate-plain-links (limit)
5378 "Run through the buffer and add overlays to links."
5379 (catch 'exit
5380 (let (f)
5381 (while (re-search-forward org-plain-link-re limit t)
5382 (setq f (get-text-property (match-beginning 0) 'face))
5383 (if (or (eq f 'org-tag)
5384 (and (listp f) (memq 'org-tag f)))
5386 (add-text-properties (match-beginning 0) (match-end 0)
5387 (list 'mouse-face 'highlight
5388 'rear-nonsticky org-nonsticky-props
5389 'keymap org-mouse-map
5391 (throw 'exit t))))))
5393 (defun org-activate-code (limit)
5394 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5395 (unless (get-text-property (match-beginning 1) 'face)
5396 (remove-text-properties (match-beginning 0) (match-end 0)
5397 '(display t invisible t intangible t))
5398 t)))
5400 (defun org-activate-angle-links (limit)
5401 "Run through the buffer and add overlays to links."
5402 (if (re-search-forward org-angle-link-re limit t)
5403 (progn
5404 (add-text-properties (match-beginning 0) (match-end 0)
5405 (list 'mouse-face 'highlight
5406 'rear-nonsticky org-nonsticky-props
5407 'keymap org-mouse-map
5409 t)))
5411 (defmacro org-maybe-intangible (props)
5412 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5413 In emacs 21, invisible text is not avoided by the command loop, so the
5414 intangible property is needed to make sure point skips this text.
5415 In Emacs 22, this is not necessary. The intangible text property has
5416 led to problems with flyspell. These problems are fixed in flyspell.el,
5417 but we still avoid setting the property in Emacs 22 and later.
5418 We use a macro so that the test can happen at compilation time."
5419 (if (< emacs-major-version 22)
5420 `(append '(intangible t) ,props)
5421 props))
5423 (defun org-activate-bracket-links (limit)
5424 "Run through the buffer and add overlays to bracketed links."
5425 (if (re-search-forward org-bracket-link-regexp limit t)
5426 (let* ((help (concat "LINK: "
5427 (org-match-string-no-properties 1)))
5428 ;; FIXME: above we should remove the escapes.
5429 ;; but that requires another match, protecting match data,
5430 ;; a lot of overhead for font-lock.
5431 (ip (org-maybe-intangible
5432 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5433 'keymap org-mouse-map 'mouse-face 'highlight
5434 'font-lock-multiline t 'help-echo help)))
5435 (vp (list 'rear-nonsticky org-nonsticky-props
5436 'keymap org-mouse-map 'mouse-face 'highlight
5437 ' font-lock-multiline t 'help-echo help)))
5438 ;; We need to remove the invisible property here. Table narrowing
5439 ;; may have made some of this invisible.
5440 (remove-text-properties (match-beginning 0) (match-end 0)
5441 '(invisible nil))
5442 (if (match-end 3)
5443 (progn
5444 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5445 (add-text-properties (match-beginning 3) (match-end 3) vp)
5446 (add-text-properties (match-end 3) (match-end 0) ip))
5447 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5448 (add-text-properties (match-beginning 1) (match-end 1) vp)
5449 (add-text-properties (match-end 1) (match-end 0) ip))
5450 t)))
5452 (defun org-activate-dates (limit)
5453 "Run through the buffer and add overlays to dates."
5454 (if (re-search-forward org-tsr-regexp-both limit t)
5455 (progn
5456 (add-text-properties (match-beginning 0) (match-end 0)
5457 (list 'mouse-face 'highlight
5458 'rear-nonsticky org-nonsticky-props
5459 'keymap org-mouse-map))
5460 (when org-display-custom-times
5461 (if (match-end 3)
5462 (org-display-custom-time (match-beginning 3) (match-end 3)))
5463 (org-display-custom-time (match-beginning 1) (match-end 1)))
5464 t)))
5466 (defvar org-target-link-regexp nil
5467 "Regular expression matching radio targets in plain text.")
5468 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5469 "Regular expression matching a link target.")
5470 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5471 "Regular expression matching a radio target.")
5472 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5473 "Regular expression matching any target.")
5475 (defun org-activate-target-links (limit)
5476 "Run through the buffer and add overlays to target matches."
5477 (when org-target-link-regexp
5478 (let ((case-fold-search t))
5479 (if (re-search-forward org-target-link-regexp limit t)
5480 (progn
5481 (add-text-properties (match-beginning 0) (match-end 0)
5482 (list 'mouse-face 'highlight
5483 'rear-nonsticky org-nonsticky-props
5484 'keymap org-mouse-map
5485 'help-echo "Radio target link"
5486 'org-linked-text t))
5487 t)))))
5489 (defun org-update-radio-target-regexp ()
5490 "Find all radio targets in this file and update the regular expression."
5491 (interactive)
5492 (when (memq 'radio org-activate-links)
5493 (setq org-target-link-regexp
5494 (org-make-target-link-regexp (org-all-targets 'radio)))
5495 (org-restart-font-lock)))
5497 (defun org-hide-wide-columns (limit)
5498 (let (s e)
5499 (setq s (text-property-any (point) (or limit (point-max))
5500 'org-cwidth t))
5501 (when s
5502 (setq e (next-single-property-change s 'org-cwidth))
5503 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5504 (goto-char e)
5505 t)))
5507 (defvar org-latex-and-specials-regexp nil
5508 "Regular expression for highlighting export special stuff.")
5509 (defvar org-match-substring-regexp)
5510 (defvar org-match-substring-with-braces-regexp)
5511 (defvar org-export-html-special-string-regexps)
5513 (defun org-compute-latex-and-specials-regexp ()
5514 "Compute regular expression for stuff treated specially by exporters."
5515 (if (not org-highlight-latex-fragments-and-specials)
5516 (org-set-local 'org-latex-and-specials-regexp nil)
5517 (let*
5518 ((matchers (plist-get org-format-latex-options :matchers))
5519 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5520 org-latex-regexps)))
5521 (options (org-combine-plists (org-default-export-plist)
5522 (org-infile-export-plist)))
5523 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5524 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5525 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5526 (org-export-html-expand (plist-get options :expand-quoted-html))
5527 (org-export-with-special-strings (plist-get options :special-strings))
5528 (re-sub
5529 (cond
5530 ((equal org-export-with-sub-superscripts '{})
5531 (list org-match-substring-with-braces-regexp))
5532 (org-export-with-sub-superscripts
5533 (list org-match-substring-regexp))
5534 (t nil)))
5535 (re-latex
5536 (if org-export-with-LaTeX-fragments
5537 (mapcar (lambda (x) (nth 1 x)) latexs)))
5538 (re-macros
5539 (if org-export-with-TeX-macros
5540 (list (concat "\\\\"
5541 (regexp-opt
5542 (append (mapcar 'car org-html-entities)
5543 (if (boundp 'org-latex-entities)
5544 org-latex-entities nil))
5545 'words))) ; FIXME
5547 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5548 (re-special (if org-export-with-special-strings
5549 (mapcar (lambda (x) (car x))
5550 org-export-html-special-string-regexps)))
5551 (re-rest
5552 (delq nil
5553 (list
5554 (if org-export-html-expand "@<[^>\n]+>")
5555 ))))
5556 (org-set-local
5557 'org-latex-and-specials-regexp
5558 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5559 re-rest) "\\|")))))
5561 (defface org-latex-and-export-specials
5562 (let ((font (cond ((assq :inherit custom-face-attributes)
5563 '(:inherit underline))
5564 (t '(:underline t)))))
5565 `((((class grayscale) (background light))
5566 (:foreground "DimGray" ,@font))
5567 (((class grayscale) (background dark))
5568 (:foreground "LightGray" ,@font))
5569 (((class color) (background light))
5570 (:foreground "SaddleBrown"))
5571 (((class color) (background dark))
5572 (:foreground "burlywood"))
5573 (t (,@font))))
5574 "Face used to highlight math latex and other special exporter stuff."
5575 :group 'org-faces)
5577 (defun org-do-latex-and-special-faces (limit)
5578 "Run through the buffer and add overlays to links."
5579 (when org-latex-and-specials-regexp
5580 (let (rtn d)
5581 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5582 limit t))
5583 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5584 'face))
5585 '(org-code org-verbatim underline)))
5586 (progn
5587 (setq rtn t
5588 d (cond ((member (char-after (1+ (match-beginning 0)))
5589 '(?_ ?^)) 1)
5590 (t 0)))
5591 (font-lock-prepend-text-property
5592 (+ d (match-beginning 0)) (match-end 0)
5593 'face 'org-latex-and-export-specials)
5594 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5595 '(font-lock-multiline t)))))
5596 rtn)))
5598 (defun org-restart-font-lock ()
5599 "Restart font-lock-mode, to force refontification."
5600 (when (and (boundp 'font-lock-mode) font-lock-mode)
5601 (font-lock-mode -1)
5602 (font-lock-mode 1)))
5604 (defun org-all-targets (&optional radio)
5605 "Return a list of all targets in this file.
5606 With optional argument RADIO, only find radio targets."
5607 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5608 rtn)
5609 (save-excursion
5610 (goto-char (point-min))
5611 (while (re-search-forward re nil t)
5612 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5613 rtn)))
5615 (defun org-make-target-link-regexp (targets)
5616 "Make regular expression matching all strings in TARGETS.
5617 The regular expression finds the targets also if there is a line break
5618 between words."
5619 (and targets
5620 (concat
5621 "\\<\\("
5622 (mapconcat
5623 (lambda (x)
5624 (while (string-match " +" x)
5625 (setq x (replace-match "\\s-+" t t x)))
5627 targets
5628 "\\|")
5629 "\\)\\>")))
5631 (defun org-activate-tags (limit)
5632 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5633 (progn
5634 (add-text-properties (match-beginning 1) (match-end 1)
5635 (list 'mouse-face 'highlight
5636 'rear-nonsticky org-nonsticky-props
5637 'keymap org-mouse-map))
5638 t)))
5640 (defun org-outline-level ()
5641 (save-excursion
5642 (looking-at outline-regexp)
5643 (if (match-beginning 1)
5644 (+ (org-get-string-indentation (match-string 1)) 1000)
5645 (1- (- (match-end 0) (match-beginning 0))))))
5647 (defvar org-font-lock-keywords nil)
5649 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5650 "Regular expression matching a property line.")
5652 (defun org-set-font-lock-defaults ()
5653 (let* ((em org-fontify-emphasized-text)
5654 (lk org-activate-links)
5655 (org-font-lock-extra-keywords
5656 (list
5657 ;; Headlines
5658 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5659 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5660 ;; Table lines
5661 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5662 (1 'org-table t))
5663 ;; Table internals
5664 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5665 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5666 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5667 ;; Drawers
5668 (list org-drawer-regexp '(0 'org-special-keyword t))
5669 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5670 ;; Properties
5671 (list org-property-re
5672 '(1 'org-special-keyword t)
5673 '(3 'org-property-value t))
5674 (if org-format-transports-properties-p
5675 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5676 ;; Links
5677 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5678 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5679 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5680 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5681 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5682 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5683 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5684 '(org-hide-wide-columns (0 nil append))
5685 ;; TODO lines
5686 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5687 '(1 (org-get-todo-face 1) t))
5688 ;; DONE
5689 (if org-fontify-done-headline
5690 (list (concat "^[*]+ +\\<\\("
5691 (mapconcat 'regexp-quote org-done-keywords "\\|")
5692 "\\)\\(.*\\)")
5693 '(2 'org-headline-done t))
5694 nil)
5695 ;; Priorities
5696 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5697 ;; Special keywords
5698 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5699 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5700 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5701 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5702 ;; Emphasis
5703 (if em
5704 (if (featurep 'xemacs)
5705 '(org-do-emphasis-faces (0 nil append))
5706 '(org-do-emphasis-faces)))
5707 ;; Checkboxes
5708 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5709 2 'bold prepend)
5710 (if org-provide-checkbox-statistics
5711 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5712 (0 (org-get-checkbox-statistics-face) t)))
5713 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5714 '(1 'org-archived prepend))
5715 ;; Specials
5716 '(org-do-latex-and-special-faces)
5717 ;; Code
5718 '(org-activate-code (1 'org-code t))
5719 ;; COMMENT
5720 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5721 "\\|" org-quote-string "\\)\\>")
5722 '(1 'org-special-keyword t))
5723 '("^#.*" (0 'font-lock-comment-face t))
5725 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5726 ;; Now set the full font-lock-keywords
5727 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5728 (org-set-local 'font-lock-defaults
5729 '(org-font-lock-keywords t nil nil backward-paragraph))
5730 (kill-local-variable 'font-lock-keywords) nil))
5732 (defvar org-m nil)
5733 (defvar org-l nil)
5734 (defvar org-f nil)
5735 (defun org-get-level-face (n)
5736 "Get the right face for match N in font-lock matching of healdines."
5737 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5738 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5739 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5740 (cond
5741 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5742 ((eq n 2) org-f)
5743 (t (if org-level-color-stars-only nil org-f))))
5745 (defun org-get-todo-face (kwd)
5746 "Get the right face for a TODO keyword KWD.
5747 If KWD is a number, get the corresponding match group."
5748 (if (numberp kwd) (setq kwd (match-string kwd)))
5749 (or (cdr (assoc kwd org-todo-keyword-faces))
5750 (and (member kwd org-done-keywords) 'org-done)
5751 'org-todo))
5753 (defun org-unfontify-region (beg end &optional maybe_loudly)
5754 "Remove fontification and activation overlays from links."
5755 (font-lock-default-unfontify-region beg end)
5756 (let* ((buffer-undo-list t)
5757 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5758 (inhibit-modification-hooks t)
5759 deactivate-mark buffer-file-name buffer-file-truename)
5760 (remove-text-properties beg end
5761 '(mouse-face t keymap t org-linked-text t
5762 invisible t intangible t))))
5764 ;;;; Visibility cycling, including org-goto and indirect buffer
5766 ;;; Cycling
5768 (defvar org-cycle-global-status nil)
5769 (make-variable-buffer-local 'org-cycle-global-status)
5770 (defvar org-cycle-subtree-status nil)
5771 (make-variable-buffer-local 'org-cycle-subtree-status)
5773 ;;;###autoload
5774 (defun org-cycle (&optional arg)
5775 "Visibility cycling for Org-mode.
5777 - When this function is called with a prefix argument, rotate the entire
5778 buffer through 3 states (global cycling)
5779 1. OVERVIEW: Show only top-level headlines.
5780 2. CONTENTS: Show all headlines of all levels, but no body text.
5781 3. SHOW ALL: Show everything.
5783 - When point is at the beginning of a headline, rotate the subtree started
5784 by this line through 3 different states (local cycling)
5785 1. FOLDED: Only the main headline is shown.
5786 2. CHILDREN: The main headline and the direct children are shown.
5787 From this state, you can move to one of the children
5788 and zoom in further.
5789 3. SUBTREE: Show the entire subtree, including body text.
5791 - When there is a numeric prefix, go up to a heading with level ARG, do
5792 a `show-subtree' and return to the previous cursor position. If ARG
5793 is negative, go up that many levels.
5795 - When point is not at the beginning of a headline, execute
5796 `indent-relative', like TAB normally does. See the option
5797 `org-cycle-emulate-tab' for details.
5799 - Special case: if point is at the beginning of the buffer and there is
5800 no headline in line 1, this function will act as if called with prefix arg.
5801 But only if also the variable `org-cycle-global-at-bob' is t."
5802 (interactive "P")
5803 (org-load-modules-maybe)
5804 (let* ((outline-regexp
5805 (if (and (org-mode-p) org-cycle-include-plain-lists)
5806 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5807 outline-regexp))
5808 (bob-special (and org-cycle-global-at-bob (bobp)
5809 (not (looking-at outline-regexp))))
5810 (org-cycle-hook
5811 (if bob-special
5812 (delq 'org-optimize-window-after-visibility-change
5813 (copy-sequence org-cycle-hook))
5814 org-cycle-hook))
5815 (pos (point)))
5817 (if (or bob-special (equal arg '(4)))
5818 ;; special case: use global cycling
5819 (setq arg t))
5821 (cond
5823 ((org-at-table-p 'any)
5824 ;; Enter the table or move to the next field in the table
5825 (or (org-table-recognize-table.el)
5826 (progn
5827 (if arg (org-table-edit-field t)
5828 (org-table-justify-field-maybe)
5829 (call-interactively 'org-table-next-field)))))
5831 ((eq arg t) ;; Global cycling
5833 (cond
5834 ((and (eq last-command this-command)
5835 (eq org-cycle-global-status 'overview))
5836 ;; We just created the overview - now do table of contents
5837 ;; This can be slow in very large buffers, so indicate action
5838 (message "CONTENTS...")
5839 (org-content)
5840 (message "CONTENTS...done")
5841 (setq org-cycle-global-status 'contents)
5842 (run-hook-with-args 'org-cycle-hook 'contents))
5844 ((and (eq last-command this-command)
5845 (eq org-cycle-global-status 'contents))
5846 ;; We just showed the table of contents - now show everything
5847 (show-all)
5848 (message "SHOW ALL")
5849 (setq org-cycle-global-status 'all)
5850 (run-hook-with-args 'org-cycle-hook 'all))
5853 ;; Default action: go to overview
5854 (org-overview)
5855 (message "OVERVIEW")
5856 (setq org-cycle-global-status 'overview)
5857 (run-hook-with-args 'org-cycle-hook 'overview))))
5859 ((and org-drawers org-drawer-regexp
5860 (save-excursion
5861 (beginning-of-line 1)
5862 (looking-at org-drawer-regexp)))
5863 ;; Toggle block visibility
5864 (org-flag-drawer
5865 (not (get-char-property (match-end 0) 'invisible))))
5867 ((integerp arg)
5868 ;; Show-subtree, ARG levels up from here.
5869 (save-excursion
5870 (org-back-to-heading)
5871 (outline-up-heading (if (< arg 0) (- arg)
5872 (- (funcall outline-level) arg)))
5873 (org-show-subtree)))
5875 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5876 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5877 ;; At a heading: rotate between three different views
5878 (org-back-to-heading)
5879 (let ((goal-column 0) eoh eol eos)
5880 ;; First, some boundaries
5881 (save-excursion
5882 (org-back-to-heading)
5883 (save-excursion
5884 (beginning-of-line 2)
5885 (while (and (not (eobp)) ;; this is like `next-line'
5886 (get-char-property (1- (point)) 'invisible))
5887 (beginning-of-line 2)) (setq eol (point)))
5888 (outline-end-of-heading) (setq eoh (point))
5889 (org-end-of-subtree t)
5890 (unless (eobp)
5891 (skip-chars-forward " \t\n")
5892 (beginning-of-line 1) ; in case this is an item
5894 (setq eos (1- (point))))
5895 ;; Find out what to do next and set `this-command'
5896 (cond
5897 ((= eos eoh)
5898 ;; Nothing is hidden behind this heading
5899 (message "EMPTY ENTRY")
5900 (setq org-cycle-subtree-status nil)
5901 (save-excursion
5902 (goto-char eos)
5903 (outline-next-heading)
5904 (if (org-invisible-p) (org-flag-heading nil))))
5905 ((or (>= eol eos)
5906 (not (string-match "\\S-" (buffer-substring eol eos))))
5907 ;; Entire subtree is hidden in one line: open it
5908 (org-show-entry)
5909 (show-children)
5910 (message "CHILDREN")
5911 (save-excursion
5912 (goto-char eos)
5913 (outline-next-heading)
5914 (if (org-invisible-p) (org-flag-heading nil)))
5915 (setq org-cycle-subtree-status 'children)
5916 (run-hook-with-args 'org-cycle-hook 'children))
5917 ((and (eq last-command this-command)
5918 (eq org-cycle-subtree-status 'children))
5919 ;; We just showed the children, now show everything.
5920 (org-show-subtree)
5921 (message "SUBTREE")
5922 (setq org-cycle-subtree-status 'subtree)
5923 (run-hook-with-args 'org-cycle-hook 'subtree))
5925 ;; Default action: hide the subtree.
5926 (hide-subtree)
5927 (message "FOLDED")
5928 (setq org-cycle-subtree-status 'folded)
5929 (run-hook-with-args 'org-cycle-hook 'folded)))))
5931 ;; TAB emulation
5932 (buffer-read-only (org-back-to-heading))
5934 ((org-try-cdlatex-tab))
5936 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5937 (or (not (bolp))
5938 (not (looking-at outline-regexp))))
5939 (call-interactively (global-key-binding "\t")))
5941 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5942 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5943 (or (and (eq org-cycle-emulate-tab 'white)
5944 (= (match-end 0) (point-at-eol)))
5945 (and (eq org-cycle-emulate-tab 'whitestart)
5946 (>= (match-end 0) pos))))
5948 (eq org-cycle-emulate-tab t))
5949 ; (if (and (looking-at "[ \n\r\t]")
5950 ; (string-match "^[ \t]*$" (buffer-substring
5951 ; (point-at-bol) (point))))
5952 ; (progn
5953 ; (beginning-of-line 1)
5954 ; (and (looking-at "[ \t]+") (replace-match ""))))
5955 (call-interactively (global-key-binding "\t")))
5957 (t (save-excursion
5958 (org-back-to-heading)
5959 (org-cycle))))))
5961 ;;;###autoload
5962 (defun org-global-cycle (&optional arg)
5963 "Cycle the global visibility. For details see `org-cycle'."
5964 (interactive "P")
5965 (let ((org-cycle-include-plain-lists
5966 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5967 (if (integerp arg)
5968 (progn
5969 (show-all)
5970 (hide-sublevels arg)
5971 (setq org-cycle-global-status 'contents))
5972 (org-cycle '(4)))))
5974 (defun org-overview ()
5975 "Switch to overview mode, shoing only top-level headlines.
5976 Really, this shows all headlines with level equal or greater than the level
5977 of the first headline in the buffer. This is important, because if the
5978 first headline is not level one, then (hide-sublevels 1) gives confusing
5979 results."
5980 (interactive)
5981 (let ((level (save-excursion
5982 (goto-char (point-min))
5983 (if (re-search-forward (concat "^" outline-regexp) nil t)
5984 (progn
5985 (goto-char (match-beginning 0))
5986 (funcall outline-level))))))
5987 (and level (hide-sublevels level))))
5989 (defun org-content (&optional arg)
5990 "Show all headlines in the buffer, like a table of contents.
5991 With numerical argument N, show content up to level N."
5992 (interactive "P")
5993 (save-excursion
5994 ;; Visit all headings and show their offspring
5995 (and (integerp arg) (org-overview))
5996 (goto-char (point-max))
5997 (catch 'exit
5998 (while (and (progn (condition-case nil
5999 (outline-previous-visible-heading 1)
6000 (error (goto-char (point-min))))
6002 (looking-at outline-regexp))
6003 (if (integerp arg)
6004 (show-children (1- arg))
6005 (show-branches))
6006 (if (bobp) (throw 'exit nil))))))
6009 (defun org-optimize-window-after-visibility-change (state)
6010 "Adjust the window after a change in outline visibility.
6011 This function is the default value of the hook `org-cycle-hook'."
6012 (when (get-buffer-window (current-buffer))
6013 (cond
6014 ; ((eq state 'overview) (org-first-headline-recenter 1))
6015 ; ((eq state 'overview) (org-beginning-of-line))
6016 ((eq state 'content) nil)
6017 ((eq state 'all) nil)
6018 ((eq state 'folded) nil)
6019 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6020 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6022 (defun org-compact-display-after-subtree-move ()
6023 (let (beg end)
6024 (save-excursion
6025 (if (org-up-heading-safe)
6026 (progn
6027 (hide-subtree)
6028 (show-entry)
6029 (show-children)
6030 (org-cycle-show-empty-lines 'children)
6031 (org-cycle-hide-drawers 'children))
6032 (org-overview)))))
6034 (defun org-cycle-show-empty-lines (state)
6035 "Show empty lines above all visible headlines.
6036 The region to be covered depends on STATE when called through
6037 `org-cycle-hook'. Lisp program can use t for STATE to get the
6038 entire buffer covered. Note that an empty line is only shown if there
6039 are at least `org-cycle-separator-lines' empty lines before the headeline."
6040 (when (> org-cycle-separator-lines 0)
6041 (save-excursion
6042 (let* ((n org-cycle-separator-lines)
6043 (re (cond
6044 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6045 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6046 (t (let ((ns (number-to-string (- n 2))))
6047 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6048 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6049 beg end)
6050 (cond
6051 ((memq state '(overview contents t))
6052 (setq beg (point-min) end (point-max)))
6053 ((memq state '(children folded))
6054 (setq beg (point) end (progn (org-end-of-subtree t t)
6055 (beginning-of-line 2)
6056 (point)))))
6057 (when beg
6058 (goto-char beg)
6059 (while (re-search-forward re end t)
6060 (if (not (get-char-property (match-end 1) 'invisible))
6061 (outline-flag-region
6062 (match-beginning 1) (match-end 1) nil)))))))
6063 ;; Never hide empty lines at the end of the file.
6064 (save-excursion
6065 (goto-char (point-max))
6066 (outline-previous-heading)
6067 (outline-end-of-heading)
6068 (if (and (looking-at "[ \t\n]+")
6069 (= (match-end 0) (point-max)))
6070 (outline-flag-region (point) (match-end 0) nil))))
6072 (defun org-subtree-end-visible-p ()
6073 "Is the end of the current subtree visible?"
6074 (pos-visible-in-window-p
6075 (save-excursion (org-end-of-subtree t) (point))))
6077 (defun org-first-headline-recenter (&optional N)
6078 "Move cursor to the first headline and recenter the headline.
6079 Optional argument N means, put the headline into the Nth line of the window."
6080 (goto-char (point-min))
6081 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6082 (beginning-of-line)
6083 (recenter (prefix-numeric-value N))))
6085 ;;; Org-goto
6087 (defvar org-goto-window-configuration nil)
6088 (defvar org-goto-marker nil)
6089 (defvar org-goto-map
6090 (let ((map (make-sparse-keymap)))
6091 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6092 (while (setq cmd (pop cmds))
6093 (substitute-key-definition cmd cmd map global-map)))
6094 (suppress-keymap map)
6095 (org-defkey map "\C-m" 'org-goto-ret)
6096 (org-defkey map [(return)] 'org-goto-ret)
6097 (org-defkey map [(left)] 'org-goto-left)
6098 (org-defkey map [(right)] 'org-goto-right)
6099 (org-defkey map [(control ?g)] 'org-goto-quit)
6100 (org-defkey map "\C-i" 'org-cycle)
6101 (org-defkey map [(tab)] 'org-cycle)
6102 (org-defkey map [(down)] 'outline-next-visible-heading)
6103 (org-defkey map [(up)] 'outline-previous-visible-heading)
6104 (if org-goto-auto-isearch
6105 (if (fboundp 'define-key-after)
6106 (define-key-after map [t] 'org-goto-local-auto-isearch)
6107 nil)
6108 (org-defkey map "q" 'org-goto-quit)
6109 (org-defkey map "n" 'outline-next-visible-heading)
6110 (org-defkey map "p" 'outline-previous-visible-heading)
6111 (org-defkey map "f" 'outline-forward-same-level)
6112 (org-defkey map "b" 'outline-backward-same-level)
6113 (org-defkey map "u" 'outline-up-heading))
6114 (org-defkey map "/" 'org-occur)
6115 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6116 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6117 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6118 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6119 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6120 map))
6122 (defconst org-goto-help
6123 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6124 RET=jump to location [Q]uit and return to previous location
6125 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6127 (defvar org-goto-start-pos) ; dynamically scoped parameter
6129 (defun org-goto (&optional alternative-interface)
6130 "Look up a different location in the current file, keeping current visibility.
6132 When you want look-up or go to a different location in a document, the
6133 fastest way is often to fold the entire buffer and then dive into the tree.
6134 This method has the disadvantage, that the previous location will be folded,
6135 which may not be what you want.
6137 This command works around this by showing a copy of the current buffer
6138 in an indirect buffer, in overview mode. You can dive into the tree in
6139 that copy, use org-occur and incremental search to find a location.
6140 When pressing RET or `Q', the command returns to the original buffer in
6141 which the visibility is still unchanged. After RET is will also jump to
6142 the location selected in the indirect buffer and expose the
6143 the headline hierarchy above."
6144 (interactive "P")
6145 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
6146 (org-refile-use-outline-path t)
6147 (interface
6148 (if (not alternative-interface)
6149 org-goto-interface
6150 (if (eq org-goto-interface 'outline)
6151 'outline-path-completion
6152 'outline)))
6153 (org-goto-start-pos (point))
6154 (selected-point
6155 (if (eq interface 'outline)
6156 (car (org-get-location (current-buffer) org-goto-help))
6157 (nth 3 (org-refile-get-location "Goto: ")))))
6158 (if selected-point
6159 (progn
6160 (org-mark-ring-push org-goto-start-pos)
6161 (goto-char selected-point)
6162 (if (or (org-invisible-p) (org-invisible-p2))
6163 (org-show-context 'org-goto)))
6164 (message "Quit"))))
6166 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6167 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6168 (defvar org-goto-local-auto-isearch-map) ; defined below
6170 (defun org-get-location (buf help)
6171 "Let the user select a location in the Org-mode buffer BUF.
6172 This function uses a recursive edit. It returns the selected position
6173 or nil."
6174 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6175 (isearch-hide-immediately nil)
6176 (isearch-search-fun-function
6177 (lambda () 'org-goto-local-search-forward-headings))
6178 (org-goto-selected-point org-goto-exit-command))
6179 (save-excursion
6180 (save-window-excursion
6181 (delete-other-windows)
6182 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6183 (switch-to-buffer
6184 (condition-case nil
6185 (make-indirect-buffer (current-buffer) "*org-goto*")
6186 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6187 (with-output-to-temp-buffer "*Help*"
6188 (princ help))
6189 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
6190 (setq buffer-read-only nil)
6191 (let ((org-startup-truncated t)
6192 (org-startup-folded nil)
6193 (org-startup-align-all-tables nil))
6194 (org-mode)
6195 (org-overview))
6196 (setq buffer-read-only t)
6197 (if (and (boundp 'org-goto-start-pos)
6198 (integer-or-marker-p org-goto-start-pos))
6199 (let ((org-show-hierarchy-above t)
6200 (org-show-siblings t)
6201 (org-show-following-heading t))
6202 (goto-char org-goto-start-pos)
6203 (and (org-invisible-p) (org-show-context)))
6204 (goto-char (point-min)))
6205 (org-beginning-of-line)
6206 (message "Select location and press RET")
6207 (use-local-map org-goto-map)
6208 (recursive-edit)
6210 (kill-buffer "*org-goto*")
6211 (cons org-goto-selected-point org-goto-exit-command)))
6213 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6214 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6215 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6216 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6218 (defun org-goto-local-search-forward-headings (string bound noerror)
6219 "Search and make sure that anu matches are in headlines."
6220 (catch 'return
6221 (while (search-forward string bound noerror)
6222 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6223 (and (member :headline context)
6224 (not (member :tags context))))
6225 (throw 'return (point))))))
6227 (defun org-goto-local-auto-isearch ()
6228 "Start isearch."
6229 (interactive)
6230 (goto-char (point-min))
6231 (let ((keys (this-command-keys)))
6232 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6233 (isearch-mode t)
6234 (isearch-process-search-char (string-to-char keys)))))
6236 (defun org-goto-ret (&optional arg)
6237 "Finish `org-goto' by going to the new location."
6238 (interactive "P")
6239 (setq org-goto-selected-point (point)
6240 org-goto-exit-command 'return)
6241 (throw 'exit nil))
6243 (defun org-goto-left ()
6244 "Finish `org-goto' by going to the new location."
6245 (interactive)
6246 (if (org-on-heading-p)
6247 (progn
6248 (beginning-of-line 1)
6249 (setq org-goto-selected-point (point)
6250 org-goto-exit-command 'left)
6251 (throw 'exit nil))
6252 (error "Not on a heading")))
6254 (defun org-goto-right ()
6255 "Finish `org-goto' by going to the new location."
6256 (interactive)
6257 (if (org-on-heading-p)
6258 (progn
6259 (setq org-goto-selected-point (point)
6260 org-goto-exit-command 'right)
6261 (throw 'exit nil))
6262 (error "Not on a heading")))
6264 (defun org-goto-quit ()
6265 "Finish `org-goto' without cursor motion."
6266 (interactive)
6267 (setq org-goto-selected-point nil)
6268 (setq org-goto-exit-command 'quit)
6269 (throw 'exit nil))
6271 ;;; Indirect buffer display of subtrees
6273 (defvar org-indirect-dedicated-frame nil
6274 "This is the frame being used for indirect tree display.")
6275 (defvar org-last-indirect-buffer nil)
6277 (defun org-tree-to-indirect-buffer (&optional arg)
6278 "Create indirect buffer and narrow it to current subtree.
6279 With numerical prefix ARG, go up to this level and then take that tree.
6280 If ARG is negative, go up that many levels.
6281 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6282 indirect buffer previously made with this command, to avoid proliferation of
6283 indirect buffers. However, when you call the command with a `C-u' prefix, or
6284 when `org-indirect-buffer-display' is `new-frame', the last buffer
6285 is kept so that you can work with several indirect buffers at the same time.
6286 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6287 requests that a new frame be made for the new buffer, so that the dedicated
6288 frame is not changed."
6289 (interactive "P")
6290 (let ((cbuf (current-buffer))
6291 (cwin (selected-window))
6292 (pos (point))
6293 beg end level heading ibuf)
6294 (save-excursion
6295 (org-back-to-heading t)
6296 (when (numberp arg)
6297 (setq level (org-outline-level))
6298 (if (< arg 0) (setq arg (+ level arg)))
6299 (while (> (setq level (org-outline-level)) arg)
6300 (outline-up-heading 1 t)))
6301 (setq beg (point)
6302 heading (org-get-heading))
6303 (org-end-of-subtree t) (setq end (point)))
6304 (if (and (buffer-live-p org-last-indirect-buffer)
6305 (not (eq org-indirect-buffer-display 'new-frame))
6306 (not arg))
6307 (kill-buffer org-last-indirect-buffer))
6308 (setq ibuf (org-get-indirect-buffer cbuf)
6309 org-last-indirect-buffer ibuf)
6310 (cond
6311 ((or (eq org-indirect-buffer-display 'new-frame)
6312 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6313 (select-frame (make-frame))
6314 (delete-other-windows)
6315 (switch-to-buffer ibuf)
6316 (org-set-frame-title heading))
6317 ((eq org-indirect-buffer-display 'dedicated-frame)
6318 (raise-frame
6319 (select-frame (or (and org-indirect-dedicated-frame
6320 (frame-live-p org-indirect-dedicated-frame)
6321 org-indirect-dedicated-frame)
6322 (setq org-indirect-dedicated-frame (make-frame)))))
6323 (delete-other-windows)
6324 (switch-to-buffer ibuf)
6325 (org-set-frame-title (concat "Indirect: " heading)))
6326 ((eq org-indirect-buffer-display 'current-window)
6327 (switch-to-buffer ibuf))
6328 ((eq org-indirect-buffer-display 'other-window)
6329 (pop-to-buffer ibuf))
6330 (t (error "Invalid value.")))
6331 (if (featurep 'xemacs)
6332 (save-excursion (org-mode) (turn-on-font-lock)))
6333 (narrow-to-region beg end)
6334 (show-all)
6335 (goto-char pos)
6336 (and (window-live-p cwin) (select-window cwin))))
6338 (defun org-get-indirect-buffer (&optional buffer)
6339 (setq buffer (or buffer (current-buffer)))
6340 (let ((n 1) (base (buffer-name buffer)) bname)
6341 (while (buffer-live-p
6342 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6343 (setq n (1+ n)))
6344 (condition-case nil
6345 (make-indirect-buffer buffer bname 'clone)
6346 (error (make-indirect-buffer buffer bname)))))
6348 (defun org-set-frame-title (title)
6349 "Set the title of the current frame to the string TITLE."
6350 ;; FIXME: how to name a single frame in XEmacs???
6351 (unless (featurep 'xemacs)
6352 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6354 ;;;; Structure editing
6356 ;;; Inserting headlines
6358 (defun org-insert-heading (&optional force-heading)
6359 "Insert a new heading or item with same depth at point.
6360 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6361 If point is at the beginning of a headline, insert a sibling before the
6362 current headline. If point is not at the beginning, do not split the line,
6363 but create the new hedline after the current line."
6364 (interactive "P")
6365 (if (= (buffer-size) 0)
6366 (insert "\n* ")
6367 (when (or force-heading (not (org-insert-item)))
6368 (let* ((head (save-excursion
6369 (condition-case nil
6370 (progn
6371 (org-back-to-heading)
6372 (match-string 0))
6373 (error "*"))))
6374 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6375 pos)
6376 (cond
6377 ((and (org-on-heading-p) (bolp)
6378 (or (bobp)
6379 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6380 ;; insert before the current line
6381 (open-line (if blank 2 1)))
6382 ((and (bolp)
6383 (or (bobp)
6384 (save-excursion
6385 (backward-char 1) (not (org-invisible-p)))))
6386 ;; insert right here
6387 nil)
6389 ; ;; in the middle of the line
6390 ; (org-show-entry)
6391 ; (if (org-get-alist-option org-M-RET-may-split-line 'headline)
6392 ; (if (and
6393 ; (org-on-heading-p)
6394 ; (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \r\n]"))
6395 ; ;; protect the tags
6396 ;; (let ((tags (match-string 2)) pos)
6397 ; (delete-region (match-beginning 1) (match-end 1))
6398 ; (setq pos (point-at-bol))
6399 ; (newline (if blank 2 1))
6400 ; (save-excursion
6401 ; (goto-char pos)
6402 ; (end-of-line 1)
6403 ; (insert " " tags)
6404 ; (org-set-tags nil 'align)))
6405 ; (newline (if blank 2 1)))
6406 ; (newline (if blank 2 1))))
6409 ;; in the middle of the line
6410 (org-show-entry)
6411 (let ((split
6412 (org-get-alist-option org-M-RET-may-split-line 'headline))
6413 tags pos)
6414 (if (org-on-heading-p)
6415 (progn
6416 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6417 (setq tags (and (match-end 2) (match-string 2)))
6418 (and (match-end 1)
6419 (delete-region (match-beginning 1) (match-end 1)))
6420 (setq pos (point-at-bol))
6421 (or split (end-of-line 1))
6422 (delete-horizontal-space)
6423 (newline (if blank 2 1))
6424 (when tags
6425 (save-excursion
6426 (goto-char pos)
6427 (end-of-line 1)
6428 (insert " " tags)
6429 (org-set-tags nil 'align))))
6430 (or split (end-of-line 1))
6431 (newline (if blank 2 1))))))
6432 (insert head) (just-one-space)
6433 (setq pos (point))
6434 (end-of-line 1)
6435 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6436 (run-hooks 'org-insert-heading-hook)))))
6438 (defun org-insert-heading-after-current ()
6439 "Insert a new heading with same level as current, after current subtree."
6440 (interactive)
6441 (org-back-to-heading)
6442 (org-insert-heading)
6443 (org-move-subtree-down)
6444 (end-of-line 1))
6446 (defun org-insert-todo-heading (arg)
6447 "Insert a new heading with the same level and TODO state as current heading.
6448 If the heading has no TODO state, or if the state is DONE, use the first
6449 state (TODO by default). Also with prefix arg, force first state."
6450 (interactive "P")
6451 (when (not (org-insert-item 'checkbox))
6452 (org-insert-heading)
6453 (save-excursion
6454 (org-back-to-heading)
6455 (outline-previous-heading)
6456 (looking-at org-todo-line-regexp))
6457 (if (or arg
6458 (not (match-beginning 2))
6459 (member (match-string 2) org-done-keywords))
6460 (insert (car org-todo-keywords-1) " ")
6461 (insert (match-string 2) " "))))
6463 (defun org-insert-subheading (arg)
6464 "Insert a new subheading and demote it.
6465 Works for outline headings and for plain lists alike."
6466 (interactive "P")
6467 (org-insert-heading arg)
6468 (cond
6469 ((org-on-heading-p) (org-do-demote))
6470 ((org-at-item-p) (org-indent-item 1))))
6472 (defun org-insert-todo-subheading (arg)
6473 "Insert a new subheading with TODO keyword or checkbox and demote it.
6474 Works for outline headings and for plain lists alike."
6475 (interactive "P")
6476 (org-insert-todo-heading arg)
6477 (cond
6478 ((org-on-heading-p) (org-do-demote))
6479 ((org-at-item-p) (org-indent-item 1))))
6481 ;;; Promotion and Demotion
6483 (defun org-promote-subtree ()
6484 "Promote the entire subtree.
6485 See also `org-promote'."
6486 (interactive)
6487 (save-excursion
6488 (org-map-tree 'org-promote))
6489 (org-fix-position-after-promote))
6491 (defun org-demote-subtree ()
6492 "Demote the entire subtree. See `org-demote'.
6493 See also `org-promote'."
6494 (interactive)
6495 (save-excursion
6496 (org-map-tree 'org-demote))
6497 (org-fix-position-after-promote))
6500 (defun org-do-promote ()
6501 "Promote the current heading higher up the tree.
6502 If the region is active in `transient-mark-mode', promote all headings
6503 in the region."
6504 (interactive)
6505 (save-excursion
6506 (if (org-region-active-p)
6507 (org-map-region 'org-promote (region-beginning) (region-end))
6508 (org-promote)))
6509 (org-fix-position-after-promote))
6511 (defun org-do-demote ()
6512 "Demote the current heading lower down the tree.
6513 If the region is active in `transient-mark-mode', demote all headings
6514 in the region."
6515 (interactive)
6516 (save-excursion
6517 (if (org-region-active-p)
6518 (org-map-region 'org-demote (region-beginning) (region-end))
6519 (org-demote)))
6520 (org-fix-position-after-promote))
6522 (defun org-fix-position-after-promote ()
6523 "Make sure that after pro/demotion cursor position is right."
6524 (let ((pos (point)))
6525 (when (save-excursion
6526 (beginning-of-line 1)
6527 (looking-at org-todo-line-regexp)
6528 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6529 (cond ((eobp) (insert " "))
6530 ((eolp) (insert " "))
6531 ((equal (char-after) ?\ ) (forward-char 1))))))
6533 (defun org-reduced-level (l)
6534 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6536 (defun org-get-valid-level (level &optional change)
6537 "Rectify a level change under the influence of `org-odd-levels-only'
6538 LEVEL is a current level, CHANGE is by how much the level should be
6539 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6540 even level numbers will become the next higher odd number."
6541 (if org-odd-levels-only
6542 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6543 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6544 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6545 (max 1 (+ level change))))
6547 (if (featurep 'xemacs)
6548 (define-obsolete-function-alias 'org-get-legal-level
6549 'org-get-valid-level)
6550 (define-obsolete-function-alias 'org-get-legal-level
6551 'org-get-valid-level "23.1"))
6553 (defun org-promote ()
6554 "Promote the current heading higher up the tree.
6555 If the region is active in `transient-mark-mode', promote all headings
6556 in the region."
6557 (org-back-to-heading t)
6558 (let* ((level (save-match-data (funcall outline-level)))
6559 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6560 (diff (abs (- level (length up-head) -1))))
6561 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6562 (replace-match up-head nil t)
6563 ;; Fixup tag positioning
6564 (and org-auto-align-tags (org-set-tags nil t))
6565 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6567 (defun org-demote ()
6568 "Demote the current heading lower down the tree.
6569 If the region is active in `transient-mark-mode', demote all headings
6570 in the region."
6571 (org-back-to-heading t)
6572 (let* ((level (save-match-data (funcall outline-level)))
6573 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6574 (diff (abs (- level (length down-head) -1))))
6575 (replace-match down-head nil t)
6576 ;; Fixup tag positioning
6577 (and org-auto-align-tags (org-set-tags nil t))
6578 (if org-adapt-indentation (org-fixup-indentation diff))))
6580 (defun org-map-tree (fun)
6581 "Call FUN for every heading underneath the current one."
6582 (org-back-to-heading)
6583 (let ((level (funcall outline-level)))
6584 (save-excursion
6585 (funcall fun)
6586 (while (and (progn
6587 (outline-next-heading)
6588 (> (funcall outline-level) level))
6589 (not (eobp)))
6590 (funcall fun)))))
6592 (defun org-map-region (fun beg end)
6593 "Call FUN for every heading between BEG and END."
6594 (let ((org-ignore-region t))
6595 (save-excursion
6596 (setq end (copy-marker end))
6597 (goto-char beg)
6598 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6599 (< (point) end))
6600 (funcall fun))
6601 (while (and (progn
6602 (outline-next-heading)
6603 (< (point) end))
6604 (not (eobp)))
6605 (funcall fun)))))
6607 (defun org-fixup-indentation (diff)
6608 "Change the indentation in the current entry by DIFF
6609 However, if any line in the current entry has no indentation, or if it
6610 would end up with no indentation after the change, nothing at all is done."
6611 (save-excursion
6612 (let ((end (save-excursion (outline-next-heading)
6613 (point-marker)))
6614 (prohibit (if (> diff 0)
6615 "^\\S-"
6616 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6617 col)
6618 (unless (save-excursion (end-of-line 1)
6619 (re-search-forward prohibit end t))
6620 (while (and (< (point) end)
6621 (re-search-forward "^[ \t]+" end t))
6622 (goto-char (match-end 0))
6623 (setq col (current-column))
6624 (if (< diff 0) (replace-match ""))
6625 (indent-to (+ diff col))))
6626 (move-marker end nil))))
6628 (defun org-convert-to-odd-levels ()
6629 "Convert an org-mode file with all levels allowed to one with odd levels.
6630 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6631 level 5 etc."
6632 (interactive)
6633 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6634 (let ((org-odd-levels-only nil) n)
6635 (save-excursion
6636 (goto-char (point-min))
6637 (while (re-search-forward "^\\*\\*+ " nil t)
6638 (setq n (- (length (match-string 0)) 2))
6639 (while (>= (setq n (1- n)) 0)
6640 (org-demote))
6641 (end-of-line 1))))))
6644 (defun org-convert-to-oddeven-levels ()
6645 "Convert an org-mode file with only odd levels to one with odd and even levels.
6646 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6647 section with an even level, conversion would destroy the structure of the file. An error
6648 is signaled in this case."
6649 (interactive)
6650 (goto-char (point-min))
6651 ;; First check if there are no even levels
6652 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6653 (org-show-context t)
6654 (error "Not all levels are odd in this file. Conversion not possible."))
6655 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6656 (let ((org-odd-levels-only nil) n)
6657 (save-excursion
6658 (goto-char (point-min))
6659 (while (re-search-forward "^\\*\\*+ " nil t)
6660 (setq n (/ (1- (length (match-string 0))) 2))
6661 (while (>= (setq n (1- n)) 0)
6662 (org-promote))
6663 (end-of-line 1))))))
6665 (defun org-tr-level (n)
6666 "Make N odd if required."
6667 (if org-odd-levels-only (1+ (/ n 2)) n))
6669 ;;; Vertical tree motion, cutting and pasting of subtrees
6671 (defun org-move-subtree-up (&optional arg)
6672 "Move the current subtree up past ARG headlines of the same level."
6673 (interactive "p")
6674 (org-move-subtree-down (- (prefix-numeric-value arg))))
6676 (defun org-move-subtree-down (&optional arg)
6677 "Move the current subtree down past ARG headlines of the same level."
6678 (interactive "p")
6679 (setq arg (prefix-numeric-value arg))
6680 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6681 'outline-get-last-sibling))
6682 (ins-point (make-marker))
6683 (cnt (abs arg))
6684 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6685 ;; Select the tree
6686 (org-back-to-heading)
6687 (setq beg0 (point))
6688 (save-excursion
6689 (setq ne-beg (org-back-over-empty-lines))
6690 (setq beg (point)))
6691 (save-match-data
6692 (save-excursion (outline-end-of-heading)
6693 (setq folded (org-invisible-p)))
6694 (outline-end-of-subtree))
6695 (outline-next-heading)
6696 (setq ne-end (org-back-over-empty-lines))
6697 (setq end (point))
6698 (goto-char beg0)
6699 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6700 ;; include less whitespace
6701 (save-excursion
6702 (goto-char beg)
6703 (forward-line (- ne-beg ne-end))
6704 (setq beg (point))))
6705 ;; Find insertion point, with error handling
6706 (while (> cnt 0)
6707 (or (and (funcall movfunc) (looking-at outline-regexp))
6708 (progn (goto-char beg0)
6709 (error "Cannot move past superior level or buffer limit")))
6710 (setq cnt (1- cnt)))
6711 (if (> arg 0)
6712 ;; Moving forward - still need to move over subtree
6713 (progn (org-end-of-subtree t t)
6714 (save-excursion
6715 (org-back-over-empty-lines)
6716 (or (bolp) (newline)))))
6717 (setq ne-ins (org-back-over-empty-lines))
6718 (move-marker ins-point (point))
6719 (setq txt (buffer-substring beg end))
6720 (delete-region beg end)
6721 (outline-flag-region (1- beg) beg nil)
6722 (outline-flag-region (1- (point)) (point) nil)
6723 (insert txt)
6724 (or (bolp) (insert "\n"))
6725 (setq ins-end (point))
6726 (goto-char ins-point)
6727 (org-skip-whitespace)
6728 (when (and (< arg 0)
6729 (org-first-sibling-p)
6730 (> ne-ins ne-beg))
6731 ;; Move whitespace back to beginning
6732 (save-excursion
6733 (goto-char ins-end)
6734 (let ((kill-whole-line t))
6735 (kill-line (- ne-ins ne-beg)) (point)))
6736 (insert (make-string (- ne-ins ne-beg) ?\n)))
6737 (move-marker ins-point nil)
6738 (org-compact-display-after-subtree-move)
6739 (unless folded
6740 (org-show-entry)
6741 (show-children)
6742 (org-cycle-hide-drawers 'children))))
6744 (defvar org-subtree-clip ""
6745 "Clipboard for cut and paste of subtrees.
6746 This is actually only a copy of the kill, because we use the normal kill
6747 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6749 (defvar org-subtree-clip-folded nil
6750 "Was the last copied subtree folded?
6751 This is used to fold the tree back after pasting.")
6753 (defun org-cut-subtree (&optional n)
6754 "Cut the current subtree into the clipboard.
6755 With prefix arg N, cut this many sequential subtrees.
6756 This is a short-hand for marking the subtree and then cutting it."
6757 (interactive "p")
6758 (org-copy-subtree n 'cut))
6760 (defun org-copy-subtree (&optional n cut)
6761 "Cut the current subtree into the clipboard.
6762 With prefix arg N, cut this many sequential subtrees.
6763 This is a short-hand for marking the subtree and then copying it.
6764 If CUT is non-nil, actually cut the subtree."
6765 (interactive "p")
6766 (let (beg end folded (beg0 (point)))
6767 (if (interactive-p)
6768 (org-back-to-heading nil) ; take what looks like a subtree
6769 (org-back-to-heading t)) ; take what is really there
6770 (org-back-over-empty-lines)
6771 (setq beg (point))
6772 (skip-chars-forward " \t\r\n")
6773 (save-match-data
6774 (save-excursion (outline-end-of-heading)
6775 (setq folded (org-invisible-p)))
6776 (condition-case nil
6777 (outline-forward-same-level (1- n))
6778 (error nil))
6779 (org-end-of-subtree t t))
6780 (org-back-over-empty-lines)
6781 (setq end (point))
6782 (goto-char beg0)
6783 (when (> end beg)
6784 (setq org-subtree-clip-folded folded)
6785 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6786 (setq org-subtree-clip (current-kill 0))
6787 (message "%s: Subtree(s) with %d characters"
6788 (if cut "Cut" "Copied")
6789 (length org-subtree-clip)))))
6791 (defun org-paste-subtree (&optional level tree)
6792 "Paste the clipboard as a subtree, with modification of headline level.
6793 The entire subtree is promoted or demoted in order to match a new headline
6794 level. By default, the new level is derived from the visible headings
6795 before and after the insertion point, and taken to be the inferior headline
6796 level of the two. So if the previous visible heading is level 3 and the
6797 next is level 4 (or vice versa), level 4 will be used for insertion.
6798 This makes sure that the subtree remains an independent subtree and does
6799 not swallow low level entries.
6801 You can also force a different level, either by using a numeric prefix
6802 argument, or by inserting the heading marker by hand. For example, if the
6803 cursor is after \"*****\", then the tree will be shifted to level 5.
6805 If you want to insert the tree as is, just use \\[yank].
6807 If optional TREE is given, use this text instead of the kill ring."
6808 (interactive "P")
6809 (unless (org-kill-is-subtree-p tree)
6810 (error "%s"
6811 (substitute-command-keys
6812 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6813 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6814 (^re (concat "^\\(" outline-regexp "\\)"))
6815 (re (concat "\\(" outline-regexp "\\)"))
6816 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6818 (old-level (if (string-match ^re txt)
6819 (- (match-end 0) (match-beginning 0) 1)
6820 -1))
6821 (force-level (cond (level (prefix-numeric-value level))
6822 ((string-match
6823 ^re_ (buffer-substring (point-at-bol) (point)))
6824 (- (match-end 1) (match-beginning 1)))
6825 (t nil)))
6826 (previous-level (save-excursion
6827 (condition-case nil
6828 (progn
6829 (outline-previous-visible-heading 1)
6830 (if (looking-at re)
6831 (- (match-end 0) (match-beginning 0) 1)
6833 (error 1))))
6834 (next-level (save-excursion
6835 (condition-case nil
6836 (progn
6837 (or (looking-at outline-regexp)
6838 (outline-next-visible-heading 1))
6839 (if (looking-at re)
6840 (- (match-end 0) (match-beginning 0) 1)
6842 (error 1))))
6843 (new-level (or force-level (max previous-level next-level)))
6844 (shift (if (or (= old-level -1)
6845 (= new-level -1)
6846 (= old-level new-level))
6848 (- new-level old-level)))
6849 (delta (if (> shift 0) -1 1))
6850 (func (if (> shift 0) 'org-demote 'org-promote))
6851 (org-odd-levels-only nil)
6852 beg end)
6853 ;; Remove the forced level indicator
6854 (if force-level
6855 (delete-region (point-at-bol) (point)))
6856 ;; Paste
6857 (beginning-of-line 1)
6858 (org-back-over-empty-lines) ;; FIXME: correct fix????
6859 (setq beg (point))
6860 (insert-before-markers txt) ;; FIXME: correct fix????
6861 (unless (string-match "\n\\'" txt) (insert "\n"))
6862 (setq end (point))
6863 (goto-char beg)
6864 (skip-chars-forward " \t\n\r")
6865 (setq beg (point))
6866 ;; Shift if necessary
6867 (unless (= shift 0)
6868 (save-restriction
6869 (narrow-to-region beg end)
6870 (while (not (= shift 0))
6871 (org-map-region func (point-min) (point-max))
6872 (setq shift (+ delta shift)))
6873 (goto-char (point-min))))
6874 (when (interactive-p)
6875 (message "Clipboard pasted as level %d subtree" new-level))
6876 (if (and kill-ring
6877 (eq org-subtree-clip (current-kill 0))
6878 org-subtree-clip-folded)
6879 ;; The tree was folded before it was killed/copied
6880 (hide-subtree))))
6882 (defun org-kill-is-subtree-p (&optional txt)
6883 "Check if the current kill is an outline subtree, or a set of trees.
6884 Returns nil if kill does not start with a headline, or if the first
6885 headline level is not the largest headline level in the tree.
6886 So this will actually accept several entries of equal levels as well,
6887 which is OK for `org-paste-subtree'.
6888 If optional TXT is given, check this string instead of the current kill."
6889 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6890 (start-level (and kill
6891 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6892 org-outline-regexp "\\)")
6893 kill)
6894 (- (match-end 2) (match-beginning 2) 1)))
6895 (re (concat "^" org-outline-regexp))
6896 (start (1+ (match-beginning 2))))
6897 (if (not start-level)
6898 (progn
6899 nil) ;; does not even start with a heading
6900 (catch 'exit
6901 (while (setq start (string-match re kill (1+ start)))
6902 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6903 (throw 'exit nil)))
6904 t))))
6906 (defun org-narrow-to-subtree ()
6907 "Narrow buffer to the current subtree."
6908 (interactive)
6909 (save-excursion
6910 (save-match-data
6911 (narrow-to-region
6912 (progn (org-back-to-heading) (point))
6913 (progn (org-end-of-subtree t t) (point))))))
6916 ;;; Outline Sorting
6918 (defun org-sort (with-case)
6919 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6920 Optional argument WITH-CASE means sort case-sensitively."
6921 (interactive "P")
6922 (if (org-at-table-p)
6923 (org-call-with-arg 'org-table-sort-lines with-case)
6924 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6926 (defvar org-priority-regexp) ; defined later in the file
6928 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6929 "Sort entries on a certain level of an outline tree.
6930 If there is an active region, the entries in the region are sorted.
6931 Else, if the cursor is before the first entry, sort the top-level items.
6932 Else, the children of the entry at point are sorted.
6934 Sorting can be alphabetically, numerically, and by date/time as given by
6935 the first time stamp in the entry. The command prompts for the sorting
6936 type unless it has been given to the function through the SORTING-TYPE
6937 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6938 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6939 called with point at the beginning of the record. It must return either
6940 a string or a number that should serve as the sorting key for that record.
6942 Comparing entries ignores case by default. However, with an optional argument
6943 WITH-CASE, the sorting considers case as well."
6944 (interactive "P")
6945 (let ((case-func (if with-case 'identity 'downcase))
6946 start beg end stars re re2
6947 txt what tmp plain-list-p)
6948 ;; Find beginning and end of region to sort
6949 (cond
6950 ((org-region-active-p)
6951 ;; we will sort the region
6952 (setq end (region-end)
6953 what "region")
6954 (goto-char (region-beginning))
6955 (if (not (org-on-heading-p)) (outline-next-heading))
6956 (setq start (point)))
6957 ((org-at-item-p)
6958 ;; we will sort this plain list
6959 (org-beginning-of-item-list) (setq start (point))
6960 (org-end-of-item-list) (setq end (point))
6961 (goto-char start)
6962 (setq plain-list-p t
6963 what "plain list"))
6964 ((or (org-on-heading-p)
6965 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6966 ;; we will sort the children of the current headline
6967 (org-back-to-heading)
6968 (setq start (point)
6969 end (progn (org-end-of-subtree t t)
6970 (org-back-over-empty-lines)
6971 (point))
6972 what "children")
6973 (goto-char start)
6974 (show-subtree)
6975 (outline-next-heading))
6977 ;; we will sort the top-level entries in this file
6978 (goto-char (point-min))
6979 (or (org-on-heading-p) (outline-next-heading))
6980 (setq start (point) end (point-max) what "top-level")
6981 (goto-char start)
6982 (show-all)))
6984 (setq beg (point))
6985 (if (>= beg end) (error "Nothing to sort"))
6987 (unless plain-list-p
6988 (looking-at "\\(\\*+\\)")
6989 (setq stars (match-string 1)
6990 re (concat "^" (regexp-quote stars) " +")
6991 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6992 txt (buffer-substring beg end))
6993 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6994 (if (and (not (equal stars "*")) (string-match re2 txt))
6995 (error "Region to sort contains a level above the first entry")))
6997 (unless sorting-type
6998 (message
6999 (if plain-list-p
7000 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7001 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
7002 what)
7003 (setq sorting-type (read-char-exclusive))
7005 (and (= (downcase sorting-type) ?f)
7006 (setq getkey-func
7007 (completing-read "Sort using function: "
7008 obarray 'fboundp t nil nil))
7009 (setq getkey-func (intern getkey-func)))
7011 (and (= (downcase sorting-type) ?r)
7012 (setq property
7013 (completing-read "Property: "
7014 (mapcar 'list (org-buffer-property-keys t))
7015 nil t))))
7017 (message "Sorting entries...")
7019 (save-restriction
7020 (narrow-to-region start end)
7022 (let ((dcst (downcase sorting-type))
7023 (now (current-time)))
7024 (sort-subr
7025 (/= dcst sorting-type)
7026 ;; This function moves to the beginning character of the "record" to
7027 ;; be sorted.
7028 (if plain-list-p
7029 (lambda nil
7030 (if (org-at-item-p) t (goto-char (point-max))))
7031 (lambda nil
7032 (if (re-search-forward re nil t)
7033 (goto-char (match-beginning 0))
7034 (goto-char (point-max)))))
7035 ;; This function moves to the last character of the "record" being
7036 ;; sorted.
7037 (if plain-list-p
7038 'org-end-of-item
7039 (lambda nil
7040 (save-match-data
7041 (condition-case nil
7042 (outline-forward-same-level 1)
7043 (error
7044 (goto-char (point-max)))))))
7046 ;; This function returns the value that gets sorted against.
7047 (if plain-list-p
7048 (lambda nil
7049 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7050 (cond
7051 ((= dcst ?n)
7052 (string-to-number (buffer-substring (match-end 0)
7053 (point-at-eol))))
7054 ((= dcst ?a)
7055 (buffer-substring (match-end 0) (point-at-eol)))
7056 ((= dcst ?t)
7057 (if (re-search-forward org-ts-regexp
7058 (point-at-eol) t)
7059 (org-time-string-to-time (match-string 0))
7060 now))
7061 ((= dcst ?f)
7062 (if getkey-func
7063 (progn
7064 (setq tmp (funcall getkey-func))
7065 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7066 tmp)
7067 (error "Invalid key function `%s'" getkey-func)))
7068 (t (error "Invalid sorting type `%c'" sorting-type)))))
7069 (lambda nil
7070 (cond
7071 ((= dcst ?n)
7072 (if (looking-at outline-regexp)
7073 (string-to-number (buffer-substring (match-end 0)
7074 (point-at-eol)))
7075 nil))
7076 ((= dcst ?a)
7077 (funcall case-func (buffer-substring (point-at-bol)
7078 (point-at-eol))))
7079 ((= dcst ?t)
7080 (if (re-search-forward org-ts-regexp
7081 (save-excursion
7082 (forward-line 2)
7083 (point)) t)
7084 (org-time-string-to-time (match-string 0))
7085 now))
7086 ((= dcst ?p)
7087 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7088 (string-to-char (match-string 2))
7089 org-default-priority))
7090 ((= dcst ?r)
7091 (or (org-entry-get nil property) ""))
7092 ((= dcst ?f)
7093 (if getkey-func
7094 (progn
7095 (setq tmp (funcall getkey-func))
7096 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7097 tmp)
7098 (error "Invalid key function `%s'" getkey-func)))
7099 (t (error "Invalid sorting type `%c'" sorting-type)))))
7101 (cond
7102 ((= dcst ?a) 'string<)
7103 ((= dcst ?t) 'time-less-p)
7104 (t nil)))))
7105 (message "Sorting entries...done")))
7107 (defun org-do-sort (table what &optional with-case sorting-type)
7108 "Sort TABLE of WHAT according to SORTING-TYPE.
7109 The user will be prompted for the SORTING-TYPE if the call to this
7110 function does not specify it. WHAT is only for the prompt, to indicate
7111 what is being sorted. The sorting key will be extracted from
7112 the car of the elements of the table.
7113 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7114 (unless sorting-type
7115 (message
7116 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7117 what)
7118 (setq sorting-type (read-char-exclusive)))
7119 (let ((dcst (downcase sorting-type))
7120 extractfun comparefun)
7121 ;; Define the appropriate functions
7122 (cond
7123 ((= dcst ?n)
7124 (setq extractfun 'string-to-number
7125 comparefun (if (= dcst sorting-type) '< '>)))
7126 ((= dcst ?a)
7127 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7128 (lambda(x) (downcase (org-sort-remove-invisible x))))
7129 comparefun (if (= dcst sorting-type)
7130 'string<
7131 (lambda (a b) (and (not (string< a b))
7132 (not (string= a b)))))))
7133 ((= dcst ?t)
7134 (setq extractfun
7135 (lambda (x)
7136 (if (string-match org-ts-regexp x)
7137 (time-to-seconds
7138 (org-time-string-to-time (match-string 0 x)))
7140 comparefun (if (= dcst sorting-type) '< '>)))
7141 (t (error "Invalid sorting type `%c'" sorting-type)))
7143 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7144 table)
7145 (lambda (a b) (funcall comparefun (car a) (car b))))))
7147 ;;;; Plain list items, including checkboxes
7149 ;;; Plain list items
7151 (defun org-at-item-p ()
7152 "Is point in a line starting a hand-formatted item?"
7153 (let ((llt org-plain-list-ordered-item-terminator))
7154 (save-excursion
7155 (goto-char (point-at-bol))
7156 (looking-at
7157 (cond
7158 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7159 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7160 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7161 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
7163 (defun org-in-item-p ()
7164 "It the cursor inside a plain list item.
7165 Does not have to be the first line."
7166 (save-excursion
7167 (condition-case nil
7168 (progn
7169 (org-beginning-of-item)
7170 (org-at-item-p)
7172 (error nil))))
7174 (defun org-insert-item (&optional checkbox)
7175 "Insert a new item at the current level.
7176 Return t when things worked, nil when we are not in an item."
7177 (when (save-excursion
7178 (condition-case nil
7179 (progn
7180 (org-beginning-of-item)
7181 (org-at-item-p)
7182 (if (org-invisible-p) (error "Invisible item"))
7184 (error nil)))
7185 (let* ((bul (match-string 0))
7186 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
7187 (match-end 0)))
7188 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
7189 pos)
7190 (cond
7191 ((and (org-at-item-p) (<= (point) eow))
7192 ;; before the bullet
7193 (beginning-of-line 1)
7194 (open-line (if blank 2 1)))
7195 ((<= (point) eow)
7196 (beginning-of-line 1))
7198 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
7199 (end-of-line 1)
7200 (delete-horizontal-space))
7201 (newline (if blank 2 1))))
7202 (insert bul (if checkbox "[ ]" ""))
7203 (just-one-space)
7204 (setq pos (point))
7205 (end-of-line 1)
7206 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
7207 (org-maybe-renumber-ordered-list)
7208 (and checkbox (org-update-checkbox-count-maybe))
7211 ;;; Checkboxes
7213 (defun org-at-item-checkbox-p ()
7214 "Is point at a line starting a plain-list item with a checklet?"
7215 (and (org-at-item-p)
7216 (save-excursion
7217 (goto-char (match-end 0))
7218 (skip-chars-forward " \t")
7219 (looking-at "\\[[- X]\\]"))))
7221 (defun org-toggle-checkbox (&optional arg)
7222 "Toggle the checkbox in the current line."
7223 (interactive "P")
7224 (catch 'exit
7225 (let (beg end status (firstnew 'unknown))
7226 (cond
7227 ((org-region-active-p)
7228 (setq beg (region-beginning) end (region-end)))
7229 ((org-on-heading-p)
7230 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
7231 ((org-at-item-checkbox-p)
7232 (let ((pos (point)))
7233 (replace-match
7234 (cond (arg "[-]")
7235 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
7236 (t "[ ]"))
7237 t t)
7238 (goto-char pos))
7239 (throw 'exit t))
7240 (t (error "Not at a checkbox or heading, and no active region")))
7241 (save-excursion
7242 (goto-char beg)
7243 (while (< (point) end)
7244 (when (org-at-item-checkbox-p)
7245 (setq status (equal (match-string 0) "[X]"))
7246 (when (eq firstnew 'unknown)
7247 (setq firstnew (not status)))
7248 (replace-match
7249 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
7250 (beginning-of-line 2)))))
7251 (org-update-checkbox-count-maybe))
7253 (defun org-update-checkbox-count-maybe ()
7254 "Update checkbox statistics unless turned off by user."
7255 (when org-provide-checkbox-statistics
7256 (org-update-checkbox-count)))
7258 (defun org-update-checkbox-count (&optional all)
7259 "Update the checkbox statistics in the current section.
7260 This will find all statistic cookies like [57%] and [6/12] and update them
7261 with the current numbers. With optional prefix argument ALL, do this for
7262 the whole buffer."
7263 (interactive "P")
7264 (save-excursion
7265 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7266 (beg (condition-case nil
7267 (progn (outline-back-to-heading) (point))
7268 (error (point-min))))
7269 (end (move-marker (make-marker)
7270 (progn (outline-next-heading) (point))))
7271 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7272 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7273 (re-find (concat re "\\|" re-box))
7274 beg-cookie end-cookie is-percent c-on c-off lim
7275 eline curr-ind next-ind continue-from startsearch
7276 (cstat 0)
7278 (when all
7279 (goto-char (point-min))
7280 (outline-next-heading)
7281 (setq beg (point) end (point-max)))
7282 (goto-char end)
7283 ;; find each statistic cookie
7284 (while (re-search-backward re-find beg t)
7285 (setq beg-cookie (match-beginning 1)
7286 end-cookie (match-end 1)
7287 cstat (+ cstat (if end-cookie 1 0))
7288 startsearch (point-at-eol)
7289 continue-from (point-at-bol)
7290 is-percent (match-beginning 2)
7291 lim (cond
7292 ((org-on-heading-p) (outline-next-heading) (point))
7293 ((org-at-item-p) (org-end-of-item) (point))
7294 (t nil))
7295 c-on 0
7296 c-off 0)
7297 (when lim
7298 ;; find first checkbox for this cookie and gather
7299 ;; statistics from all that are at this indentation level
7300 (goto-char startsearch)
7301 (if (re-search-forward re-box lim t)
7302 (progn
7303 (org-beginning-of-item)
7304 (setq curr-ind (org-get-indentation))
7305 (setq next-ind curr-ind)
7306 (while (= curr-ind next-ind)
7307 (save-excursion (end-of-line) (setq eline (point)))
7308 (if (re-search-forward re-box eline t)
7309 (if (member (match-string 2) '("[ ]" "[-]"))
7310 (setq c-off (1+ c-off))
7311 (setq c-on (1+ c-on))
7314 (org-end-of-item)
7315 (setq next-ind (org-get-indentation))
7317 (goto-char continue-from)
7318 ;; update cookie
7319 (when end-cookie
7320 (delete-region beg-cookie end-cookie)
7321 (goto-char beg-cookie)
7322 (insert
7323 (if is-percent
7324 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7325 (format "[%d/%d]" c-on (+ c-on c-off)))))
7326 ;; update items checkbox if it has one
7327 (when (org-at-item-p)
7328 (org-beginning-of-item)
7329 (when (and (> (+ c-on c-off) 0)
7330 (re-search-forward re-box (point-at-eol) t))
7331 (setq beg-cookie (match-beginning 2)
7332 end-cookie (match-end 2))
7333 (delete-region beg-cookie end-cookie)
7334 (goto-char beg-cookie)
7335 (cond ((= c-off 0) (insert "[X]"))
7336 ((= c-on 0) (insert "[ ]"))
7337 (t (insert "[-]")))
7339 (goto-char continue-from))
7340 (when (interactive-p)
7341 (message "Checkbox satistics updated %s (%d places)"
7342 (if all "in entire file" "in current outline entry") cstat)))))
7344 (defun org-get-checkbox-statistics-face ()
7345 "Select the face for checkbox statistics.
7346 The face will be `org-done' when all relevant boxes are checked. Otherwise
7347 it will be `org-todo'."
7348 (if (match-end 1)
7349 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7350 (if (and (> (match-end 2) (match-beginning 2))
7351 (equal (match-string 2) (match-string 3)))
7352 'org-done
7353 'org-todo)))
7355 (defun org-get-indentation (&optional line)
7356 "Get the indentation of the current line, interpreting tabs.
7357 When LINE is given, assume it represents a line and compute its indentation."
7358 (if line
7359 (if (string-match "^ *" (org-remove-tabs line))
7360 (match-end 0))
7361 (save-excursion
7362 (beginning-of-line 1)
7363 (skip-chars-forward " \t")
7364 (current-column))))
7366 (defun org-remove-tabs (s &optional width)
7367 "Replace tabulators in S with spaces.
7368 Assumes that s is a single line, starting in column 0."
7369 (setq width (or width tab-width))
7370 (while (string-match "\t" s)
7371 (setq s (replace-match
7372 (make-string
7373 (- (* width (/ (+ (match-beginning 0) width) width))
7374 (match-beginning 0)) ?\ )
7375 t t s)))
7378 (defun org-fix-indentation (line ind)
7379 "Fix indentation in LINE.
7380 IND is a cons cell with target and minimum indentation.
7381 If the current indenation in LINE is smaller than the minimum,
7382 leave it alone. If it is larger than ind, set it to the target."
7383 (let* ((l (org-remove-tabs line))
7384 (i (org-get-indentation l))
7385 (i1 (car ind)) (i2 (cdr ind)))
7386 (if (>= i i2) (setq l (substring line i2)))
7387 (if (> i1 0)
7388 (concat (make-string i1 ?\ ) l)
7389 l)))
7391 (defcustom org-empty-line-terminates-plain-lists nil
7392 "Non-nil means, an empty line ends all plain list levels.
7393 When nil, empty lines are part of the preceeding item."
7394 :group 'org-plain-lists
7395 :type 'boolean)
7397 (defun org-beginning-of-item ()
7398 "Go to the beginning of the current hand-formatted item.
7399 If the cursor is not in an item, throw an error."
7400 (interactive)
7401 (let ((pos (point))
7402 (limit (save-excursion
7403 (condition-case nil
7404 (progn
7405 (org-back-to-heading)
7406 (beginning-of-line 2) (point))
7407 (error (point-min)))))
7408 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7409 ind ind1)
7410 (if (org-at-item-p)
7411 (beginning-of-line 1)
7412 (beginning-of-line 1)
7413 (skip-chars-forward " \t")
7414 (setq ind (current-column))
7415 (if (catch 'exit
7416 (while t
7417 (beginning-of-line 0)
7418 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7420 (if (looking-at "[ \t]*$")
7421 (setq ind1 ind-empty)
7422 (skip-chars-forward " \t")
7423 (setq ind1 (current-column)))
7424 (if (< ind1 ind)
7425 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7427 (goto-char pos)
7428 (error "Not in an item")))))
7430 (defun org-end-of-item ()
7431 "Go to the end of the current hand-formatted item.
7432 If the cursor is not in an item, throw an error."
7433 (interactive)
7434 (let* ((pos (point))
7435 ind1
7436 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7437 (limit (save-excursion (outline-next-heading) (point)))
7438 (ind (save-excursion
7439 (org-beginning-of-item)
7440 (skip-chars-forward " \t")
7441 (current-column)))
7442 (end (catch 'exit
7443 (while t
7444 (beginning-of-line 2)
7445 (if (eobp) (throw 'exit (point)))
7446 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7447 (if (looking-at "[ \t]*$")
7448 (setq ind1 ind-empty)
7449 (skip-chars-forward " \t")
7450 (setq ind1 (current-column)))
7451 (if (<= ind1 ind)
7452 (throw 'exit (point-at-bol)))))))
7453 (if end
7454 (goto-char end)
7455 (goto-char pos)
7456 (error "Not in an item"))))
7458 (defun org-next-item ()
7459 "Move to the beginning of the next item in the current plain list.
7460 Error if not at a plain list, or if this is the last item in the list."
7461 (interactive)
7462 (let (ind ind1 (pos (point)))
7463 (org-beginning-of-item)
7464 (setq ind (org-get-indentation))
7465 (org-end-of-item)
7466 (setq ind1 (org-get-indentation))
7467 (unless (and (org-at-item-p) (= ind ind1))
7468 (goto-char pos)
7469 (error "On last item"))))
7471 (defun org-previous-item ()
7472 "Move to the beginning of the previous item in the current plain list.
7473 Error if not at a plain list, or if this is the first item in the list."
7474 (interactive)
7475 (let (beg ind ind1 (pos (point)))
7476 (org-beginning-of-item)
7477 (setq beg (point))
7478 (setq ind (org-get-indentation))
7479 (goto-char beg)
7480 (catch 'exit
7481 (while t
7482 (beginning-of-line 0)
7483 (if (looking-at "[ \t]*$")
7485 (if (<= (setq ind1 (org-get-indentation)) ind)
7486 (throw 'exit t)))))
7487 (condition-case nil
7488 (if (or (not (org-at-item-p))
7489 (< ind1 (1- ind)))
7490 (error "")
7491 (org-beginning-of-item))
7492 (error (goto-char pos)
7493 (error "On first item")))))
7495 (defun org-first-list-item-p ()
7496 "Is this heading the item in a plain list?"
7497 (unless (org-at-item-p)
7498 (error "Not at a plain list item"))
7499 (org-beginning-of-item)
7500 (= (point) (save-excursion (org-beginning-of-item-list))))
7502 (defun org-move-item-down ()
7503 "Move the plain list item at point down, i.e. swap with following item.
7504 Subitems (items with larger indentation) are considered part of the item,
7505 so this really moves item trees."
7506 (interactive)
7507 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7508 (org-beginning-of-item)
7509 (setq beg0 (point))
7510 (save-excursion
7511 (setq ne-beg (org-back-over-empty-lines))
7512 (setq beg (point)))
7513 (goto-char beg0)
7514 (setq ind (org-get-indentation))
7515 (org-end-of-item)
7516 (setq end0 (point))
7517 (setq ind1 (org-get-indentation))
7518 (setq ne-end (org-back-over-empty-lines))
7519 (setq end (point))
7520 (goto-char beg0)
7521 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7522 ;; include less whitespace
7523 (save-excursion
7524 (goto-char beg)
7525 (forward-line (- ne-beg ne-end))
7526 (setq beg (point))))
7527 (goto-char end0)
7528 (if (and (org-at-item-p) (= ind ind1))
7529 (progn
7530 (org-end-of-item)
7531 (org-back-over-empty-lines)
7532 (setq txt (buffer-substring beg end))
7533 (save-excursion
7534 (delete-region beg end))
7535 (setq pos (point))
7536 (insert txt)
7537 (goto-char pos) (org-skip-whitespace)
7538 (org-maybe-renumber-ordered-list))
7539 (goto-char pos)
7540 (error "Cannot move this item further down"))))
7542 (defun org-move-item-up (arg)
7543 "Move the plain list item at point up, i.e. swap with previous item.
7544 Subitems (items with larger indentation) are considered part of the item,
7545 so this really moves item trees."
7546 (interactive "p")
7547 (let (beg beg0 end ind ind1 (pos (point)) txt
7548 ne-beg ne-ins ins-end)
7549 (org-beginning-of-item)
7550 (setq beg0 (point))
7551 (setq ind (org-get-indentation))
7552 (save-excursion
7553 (setq ne-beg (org-back-over-empty-lines))
7554 (setq beg (point)))
7555 (goto-char beg0)
7556 (org-end-of-item)
7557 (setq end (point))
7558 (goto-char beg0)
7559 (catch 'exit
7560 (while t
7561 (beginning-of-line 0)
7562 (if (looking-at "[ \t]*$")
7563 (if org-empty-line-terminates-plain-lists
7564 (progn
7565 (goto-char pos)
7566 (error "Cannot move this item further up"))
7567 nil)
7568 (if (<= (setq ind1 (org-get-indentation)) ind)
7569 (throw 'exit t)))))
7570 (condition-case nil
7571 (org-beginning-of-item)
7572 (error (goto-char beg)
7573 (error "Cannot move this item further up")))
7574 (setq ind1 (org-get-indentation))
7575 (if (and (org-at-item-p) (= ind ind1))
7576 (progn
7577 (setq ne-ins (org-back-over-empty-lines))
7578 (setq txt (buffer-substring beg end))
7579 (save-excursion
7580 (delete-region beg end))
7581 (setq pos (point))
7582 (insert txt)
7583 (setq ins-end (point))
7584 (goto-char pos) (org-skip-whitespace)
7586 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7587 ;; Move whitespace back to beginning
7588 (save-excursion
7589 (goto-char ins-end)
7590 (let ((kill-whole-line t))
7591 (kill-line (- ne-ins ne-beg)) (point)))
7592 (insert (make-string (- ne-ins ne-beg) ?\n)))
7594 (org-maybe-renumber-ordered-list))
7595 (goto-char pos)
7596 (error "Cannot move this item further up"))))
7598 (defun org-maybe-renumber-ordered-list ()
7599 "Renumber the ordered list at point if setup allows it.
7600 This tests the user option `org-auto-renumber-ordered-lists' before
7601 doing the renumbering."
7602 (interactive)
7603 (when (and org-auto-renumber-ordered-lists
7604 (org-at-item-p))
7605 (if (match-beginning 3)
7606 (org-renumber-ordered-list 1)
7607 (org-fix-bullet-type))))
7609 (defun org-maybe-renumber-ordered-list-safe ()
7610 (condition-case nil
7611 (save-excursion
7612 (org-maybe-renumber-ordered-list))
7613 (error nil)))
7615 (defun org-cycle-list-bullet (&optional which)
7616 "Cycle through the different itemize/enumerate bullets.
7617 This cycle the entire list level through the sequence:
7619 `-' -> `+' -> `*' -> `1.' -> `1)'
7621 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7622 0 meand `-', 1 means `+' etc."
7623 (interactive "P")
7624 (org-preserve-lc
7625 (org-beginning-of-item-list)
7626 (org-at-item-p)
7627 (beginning-of-line 1)
7628 (let ((current (match-string 0))
7629 (prevp (eq which 'previous))
7630 new)
7631 (setq new (cond
7632 ((and (numberp which)
7633 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7634 ((string-match "-" current) (if prevp "1)" "+"))
7635 ((string-match "\\+" current)
7636 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7637 ((string-match "\\*" current) (if prevp "+" "1."))
7638 ((string-match "\\." current) (if prevp "*" "1)"))
7639 ((string-match ")" current) (if prevp "1." "-"))
7640 (t (error "This should not happen"))))
7641 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7642 (org-fix-bullet-type)
7643 (org-maybe-renumber-ordered-list))))
7645 (defun org-get-string-indentation (s)
7646 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7647 (let ((n -1) (i 0) (w tab-width) c)
7648 (catch 'exit
7649 (while (< (setq n (1+ n)) (length s))
7650 (setq c (aref s n))
7651 (cond ((= c ?\ ) (setq i (1+ i)))
7652 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7653 (t (throw 'exit t)))))
7656 (defun org-renumber-ordered-list (arg)
7657 "Renumber an ordered plain list.
7658 Cursor needs to be in the first line of an item, the line that starts
7659 with something like \"1.\" or \"2)\"."
7660 (interactive "p")
7661 (unless (and (org-at-item-p)
7662 (match-beginning 3))
7663 (error "This is not an ordered list"))
7664 (let ((line (org-current-line))
7665 (col (current-column))
7666 (ind (org-get-string-indentation
7667 (buffer-substring (point-at-bol) (match-beginning 3))))
7668 ;; (term (substring (match-string 3) -1))
7669 ind1 (n (1- arg))
7670 fmt)
7671 ;; find where this list begins
7672 (org-beginning-of-item-list)
7673 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7674 (setq fmt (concat "%d" (match-string 1)))
7675 (beginning-of-line 0)
7676 ;; walk forward and replace these numbers
7677 (catch 'exit
7678 (while t
7679 (catch 'next
7680 (beginning-of-line 2)
7681 (if (eobp) (throw 'exit nil))
7682 (if (looking-at "[ \t]*$") (throw 'next nil))
7683 (skip-chars-forward " \t") (setq ind1 (current-column))
7684 (if (> ind1 ind) (throw 'next t))
7685 (if (< ind1 ind) (throw 'exit t))
7686 (if (not (org-at-item-p)) (throw 'exit nil))
7687 (delete-region (match-beginning 2) (match-end 2))
7688 (goto-char (match-beginning 2))
7689 (insert (format fmt (setq n (1+ n)))))))
7690 (goto-line line)
7691 (move-to-column col)))
7693 (defun org-fix-bullet-type ()
7694 "Make sure all items in this list have the same bullet as the firsst item."
7695 (interactive)
7696 (unless (org-at-item-p) (error "This is not a list"))
7697 (let ((line (org-current-line))
7698 (col (current-column))
7699 (ind (current-indentation))
7700 ind1 bullet)
7701 ;; find where this list begins
7702 (org-beginning-of-item-list)
7703 (beginning-of-line 1)
7704 ;; find out what the bullet type is
7705 (looking-at "[ \t]*\\(\\S-+\\)")
7706 (setq bullet (match-string 1))
7707 ;; walk forward and replace these numbers
7708 (beginning-of-line 0)
7709 (catch 'exit
7710 (while t
7711 (catch 'next
7712 (beginning-of-line 2)
7713 (if (eobp) (throw 'exit nil))
7714 (if (looking-at "[ \t]*$") (throw 'next nil))
7715 (skip-chars-forward " \t") (setq ind1 (current-column))
7716 (if (> ind1 ind) (throw 'next t))
7717 (if (< ind1 ind) (throw 'exit t))
7718 (if (not (org-at-item-p)) (throw 'exit nil))
7719 (skip-chars-forward " \t")
7720 (looking-at "\\S-+")
7721 (replace-match bullet))))
7722 (goto-line line)
7723 (move-to-column col)
7724 (if (string-match "[0-9]" bullet)
7725 (org-renumber-ordered-list 1))))
7727 (defun org-beginning-of-item-list ()
7728 "Go to the beginning of the current item list.
7729 I.e. to the first item in this list."
7730 (interactive)
7731 (org-beginning-of-item)
7732 (let ((pos (point-at-bol))
7733 (ind (org-get-indentation))
7734 ind1)
7735 ;; find where this list begins
7736 (catch 'exit
7737 (while t
7738 (catch 'next
7739 (beginning-of-line 0)
7740 (if (looking-at "[ \t]*$")
7741 (throw (if (bobp) 'exit 'next) t))
7742 (skip-chars-forward " \t") (setq ind1 (current-column))
7743 (if (or (< ind1 ind)
7744 (and (= ind1 ind)
7745 (not (org-at-item-p)))
7746 (bobp))
7747 (throw 'exit t)
7748 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7749 (goto-char pos)))
7752 (defun org-end-of-item-list ()
7753 "Go to the end of the current item list.
7754 I.e. to the text after the last item."
7755 (interactive)
7756 (org-beginning-of-item)
7757 (let ((pos (point-at-bol))
7758 (ind (org-get-indentation))
7759 ind1)
7760 ;; find where this list begins
7761 (catch 'exit
7762 (while t
7763 (catch 'next
7764 (beginning-of-line 2)
7765 (if (looking-at "[ \t]*$")
7766 (throw (if (eobp) 'exit 'next) t))
7767 (skip-chars-forward " \t") (setq ind1 (current-column))
7768 (if (or (< ind1 ind)
7769 (and (= ind1 ind)
7770 (not (org-at-item-p)))
7771 (eobp))
7772 (progn
7773 (setq pos (point-at-bol))
7774 (throw 'exit t))))))
7775 (goto-char pos)))
7778 (defvar org-last-indent-begin-marker (make-marker))
7779 (defvar org-last-indent-end-marker (make-marker))
7781 (defun org-outdent-item (arg)
7782 "Outdent a local list item."
7783 (interactive "p")
7784 (org-indent-item (- arg)))
7786 (defun org-indent-item (arg)
7787 "Indent a local list item."
7788 (interactive "p")
7789 (unless (org-at-item-p)
7790 (error "Not on an item"))
7791 (save-excursion
7792 (let (beg end ind ind1 tmp delta ind-down ind-up)
7793 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7794 (setq beg org-last-indent-begin-marker
7795 end org-last-indent-end-marker)
7796 (org-beginning-of-item)
7797 (setq beg (move-marker org-last-indent-begin-marker (point)))
7798 (org-end-of-item)
7799 (setq end (move-marker org-last-indent-end-marker (point))))
7800 (goto-char beg)
7801 (setq tmp (org-item-indent-positions)
7802 ind (car tmp)
7803 ind-down (nth 2 tmp)
7804 ind-up (nth 1 tmp)
7805 delta (if (> arg 0)
7806 (if ind-down (- ind-down ind) 2)
7807 (if ind-up (- ind-up ind) -2)))
7808 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7809 (while (< (point) end)
7810 (beginning-of-line 1)
7811 (skip-chars-forward " \t") (setq ind1 (current-column))
7812 (delete-region (point-at-bol) (point))
7813 (or (eolp) (indent-to-column (+ ind1 delta)))
7814 (beginning-of-line 2))))
7815 (org-fix-bullet-type)
7816 (org-maybe-renumber-ordered-list-safe)
7817 (save-excursion
7818 (beginning-of-line 0)
7819 (condition-case nil (org-beginning-of-item) (error nil))
7820 (org-maybe-renumber-ordered-list-safe)))
7822 (defun org-item-indent-positions ()
7823 "Return indentation for plain list items.
7824 This returns a list with three values: The current indentation, the
7825 parent indentation and the indentation a child should habe.
7826 Assumes cursor in item line."
7827 (let* ((bolpos (point-at-bol))
7828 (ind (org-get-indentation))
7829 ind-down ind-up pos)
7830 (save-excursion
7831 (org-beginning-of-item-list)
7832 (skip-chars-backward "\n\r \t")
7833 (when (org-in-item-p)
7834 (org-beginning-of-item)
7835 (setq ind-up (org-get-indentation))))
7836 (setq pos (point))
7837 (save-excursion
7838 (cond
7839 ((and (condition-case nil (progn (org-previous-item) t)
7840 (error nil))
7841 (or (forward-char 1) t)
7842 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7843 (setq ind-down (org-get-indentation)))
7844 ((and (goto-char pos)
7845 (org-at-item-p))
7846 (goto-char (match-end 0))
7847 (skip-chars-forward " \t")
7848 (setq ind-down (current-column)))))
7849 (list ind ind-up ind-down)))
7851 ;;; The orgstruct minor mode
7853 ;; Define a minor mode which can be used in other modes in order to
7854 ;; integrate the org-mode structure editing commands.
7856 ;; This is really a hack, because the org-mode structure commands use
7857 ;; keys which normally belong to the major mode. Here is how it
7858 ;; works: The minor mode defines all the keys necessary to operate the
7859 ;; structure commands, but wraps the commands into a function which
7860 ;; tests if the cursor is currently at a headline or a plain list
7861 ;; item. If that is the case, the structure command is used,
7862 ;; temporarily setting many Org-mode variables like regular
7863 ;; expressions for filling etc. However, when any of those keys is
7864 ;; used at a different location, function uses `key-binding' to look
7865 ;; up if the key has an associated command in another currently active
7866 ;; keymap (minor modes, major mode, global), and executes that
7867 ;; command. There might be problems if any of the keys is otherwise
7868 ;; used as a prefix key.
7870 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7871 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7872 ;; addresses this by checking explicitly for both bindings.
7874 (defvar orgstruct-mode-map (make-sparse-keymap)
7875 "Keymap for the minor `orgstruct-mode'.")
7877 (defvar org-local-vars nil
7878 "List of local variables, for use by `orgstruct-mode'")
7880 ;;;###autoload
7881 (define-minor-mode orgstruct-mode
7882 "Toggle the minor more `orgstruct-mode'.
7883 This mode is for using Org-mode structure commands in other modes.
7884 The following key behave as if Org-mode was active, if the cursor
7885 is on a headline, or on a plain list item (both in the definition
7886 of Org-mode).
7888 M-up Move entry/item up
7889 M-down Move entry/item down
7890 M-left Promote
7891 M-right Demote
7892 M-S-up Move entry/item up
7893 M-S-down Move entry/item down
7894 M-S-left Promote subtree
7895 M-S-right Demote subtree
7896 M-q Fill paragraph and items like in Org-mode
7897 C-c ^ Sort entries
7898 C-c - Cycle list bullet
7899 TAB Cycle item visibility
7900 M-RET Insert new heading/item
7901 S-M-RET Insert new TODO heading / Chekbox item
7902 C-c C-c Set tags / toggle checkbox"
7903 nil " OrgStruct" nil
7904 (org-load-modules-maybe)
7905 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7907 ;;;###autoload
7908 (defun turn-on-orgstruct ()
7909 "Unconditionally turn on `orgstruct-mode'."
7910 (orgstruct-mode 1))
7912 ;;;###autoload
7913 (defun turn-on-orgstruct++ ()
7914 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7915 In addition to setting orgstruct-mode, this also exports all indentation and
7916 autofilling variables from org-mode into the buffer. Note that turning
7917 off orgstruct-mode will *not* remove these additional settings."
7918 (orgstruct-mode 1)
7919 (let (var val)
7920 (mapc
7921 (lambda (x)
7922 (when (string-match
7923 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7924 (symbol-name (car x)))
7925 (setq var (car x) val (nth 1 x))
7926 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7927 org-local-vars)))
7929 (defun orgstruct-error ()
7930 "Error when there is no default binding for a structure key."
7931 (interactive)
7932 (error "This key has no function outside structure elements"))
7934 (defun orgstruct-setup ()
7935 "Setup orgstruct keymaps."
7936 (let ((nfunc 0)
7937 (bindings
7938 (list
7939 '([(meta up)] org-metaup)
7940 '([(meta down)] org-metadown)
7941 '([(meta left)] org-metaleft)
7942 '([(meta right)] org-metaright)
7943 '([(meta shift up)] org-shiftmetaup)
7944 '([(meta shift down)] org-shiftmetadown)
7945 '([(meta shift left)] org-shiftmetaleft)
7946 '([(meta shift right)] org-shiftmetaright)
7947 '([(shift up)] org-shiftup)
7948 '([(shift down)] org-shiftdown)
7949 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7950 '("\M-q" fill-paragraph)
7951 '("\C-c^" org-sort)
7952 '("\C-c-" org-cycle-list-bullet)))
7953 elt key fun cmd)
7954 (while (setq elt (pop bindings))
7955 (setq nfunc (1+ nfunc))
7956 (setq key (org-key (car elt))
7957 fun (nth 1 elt)
7958 cmd (orgstruct-make-binding fun nfunc key))
7959 (org-defkey orgstruct-mode-map key cmd))
7961 ;; Special treatment needed for TAB and RET
7962 (org-defkey orgstruct-mode-map [(tab)]
7963 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7964 (org-defkey orgstruct-mode-map "\C-i"
7965 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7967 (org-defkey orgstruct-mode-map "\M-\C-m"
7968 (orgstruct-make-binding 'org-insert-heading 105
7969 "\M-\C-m" [(meta return)]))
7970 (org-defkey orgstruct-mode-map [(meta return)]
7971 (orgstruct-make-binding 'org-insert-heading 106
7972 [(meta return)] "\M-\C-m"))
7974 (org-defkey orgstruct-mode-map [(shift meta return)]
7975 (orgstruct-make-binding 'org-insert-todo-heading 107
7976 [(meta return)] "\M-\C-m"))
7978 (unless org-local-vars
7979 (setq org-local-vars (org-get-local-variables)))
7983 (defun orgstruct-make-binding (fun n &rest keys)
7984 "Create a function for binding in the structure minor mode.
7985 FUN is the command to call inside a table. N is used to create a unique
7986 command name. KEYS are keys that should be checked in for a command
7987 to execute outside of tables."
7988 (eval
7989 (list 'defun
7990 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7991 '(arg)
7992 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7993 "Outside of structure, run the binding of `"
7994 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7995 "'.")
7996 '(interactive "p")
7997 (list 'if
7998 '(org-context-p 'headline 'item)
7999 (list 'org-run-like-in-org-mode (list 'quote fun))
8000 (list 'let '(orgstruct-mode)
8001 (list 'call-interactively
8002 (append '(or)
8003 (mapcar (lambda (k)
8004 (list 'key-binding k))
8005 keys)
8006 '('orgstruct-error))))))))
8008 (defun org-context-p (&rest contexts)
8009 "Check if local context is and of CONTEXTS.
8010 Possible values in the list of contexts are `table', `headline', and `item'."
8011 (let ((pos (point)))
8012 (goto-char (point-at-bol))
8013 (prog1 (or (and (memq 'table contexts)
8014 (looking-at "[ \t]*|"))
8015 (and (memq 'headline contexts)
8016 (looking-at "\\*+"))
8017 (and (memq 'item contexts)
8018 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
8019 (goto-char pos))))
8021 (defun org-get-local-variables ()
8022 "Return a list of all local variables in an org-mode buffer."
8023 (let (varlist)
8024 (with-current-buffer (get-buffer-create "*Org tmp*")
8025 (erase-buffer)
8026 (org-mode)
8027 (setq varlist (buffer-local-variables)))
8028 (kill-buffer "*Org tmp*")
8029 (delq nil
8030 (mapcar
8031 (lambda (x)
8032 (setq x
8033 (if (symbolp x)
8034 (list x)
8035 (list (car x) (list 'quote (cdr x)))))
8036 (if (string-match
8037 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8038 (symbol-name (car x)))
8039 x nil))
8040 varlist))))
8042 ;;;###autoload
8043 (defun org-run-like-in-org-mode (cmd)
8044 (org-load-modules-maybe)
8045 (unless org-local-vars
8046 (setq org-local-vars (org-get-local-variables)))
8047 (eval (list 'let org-local-vars
8048 (list 'call-interactively (list 'quote cmd)))))
8050 ;;;; Archiving
8052 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
8054 (defun org-archive-subtree (&optional find-done)
8055 "Move the current subtree to the archive.
8056 The archive can be a certain top-level heading in the current file, or in
8057 a different file. The tree will be moved to that location, the subtree
8058 heading be marked DONE, and the current time will be added.
8060 When called with prefix argument FIND-DONE, find whole trees without any
8061 open TODO items and archive them (after getting confirmation from the user).
8062 If the cursor is not at a headline when this comand is called, try all level
8063 1 trees. If the cursor is on a headline, only try the direct children of
8064 this heading."
8065 (interactive "P")
8066 (if find-done
8067 (org-archive-all-done)
8068 ;; Save all relevant TODO keyword-relatex variables
8070 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
8071 (tr-org-todo-keywords-1 org-todo-keywords-1)
8072 (tr-org-todo-kwd-alist org-todo-kwd-alist)
8073 (tr-org-done-keywords org-done-keywords)
8074 (tr-org-todo-regexp org-todo-regexp)
8075 (tr-org-todo-line-regexp org-todo-line-regexp)
8076 (tr-org-odd-levels-only org-odd-levels-only)
8077 (this-buffer (current-buffer))
8078 (org-archive-location org-archive-location)
8079 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
8080 ;; start of variables that will be used for saving context
8081 ;; The compiler complains about them - keep them anyway!
8082 (file (abbreviate-file-name (buffer-file-name)))
8083 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
8084 (time (format-time-string
8085 (substring (cdr org-time-stamp-formats) 1 -1)
8086 (current-time)))
8087 afile heading buffer level newfile-p
8088 category todo priority
8089 ;; start of variables that will be used for savind context
8090 ltags itags prop)
8092 ;; Try to find a local archive location
8093 (save-excursion
8094 (save-restriction
8095 (widen)
8096 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
8097 (if (and prop (string-match "\\S-" prop))
8098 (setq org-archive-location prop)
8099 (if (or (re-search-backward re nil t)
8100 (re-search-forward re nil t))
8101 (setq org-archive-location (match-string 1))))))
8103 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
8104 (progn
8105 (setq afile (format (match-string 1 org-archive-location)
8106 (file-name-nondirectory buffer-file-name))
8107 heading (match-string 2 org-archive-location)))
8108 (error "Invalid `org-archive-location'"))
8109 (if (> (length afile) 0)
8110 (setq newfile-p (not (file-exists-p afile))
8111 buffer (find-file-noselect afile))
8112 (setq buffer (current-buffer)))
8113 (unless buffer
8114 (error "Cannot access file \"%s\"" afile))
8115 (if (and (> (length heading) 0)
8116 (string-match "^\\*+" heading))
8117 (setq level (match-end 0))
8118 (setq heading nil level 0))
8119 (save-excursion
8120 (org-back-to-heading t)
8121 ;; Get context information that will be lost by moving the tree
8122 (org-refresh-category-properties)
8123 (setq category (org-get-category)
8124 todo (and (looking-at org-todo-line-regexp)
8125 (match-string 2))
8126 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
8127 ltags (org-get-tags)
8128 itags (org-delete-all ltags (org-get-tags-at)))
8129 (setq ltags (mapconcat 'identity ltags " ")
8130 itags (mapconcat 'identity itags " "))
8131 ;; We first only copy, in case something goes wrong
8132 ;; we need to protect this-command, to avoid kill-region sets it,
8133 ;; which would lead to duplication of subtrees
8134 (let (this-command) (org-copy-subtree))
8135 (set-buffer buffer)
8136 ;; Enforce org-mode for the archive buffer
8137 (if (not (org-mode-p))
8138 ;; Force the mode for future visits.
8139 (let ((org-insert-mode-line-in-empty-file t)
8140 (org-inhibit-startup t))
8141 (call-interactively 'org-mode)))
8142 (when newfile-p
8143 (goto-char (point-max))
8144 (insert (format "\nArchived entries from file %s\n\n"
8145 (buffer-file-name this-buffer))))
8146 ;; Force the TODO keywords of the original buffer
8147 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
8148 (org-todo-keywords-1 tr-org-todo-keywords-1)
8149 (org-todo-kwd-alist tr-org-todo-kwd-alist)
8150 (org-done-keywords tr-org-done-keywords)
8151 (org-todo-regexp tr-org-todo-regexp)
8152 (org-todo-line-regexp tr-org-todo-line-regexp)
8153 (org-odd-levels-only
8154 (if (local-variable-p 'org-odd-levels-only (current-buffer))
8155 org-odd-levels-only
8156 tr-org-odd-levels-only)))
8157 (goto-char (point-min))
8158 (show-all)
8159 (if heading
8160 (progn
8161 (if (re-search-forward
8162 (concat "^" (regexp-quote heading)
8163 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
8164 nil t)
8165 (goto-char (match-end 0))
8166 ;; Heading not found, just insert it at the end
8167 (goto-char (point-max))
8168 (or (bolp) (insert "\n"))
8169 (insert "\n" heading "\n")
8170 (end-of-line 0))
8171 ;; Make the subtree visible
8172 (show-subtree)
8173 (org-end-of-subtree t)
8174 (skip-chars-backward " \t\r\n")
8175 (and (looking-at "[ \t\r\n]*")
8176 (replace-match "\n\n")))
8177 ;; No specific heading, just go to end of file.
8178 (goto-char (point-max)) (insert "\n"))
8179 ;; Paste
8180 (org-paste-subtree (org-get-valid-level level 1))
8182 ;; Mark the entry as done
8183 (when (and org-archive-mark-done
8184 (looking-at org-todo-line-regexp)
8185 (or (not (match-end 2))
8186 (not (member (match-string 2) org-done-keywords))))
8187 (let (org-log-done org-todo-log-states)
8188 (org-todo
8189 (car (or (member org-archive-mark-done org-done-keywords)
8190 org-done-keywords)))))
8192 ;; Add the context info
8193 (when org-archive-save-context-info
8194 (let ((l org-archive-save-context-info) e n v)
8195 (while (setq e (pop l))
8196 (when (and (setq v (symbol-value e))
8197 (stringp v) (string-match "\\S-" v))
8198 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
8199 (org-entry-put (point) n v)))))
8201 ;; Save and kill the buffer, if it is not the same buffer.
8202 (if (not (eq this-buffer buffer))
8203 (progn (save-buffer) (kill-buffer buffer)))))
8204 ;; Here we are back in the original buffer. Everything seems to have
8205 ;; worked. So now cut the tree and finish up.
8206 (let (this-command) (org-cut-subtree))
8207 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
8208 (message "Subtree archived %s"
8209 (if (eq this-buffer buffer)
8210 (concat "under heading: " heading)
8211 (concat "in file: " (abbreviate-file-name afile)))))))
8213 (defun org-refresh-category-properties ()
8214 "Refresh category text properties in teh buffer."
8215 (let ((def-cat (cond
8216 ((null org-category)
8217 (if buffer-file-name
8218 (file-name-sans-extension
8219 (file-name-nondirectory buffer-file-name))
8220 "???"))
8221 ((symbolp org-category) (symbol-name org-category))
8222 (t org-category)))
8223 beg end cat pos optionp)
8224 (org-unmodified
8225 (save-excursion
8226 (save-restriction
8227 (widen)
8228 (goto-char (point-min))
8229 (put-text-property (point) (point-max) 'org-category def-cat)
8230 (while (re-search-forward
8231 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8232 (setq pos (match-end 0)
8233 optionp (equal (char-after (match-beginning 0)) ?#)
8234 cat (org-trim (match-string 2)))
8235 (if optionp
8236 (setq beg (point-at-bol) end (point-max))
8237 (org-back-to-heading t)
8238 (setq beg (point) end (org-end-of-subtree t t)))
8239 (put-text-property beg end 'org-category cat)
8240 (goto-char pos)))))))
8242 (defun org-archive-all-done (&optional tag)
8243 "Archive sublevels of the current tree without open TODO items.
8244 If the cursor is not on a headline, try all level 1 trees. If
8245 it is on a headline, try all direct children.
8246 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
8247 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
8248 (rea (concat ".*:" org-archive-tag ":"))
8249 (begm (make-marker))
8250 (endm (make-marker))
8251 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
8252 "Move subtree to archive (no open TODO items)? "))
8253 beg end (cntarch 0))
8254 (if (org-on-heading-p)
8255 (progn
8256 (setq re1 (concat "^" (regexp-quote
8257 (make-string
8258 (1+ (- (match-end 0) (match-beginning 0) 1))
8259 ?*))
8260 " "))
8261 (move-marker begm (point))
8262 (move-marker endm (org-end-of-subtree t)))
8263 (setq re1 "^* ")
8264 (move-marker begm (point-min))
8265 (move-marker endm (point-max)))
8266 (save-excursion
8267 (goto-char begm)
8268 (while (re-search-forward re1 endm t)
8269 (setq beg (match-beginning 0)
8270 end (save-excursion (org-end-of-subtree t) (point)))
8271 (goto-char beg)
8272 (if (re-search-forward re end t)
8273 (goto-char end)
8274 (goto-char beg)
8275 (if (and (or (not tag) (not (looking-at rea)))
8276 (y-or-n-p question))
8277 (progn
8278 (if tag
8279 (org-toggle-tag org-archive-tag 'on)
8280 (org-archive-subtree))
8281 (setq cntarch (1+ cntarch)))
8282 (goto-char end)))))
8283 (message "%d trees archived" cntarch)))
8285 (defun org-cycle-hide-drawers (state)
8286 "Re-hide all drawers after a visibility state change."
8287 (when (and (org-mode-p)
8288 (not (memq state '(overview folded))))
8289 (save-excursion
8290 (let* ((globalp (memq state '(contents all)))
8291 (beg (if globalp (point-min) (point)))
8292 (end (if globalp (point-max) (org-end-of-subtree t))))
8293 (goto-char beg)
8294 (while (re-search-forward org-drawer-regexp end t)
8295 (org-flag-drawer t))))))
8297 (defun org-flag-drawer (flag)
8298 (save-excursion
8299 (beginning-of-line 1)
8300 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8301 (let ((b (match-end 0))
8302 (outline-regexp org-outline-regexp))
8303 (if (re-search-forward
8304 "^[ \t]*:END:"
8305 (save-excursion (outline-next-heading) (point)) t)
8306 (outline-flag-region b (point-at-eol) flag)
8307 (error ":END: line missing"))))))
8309 (defun org-cycle-hide-archived-subtrees (state)
8310 "Re-hide all archived subtrees after a visibility state change."
8311 (when (and (not org-cycle-open-archived-trees)
8312 (not (memq state '(overview folded))))
8313 (save-excursion
8314 (let* ((globalp (memq state '(contents all)))
8315 (beg (if globalp (point-min) (point)))
8316 (end (if globalp (point-max) (org-end-of-subtree t))))
8317 (org-hide-archived-subtrees beg end)
8318 (goto-char beg)
8319 (if (looking-at (concat ".*:" org-archive-tag ":"))
8320 (message "%s" (substitute-command-keys
8321 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8323 (defun org-force-cycle-archived ()
8324 "Cycle subtree even if it is archived."
8325 (interactive)
8326 (setq this-command 'org-cycle)
8327 (let ((org-cycle-open-archived-trees t))
8328 (call-interactively 'org-cycle)))
8330 (defun org-hide-archived-subtrees (beg end)
8331 "Re-hide all archived subtrees after a visibility state change."
8332 (save-excursion
8333 (let* ((re (concat ":" org-archive-tag ":")))
8334 (goto-char beg)
8335 (while (re-search-forward re end t)
8336 (and (org-on-heading-p) (hide-subtree))
8337 (org-end-of-subtree t)))))
8339 (defun org-toggle-tag (tag &optional onoff)
8340 "Toggle the tag TAG for the current line.
8341 If ONOFF is `on' or `off', don't toggle but set to this state."
8342 (unless (org-on-heading-p t) (error "Not on headling"))
8343 (let (res current)
8344 (save-excursion
8345 (beginning-of-line)
8346 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8347 (point-at-eol) t)
8348 (progn
8349 (setq current (match-string 1))
8350 (replace-match ""))
8351 (setq current ""))
8352 (setq current (nreverse (org-split-string current ":")))
8353 (cond
8354 ((eq onoff 'on)
8355 (setq res t)
8356 (or (member tag current) (push tag current)))
8357 ((eq onoff 'off)
8358 (or (not (member tag current)) (setq current (delete tag current))))
8359 (t (if (member tag current)
8360 (setq current (delete tag current))
8361 (setq res t)
8362 (push tag current))))
8363 (end-of-line 1)
8364 (if current
8365 (progn
8366 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8367 (org-set-tags nil t))
8368 (delete-horizontal-space))
8369 (run-hooks 'org-after-tags-change-hook))
8370 res))
8372 (defun org-toggle-archive-tag (&optional arg)
8373 "Toggle the archive tag for the current headline.
8374 With prefix ARG, check all children of current headline and offer tagging
8375 the children that do not contain any open TODO items."
8376 (interactive "P")
8377 (if arg
8378 (org-archive-all-done 'tag)
8379 (let (set)
8380 (save-excursion
8381 (org-back-to-heading t)
8382 (setq set (org-toggle-tag org-archive-tag))
8383 (when set (hide-subtree)))
8384 (and set (beginning-of-line 1))
8385 (message "Subtree %s" (if set "archived" "unarchived")))))
8388 ;;;; Tables
8390 ;;; The table editor
8392 ;; Watch out: Here we are talking about two different kind of tables.
8393 ;; Most of the code is for the tables created with the Org-mode table editor.
8394 ;; Sometimes, we talk about tables created and edited with the table.el
8395 ;; Emacs package. We call the former org-type tables, and the latter
8396 ;; table.el-type tables.
8398 (defun org-before-change-function (beg end)
8399 "Every change indicates that a table might need an update."
8400 (setq org-table-may-need-update t))
8402 (defconst org-table-line-regexp "^[ \t]*|"
8403 "Detects an org-type table line.")
8404 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8405 "Detects an org-type table line.")
8406 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8407 "Detects a table line marked for automatic recalculation.")
8408 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8409 "Detects a table line marked for automatic recalculation.")
8410 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8411 "Detects a table line marked for automatic recalculation.")
8412 (defconst org-table-hline-regexp "^[ \t]*|-"
8413 "Detects an org-type table hline.")
8414 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8415 "Detects a table-type table hline.")
8416 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8417 "Detects an org-type or table-type table.")
8418 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8419 "Searching from within a table (any type) this finds the first line
8420 outside the table.")
8421 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8422 "Searching from within a table (any type) this finds the first line
8423 outside the table.")
8425 (defvar org-table-last-highlighted-reference nil)
8426 (defvar org-table-formula-history nil)
8428 (defvar org-table-column-names nil
8429 "Alist with column names, derived from the `!' line.")
8430 (defvar org-table-column-name-regexp nil
8431 "Regular expression matching the current column names.")
8432 (defvar org-table-local-parameters nil
8433 "Alist with parameter names, derived from the `$' line.")
8434 (defvar org-table-named-field-locations nil
8435 "Alist with locations of named fields.")
8437 (defvar org-table-current-line-types nil
8438 "Table row types, non-nil only for the duration of a comand.")
8439 (defvar org-table-current-begin-line nil
8440 "Table begin line, non-nil only for the duration of a comand.")
8441 (defvar org-table-current-begin-pos nil
8442 "Table begin position, non-nil only for the duration of a comand.")
8443 (defvar org-table-dlines nil
8444 "Vector of data line line numbers in the current table.")
8445 (defvar org-table-hlines nil
8446 "Vector of hline line numbers in the current table.")
8448 (defconst org-table-range-regexp
8449 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8450 ;; 1 2 3 4 5
8451 "Regular expression for matching ranges in formulas.")
8453 (defconst org-table-range-regexp2
8454 (concat
8455 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8456 "\\.\\."
8457 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8458 "Match a range for reference display.")
8460 (defconst org-table-translate-regexp
8461 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8462 "Match a reference that needs translation, for reference display.")
8464 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8466 (defun org-table-create-with-table.el ()
8467 "Use the table.el package to insert a new table.
8468 If there is already a table at point, convert between Org-mode tables
8469 and table.el tables."
8470 (interactive)
8471 (require 'table)
8472 (cond
8473 ((org-at-table.el-p)
8474 (if (y-or-n-p "Convert table to Org-mode table? ")
8475 (org-table-convert)))
8476 ((org-at-table-p)
8477 (if (y-or-n-p "Convert table to table.el table? ")
8478 (org-table-convert)))
8479 (t (call-interactively 'table-insert))))
8481 (defun org-table-create-or-convert-from-region (arg)
8482 "Convert region to table, or create an empty table.
8483 If there is an active region, convert it to a table, using the function
8484 `org-table-convert-region'. See the documentation of that function
8485 to learn how the prefix argument is interpreted to determine the field
8486 separator.
8487 If there is no such region, create an empty table with `org-table-create'."
8488 (interactive "P")
8489 (if (org-region-active-p)
8490 (org-table-convert-region (region-beginning) (region-end) arg)
8491 (org-table-create arg)))
8493 (defun org-table-create (&optional size)
8494 "Query for a size and insert a table skeleton.
8495 SIZE is a string Columns x Rows like for example \"3x2\"."
8496 (interactive "P")
8497 (unless size
8498 (setq size (read-string
8499 (concat "Table size Columns x Rows [e.g. "
8500 org-table-default-size "]: ")
8501 "" nil org-table-default-size)))
8503 (let* ((pos (point))
8504 (indent (make-string (current-column) ?\ ))
8505 (split (org-split-string size " *x *"))
8506 (rows (string-to-number (nth 1 split)))
8507 (columns (string-to-number (car split)))
8508 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8509 "\n")))
8510 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8511 (point-at-bol) (point)))
8512 (beginning-of-line 1)
8513 (newline))
8514 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8515 (dotimes (i rows) (insert line))
8516 (goto-char pos)
8517 (if (> rows 1)
8518 ;; Insert a hline after the first row.
8519 (progn
8520 (end-of-line 1)
8521 (insert "\n|-")
8522 (goto-char pos)))
8523 (org-table-align)))
8525 (defun org-table-convert-region (beg0 end0 &optional separator)
8526 "Convert region to a table.
8527 The region goes from BEG0 to END0, but these borders will be moved
8528 slightly, to make sure a beginning of line in the first line is included.
8530 SEPARATOR specifies the field separator in the lines. It can have the
8531 following values:
8533 '(4) Use the comma as a field separator
8534 '(16) Use a TAB as field separator
8535 integer When a number, use that many spaces as field separator
8536 nil When nil, the command tries to be smart and figure out the
8537 separator in the following way:
8538 - when each line contains a TAB, assume TAB-separated material
8539 - when each line contains a comme, assume CSV material
8540 - else, assume one or more SPACE charcters as separator."
8541 (interactive "rP")
8542 (let* ((beg (min beg0 end0))
8543 (end (max beg0 end0))
8545 (goto-char beg)
8546 (beginning-of-line 1)
8547 (setq beg (move-marker (make-marker) (point)))
8548 (goto-char end)
8549 (if (bolp) (backward-char 1) (end-of-line 1))
8550 (setq end (move-marker (make-marker) (point)))
8551 ;; Get the right field separator
8552 (unless separator
8553 (goto-char beg)
8554 (setq separator
8555 (cond
8556 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8557 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8558 (t 1))))
8559 (setq re (cond
8560 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8561 ((equal separator '(16)) "^\\|\t")
8562 ((integerp separator)
8563 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8564 (t (error "This should not happen"))))
8565 (goto-char beg)
8566 (while (re-search-forward re end t)
8567 (replace-match "| " t t))
8568 (goto-char beg)
8569 (insert " ")
8570 (org-table-align)))
8572 (defun org-table-import (file arg)
8573 "Import FILE as a table.
8574 The file is assumed to be tab-separated. Such files can be produced by most
8575 spreadsheet and database applications. If no tabs (at least one per line)
8576 are found, lines will be split on whitespace into fields."
8577 (interactive "f\nP")
8578 (or (bolp) (newline))
8579 (let ((beg (point))
8580 (pm (point-max)))
8581 (insert-file-contents file)
8582 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8584 (defun org-table-export ()
8585 "Export table as a tab-separated file.
8586 Such a file can be imported into a spreadsheet program like Excel."
8587 (interactive)
8588 (let* ((beg (org-table-begin))
8589 (end (org-table-end))
8590 (table (buffer-substring beg end))
8591 (file (read-file-name "Export table to: "))
8592 buf)
8593 (unless (or (not (file-exists-p file))
8594 (y-or-n-p (format "Overwrite file %s? " file)))
8595 (error "Abort"))
8596 (with-current-buffer (find-file-noselect file)
8597 (setq buf (current-buffer))
8598 (erase-buffer)
8599 (fundamental-mode)
8600 (insert table)
8601 (goto-char (point-min))
8602 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8603 (replace-match "" t t)
8604 (end-of-line 1))
8605 (goto-char (point-min))
8606 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8607 (replace-match "" t t)
8608 (goto-char (min (1+ (point)) (point-max))))
8609 (goto-char (point-min))
8610 (while (re-search-forward "^-[-+]*$" nil t)
8611 (replace-match "")
8612 (if (looking-at "\n")
8613 (delete-char 1)))
8614 (goto-char (point-min))
8615 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8616 (replace-match "\t" t t))
8617 (save-buffer))
8618 (kill-buffer buf)))
8620 (defvar org-table-aligned-begin-marker (make-marker)
8621 "Marker at the beginning of the table last aligned.
8622 Used to check if cursor still is in that table, to minimize realignment.")
8623 (defvar org-table-aligned-end-marker (make-marker)
8624 "Marker at the end of the table last aligned.
8625 Used to check if cursor still is in that table, to minimize realignment.")
8626 (defvar org-table-last-alignment nil
8627 "List of flags for flushright alignment, from the last re-alignment.
8628 This is being used to correctly align a single field after TAB or RET.")
8629 (defvar org-table-last-column-widths nil
8630 "List of max width of fields in each column.
8631 This is being used to correctly align a single field after TAB or RET.")
8632 (defvar org-table-overlay-coordinates nil
8633 "Overlay coordinates after each align of a table.")
8634 (make-variable-buffer-local 'org-table-overlay-coordinates)
8636 (defvar org-last-recalc-line nil)
8637 (defconst org-narrow-column-arrow "=>"
8638 "Used as display property in narrowed table columns.")
8640 (defun org-table-align ()
8641 "Align the table at point by aligning all vertical bars."
8642 (interactive)
8643 (let* (
8644 ;; Limits of table
8645 (beg (org-table-begin))
8646 (end (org-table-end))
8647 ;; Current cursor position
8648 (linepos (org-current-line))
8649 (colpos (org-table-current-column))
8650 (winstart (window-start))
8651 (winstartline (org-current-line (min winstart (1- (point-max)))))
8652 lines (new "") lengths l typenums ty fields maxfields i
8653 column
8654 (indent "") cnt frac
8655 rfmt hfmt
8656 (spaces '(1 . 1))
8657 (sp1 (car spaces))
8658 (sp2 (cdr spaces))
8659 (rfmt1 (concat
8660 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8661 (hfmt1 (concat
8662 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8663 emptystrings links dates emph narrow fmax f1 len c e)
8664 (untabify beg end)
8665 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8666 ;; Check if we have links or dates
8667 (goto-char beg)
8668 (setq links (re-search-forward org-bracket-link-regexp end t))
8669 (goto-char beg)
8670 (setq emph (and org-hide-emphasis-markers
8671 (re-search-forward org-emph-re end t)))
8672 (goto-char beg)
8673 (setq dates (and org-display-custom-times
8674 (re-search-forward org-ts-regexp-both end t)))
8675 ;; Make sure the link properties are right
8676 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8677 ;; Make sure the date properties are right
8678 (when dates (goto-char beg) (while (org-activate-dates end)))
8679 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8681 ;; Check if we are narrowing any columns
8682 (goto-char beg)
8683 (setq narrow (and org-format-transports-properties-p
8684 (re-search-forward "<[0-9]+>" end t)))
8685 ;; Get the rows
8686 (setq lines (org-split-string
8687 (buffer-substring beg end) "\n"))
8688 ;; Store the indentation of the first line
8689 (if (string-match "^ *" (car lines))
8690 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8691 ;; Mark the hlines by setting the corresponding element to nil
8692 ;; At the same time, we remove trailing space.
8693 (setq lines (mapcar (lambda (l)
8694 (if (string-match "^ *|-" l)
8696 (if (string-match "[ \t]+$" l)
8697 (substring l 0 (match-beginning 0))
8698 l)))
8699 lines))
8700 ;; Get the data fields by splitting the lines.
8701 (setq fields (mapcar
8702 (lambda (l)
8703 (org-split-string l " *| *"))
8704 (delq nil (copy-sequence lines))))
8705 ;; How many fields in the longest line?
8706 (condition-case nil
8707 (setq maxfields (apply 'max (mapcar 'length fields)))
8708 (error
8709 (kill-region beg end)
8710 (org-table-create org-table-default-size)
8711 (error "Empty table - created default table")))
8712 ;; A list of empty strings to fill any short rows on output
8713 (setq emptystrings (make-list maxfields ""))
8714 ;; Check for special formatting.
8715 (setq i -1)
8716 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8717 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8718 ;; Check if there is an explicit width specified
8719 (when narrow
8720 (setq c column fmax nil)
8721 (while c
8722 (setq e (pop c))
8723 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8724 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8725 ;; Find fields that are wider than fmax, and shorten them
8726 (when fmax
8727 (loop for xx in column do
8728 (when (and (stringp xx)
8729 (> (org-string-width xx) fmax))
8730 (org-add-props xx nil
8731 'help-echo
8732 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8733 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8734 (unless (> f1 1)
8735 (error "Cannot narrow field starting with wide link \"%s\""
8736 (match-string 0 xx)))
8737 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8738 (add-text-properties (- f1 2) f1
8739 (list 'display org-narrow-column-arrow)
8740 xx)))))
8741 ;; Get the maximum width for each column
8742 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8743 ;; Get the fraction of numbers, to decide about alignment of the column
8744 (setq cnt 0 frac 0.0)
8745 (loop for x in column do
8746 (if (equal x "")
8748 (setq frac ( / (+ (* frac cnt)
8749 (if (string-match org-table-number-regexp x) 1 0))
8750 (setq cnt (1+ cnt))))))
8751 (push (>= frac org-table-number-fraction) typenums))
8752 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8754 ;; Store the alignment of this table, for later editing of single fields
8755 (setq org-table-last-alignment typenums
8756 org-table-last-column-widths lengths)
8758 ;; With invisible characters, `format' does not get the field width right
8759 ;; So we need to make these fields wide by hand.
8760 (when (or links emph)
8761 (loop for i from 0 upto (1- maxfields) do
8762 (setq len (nth i lengths))
8763 (loop for j from 0 upto (1- (length fields)) do
8764 (setq c (nthcdr i (car (nthcdr j fields))))
8765 (if (and (stringp (car c))
8766 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8767 ; (string-match org-bracket-link-regexp (car c))
8768 (< (org-string-width (car c)) len))
8769 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8771 ;; Compute the formats needed for output of the table
8772 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8773 (while (setq l (pop lengths))
8774 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8775 (setq rfmt (concat rfmt (format rfmt1 ty l))
8776 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8777 (setq rfmt (concat rfmt "\n")
8778 hfmt (concat (substring hfmt 0 -1) "|\n"))
8780 (setq new (mapconcat
8781 (lambda (l)
8782 (if l (apply 'format rfmt
8783 (append (pop fields) emptystrings))
8784 hfmt))
8785 lines ""))
8786 ;; Replace the old one
8787 (delete-region beg end)
8788 (move-marker end nil)
8789 (move-marker org-table-aligned-begin-marker (point))
8790 (insert new)
8791 (move-marker org-table-aligned-end-marker (point))
8792 (when (and orgtbl-mode (not (org-mode-p)))
8793 (goto-char org-table-aligned-begin-marker)
8794 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8795 ;; Try to move to the old location
8796 (goto-line winstartline)
8797 (setq winstart (point-at-bol))
8798 (goto-line linepos)
8799 (set-window-start (selected-window) winstart 'noforce)
8800 (org-table-goto-column colpos)
8801 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8802 (setq org-table-may-need-update nil)
8805 (defun org-string-width (s)
8806 "Compute width of string, ignoring invisible characters.
8807 This ignores character with invisibility property `org-link', and also
8808 characters with property `org-cwidth', because these will become invisible
8809 upon the next fontification round."
8810 (let (b l)
8811 (when (or (eq t buffer-invisibility-spec)
8812 (assq 'org-link buffer-invisibility-spec))
8813 (while (setq b (text-property-any 0 (length s)
8814 'invisible 'org-link s))
8815 (setq s (concat (substring s 0 b)
8816 (substring s (or (next-single-property-change
8817 b 'invisible s) (length s)))))))
8818 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8819 (setq s (concat (substring s 0 b)
8820 (substring s (or (next-single-property-change
8821 b 'org-cwidth s) (length s))))))
8822 (setq l (string-width s) b -1)
8823 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8824 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8827 (defun org-table-begin (&optional table-type)
8828 "Find the beginning of the table and return its position.
8829 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8830 (save-excursion
8831 (if (not (re-search-backward
8832 (if table-type org-table-any-border-regexp
8833 org-table-border-regexp)
8834 nil t))
8835 (progn (goto-char (point-min)) (point))
8836 (goto-char (match-beginning 0))
8837 (beginning-of-line 2)
8838 (point))))
8840 (defun org-table-end (&optional table-type)
8841 "Find the end of the table and return its position.
8842 With argument TABLE-TYPE, go to the end of a table.el-type table."
8843 (save-excursion
8844 (if (not (re-search-forward
8845 (if table-type org-table-any-border-regexp
8846 org-table-border-regexp)
8847 nil t))
8848 (goto-char (point-max))
8849 (goto-char (match-beginning 0)))
8850 (point-marker)))
8852 (defun org-table-justify-field-maybe (&optional new)
8853 "Justify the current field, text to left, number to right.
8854 Optional argument NEW may specify text to replace the current field content."
8855 (cond
8856 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8857 ((org-at-table-hline-p))
8858 ((and (not new)
8859 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8860 (current-buffer)))
8861 (< (point) org-table-aligned-begin-marker)
8862 (>= (point) org-table-aligned-end-marker)))
8863 ;; This is not the same table, force a full re-align
8864 (setq org-table-may-need-update t))
8865 (t ;; realign the current field, based on previous full realign
8866 (let* ((pos (point)) s
8867 (col (org-table-current-column))
8868 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8869 l f n o e)
8870 (when (> col 0)
8871 (skip-chars-backward "^|\n")
8872 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8873 (progn
8874 (setq s (match-string 1)
8875 o (match-string 0)
8876 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8877 e (not (= (match-beginning 2) (match-end 2))))
8878 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8879 l (if e "|" (setq org-table-may-need-update t) ""))
8880 n (format f s))
8881 (if new
8882 (if (<= (length new) l) ;; FIXME: length -> str-width?
8883 (setq n (format f new))
8884 (setq n (concat new "|") org-table-may-need-update t)))
8885 (or (equal n o)
8886 (let (org-table-may-need-update)
8887 (replace-match n t t))))
8888 (setq org-table-may-need-update t))
8889 (goto-char pos))))))
8891 (defun org-table-next-field ()
8892 "Go to the next field in the current table, creating new lines as needed.
8893 Before doing so, re-align the table if necessary."
8894 (interactive)
8895 (org-table-maybe-eval-formula)
8896 (org-table-maybe-recalculate-line)
8897 (if (and org-table-automatic-realign
8898 org-table-may-need-update)
8899 (org-table-align))
8900 (let ((end (org-table-end)))
8901 (if (org-at-table-hline-p)
8902 (end-of-line 1))
8903 (condition-case nil
8904 (progn
8905 (re-search-forward "|" end)
8906 (if (looking-at "[ \t]*$")
8907 (re-search-forward "|" end))
8908 (if (and (looking-at "-")
8909 org-table-tab-jumps-over-hlines
8910 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8911 (goto-char (match-beginning 1)))
8912 (if (looking-at "-")
8913 (progn
8914 (beginning-of-line 0)
8915 (org-table-insert-row 'below))
8916 (if (looking-at " ") (forward-char 1))))
8917 (error
8918 (org-table-insert-row 'below)))))
8920 (defun org-table-previous-field ()
8921 "Go to the previous field in the table.
8922 Before doing so, re-align the table if necessary."
8923 (interactive)
8924 (org-table-justify-field-maybe)
8925 (org-table-maybe-recalculate-line)
8926 (if (and org-table-automatic-realign
8927 org-table-may-need-update)
8928 (org-table-align))
8929 (if (org-at-table-hline-p)
8930 (end-of-line 1))
8931 (re-search-backward "|" (org-table-begin))
8932 (re-search-backward "|" (org-table-begin))
8933 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8934 (re-search-backward "|" (org-table-begin)))
8935 (if (looking-at "| ?")
8936 (goto-char (match-end 0))))
8938 (defun org-table-next-row ()
8939 "Go to the next row (same column) in the current table.
8940 Before doing so, re-align the table if necessary."
8941 (interactive)
8942 (org-table-maybe-eval-formula)
8943 (org-table-maybe-recalculate-line)
8944 (if (or (looking-at "[ \t]*$")
8945 (save-excursion (skip-chars-backward " \t") (bolp)))
8946 (newline)
8947 (if (and org-table-automatic-realign
8948 org-table-may-need-update)
8949 (org-table-align))
8950 (let ((col (org-table-current-column)))
8951 (beginning-of-line 2)
8952 (if (or (not (org-at-table-p))
8953 (org-at-table-hline-p))
8954 (progn
8955 (beginning-of-line 0)
8956 (org-table-insert-row 'below)))
8957 (org-table-goto-column col)
8958 (skip-chars-backward "^|\n\r")
8959 (if (looking-at " ") (forward-char 1)))))
8961 (defun org-table-copy-down (n)
8962 "Copy a field down in the current column.
8963 If the field at the cursor is empty, copy into it the content of the nearest
8964 non-empty field above. With argument N, use the Nth non-empty field.
8965 If the current field is not empty, it is copied down to the next row, and
8966 the cursor is moved with it. Therefore, repeating this command causes the
8967 column to be filled row-by-row.
8968 If the variable `org-table-copy-increment' is non-nil and the field is an
8969 integer or a timestamp, it will be incremented while copying. In the case of
8970 a timestamp, if the cursor is on the year, change the year. If it is on the
8971 month or the day, change that. Point will stay on the current date field
8972 in order to easily repeat the interval."
8973 (interactive "p")
8974 (let* ((colpos (org-table-current-column))
8975 (col (current-column))
8976 (field (org-table-get-field))
8977 (non-empty (string-match "[^ \t]" field))
8978 (beg (org-table-begin))
8979 txt)
8980 (org-table-check-inside-data-field)
8981 (if non-empty
8982 (progn
8983 (setq txt (org-trim field))
8984 (org-table-next-row)
8985 (org-table-blank-field))
8986 (save-excursion
8987 (setq txt
8988 (catch 'exit
8989 (while (progn (beginning-of-line 1)
8990 (re-search-backward org-table-dataline-regexp
8991 beg t))
8992 (org-table-goto-column colpos t)
8993 (if (and (looking-at
8994 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8995 (= (setq n (1- n)) 0))
8996 (throw 'exit (match-string 1))))))))
8997 (if txt
8998 (progn
8999 (if (and org-table-copy-increment
9000 (string-match "^[0-9]+$" txt))
9001 (setq txt (format "%d" (+ (string-to-number txt) 1))))
9002 (insert txt)
9003 (move-to-column col)
9004 (if (and org-table-copy-increment (org-at-timestamp-p t))
9005 (org-timestamp-up 1)
9006 (org-table-maybe-recalculate-line))
9007 (org-table-align)
9008 (move-to-column col))
9009 (error "No non-empty field found"))))
9011 (defun org-table-check-inside-data-field ()
9012 "Is point inside a table data field?
9013 I.e. not on a hline or before the first or after the last column?
9014 This actually throws an error, so it aborts the current command."
9015 (if (or (not (org-at-table-p))
9016 (= (org-table-current-column) 0)
9017 (org-at-table-hline-p)
9018 (looking-at "[ \t]*$"))
9019 (error "Not in table data field")))
9021 (defvar org-table-clip nil
9022 "Clipboard for table regions.")
9024 (defun org-table-blank-field ()
9025 "Blank the current table field or active region."
9026 (interactive)
9027 (org-table-check-inside-data-field)
9028 (if (and (interactive-p) (org-region-active-p))
9029 (let (org-table-clip)
9030 (org-table-cut-region (region-beginning) (region-end)))
9031 (skip-chars-backward "^|")
9032 (backward-char 1)
9033 (if (looking-at "|[^|\n]+")
9034 (let* ((pos (match-beginning 0))
9035 (match (match-string 0))
9036 (len (org-string-width match)))
9037 (replace-match (concat "|" (make-string (1- len) ?\ )))
9038 (goto-char (+ 2 pos))
9039 (substring match 1)))))
9041 (defun org-table-get-field (&optional n replace)
9042 "Return the value of the field in column N of current row.
9043 N defaults to current field.
9044 If REPLACE is a string, replace field with this value. The return value
9045 is always the old value."
9046 (and n (org-table-goto-column n))
9047 (skip-chars-backward "^|\n")
9048 (backward-char 1)
9049 (if (looking-at "|[^|\r\n]*")
9050 (let* ((pos (match-beginning 0))
9051 (val (buffer-substring (1+ pos) (match-end 0))))
9052 (if replace
9053 (replace-match (concat "|" replace) t t))
9054 (goto-char (min (point-at-eol) (+ 2 pos)))
9055 val)
9056 (forward-char 1) ""))
9058 (defun org-table-field-info (arg)
9059 "Show info about the current field, and highlight any reference at point."
9060 (interactive "P")
9061 (org-table-get-specials)
9062 (save-excursion
9063 (let* ((pos (point))
9064 (col (org-table-current-column))
9065 (cname (car (rassoc (int-to-string col) org-table-column-names)))
9066 (name (car (rassoc (list (org-current-line) col)
9067 org-table-named-field-locations)))
9068 (eql (org-table-get-stored-formulas))
9069 (dline (org-table-current-dline))
9070 (ref (format "@%d$%d" dline col))
9071 (ref1 (org-table-convert-refs-to-an ref))
9072 (fequation (or (assoc name eql) (assoc ref eql)))
9073 (cequation (assoc (int-to-string col) eql))
9074 (eqn (or fequation cequation)))
9075 (goto-char pos)
9076 (condition-case nil
9077 (org-table-show-reference 'local)
9078 (error nil))
9079 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
9080 dline col
9081 (if cname (concat " or $" cname) "")
9082 dline col ref1
9083 (if name (concat " or $" name) "")
9084 ;; FIXME: formula info not correct if special table line
9085 (if eqn
9086 (concat ", formula: "
9087 (org-table-formula-to-user
9088 (concat
9089 (if (string-match "^[$@]"(car eqn)) "" "$")
9090 (car eqn) "=" (cdr eqn))))
9091 "")))))
9093 (defun org-table-current-column ()
9094 "Find out which column we are in.
9095 When called interactively, column is also displayed in echo area."
9096 (interactive)
9097 (if (interactive-p) (org-table-check-inside-data-field))
9098 (save-excursion
9099 (let ((cnt 0) (pos (point)))
9100 (beginning-of-line 1)
9101 (while (search-forward "|" pos t)
9102 (setq cnt (1+ cnt)))
9103 (if (interactive-p) (message "This is table column %d" cnt))
9104 cnt)))
9106 (defun org-table-current-dline ()
9107 "Find out what table data line we are in.
9108 Only datalins count for this."
9109 (interactive)
9110 (if (interactive-p) (org-table-check-inside-data-field))
9111 (save-excursion
9112 (let ((cnt 0) (pos (point)))
9113 (goto-char (org-table-begin))
9114 (while (<= (point) pos)
9115 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
9116 (beginning-of-line 2))
9117 (if (interactive-p) (message "This is table line %d" cnt))
9118 cnt)))
9120 (defun org-table-goto-column (n &optional on-delim force)
9121 "Move the cursor to the Nth column in the current table line.
9122 With optional argument ON-DELIM, stop with point before the left delimiter
9123 of the field.
9124 If there are less than N fields, just go to after the last delimiter.
9125 However, when FORCE is non-nil, create new columns if necessary."
9126 (interactive "p")
9127 (let ((pos (point-at-eol)))
9128 (beginning-of-line 1)
9129 (when (> n 0)
9130 (while (and (> (setq n (1- n)) -1)
9131 (or (search-forward "|" pos t)
9132 (and force
9133 (progn (end-of-line 1)
9134 (skip-chars-backward "^|")
9135 (insert " | "))))))
9136 ; (backward-char 2) t)))))
9137 (when (and force (not (looking-at ".*|")))
9138 (save-excursion (end-of-line 1) (insert " | ")))
9139 (if on-delim
9140 (backward-char 1)
9141 (if (looking-at " ") (forward-char 1))))))
9143 (defun org-at-table-p (&optional table-type)
9144 "Return t if the cursor is inside an org-type table.
9145 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9146 (if org-enable-table-editor
9147 (save-excursion
9148 (beginning-of-line 1)
9149 (looking-at (if table-type org-table-any-line-regexp
9150 org-table-line-regexp)))
9151 nil))
9153 (defun org-at-table.el-p ()
9154 "Return t if and only if we are at a table.el table."
9155 (and (org-at-table-p 'any)
9156 (save-excursion
9157 (goto-char (org-table-begin 'any))
9158 (looking-at org-table1-hline-regexp))))
9160 (defun org-table-recognize-table.el ()
9161 "If there is a table.el table nearby, recognize it and move into it."
9162 (if org-table-tab-recognizes-table.el
9163 (if (org-at-table.el-p)
9164 (progn
9165 (beginning-of-line 1)
9166 (if (looking-at org-table-dataline-regexp)
9168 (if (looking-at org-table1-hline-regexp)
9169 (progn
9170 (beginning-of-line 2)
9171 (if (looking-at org-table-any-border-regexp)
9172 (beginning-of-line -1)))))
9173 (if (re-search-forward "|" (org-table-end t) t)
9174 (progn
9175 (require 'table)
9176 (if (table--at-cell-p (point))
9178 (message "recognizing table.el table...")
9179 (table-recognize-table)
9180 (message "recognizing table.el table...done")))
9181 (error "This should not happen..."))
9183 nil)
9184 nil))
9186 (defun org-at-table-hline-p ()
9187 "Return t if the cursor is inside a hline in a table."
9188 (if org-enable-table-editor
9189 (save-excursion
9190 (beginning-of-line 1)
9191 (looking-at org-table-hline-regexp))
9192 nil))
9194 (defun org-table-insert-column ()
9195 "Insert a new column into the table."
9196 (interactive)
9197 (if (not (org-at-table-p))
9198 (error "Not at a table"))
9199 (org-table-find-dataline)
9200 (let* ((col (max 1 (org-table-current-column)))
9201 (beg (org-table-begin))
9202 (end (org-table-end))
9203 ;; Current cursor position
9204 (linepos (org-current-line))
9205 (colpos col))
9206 (goto-char beg)
9207 (while (< (point) end)
9208 (if (org-at-table-hline-p)
9210 (org-table-goto-column col t)
9211 (insert "| "))
9212 (beginning-of-line 2))
9213 (move-marker end nil)
9214 (goto-line linepos)
9215 (org-table-goto-column colpos)
9216 (org-table-align)
9217 (org-table-fix-formulas "$" nil (1- col) 1)))
9219 (defun org-table-find-dataline ()
9220 "Find a dataline in the current table, which is needed for column commands."
9221 (if (and (org-at-table-p)
9222 (not (org-at-table-hline-p)))
9224 (let ((col (current-column))
9225 (end (org-table-end)))
9226 (move-to-column col)
9227 (while (and (< (point) end)
9228 (or (not (= (current-column) col))
9229 (org-at-table-hline-p)))
9230 (beginning-of-line 2)
9231 (move-to-column col))
9232 (if (and (org-at-table-p)
9233 (not (org-at-table-hline-p)))
9235 (error
9236 "Please position cursor in a data line for column operations")))))
9238 (defun org-table-delete-column ()
9239 "Delete a column from the table."
9240 (interactive)
9241 (if (not (org-at-table-p))
9242 (error "Not at a table"))
9243 (org-table-find-dataline)
9244 (org-table-check-inside-data-field)
9245 (let* ((col (org-table-current-column))
9246 (beg (org-table-begin))
9247 (end (org-table-end))
9248 ;; Current cursor position
9249 (linepos (org-current-line))
9250 (colpos col))
9251 (goto-char beg)
9252 (while (< (point) end)
9253 (if (org-at-table-hline-p)
9255 (org-table-goto-column col t)
9256 (and (looking-at "|[^|\n]+|")
9257 (replace-match "|")))
9258 (beginning-of-line 2))
9259 (move-marker end nil)
9260 (goto-line linepos)
9261 (org-table-goto-column colpos)
9262 (org-table-align)
9263 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9264 col -1 col)))
9266 (defun org-table-move-column-right ()
9267 "Move column to the right."
9268 (interactive)
9269 (org-table-move-column nil))
9270 (defun org-table-move-column-left ()
9271 "Move column to the left."
9272 (interactive)
9273 (org-table-move-column 'left))
9275 (defun org-table-move-column (&optional left)
9276 "Move the current column to the right. With arg LEFT, move to the left."
9277 (interactive "P")
9278 (if (not (org-at-table-p))
9279 (error "Not at a table"))
9280 (org-table-find-dataline)
9281 (org-table-check-inside-data-field)
9282 (let* ((col (org-table-current-column))
9283 (col1 (if left (1- col) col))
9284 (beg (org-table-begin))
9285 (end (org-table-end))
9286 ;; Current cursor position
9287 (linepos (org-current-line))
9288 (colpos (if left (1- col) (1+ col))))
9289 (if (and left (= col 1))
9290 (error "Cannot move column further left"))
9291 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9292 (error "Cannot move column further right"))
9293 (goto-char beg)
9294 (while (< (point) end)
9295 (if (org-at-table-hline-p)
9297 (org-table-goto-column col1 t)
9298 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9299 (replace-match "|\\2|\\1|")))
9300 (beginning-of-line 2))
9301 (move-marker end nil)
9302 (goto-line linepos)
9303 (org-table-goto-column colpos)
9304 (org-table-align)
9305 (org-table-fix-formulas
9306 "$" (list (cons (number-to-string col) (number-to-string colpos))
9307 (cons (number-to-string colpos) (number-to-string col))))))
9309 (defun org-table-move-row-down ()
9310 "Move table row down."
9311 (interactive)
9312 (org-table-move-row nil))
9313 (defun org-table-move-row-up ()
9314 "Move table row up."
9315 (interactive)
9316 (org-table-move-row 'up))
9318 (defun org-table-move-row (&optional up)
9319 "Move the current table line down. With arg UP, move it up."
9320 (interactive "P")
9321 (let* ((col (current-column))
9322 (pos (point))
9323 (hline1p (save-excursion (beginning-of-line 1)
9324 (looking-at org-table-hline-regexp)))
9325 (dline1 (org-table-current-dline))
9326 (dline2 (+ dline1 (if up -1 1)))
9327 (tonew (if up 0 2))
9328 txt hline2p)
9329 (beginning-of-line tonew)
9330 (unless (org-at-table-p)
9331 (goto-char pos)
9332 (error "Cannot move row further"))
9333 (setq hline2p (looking-at org-table-hline-regexp))
9334 (goto-char pos)
9335 (beginning-of-line 1)
9336 (setq pos (point))
9337 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9338 (delete-region (point) (1+ (point-at-eol)))
9339 (beginning-of-line tonew)
9340 (insert txt)
9341 (beginning-of-line 0)
9342 (move-to-column col)
9343 (unless (or hline1p hline2p)
9344 (org-table-fix-formulas
9345 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9346 (cons (number-to-string dline2) (number-to-string dline1)))))))
9348 (defun org-table-insert-row (&optional arg)
9349 "Insert a new row above the current line into the table.
9350 With prefix ARG, insert below the current line."
9351 (interactive "P")
9352 (if (not (org-at-table-p))
9353 (error "Not at a table"))
9354 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9355 (new (org-table-clean-line line)))
9356 ;; Fix the first field if necessary
9357 (if (string-match "^[ \t]*| *[#$] *|" line)
9358 (setq new (replace-match (match-string 0 line) t t new)))
9359 (beginning-of-line (if arg 2 1))
9360 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9361 (beginning-of-line 0)
9362 (re-search-forward "| ?" (point-at-eol) t)
9363 (and (or org-table-may-need-update org-table-overlay-coordinates)
9364 (org-table-align))
9365 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9367 (defun org-table-insert-hline (&optional above)
9368 "Insert a horizontal-line below the current line into the table.
9369 With prefix ABOVE, insert above the current line."
9370 (interactive "P")
9371 (if (not (org-at-table-p))
9372 (error "Not at a table"))
9373 (let ((line (org-table-clean-line
9374 (buffer-substring (point-at-bol) (point-at-eol))))
9375 (col (current-column)))
9376 (while (string-match "|\\( +\\)|" line)
9377 (setq line (replace-match
9378 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9379 ?-) "|") t t line)))
9380 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9381 (beginning-of-line (if above 1 2))
9382 (insert line "\n")
9383 (beginning-of-line (if above 1 -1))
9384 (move-to-column col)
9385 (and org-table-overlay-coordinates (org-table-align))))
9387 (defun org-table-hline-and-move (&optional same-column)
9388 "Insert a hline and move to the row below that line."
9389 (interactive "P")
9390 (let ((col (org-table-current-column)))
9391 (org-table-maybe-eval-formula)
9392 (org-table-maybe-recalculate-line)
9393 (org-table-insert-hline)
9394 (end-of-line 2)
9395 (if (looking-at "\n[ \t]*|-")
9396 (progn (insert "\n|") (org-table-align))
9397 (org-table-next-field))
9398 (if same-column (org-table-goto-column col))))
9400 (defun org-table-clean-line (s)
9401 "Convert a table line S into a string with only \"|\" and space.
9402 In particular, this does handle wide and invisible characters."
9403 (if (string-match "^[ \t]*|-" s)
9404 ;; It's a hline, just map the characters
9405 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9406 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9407 (setq s (replace-match
9408 (concat "|" (make-string (org-string-width (match-string 1 s))
9409 ?\ ) "|")
9410 t t s)))
9413 (defun org-table-kill-row ()
9414 "Delete the current row or horizontal line from the table."
9415 (interactive)
9416 (if (not (org-at-table-p))
9417 (error "Not at a table"))
9418 (let ((col (current-column))
9419 (dline (org-table-current-dline)))
9420 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9421 (if (not (org-at-table-p)) (beginning-of-line 0))
9422 (move-to-column col)
9423 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9424 dline -1 dline)))
9426 (defun org-table-sort-lines (with-case &optional sorting-type)
9427 "Sort table lines according to the column at point.
9429 The position of point indicates the column to be used for
9430 sorting, and the range of lines is the range between the nearest
9431 horizontal separator lines, or the entire table of no such lines
9432 exist. If point is before the first column, you will be prompted
9433 for the sorting column. If there is an active region, the mark
9434 specifies the first line and the sorting column, while point
9435 should be in the last line to be included into the sorting.
9437 The command then prompts for the sorting type which can be
9438 alphabetically, numerically, or by time (as given in a time stamp
9439 in the field). Sorting in reverse order is also possible.
9441 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9443 If SORTING-TYPE is specified when this function is called from a Lisp
9444 program, no prompting will take place. SORTING-TYPE must be a character,
9445 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9446 should be done in reverse order."
9447 (interactive "P")
9448 (let* ((thisline (org-current-line))
9449 (thiscol (org-table-current-column))
9450 beg end bcol ecol tend tbeg column lns pos)
9451 (when (equal thiscol 0)
9452 (if (interactive-p)
9453 (setq thiscol
9454 (string-to-number
9455 (read-string "Use column N for sorting: ")))
9456 (setq thiscol 1))
9457 (org-table-goto-column thiscol))
9458 (org-table-check-inside-data-field)
9459 (if (org-region-active-p)
9460 (progn
9461 (setq beg (region-beginning) end (region-end))
9462 (goto-char beg)
9463 (setq column (org-table-current-column)
9464 beg (point-at-bol))
9465 (goto-char end)
9466 (setq end (point-at-bol 2)))
9467 (setq column (org-table-current-column)
9468 pos (point)
9469 tbeg (org-table-begin)
9470 tend (org-table-end))
9471 (if (re-search-backward org-table-hline-regexp tbeg t)
9472 (setq beg (point-at-bol 2))
9473 (goto-char tbeg)
9474 (setq beg (point-at-bol 1)))
9475 (goto-char pos)
9476 (if (re-search-forward org-table-hline-regexp tend t)
9477 (setq end (point-at-bol 1))
9478 (goto-char tend)
9479 (setq end (point-at-bol))))
9480 (setq beg (move-marker (make-marker) beg)
9481 end (move-marker (make-marker) end))
9482 (untabify beg end)
9483 (goto-char beg)
9484 (org-table-goto-column column)
9485 (skip-chars-backward "^|")
9486 (setq bcol (current-column))
9487 (org-table-goto-column (1+ column))
9488 (skip-chars-backward "^|")
9489 (setq ecol (1- (current-column)))
9490 (org-table-goto-column column)
9491 (setq lns (mapcar (lambda(x) (cons
9492 (org-sort-remove-invisible
9493 (nth (1- column)
9494 (org-split-string x "[ \t]*|[ \t]*")))
9496 (org-split-string (buffer-substring beg end) "\n")))
9497 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9498 (delete-region beg end)
9499 (move-marker beg nil)
9500 (move-marker end nil)
9501 (insert (mapconcat 'cdr lns "\n") "\n")
9502 (goto-line thisline)
9503 (org-table-goto-column thiscol)
9504 (message "%d lines sorted, based on column %d" (length lns) column)))
9506 ;; FIXME: maybe we will not need this? Table sorting is broken....
9507 (defun org-sort-remove-invisible (s)
9508 (remove-text-properties 0 (length s) org-rm-props s)
9509 (while (string-match org-bracket-link-regexp s)
9510 (setq s (replace-match (if (match-end 2)
9511 (match-string 3 s)
9512 (match-string 1 s)) t t s)))
9515 (defun org-table-cut-region (beg end)
9516 "Copy region in table to the clipboard and blank all relevant fields."
9517 (interactive "r")
9518 (org-table-copy-region beg end 'cut))
9520 (defun org-table-copy-region (beg end &optional cut)
9521 "Copy rectangular region in table to clipboard.
9522 A special clipboard is used which can only be accessed
9523 with `org-table-paste-rectangle'."
9524 (interactive "rP")
9525 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9526 region cols
9527 (rpl (if cut " " nil)))
9528 (goto-char beg)
9529 (org-table-check-inside-data-field)
9530 (setq l01 (org-current-line)
9531 c01 (org-table-current-column))
9532 (goto-char end)
9533 (org-table-check-inside-data-field)
9534 (setq l02 (org-current-line)
9535 c02 (org-table-current-column))
9536 (setq l1 (min l01 l02) l2 (max l01 l02)
9537 c1 (min c01 c02) c2 (max c01 c02))
9538 (catch 'exit
9539 (while t
9540 (catch 'nextline
9541 (if (> l1 l2) (throw 'exit t))
9542 (goto-line l1)
9543 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9544 (setq cols nil ic1 c1 ic2 c2)
9545 (while (< ic1 (1+ ic2))
9546 (push (org-table-get-field ic1 rpl) cols)
9547 (setq ic1 (1+ ic1)))
9548 (push (nreverse cols) region)
9549 (setq l1 (1+ l1)))))
9550 (setq org-table-clip (nreverse region))
9551 (if cut (org-table-align))
9552 org-table-clip))
9554 (defun org-table-paste-rectangle ()
9555 "Paste a rectangular region into a table.
9556 The upper right corner ends up in the current field. All involved fields
9557 will be overwritten. If the rectangle does not fit into the present table,
9558 the table is enlarged as needed. The process ignores horizontal separator
9559 lines."
9560 (interactive)
9561 (unless (and org-table-clip (listp org-table-clip))
9562 (error "First cut/copy a region to paste!"))
9563 (org-table-check-inside-data-field)
9564 (let* ((clip org-table-clip)
9565 (line (org-current-line))
9566 (col (org-table-current-column))
9567 (org-enable-table-editor t)
9568 (org-table-automatic-realign nil)
9569 c cols field)
9570 (while (setq cols (pop clip))
9571 (while (org-at-table-hline-p) (beginning-of-line 2))
9572 (if (not (org-at-table-p))
9573 (progn (end-of-line 0) (org-table-next-field)))
9574 (setq c col)
9575 (while (setq field (pop cols))
9576 (org-table-goto-column c nil 'force)
9577 (org-table-get-field nil field)
9578 (setq c (1+ c)))
9579 (beginning-of-line 2))
9580 (goto-line line)
9581 (org-table-goto-column col)
9582 (org-table-align)))
9584 (defun org-table-convert ()
9585 "Convert from `org-mode' table to table.el and back.
9586 Obviously, this only works within limits. When an Org-mode table is
9587 converted to table.el, all horizontal separator lines get lost, because
9588 table.el uses these as cell boundaries and has no notion of horizontal lines.
9589 A table.el table can be converted to an Org-mode table only if it does not
9590 do row or column spanning. Multiline cells will become multiple cells.
9591 Beware, Org-mode does not test if the table can be successfully converted - it
9592 blindly applies a recipe that works for simple tables."
9593 (interactive)
9594 (require 'table)
9595 (if (org-at-table.el-p)
9596 ;; convert to Org-mode table
9597 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9598 (end (move-marker (make-marker) (org-table-end t))))
9599 (table-unrecognize-region beg end)
9600 (goto-char beg)
9601 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9602 (replace-match ""))
9603 (goto-char beg))
9604 (if (org-at-table-p)
9605 ;; convert to table.el table
9606 (let ((beg (move-marker (make-marker) (org-table-begin)))
9607 (end (move-marker (make-marker) (org-table-end))))
9608 ;; first, get rid of all horizontal lines
9609 (goto-char beg)
9610 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9611 (replace-match ""))
9612 ;; insert a hline before first
9613 (goto-char beg)
9614 (org-table-insert-hline 'above)
9615 (beginning-of-line -1)
9616 ;; insert a hline after each line
9617 (while (progn (beginning-of-line 3) (< (point) end))
9618 (org-table-insert-hline))
9619 (goto-char beg)
9620 (setq end (move-marker end (org-table-end)))
9621 ;; replace "+" at beginning and ending of hlines
9622 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9623 (replace-match "\\1+-"))
9624 (goto-char beg)
9625 (while (re-search-forward "-|[ \t]*$" end t)
9626 (replace-match "-+"))
9627 (goto-char beg)))))
9629 (defun org-table-wrap-region (arg)
9630 "Wrap several fields in a column like a paragraph.
9631 This is useful if you'd like to spread the contents of a field over several
9632 lines, in order to keep the table compact.
9634 If there is an active region, and both point and mark are in the same column,
9635 the text in the column is wrapped to minimum width for the given number of
9636 lines. Generally, this makes the table more compact. A prefix ARG may be
9637 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9638 formats the selected text to two lines. If the region was longer than two
9639 lines, the remaining lines remain empty. A negative prefix argument reduces
9640 the current number of lines by that amount. The wrapped text is pasted back
9641 into the table. If you formatted it to more lines than it was before, fields
9642 further down in the table get overwritten - so you might need to make space in
9643 the table first.
9645 If there is no region, the current field is split at the cursor position and
9646 the text fragment to the right of the cursor is prepended to the field one
9647 line down.
9649 If there is no region, but you specify a prefix ARG, the current field gets
9650 blank, and the content is appended to the field above."
9651 (interactive "P")
9652 (org-table-check-inside-data-field)
9653 (if (org-region-active-p)
9654 ;; There is a region: fill as a paragraph
9655 (let* ((beg (region-beginning))
9656 (cline (save-excursion (goto-char beg) (org-current-line)))
9657 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9658 nlines)
9659 (org-table-cut-region (region-beginning) (region-end))
9660 (if (> (length (car org-table-clip)) 1)
9661 (error "Region must be limited to single column"))
9662 (setq nlines (if arg
9663 (if (< arg 1)
9664 (+ (length org-table-clip) arg)
9665 arg)
9666 (length org-table-clip)))
9667 (setq org-table-clip
9668 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9669 nil nlines)))
9670 (goto-line cline)
9671 (org-table-goto-column ccol)
9672 (org-table-paste-rectangle))
9673 ;; No region, split the current field at point
9674 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
9675 (skip-chars-forward "^\r\n|"))
9676 (if arg
9677 ;; combine with field above
9678 (let ((s (org-table-blank-field))
9679 (col (org-table-current-column)))
9680 (beginning-of-line 0)
9681 (while (org-at-table-hline-p) (beginning-of-line 0))
9682 (org-table-goto-column col)
9683 (skip-chars-forward "^|")
9684 (skip-chars-backward " ")
9685 (insert " " (org-trim s))
9686 (org-table-align))
9687 ;; split field
9688 (if (looking-at "\\([^|]+\\)+|")
9689 (let ((s (match-string 1)))
9690 (replace-match " |")
9691 (goto-char (match-beginning 0))
9692 (org-table-next-row)
9693 (insert (org-trim s) " ")
9694 (org-table-align))
9695 (org-table-next-row)))))
9697 (defvar org-field-marker nil)
9699 (defun org-table-edit-field (arg)
9700 "Edit table field in a different window.
9701 This is mainly useful for fields that contain hidden parts.
9702 When called with a \\[universal-argument] prefix, just make the full field visible so that
9703 it can be edited in place."
9704 (interactive "P")
9705 (if arg
9706 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9707 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9708 (remove-text-properties b e '(org-cwidth t invisible t
9709 display t intangible t))
9710 (if (and (boundp 'font-lock-mode) font-lock-mode)
9711 (font-lock-fontify-block)))
9712 (let ((pos (move-marker (make-marker) (point)))
9713 (field (org-table-get-field))
9714 (cw (current-window-configuration))
9716 (org-switch-to-buffer-other-window "*Org tmp*")
9717 (erase-buffer)
9718 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9719 (let ((org-inhibit-startup t)) (org-mode))
9720 (goto-char (setq p (point-max)))
9721 (insert (org-trim field))
9722 (remove-text-properties p (point-max)
9723 '(invisible t org-cwidth t display t
9724 intangible t))
9725 (goto-char p)
9726 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9727 (org-set-local 'org-window-configuration cw)
9728 (org-set-local 'org-field-marker pos)
9729 (message "Edit and finish with C-c C-c"))))
9731 (defun org-table-finish-edit-field ()
9732 "Finish editing a table data field.
9733 Remove all newline characters, insert the result into the table, realign
9734 the table and kill the editing buffer."
9735 (let ((pos org-field-marker)
9736 (cw org-window-configuration)
9737 (cb (current-buffer))
9738 text)
9739 (goto-char (point-min))
9740 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9741 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9742 (replace-match " "))
9743 (setq text (org-trim (buffer-string)))
9744 (set-window-configuration cw)
9745 (kill-buffer cb)
9746 (select-window (get-buffer-window (marker-buffer pos)))
9747 (goto-char pos)
9748 (move-marker pos nil)
9749 (org-table-check-inside-data-field)
9750 (org-table-get-field nil text)
9751 (org-table-align)
9752 (message "New field value inserted")))
9754 (defun org-trim (s)
9755 "Remove whitespace at beginning and end of string."
9756 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9757 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9760 (defun org-wrap (string &optional width lines)
9761 "Wrap string to either a number of lines, or a width in characters.
9762 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9763 that costs. If there is a word longer than WIDTH, the text is actually
9764 wrapped to the length of that word.
9765 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9766 many lines, whatever width that takes.
9767 The return value is a list of lines, without newlines at the end."
9768 (let* ((words (org-split-string string "[ \t\n]+"))
9769 (maxword (apply 'max (mapcar 'org-string-width words)))
9770 w ll)
9771 (cond (width
9772 (org-do-wrap words (max maxword width)))
9773 (lines
9774 (setq w maxword)
9775 (setq ll (org-do-wrap words maxword))
9776 (if (<= (length ll) lines)
9778 (setq ll words)
9779 (while (> (length ll) lines)
9780 (setq w (1+ w))
9781 (setq ll (org-do-wrap words w)))
9782 ll))
9783 (t (error "Cannot wrap this")))))
9786 (defun org-do-wrap (words width)
9787 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9788 (let (lines line)
9789 (while words
9790 (setq line (pop words))
9791 (while (and words (< (+ (length line) (length (car words))) width))
9792 (setq line (concat line " " (pop words))))
9793 (setq lines (push line lines)))
9794 (nreverse lines)))
9796 (defun org-split-string (string &optional separators)
9797 "Splits STRING into substrings at SEPARATORS.
9798 No empty strings are returned if there are matches at the beginning
9799 and end of string."
9800 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9801 (start 0)
9802 notfirst
9803 (list nil))
9804 (while (and (string-match rexp string
9805 (if (and notfirst
9806 (= start (match-beginning 0))
9807 (< start (length string)))
9808 (1+ start) start))
9809 (< (match-beginning 0) (length string)))
9810 (setq notfirst t)
9811 (or (eq (match-beginning 0) 0)
9812 (and (eq (match-beginning 0) (match-end 0))
9813 (eq (match-beginning 0) start))
9814 (setq list
9815 (cons (substring string start (match-beginning 0))
9816 list)))
9817 (setq start (match-end 0)))
9818 (or (eq start (length string))
9819 (setq list
9820 (cons (substring string start)
9821 list)))
9822 (nreverse list)))
9824 (defun org-table-map-tables (function)
9825 "Apply FUNCTION to the start of all tables in the buffer."
9826 (save-excursion
9827 (save-restriction
9828 (widen)
9829 (goto-char (point-min))
9830 (while (re-search-forward org-table-any-line-regexp nil t)
9831 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9832 (beginning-of-line 1)
9833 (if (looking-at org-table-line-regexp)
9834 (save-excursion (funcall function)))
9835 (re-search-forward org-table-any-border-regexp nil 1))))
9836 (message "Mapping tables: done"))
9838 (defvar org-timecnt) ; dynamically scoped parameter
9840 (defun org-table-sum (&optional beg end nlast)
9841 "Sum numbers in region of current table column.
9842 The result will be displayed in the echo area, and will be available
9843 as kill to be inserted with \\[yank].
9845 If there is an active region, it is interpreted as a rectangle and all
9846 numbers in that rectangle will be summed. If there is no active
9847 region and point is located in a table column, sum all numbers in that
9848 column.
9850 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9851 numbers are assumed to be times as well (in decimal hours) and the
9852 numbers are added as such.
9854 If NLAST is a number, only the NLAST fields will actually be summed."
9855 (interactive)
9856 (save-excursion
9857 (let (col (org-timecnt 0) diff h m s org-table-clip)
9858 (cond
9859 ((and beg end)) ; beg and end given explicitly
9860 ((org-region-active-p)
9861 (setq beg (region-beginning) end (region-end)))
9863 (setq col (org-table-current-column))
9864 (goto-char (org-table-begin))
9865 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9866 (error "No table data"))
9867 (org-table-goto-column col)
9868 (setq beg (point))
9869 (goto-char (org-table-end))
9870 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9871 (error "No table data"))
9872 (org-table-goto-column col)
9873 (setq end (point))))
9874 (let* ((items (apply 'append (org-table-copy-region beg end)))
9875 (items1 (cond ((not nlast) items)
9876 ((>= nlast (length items)) items)
9877 (t (setq items (reverse items))
9878 (setcdr (nthcdr (1- nlast) items) nil)
9879 (nreverse items))))
9880 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9881 items1)))
9882 (res (apply '+ numbers))
9883 (sres (if (= org-timecnt 0)
9884 (format "%g" res)
9885 (setq diff (* 3600 res)
9886 h (floor (/ diff 3600)) diff (mod diff 3600)
9887 m (floor (/ diff 60)) diff (mod diff 60)
9888 s diff)
9889 (format "%d:%02d:%02d" h m s))))
9890 (kill-new sres)
9891 (if (interactive-p)
9892 (message "%s"
9893 (substitute-command-keys
9894 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9895 (length numbers) sres))))
9896 sres))))
9898 (defun org-table-get-number-for-summing (s)
9899 (let (n)
9900 (if (string-match "^ *|? *" s)
9901 (setq s (replace-match "" nil nil s)))
9902 (if (string-match " *|? *$" s)
9903 (setq s (replace-match "" nil nil s)))
9904 (setq n (string-to-number s))
9905 (cond
9906 ((and (string-match "0" s)
9907 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9908 ((string-match "\\`[ \t]+\\'" s) nil)
9909 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9910 (let ((h (string-to-number (or (match-string 1 s) "0")))
9911 (m (string-to-number (or (match-string 2 s) "0")))
9912 (s (string-to-number (or (match-string 4 s) "0"))))
9913 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9914 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9915 ((equal n 0) nil)
9916 (t n))))
9918 (defun org-table-current-field-formula (&optional key noerror)
9919 "Return the formula active for the current field.
9920 Assumes that specials are in place.
9921 If KEY is given, return the key to this formula.
9922 Otherwise return the formula preceeded with \"=\" or \":=\"."
9923 (let* ((name (car (rassoc (list (org-current-line)
9924 (org-table-current-column))
9925 org-table-named-field-locations)))
9926 (col (org-table-current-column))
9927 (scol (int-to-string col))
9928 (ref (format "@%d$%d" (org-table-current-dline) col))
9929 (stored-list (org-table-get-stored-formulas noerror))
9930 (ass (or (assoc name stored-list)
9931 (assoc ref stored-list)
9932 (assoc scol stored-list))))
9933 (if key
9934 (car ass)
9935 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9936 (cdr ass))))))
9938 (defun org-table-get-formula (&optional equation named)
9939 "Read a formula from the minibuffer, offer stored formula as default.
9940 When NAMED is non-nil, look for a named equation."
9941 (let* ((stored-list (org-table-get-stored-formulas))
9942 (name (car (rassoc (list (org-current-line)
9943 (org-table-current-column))
9944 org-table-named-field-locations)))
9945 (ref (format "@%d$%d" (org-table-current-dline)
9946 (org-table-current-column)))
9947 (refass (assoc ref stored-list))
9948 (scol (if named
9949 (if name name ref)
9950 (int-to-string (org-table-current-column))))
9951 (dummy (and (or name refass) (not named)
9952 (not (y-or-n-p "Replace field formula with column formula? " ))
9953 (error "Abort")))
9954 (name (or name ref))
9955 (org-table-may-need-update nil)
9956 (stored (cdr (assoc scol stored-list)))
9957 (eq (cond
9958 ((and stored equation (string-match "^ *=? *$" equation))
9959 stored)
9960 ((stringp equation)
9961 equation)
9962 (t (org-table-formula-from-user
9963 (read-string
9964 (org-table-formula-to-user
9965 (format "%s formula %s%s="
9966 (if named "Field" "Column")
9967 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9968 scol))
9969 (if stored (org-table-formula-to-user stored) "")
9970 'org-table-formula-history
9971 )))))
9972 mustsave)
9973 (when (not (string-match "\\S-" eq))
9974 ;; remove formula
9975 (setq stored-list (delq (assoc scol stored-list) stored-list))
9976 (org-table-store-formulas stored-list)
9977 (error "Formula removed"))
9978 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9979 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9980 (if (and name (not named))
9981 ;; We set the column equation, delete the named one.
9982 (setq stored-list (delq (assoc name stored-list) stored-list)
9983 mustsave t))
9984 (if stored
9985 (setcdr (assoc scol stored-list) eq)
9986 (setq stored-list (cons (cons scol eq) stored-list)))
9987 (if (or mustsave (not (equal stored eq)))
9988 (org-table-store-formulas stored-list))
9989 eq))
9991 (defun org-table-store-formulas (alist)
9992 "Store the list of formulas below the current table."
9993 (setq alist (sort alist 'org-table-formula-less-p))
9994 (save-excursion
9995 (goto-char (org-table-end))
9996 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9997 (progn
9998 ;; don't overwrite TBLFM, we might use text properties to store stuff
9999 (goto-char (match-beginning 2))
10000 (delete-region (match-beginning 2) (match-end 0)))
10001 (insert "#+TBLFM:"))
10002 (insert " "
10003 (mapconcat (lambda (x)
10004 (concat
10005 (if (equal (string-to-char (car x)) ?@) "" "$")
10006 (car x) "=" (cdr x)))
10007 alist "::")
10008 "\n")))
10010 (defsubst org-table-formula-make-cmp-string (a)
10011 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
10012 (concat
10013 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
10014 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
10015 (if (match-end 5) (concat "@@" (match-string 5 a))))))
10017 (defun org-table-formula-less-p (a b)
10018 "Compare two formulas for sorting."
10019 (let ((as (org-table-formula-make-cmp-string (car a)))
10020 (bs (org-table-formula-make-cmp-string (car b))))
10021 (and as bs (string< as bs))))
10023 (defun org-table-get-stored-formulas (&optional noerror)
10024 "Return an alist with the stored formulas directly after current table."
10025 (interactive)
10026 (let (scol eq eq-alist strings string seen)
10027 (save-excursion
10028 (goto-char (org-table-end))
10029 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
10030 (setq strings (org-split-string (match-string 2) " *:: *"))
10031 (while (setq string (pop strings))
10032 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
10033 (setq scol (if (match-end 2)
10034 (match-string 2 string)
10035 (match-string 1 string))
10036 eq (match-string 3 string)
10037 eq-alist (cons (cons scol eq) eq-alist))
10038 (if (member scol seen)
10039 (if noerror
10040 (progn
10041 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
10042 (ding)
10043 (sit-for 2))
10044 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
10045 (push scol seen))))))
10046 (nreverse eq-alist)))
10048 (defun org-table-fix-formulas (key replace &optional limit delta remove)
10049 "Modify the equations after the table structure has been edited.
10050 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
10051 For all numbers larger than LIMIT, shift them by DELTA."
10052 (save-excursion
10053 (goto-char (org-table-end))
10054 (when (looking-at "#\\+TBLFM:")
10055 (let ((re (concat key "\\([0-9]+\\)"))
10056 (re2
10057 (when remove
10058 (if (equal key "$")
10059 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
10060 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
10061 s n a)
10062 (when remove
10063 (while (re-search-forward re2 (point-at-eol) t)
10064 (replace-match "")))
10065 (while (re-search-forward re (point-at-eol) t)
10066 (setq s (match-string 1) n (string-to-number s))
10067 (cond
10068 ((setq a (assoc s replace))
10069 (replace-match (concat key (cdr a)) t t))
10070 ((and limit (> n limit))
10071 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
10073 (defun org-table-get-specials ()
10074 "Get the column names and local parameters for this table."
10075 (save-excursion
10076 (let ((beg (org-table-begin)) (end (org-table-end))
10077 names name fields fields1 field cnt
10078 c v l line col types dlines hlines)
10079 (setq org-table-column-names nil
10080 org-table-local-parameters nil
10081 org-table-named-field-locations nil
10082 org-table-current-begin-line nil
10083 org-table-current-begin-pos nil
10084 org-table-current-line-types nil)
10085 (goto-char beg)
10086 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
10087 (setq names (org-split-string (match-string 1) " *| *")
10088 cnt 1)
10089 (while (setq name (pop names))
10090 (setq cnt (1+ cnt))
10091 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
10092 (push (cons name (int-to-string cnt)) org-table-column-names))))
10093 (setq org-table-column-names (nreverse org-table-column-names))
10094 (setq org-table-column-name-regexp
10095 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
10096 (goto-char beg)
10097 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
10098 (setq fields (org-split-string (match-string 1) " *| *"))
10099 (while (setq field (pop fields))
10100 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
10101 (push (cons (match-string 1 field) (match-string 2 field))
10102 org-table-local-parameters))))
10103 (goto-char beg)
10104 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10105 (setq c (match-string 1)
10106 fields (org-split-string (match-string 2) " *| *"))
10107 (save-excursion
10108 (beginning-of-line (if (equal c "_") 2 0))
10109 (setq line (org-current-line) col 1)
10110 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10111 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10112 (while (and fields1 (setq field (pop fields)))
10113 (setq v (pop fields1) col (1+ col))
10114 (when (and (stringp field) (stringp v)
10115 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10116 (push (cons field v) org-table-local-parameters)
10117 (push (list field line col) org-table-named-field-locations))))
10118 ;; Analyse the line types
10119 (goto-char beg)
10120 (setq org-table-current-begin-line (org-current-line)
10121 org-table-current-begin-pos (point)
10122 l org-table-current-begin-line)
10123 (while (looking-at "[ \t]*|\\(-\\)?")
10124 (push (if (match-end 1) 'hline 'dline) types)
10125 (if (match-end 1) (push l hlines) (push l dlines))
10126 (beginning-of-line 2)
10127 (setq l (1+ l)))
10128 (setq org-table-current-line-types (apply 'vector (nreverse types))
10129 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
10130 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
10132 (defun org-table-maybe-eval-formula ()
10133 "Check if the current field starts with \"=\" or \":=\".
10134 If yes, store the formula and apply it."
10135 ;; We already know we are in a table. Get field will only return a formula
10136 ;; when appropriate. It might return a separator line, but no problem.
10137 (when org-table-formula-evaluate-inline
10138 (let* ((field (org-trim (or (org-table-get-field) "")))
10139 named eq)
10140 (when (string-match "^:?=\\(.*\\)" field)
10141 (setq named (equal (string-to-char field) ?:)
10142 eq (match-string 1 field))
10143 (if (or (fboundp 'calc-eval)
10144 (equal (substring eq 0 (min 2 (length eq))) "'("))
10145 (org-table-eval-formula (if named '(4) nil)
10146 (org-table-formula-from-user eq))
10147 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
10149 (defvar org-recalc-commands nil
10150 "List of commands triggering the recalculation of a line.
10151 Will be filled automatically during use.")
10153 (defvar org-recalc-marks
10154 '((" " . "Unmarked: no special line, no automatic recalculation")
10155 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10156 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10157 ("!" . "Column name definition line. Reference in formula as $name.")
10158 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10159 ("_" . "Names for values in row below this one.")
10160 ("^" . "Names for values in row above this one.")))
10162 (defun org-table-rotate-recalc-marks (&optional newchar)
10163 "Rotate the recalculation mark in the first column.
10164 If in any row, the first field is not consistent with a mark,
10165 insert a new column for the markers.
10166 When there is an active region, change all the lines in the region,
10167 after prompting for the marking character.
10168 After each change, a message will be displayed indicating the meaning
10169 of the new mark."
10170 (interactive)
10171 (unless (org-at-table-p) (error "Not at a table"))
10172 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10173 (beg (org-table-begin))
10174 (end (org-table-end))
10175 (l (org-current-line))
10176 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10177 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10178 (have-col
10179 (save-excursion
10180 (goto-char beg)
10181 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10182 (col (org-table-current-column))
10183 (forcenew (car (assoc newchar org-recalc-marks)))
10184 epos new)
10185 (when l1
10186 (message "Change region to what mark? Type # * ! $ or SPC: ")
10187 (setq newchar (char-to-string (read-char-exclusive))
10188 forcenew (car (assoc newchar org-recalc-marks))))
10189 (if (and newchar (not forcenew))
10190 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10191 newchar))
10192 (if l1 (goto-line l1))
10193 (save-excursion
10194 (beginning-of-line 1)
10195 (unless (looking-at org-table-dataline-regexp)
10196 (error "Not at a table data line")))
10197 (unless have-col
10198 (org-table-goto-column 1)
10199 (org-table-insert-column)
10200 (org-table-goto-column (1+ col)))
10201 (setq epos (point-at-eol))
10202 (save-excursion
10203 (beginning-of-line 1)
10204 (org-table-get-field
10205 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10206 (concat " "
10207 (setq new (or forcenew
10208 (cadr (member (match-string 1) marks))))
10209 " ")
10210 " # ")))
10211 (if (and l1 l2)
10212 (progn
10213 (goto-line l1)
10214 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10215 (and (looking-at org-table-dataline-regexp)
10216 (org-table-get-field 1 (concat " " new " "))))
10217 (goto-line l1)))
10218 (if (not (= epos (point-at-eol))) (org-table-align))
10219 (goto-line l)
10220 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
10222 (defun org-table-maybe-recalculate-line ()
10223 "Recompute the current line if marked for it, and if we haven't just done it."
10224 (interactive)
10225 (and org-table-allow-automatic-line-recalculation
10226 (not (and (memq last-command org-recalc-commands)
10227 (equal org-last-recalc-line (org-current-line))))
10228 (save-excursion (beginning-of-line 1)
10229 (looking-at org-table-auto-recalculate-regexp))
10230 (org-table-recalculate) t))
10232 (defvar org-table-formula-debug nil
10233 "Non-nil means, debug table formulas.
10234 When nil, simply write \"#ERROR\" in corrupted fields.")
10235 (make-variable-buffer-local 'org-table-formula-debug)
10237 (defvar modes)
10238 (defsubst org-set-calc-mode (var &optional value)
10239 (if (stringp var)
10240 (setq var (assoc var '(("D" calc-angle-mode deg)
10241 ("R" calc-angle-mode rad)
10242 ("F" calc-prefer-frac t)
10243 ("S" calc-symbolic-mode t)))
10244 value (nth 2 var) var (nth 1 var)))
10245 (if (memq var modes)
10246 (setcar (cdr (memq var modes)) value)
10247 (cons var (cons value modes)))
10248 modes)
10250 (defun org-table-eval-formula (&optional arg equation
10251 suppress-align suppress-const
10252 suppress-store suppress-analysis)
10253 "Replace the table field value at the cursor by the result of a calculation.
10255 This function makes use of Dave Gillespie's Calc package, in my view the
10256 most exciting program ever written for GNU Emacs. So you need to have Calc
10257 installed in order to use this function.
10259 In a table, this command replaces the value in the current field with the
10260 result of a formula. It also installs the formula as the \"current\" column
10261 formula, by storing it in a special line below the table. When called
10262 with a `C-u' prefix, the current field must ba a named field, and the
10263 formula is installed as valid in only this specific field.
10265 When called with two `C-u' prefixes, insert the active equation
10266 for the field back into the current field, so that it can be
10267 edited there. This is useful in order to use \\[org-table-show-reference]
10268 to check the referenced fields.
10270 When called, the command first prompts for a formula, which is read in
10271 the minibuffer. Previously entered formulas are available through the
10272 history list, and the last used formula is offered as a default.
10273 These stored formulas are adapted correctly when moving, inserting, or
10274 deleting columns with the corresponding commands.
10276 The formula can be any algebraic expression understood by the Calc package.
10277 For details, see the Org-mode manual.
10279 This function can also be called from Lisp programs and offers
10280 additional arguments: EQUATION can be the formula to apply. If this
10281 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10282 used to speed-up recursive calls by by-passing unnecessary aligns.
10283 SUPPRESS-CONST suppresses the interpretation of constants in the
10284 formula, assuming that this has been done already outside the function.
10285 SUPPRESS-STORE means the formula should not be stored, either because
10286 it is already stored, or because it is a modified equation that should
10287 not overwrite the stored one."
10288 (interactive "P")
10289 (org-table-check-inside-data-field)
10290 (or suppress-analysis (org-table-get-specials))
10291 (if (equal arg '(16))
10292 (let ((eq (org-table-current-field-formula)))
10293 (or eq (error "No equation active for current field"))
10294 (org-table-get-field nil eq)
10295 (org-table-align)
10296 (setq org-table-may-need-update t))
10297 (let* (fields
10298 (ndown (if (integerp arg) arg 1))
10299 (org-table-automatic-realign nil)
10300 (case-fold-search nil)
10301 (down (> ndown 1))
10302 (formula (if (and equation suppress-store)
10303 equation
10304 (org-table-get-formula equation (equal arg '(4)))))
10305 (n0 (org-table-current-column))
10306 (modes (copy-sequence org-calc-default-modes))
10307 (numbers nil) ; was a variable, now fixed default
10308 (keep-empty nil)
10309 n form form0 bw fmt x ev orig c lispp literal)
10310 ;; Parse the format string. Since we have a lot of modes, this is
10311 ;; a lot of work. However, I think calc still uses most of the time.
10312 (if (string-match ";" formula)
10313 (let ((tmp (org-split-string formula ";")))
10314 (setq formula (car tmp)
10315 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10316 (nth 1 tmp)))
10317 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10318 (setq c (string-to-char (match-string 1 fmt))
10319 n (string-to-number (match-string 2 fmt)))
10320 (if (= c ?p)
10321 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10322 (setq modes (org-set-calc-mode
10323 'calc-float-format
10324 (list (cdr (assoc c '((?n . float) (?f . fix)
10325 (?s . sci) (?e . eng))))
10326 n))))
10327 (setq fmt (replace-match "" t t fmt)))
10328 (if (string-match "[NT]" fmt)
10329 (setq numbers (equal (match-string 0 fmt) "N")
10330 fmt (replace-match "" t t fmt)))
10331 (if (string-match "L" fmt)
10332 (setq literal t
10333 fmt (replace-match "" t t fmt)))
10334 (if (string-match "E" fmt)
10335 (setq keep-empty t
10336 fmt (replace-match "" t t fmt)))
10337 (while (string-match "[DRFS]" fmt)
10338 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10339 (setq fmt (replace-match "" t t fmt)))
10340 (unless (string-match "\\S-" fmt)
10341 (setq fmt nil))))
10342 (if (and (not suppress-const) org-table-formula-use-constants)
10343 (setq formula (org-table-formula-substitute-names formula)))
10344 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10345 (while (> ndown 0)
10346 (setq fields (org-split-string
10347 (org-no-properties
10348 (buffer-substring (point-at-bol) (point-at-eol)))
10349 " *| *"))
10350 (if (eq numbers t)
10351 (setq fields (mapcar
10352 (lambda (x) (number-to-string (string-to-number x)))
10353 fields)))
10354 (setq ndown (1- ndown))
10355 (setq form (copy-sequence formula)
10356 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10357 (if (and lispp literal) (setq lispp 'literal))
10358 ;; Check for old vertical references
10359 (setq form (org-rewrite-old-row-references form))
10360 ;; Insert complex ranges
10361 (while (string-match org-table-range-regexp form)
10362 (setq form
10363 (replace-match
10364 (save-match-data
10365 (org-table-make-reference
10366 (org-table-get-range (match-string 0 form) nil n0)
10367 keep-empty numbers lispp))
10368 t t form)))
10369 ;; Insert simple ranges
10370 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10371 (setq form
10372 (replace-match
10373 (save-match-data
10374 (org-table-make-reference
10375 (org-sublist
10376 fields (string-to-number (match-string 1 form))
10377 (string-to-number (match-string 2 form)))
10378 keep-empty numbers lispp))
10379 t t form)))
10380 (setq form0 form)
10381 ;; Insert the references to fields in same row
10382 (while (string-match "\\$\\([0-9]+\\)" form)
10383 (setq n (string-to-number (match-string 1 form))
10384 x (nth (1- (if (= n 0) n0 n)) fields))
10385 (unless x (error "Invalid field specifier \"%s\""
10386 (match-string 0 form)))
10387 (setq form (replace-match
10388 (save-match-data
10389 (org-table-make-reference x nil numbers lispp))
10390 t t form)))
10392 (if lispp
10393 (setq ev (condition-case nil
10394 (eval (eval (read form)))
10395 (error "#ERROR"))
10396 ev (if (numberp ev) (number-to-string ev) ev))
10397 (or (fboundp 'calc-eval)
10398 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10399 (setq ev (calc-eval (cons form modes)
10400 (if numbers 'num))))
10402 (when org-table-formula-debug
10403 (with-output-to-temp-buffer "*Substitution History*"
10404 (princ (format "Substitution history of formula
10405 Orig: %s
10406 $xyz-> %s
10407 @r$c-> %s
10408 $1-> %s\n" orig formula form0 form))
10409 (if (listp ev)
10410 (princ (format " %s^\nError: %s"
10411 (make-string (car ev) ?\-) (nth 1 ev)))
10412 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10413 ev (or fmt "NONE")
10414 (if fmt (format fmt (string-to-number ev)) ev)))))
10415 (setq bw (get-buffer-window "*Substitution History*"))
10416 (shrink-window-if-larger-than-buffer bw)
10417 (unless (and (interactive-p) (not ndown))
10418 (unless (let (inhibit-redisplay)
10419 (y-or-n-p "Debugging Formula. Continue to next? "))
10420 (org-table-align)
10421 (error "Abort"))
10422 (delete-window bw)
10423 (message "")))
10424 (if (listp ev) (setq fmt nil ev "#ERROR"))
10425 (org-table-justify-field-maybe
10426 (if fmt (format fmt (string-to-number ev)) ev))
10427 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10428 (call-interactively 'org-return)
10429 (setq ndown 0)))
10430 (and down (org-table-maybe-recalculate-line))
10431 (or suppress-align (and org-table-may-need-update
10432 (org-table-align))))))
10434 (defun org-table-put-field-property (prop value)
10435 (save-excursion
10436 (put-text-property (progn (skip-chars-backward "^|") (point))
10437 (progn (skip-chars-forward "^|") (point))
10438 prop value)))
10440 (defun org-table-get-range (desc &optional tbeg col highlight)
10441 "Get a calc vector from a column, accorting to descriptor DESC.
10442 Optional arguments TBEG and COL can give the beginning of the table and
10443 the current column, to avoid unnecessary parsing.
10444 HIGHLIGHT means, just highlight the range."
10445 (if (not (equal (string-to-char desc) ?@))
10446 (setq desc (concat "@" desc)))
10447 (save-excursion
10448 (or tbeg (setq tbeg (org-table-begin)))
10449 (or col (setq col (org-table-current-column)))
10450 (let ((thisline (org-current-line))
10451 beg end c1 c2 r1 r2 rangep tmp)
10452 (unless (string-match org-table-range-regexp desc)
10453 (error "Invalid table range specifier `%s'" desc))
10454 (setq rangep (match-end 3)
10455 r1 (and (match-end 1) (match-string 1 desc))
10456 r2 (and (match-end 4) (match-string 4 desc))
10457 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10458 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10460 (and c1 (setq c1 (+ (string-to-number c1)
10461 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10462 (and c2 (setq c2 (+ (string-to-number c2)
10463 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10464 (if (equal r1 "") (setq r1 nil))
10465 (if (equal r2 "") (setq r2 nil))
10466 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10467 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10468 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10469 (if (not r1) (setq r1 thisline))
10470 (if (not r2) (setq r2 thisline))
10471 (if (not c1) (setq c1 col))
10472 (if (not c2) (setq c2 col))
10473 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10474 ;; just one field
10475 (progn
10476 (goto-line r1)
10477 (while (not (looking-at org-table-dataline-regexp))
10478 (beginning-of-line 2))
10479 (prog1 (org-trim (org-table-get-field c1))
10480 (if highlight (org-table-highlight-rectangle (point) (point)))))
10481 ;; A range, return a vector
10482 ;; First sort the numbers to get a regular ractangle
10483 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10484 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10485 (goto-line r1)
10486 (while (not (looking-at org-table-dataline-regexp))
10487 (beginning-of-line 2))
10488 (org-table-goto-column c1)
10489 (setq beg (point))
10490 (goto-line r2)
10491 (while (not (looking-at org-table-dataline-regexp))
10492 (beginning-of-line 0))
10493 (org-table-goto-column c2)
10494 (setq end (point))
10495 (if highlight
10496 (org-table-highlight-rectangle
10497 beg (progn (skip-chars-forward "^|\n") (point))))
10498 ;; return string representation of calc vector
10499 (mapcar 'org-trim
10500 (apply 'append (org-table-copy-region beg end)))))))
10502 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10503 "Analyze descriptor DESC and retrieve the corresponding line number.
10504 The cursor is currently in line CLINE, the table begins in line BLINE,
10505 and TABLE is a vector with line types."
10506 (if (string-match "^[0-9]+$" desc)
10507 (aref org-table-dlines (string-to-number desc))
10508 (setq cline (or cline (org-current-line))
10509 bline (or bline org-table-current-begin-line)
10510 table (or table org-table-current-line-types))
10511 (if (or
10512 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10513 ;; 1 2 3 4 5 6
10514 (and (not (match-end 3)) (not (match-end 6)))
10515 (and (match-end 3) (match-end 6) (not (match-end 5))))
10516 (error "invalid row descriptor `%s'" desc))
10517 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10518 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10519 (odir (and (match-end 5) (match-string 5 desc)))
10520 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10521 (i (- cline bline))
10522 (rel (and (match-end 6)
10523 (or (and (match-end 1) (not (match-end 3)))
10524 (match-end 5)))))
10525 (if (and hn (not hdir))
10526 (progn
10527 (setq i 0 hdir "+")
10528 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10529 (if (and (not hn) on (not odir))
10530 (error "should never happen");;(aref org-table-dlines on)
10531 (if (and hn (> hn 0))
10532 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10533 (if on
10534 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10535 (+ bline i)))))
10537 (defun org-find-row-type (table i type backwards relative n)
10538 (let ((l (length table)))
10539 (while (> n 0)
10540 (while (and (setq i (+ i (if backwards -1 1)))
10541 (>= i 0) (< i l)
10542 (not (eq (aref table i) type))
10543 (if (and relative (eq (aref table i) 'hline))
10544 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10545 t)))
10546 (setq n (1- n)))
10547 (if (or (< i 0) (>= i l))
10548 (error "Row descriptor leads outside table")
10549 i)))
10551 (defun org-rewrite-old-row-references (s)
10552 (if (string-match "&[-+0-9I]" s)
10553 (error "Formula contains old &row reference, please rewrite using @-syntax")
10556 (defun org-table-make-reference (elements keep-empty numbers lispp)
10557 "Convert list ELEMENTS to something appropriate to insert into formula.
10558 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10559 NUMBERS indicates that everything should be converted to numbers.
10560 LISPP means to return something appropriate for a Lisp list."
10561 (if (stringp elements) ; just a single val
10562 (if lispp
10563 (if (eq lispp 'literal)
10564 elements
10565 (prin1-to-string (if numbers (string-to-number elements) elements)))
10566 (if (equal elements "") (setq elements "0"))
10567 (if numbers (number-to-string (string-to-number elements)) elements))
10568 (unless keep-empty
10569 (setq elements
10570 (delq nil
10571 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10572 elements))))
10573 (setq elements (or elements '("0")))
10574 (if lispp
10575 (mapconcat
10576 (lambda (x)
10577 (if (eq lispp 'literal)
10579 (prin1-to-string (if numbers (string-to-number x) x))))
10580 elements " ")
10581 (concat "[" (mapconcat
10582 (lambda (x)
10583 (if numbers (number-to-string (string-to-number x)) x))
10584 elements
10585 ",") "]"))))
10587 (defun org-table-recalculate (&optional all noalign)
10588 "Recalculate the current table line by applying all stored formulas.
10589 With prefix arg ALL, do this for all lines in the table."
10590 (interactive "P")
10591 (or (memq this-command org-recalc-commands)
10592 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10593 (unless (org-at-table-p) (error "Not at a table"))
10594 (if (equal all '(16))
10595 (org-table-iterate)
10596 (org-table-get-specials)
10597 (let* ((eqlist (sort (org-table-get-stored-formulas)
10598 (lambda (a b) (string< (car a) (car b)))))
10599 (inhibit-redisplay (not debug-on-error))
10600 (line-re org-table-dataline-regexp)
10601 (thisline (org-current-line))
10602 (thiscol (org-table-current-column))
10603 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10604 ;; Insert constants in all formulas
10605 (setq eqlist
10606 (mapcar (lambda (x)
10607 (setcdr x (org-table-formula-substitute-names (cdr x)))
10609 eqlist))
10610 ;; Split the equation list
10611 (while (setq eq (pop eqlist))
10612 (if (<= (string-to-char (car eq)) ?9)
10613 (push eq eqlnum)
10614 (push eq eqlname)))
10615 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10616 (if all
10617 (progn
10618 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10619 (goto-char (setq beg (org-table-begin)))
10620 (if (re-search-forward org-table-calculate-mark-regexp end t)
10621 ;; This is a table with marked lines, compute selected lines
10622 (setq line-re org-table-recalculate-regexp)
10623 ;; Move forward to the first non-header line
10624 (if (and (re-search-forward org-table-dataline-regexp end t)
10625 (re-search-forward org-table-hline-regexp end t)
10626 (re-search-forward org-table-dataline-regexp end t))
10627 (setq beg (match-beginning 0))
10628 nil))) ;; just leave beg where it is
10629 (setq beg (point-at-bol)
10630 end (move-marker (make-marker) (1+ (point-at-eol)))))
10631 (goto-char beg)
10632 (and all (message "Re-applying formulas to full table..."))
10634 ;; First find the named fields, and mark them untouchanble
10635 (remove-text-properties beg end '(org-untouchable t))
10636 (while (setq eq (pop eqlname))
10637 (setq name (car eq)
10638 a (assoc name org-table-named-field-locations))
10639 (and (not a)
10640 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10641 (setq a (list name
10642 (aref org-table-dlines
10643 (string-to-number (match-string 1 name)))
10644 (string-to-number (match-string 2 name)))))
10645 (when (and a (or all (equal (nth 1 a) thisline)))
10646 (message "Re-applying formula to field: %s" name)
10647 (goto-line (nth 1 a))
10648 (org-table-goto-column (nth 2 a))
10649 (push (append a (list (cdr eq))) eqlname1)
10650 (org-table-put-field-property :org-untouchable t)))
10652 ;; Now evauluate the column formulas, but skip fields covered by
10653 ;; field formulas
10654 (goto-char beg)
10655 (while (re-search-forward line-re end t)
10656 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10657 ;; Unprotected line, recalculate
10658 (and all (message "Re-applying formulas to full table...(line %d)"
10659 (setq cnt (1+ cnt))))
10660 (setq org-last-recalc-line (org-current-line))
10661 (setq eql eqlnum)
10662 (while (setq entry (pop eql))
10663 (goto-line org-last-recalc-line)
10664 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10665 (unless (get-text-property (point) :org-untouchable)
10666 (org-table-eval-formula nil (cdr entry)
10667 'noalign 'nocst 'nostore 'noanalysis)))))
10669 ;; Now evaluate the field formulas
10670 (while (setq eq (pop eqlname1))
10671 (message "Re-applying formula to field: %s" (car eq))
10672 (goto-line (nth 1 eq))
10673 (org-table-goto-column (nth 2 eq))
10674 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10675 'nostore 'noanalysis))
10677 (goto-line thisline)
10678 (org-table-goto-column thiscol)
10679 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10680 (or noalign (and org-table-may-need-update (org-table-align))
10681 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10683 ;; back to initial position
10684 (message "Re-applying formulas...done")
10685 (goto-line thisline)
10686 (org-table-goto-column thiscol)
10687 (or noalign (and org-table-may-need-update (org-table-align))
10688 (and all (message "Re-applying formulas...done"))))))
10690 (defun org-table-iterate (&optional arg)
10691 "Recalculate the table until it does not change anymore."
10692 (interactive "P")
10693 (let ((imax (if arg (prefix-numeric-value arg) 10))
10694 (i 0)
10695 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10696 thistbl)
10697 (catch 'exit
10698 (while (< i imax)
10699 (setq i (1+ i))
10700 (org-table-recalculate 'all)
10701 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10702 (if (not (string= lasttbl thistbl))
10703 (setq lasttbl thistbl)
10704 (if (> i 1)
10705 (message "Convergence after %d iterations" i)
10706 (message "Table was already stable"))
10707 (throw 'exit t)))
10708 (error "No convergence after %d iterations" i))))
10710 (defun org-table-formula-substitute-names (f)
10711 "Replace $const with values in string F."
10712 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10713 ;; First, check for column names
10714 (while (setq start (string-match org-table-column-name-regexp f start))
10715 (setq start (1+ start))
10716 (setq a (assoc (match-string 1 f) org-table-column-names))
10717 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10718 ;; Parameters and constants
10719 (setq start 0)
10720 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10721 (setq start (1+ start))
10722 (if (setq a (save-match-data
10723 (org-table-get-constant (match-string 1 f))))
10724 (setq f (replace-match
10725 (concat (if pp "(") a (if pp ")")) t t f))))
10726 (if org-table-formula-debug
10727 (put-text-property 0 (length f) :orig-formula f1 f))
10730 (defun org-table-get-constant (const)
10731 "Find the value for a parameter or constant in a formula.
10732 Parameters get priority."
10733 (or (cdr (assoc const org-table-local-parameters))
10734 (cdr (assoc const org-table-formula-constants-local))
10735 (cdr (assoc const org-table-formula-constants))
10736 (and (fboundp 'constants-get) (constants-get const))
10737 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10738 (org-entry-get nil (substring const 5) 'inherit))
10739 "#UNDEFINED_NAME"))
10741 (defvar org-table-fedit-map
10742 (let ((map (make-sparse-keymap)))
10743 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10744 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10745 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10746 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10747 (org-defkey map "\C-c?" 'org-table-show-reference)
10748 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10749 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10750 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10751 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10752 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10753 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10754 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10755 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10756 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10757 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10758 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10759 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10760 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10761 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10762 map))
10764 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10765 '("Edit-Formulas"
10766 ["Finish and Install" org-table-fedit-finish t]
10767 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10768 ["Abort" org-table-fedit-abort t]
10769 "--"
10770 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10771 ["Complete Lisp Symbol" lisp-complete-symbol t]
10772 "--"
10773 "Shift Reference at Point"
10774 ["Up" org-table-fedit-ref-up t]
10775 ["Down" org-table-fedit-ref-down t]
10776 ["Left" org-table-fedit-ref-left t]
10777 ["Right" org-table-fedit-ref-right t]
10779 "Change Test Row for Column Formulas"
10780 ["Up" org-table-fedit-line-up t]
10781 ["Down" org-table-fedit-line-down t]
10782 "--"
10783 ["Scroll Table Window" org-table-fedit-scroll t]
10784 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10785 ["Show Table Grid" org-table-fedit-toggle-coordinates
10786 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10787 org-table-overlay-coordinates)]
10788 "--"
10789 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10790 :style toggle :selected org-table-buffer-is-an]))
10792 (defvar org-pos)
10794 (defun org-table-edit-formulas ()
10795 "Edit the formulas of the current table in a separate buffer."
10796 (interactive)
10797 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10798 (beginning-of-line 0))
10799 (unless (org-at-table-p) (error "Not at a table"))
10800 (org-table-get-specials)
10801 (let ((key (org-table-current-field-formula 'key 'noerror))
10802 (eql (sort (org-table-get-stored-formulas 'noerror)
10803 'org-table-formula-less-p))
10804 (pos (move-marker (make-marker) (point)))
10805 (startline 1)
10806 (wc (current-window-configuration))
10807 (titles '((column . "# Column Formulas\n")
10808 (field . "# Field Formulas\n")
10809 (named . "# Named Field Formulas\n")))
10810 entry s type title)
10811 (org-switch-to-buffer-other-window "*Edit Formulas*")
10812 (erase-buffer)
10813 ;; Keep global-font-lock-mode from turning on font-lock-mode
10814 (let ((font-lock-global-modes '(not fundamental-mode)))
10815 (fundamental-mode))
10816 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10817 (org-set-local 'org-pos pos)
10818 (org-set-local 'org-window-configuration wc)
10819 (use-local-map org-table-fedit-map)
10820 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10821 (easy-menu-add org-table-fedit-menu)
10822 (setq startline (org-current-line))
10823 (while (setq entry (pop eql))
10824 (setq type (cond
10825 ((equal (string-to-char (car entry)) ?@) 'field)
10826 ((string-match "^[0-9]" (car entry)) 'column)
10827 (t 'named)))
10828 (when (setq title (assq type titles))
10829 (or (bobp) (insert "\n"))
10830 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10831 (setq titles (delq title titles)))
10832 (if (equal key (car entry)) (setq startline (org-current-line)))
10833 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10834 (car entry) " = " (cdr entry) "\n"))
10835 (remove-text-properties 0 (length s) '(face nil) s)
10836 (insert s))
10837 (if (eq org-table-use-standard-references t)
10838 (org-table-fedit-toggle-ref-type))
10839 (goto-line startline)
10840 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10842 (defun org-table-fedit-post-command ()
10843 (when (not (memq this-command '(lisp-complete-symbol)))
10844 (let ((win (selected-window)))
10845 (save-excursion
10846 (condition-case nil
10847 (org-table-show-reference)
10848 (error nil))
10849 (select-window win)))))
10851 (defun org-table-formula-to-user (s)
10852 "Convert a formula from internal to user representation."
10853 (if (eq org-table-use-standard-references t)
10854 (org-table-convert-refs-to-an s)
10857 (defun org-table-formula-from-user (s)
10858 "Convert a formula from user to internal representation."
10859 (if org-table-use-standard-references
10860 (org-table-convert-refs-to-rc s)
10863 (defun org-table-convert-refs-to-rc (s)
10864 "Convert spreadsheet references from AB7 to @7$28.
10865 Works for single references, but also for entire formulas and even the
10866 full TBLFM line."
10867 (let ((start 0))
10868 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10869 (cond
10870 ((match-end 3)
10871 ;; format match, just advance
10872 (setq start (match-end 0)))
10873 ((and (> (match-beginning 0) 0)
10874 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10875 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10876 ;; 3.e5 or something like this.
10877 (setq start (match-end 0)))
10879 (setq start (match-beginning 0)
10880 s (replace-match
10881 (if (equal (match-string 2 s) "&")
10882 (format "$%d" (org-letters-to-number (match-string 1 s)))
10883 (format "@%d$%d"
10884 (string-to-number (match-string 2 s))
10885 (org-letters-to-number (match-string 1 s))))
10886 t t s)))))
10889 (defun org-table-convert-refs-to-an (s)
10890 "Convert spreadsheet references from to @7$28 to AB7.
10891 Works for single references, but also for entire formulas and even the
10892 full TBLFM line."
10893 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10894 (setq s (replace-match
10895 (format "%s%d"
10896 (org-number-to-letters
10897 (string-to-number (match-string 2 s)))
10898 (string-to-number (match-string 1 s)))
10899 t t s)))
10900 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10901 (setq s (replace-match (concat "\\1"
10902 (org-number-to-letters
10903 (string-to-number (match-string 2 s))) "&")
10904 t nil s)))
10907 (defun org-letters-to-number (s)
10908 "Convert a base 26 number represented by letters into an integer.
10909 For example: AB -> 28."
10910 (let ((n 0))
10911 (setq s (upcase s))
10912 (while (> (length s) 0)
10913 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10914 s (substring s 1)))
10917 (defun org-number-to-letters (n)
10918 "Convert an integer into a base 26 number represented by letters.
10919 For example: 28 -> AB."
10920 (let ((s ""))
10921 (while (> n 0)
10922 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10923 n (/ (1- n) 26)))
10926 (defun org-table-fedit-convert-buffer (function)
10927 "Convert all references in this buffer, using FUNTION."
10928 (let ((line (org-current-line)))
10929 (goto-char (point-min))
10930 (while (not (eobp))
10931 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10932 (delete-region (point) (point-at-eol))
10933 (or (eobp) (forward-char 1)))
10934 (goto-line line)))
10936 (defun org-table-fedit-toggle-ref-type ()
10937 "Convert all references in the buffer from B3 to @3$2 and back."
10938 (interactive)
10939 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10940 (org-table-fedit-convert-buffer
10941 (if org-table-buffer-is-an
10942 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10943 (message "Reference type switched to %s"
10944 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10946 (defun org-table-fedit-ref-up ()
10947 "Shift the reference at point one row/hline up."
10948 (interactive)
10949 (org-table-fedit-shift-reference 'up))
10950 (defun org-table-fedit-ref-down ()
10951 "Shift the reference at point one row/hline down."
10952 (interactive)
10953 (org-table-fedit-shift-reference 'down))
10954 (defun org-table-fedit-ref-left ()
10955 "Shift the reference at point one field to the left."
10956 (interactive)
10957 (org-table-fedit-shift-reference 'left))
10958 (defun org-table-fedit-ref-right ()
10959 "Shift the reference at point one field to the right."
10960 (interactive)
10961 (org-table-fedit-shift-reference 'right))
10963 (defun org-table-fedit-shift-reference (dir)
10964 (cond
10965 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10966 (if (memq dir '(left right))
10967 (org-rematch-and-replace 1 (eq dir 'left))
10968 (error "Cannot shift reference in this direction")))
10969 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10970 ;; A B3-like reference
10971 (if (memq dir '(up down))
10972 (org-rematch-and-replace 2 (eq dir 'up))
10973 (org-rematch-and-replace 1 (eq dir 'left))))
10974 ((org-at-regexp-p
10975 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10976 ;; An internal reference
10977 (if (memq dir '(up down))
10978 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10979 (org-rematch-and-replace 5 (eq dir 'left))))))
10981 (defun org-rematch-and-replace (n &optional decr hline)
10982 "Re-match the group N, and replace it with the shifted refrence."
10983 (or (match-end n) (error "Cannot shift reference in this direction"))
10984 (goto-char (match-beginning n))
10985 (and (looking-at (regexp-quote (match-string n)))
10986 (replace-match (org-shift-refpart (match-string 0) decr hline)
10987 t t)))
10989 (defun org-shift-refpart (ref &optional decr hline)
10990 "Shift a refrence part REF.
10991 If DECR is set, decrease the references row/column, else increase.
10992 If HLINE is set, this may be a hline reference, it certainly is not
10993 a translation reference."
10994 (save-match-data
10995 (let* ((sign (string-match "^[-+]" ref)) n)
10997 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10998 (cond
10999 ((and hline (string-match "^I+" ref))
11000 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
11001 (setq n (+ n (if decr -1 1)))
11002 (if (= n 0) (setq n (+ n (if decr -1 1))))
11003 (if sign
11004 (setq sign (if (< n 0) "-" "+") n (abs n))
11005 (setq n (max 1 n)))
11006 (concat sign (make-string n ?I)))
11008 ((string-match "^[0-9]+" ref)
11009 (setq n (string-to-number (concat sign ref)))
11010 (setq n (+ n (if decr -1 1)))
11011 (if sign
11012 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
11013 (number-to-string (max 1 n))))
11015 ((string-match "^[a-zA-Z]+" ref)
11016 (org-number-to-letters
11017 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
11019 (t (error "Cannot shift reference"))))))
11021 (defun org-table-fedit-toggle-coordinates ()
11022 "Toggle the display of coordinates in the refrenced table."
11023 (interactive)
11024 (let ((pos (marker-position org-pos)))
11025 (with-current-buffer (marker-buffer org-pos)
11026 (save-excursion
11027 (goto-char pos)
11028 (org-table-toggle-coordinate-overlays)))))
11030 (defun org-table-fedit-finish (&optional arg)
11031 "Parse the buffer for formula definitions and install them.
11032 With prefix ARG, apply the new formulas to the table."
11033 (interactive "P")
11034 (org-table-remove-rectangle-highlight)
11035 (if org-table-use-standard-references
11036 (progn
11037 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
11038 (setq org-table-buffer-is-an nil)))
11039 (let ((pos org-pos) eql var form)
11040 (goto-char (point-min))
11041 (while (re-search-forward
11042 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
11043 nil t)
11044 (setq var (if (match-end 2) (match-string 2) (match-string 1))
11045 form (match-string 3))
11046 (setq form (org-trim form))
11047 (when (not (equal form ""))
11048 (while (string-match "[ \t]*\n[ \t]*" form)
11049 (setq form (replace-match " " t t form)))
11050 (when (assoc var eql)
11051 (error "Double formulas for %s" var))
11052 (push (cons var form) eql)))
11053 (setq org-pos nil)
11054 (set-window-configuration org-window-configuration)
11055 (select-window (get-buffer-window (marker-buffer pos)))
11056 (goto-char pos)
11057 (unless (org-at-table-p)
11058 (error "Lost table position - cannot install formulae"))
11059 (org-table-store-formulas eql)
11060 (move-marker pos nil)
11061 (kill-buffer "*Edit Formulas*")
11062 (if arg
11063 (org-table-recalculate 'all)
11064 (message "New formulas installed - press C-u C-c C-c to apply."))))
11066 (defun org-table-fedit-abort ()
11067 "Abort editing formulas, without installing the changes."
11068 (interactive)
11069 (org-table-remove-rectangle-highlight)
11070 (let ((pos org-pos))
11071 (set-window-configuration org-window-configuration)
11072 (select-window (get-buffer-window (marker-buffer pos)))
11073 (goto-char pos)
11074 (move-marker pos nil)
11075 (message "Formula editing aborted without installing changes")))
11077 (defun org-table-fedit-lisp-indent ()
11078 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
11079 (interactive)
11080 (let ((pos (point)) beg end ind)
11081 (beginning-of-line 1)
11082 (cond
11083 ((looking-at "[ \t]")
11084 (goto-char pos)
11085 (call-interactively 'lisp-indent-line))
11086 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
11087 ((not (fboundp 'pp-buffer))
11088 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
11089 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
11090 (goto-char (- (match-end 0) 2))
11091 (setq beg (point))
11092 (setq ind (make-string (current-column) ?\ ))
11093 (condition-case nil (forward-sexp 1)
11094 (error
11095 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
11096 (setq end (point))
11097 (save-restriction
11098 (narrow-to-region beg end)
11099 (if (eq last-command this-command)
11100 (progn
11101 (goto-char (point-min))
11102 (setq this-command nil)
11103 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
11104 (replace-match " ")))
11105 (pp-buffer)
11106 (untabify (point-min) (point-max))
11107 (goto-char (1+ (point-min)))
11108 (while (re-search-forward "^." nil t)
11109 (beginning-of-line 1)
11110 (insert ind))
11111 (goto-char (point-max))
11112 (backward-delete-char 1)))
11113 (goto-char beg))
11114 (t nil))))
11116 (defvar org-show-positions nil)
11118 (defun org-table-show-reference (&optional local)
11119 "Show the location/value of the $ expression at point."
11120 (interactive)
11121 (org-table-remove-rectangle-highlight)
11122 (catch 'exit
11123 (let ((pos (if local (point) org-pos))
11124 (face2 'highlight)
11125 (org-inhibit-highlight-removal t)
11126 (win (selected-window))
11127 (org-show-positions nil)
11128 var name e what match dest)
11129 (if local (org-table-get-specials))
11130 (setq what (cond
11131 ((or (org-at-regexp-p org-table-range-regexp2)
11132 (org-at-regexp-p org-table-translate-regexp)
11133 (org-at-regexp-p org-table-range-regexp))
11134 (setq match
11135 (save-match-data
11136 (org-table-convert-refs-to-rc (match-string 0))))
11137 'range)
11138 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
11139 ((org-at-regexp-p "\\$[0-9]+") 'column)
11140 ((not local) nil)
11141 (t (error "No reference at point")))
11142 match (and what (or match (match-string 0))))
11143 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
11144 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
11145 'secondary-selection))
11146 (org-add-hook 'before-change-functions
11147 'org-table-remove-rectangle-highlight)
11148 (if (eq what 'name) (setq var (substring match 1)))
11149 (when (eq what 'range)
11150 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
11151 (setq match (org-table-formula-substitute-names match)))
11152 (unless local
11153 (save-excursion
11154 (end-of-line 1)
11155 (re-search-backward "^\\S-" nil t)
11156 (beginning-of-line 1)
11157 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
11158 (setq dest
11159 (save-match-data
11160 (org-table-convert-refs-to-rc (match-string 1))))
11161 (org-table-add-rectangle-overlay
11162 (match-beginning 1) (match-end 1) face2))))
11163 (if (and (markerp pos) (marker-buffer pos))
11164 (if (get-buffer-window (marker-buffer pos))
11165 (select-window (get-buffer-window (marker-buffer pos)))
11166 (org-switch-to-buffer-other-window (get-buffer-window
11167 (marker-buffer pos)))))
11168 (goto-char pos)
11169 (org-table-force-dataline)
11170 (when dest
11171 (setq name (substring dest 1))
11172 (cond
11173 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
11174 (setq e (assoc name org-table-named-field-locations))
11175 (goto-line (nth 1 e))
11176 (org-table-goto-column (nth 2 e)))
11177 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
11178 (let ((l (string-to-number (match-string 1 dest)))
11179 (c (string-to-number (match-string 2 dest))))
11180 (goto-line (aref org-table-dlines l))
11181 (org-table-goto-column c)))
11182 (t (org-table-goto-column (string-to-number name))))
11183 (move-marker pos (point))
11184 (org-table-highlight-rectangle nil nil face2))
11185 (cond
11186 ((equal dest match))
11187 ((not match))
11188 ((eq what 'range)
11189 (condition-case nil
11190 (save-excursion
11191 (org-table-get-range match nil nil 'highlight))
11192 (error nil)))
11193 ((setq e (assoc var org-table-named-field-locations))
11194 (goto-line (nth 1 e))
11195 (org-table-goto-column (nth 2 e))
11196 (org-table-highlight-rectangle (point) (point))
11197 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11198 ((setq e (assoc var org-table-column-names))
11199 (org-table-goto-column (string-to-number (cdr e)))
11200 (org-table-highlight-rectangle (point) (point))
11201 (goto-char (org-table-begin))
11202 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11203 (org-table-end) t)
11204 (progn
11205 (goto-char (match-beginning 1))
11206 (org-table-highlight-rectangle)
11207 (message "Named column (column %s)" (cdr e)))
11208 (error "Column name not found")))
11209 ((eq what 'column)
11210 ;; column number
11211 (org-table-goto-column (string-to-number (substring match 1)))
11212 (org-table-highlight-rectangle (point) (point))
11213 (message "Column %s" (substring match 1)))
11214 ((setq e (assoc var org-table-local-parameters))
11215 (goto-char (org-table-begin))
11216 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11217 (progn
11218 (goto-char (match-beginning 1))
11219 (org-table-highlight-rectangle)
11220 (message "Local parameter."))
11221 (error "Parameter not found")))
11223 (cond
11224 ((not var) (error "No reference at point"))
11225 ((setq e (assoc var org-table-formula-constants-local))
11226 (message "Local Constant: $%s=%s in #+CONSTANTS line."
11227 var (cdr e)))
11228 ((setq e (assoc var org-table-formula-constants))
11229 (message "Constant: $%s=%s in `org-table-formula-constants'."
11230 var (cdr e)))
11231 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11232 (message "Constant: $%s=%s, from `constants.el'%s."
11233 var e (format " (%s units)" constants-unit-system)))
11234 (t (error "Undefined name $%s" var)))))
11235 (goto-char pos)
11236 (when (and org-show-positions
11237 (not (memq this-command '(org-table-fedit-scroll
11238 org-table-fedit-scroll-down))))
11239 (push pos org-show-positions)
11240 (push org-table-current-begin-pos org-show-positions)
11241 (let ((min (apply 'min org-show-positions))
11242 (max (apply 'max org-show-positions)))
11243 (goto-char min) (recenter 0)
11244 (goto-char max)
11245 (or (pos-visible-in-window-p max) (recenter -1))))
11246 (select-window win))))
11248 (defun org-table-force-dataline ()
11249 "Make sure the cursor is in a dataline in a table."
11250 (unless (save-excursion
11251 (beginning-of-line 1)
11252 (looking-at org-table-dataline-regexp))
11253 (let* ((re org-table-dataline-regexp)
11254 (p1 (save-excursion (re-search-forward re nil 'move)))
11255 (p2 (save-excursion (re-search-backward re nil 'move))))
11256 (cond ((and p1 p2)
11257 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
11258 p1 p2)))
11259 ((or p1 p2) (goto-char (or p1 p2)))
11260 (t (error "No table dataline around here"))))))
11262 (defun org-table-fedit-line-up ()
11263 "Move cursor one line up in the window showing the table."
11264 (interactive)
11265 (org-table-fedit-move 'previous-line))
11267 (defun org-table-fedit-line-down ()
11268 "Move cursor one line down in the window showing the table."
11269 (interactive)
11270 (org-table-fedit-move 'next-line))
11272 (defun org-table-fedit-move (command)
11273 "Move the cursor in the window shoinw the table.
11274 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11275 (let ((org-table-allow-automatic-line-recalculation nil)
11276 (pos org-pos) (win (selected-window)) p)
11277 (select-window (get-buffer-window (marker-buffer org-pos)))
11278 (setq p (point))
11279 (call-interactively command)
11280 (while (and (org-at-table-p)
11281 (org-at-table-hline-p))
11282 (call-interactively command))
11283 (or (org-at-table-p) (goto-char p))
11284 (move-marker pos (point))
11285 (select-window win)))
11287 (defun org-table-fedit-scroll (N)
11288 (interactive "p")
11289 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11290 (scroll-other-window N)))
11292 (defun org-table-fedit-scroll-down (N)
11293 (interactive "p")
11294 (org-table-fedit-scroll (- N)))
11296 (defvar org-table-rectangle-overlays nil)
11298 (defun org-table-add-rectangle-overlay (beg end &optional face)
11299 "Add a new overlay."
11300 (let ((ov (org-make-overlay beg end)))
11301 (org-overlay-put ov 'face (or face 'secondary-selection))
11302 (push ov org-table-rectangle-overlays)))
11304 (defun org-table-highlight-rectangle (&optional beg end face)
11305 "Highlight rectangular region in a table."
11306 (setq beg (or beg (point)) end (or end (point)))
11307 (let ((b (min beg end))
11308 (e (max beg end))
11309 l1 c1 l2 c2 tmp)
11310 (and (boundp 'org-show-positions)
11311 (setq org-show-positions (cons b (cons e org-show-positions))))
11312 (goto-char (min beg end))
11313 (setq l1 (org-current-line)
11314 c1 (org-table-current-column))
11315 (goto-char (max beg end))
11316 (setq l2 (org-current-line)
11317 c2 (org-table-current-column))
11318 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11319 (goto-line l1)
11320 (beginning-of-line 1)
11321 (loop for line from l1 to l2 do
11322 (when (looking-at org-table-dataline-regexp)
11323 (org-table-goto-column c1)
11324 (skip-chars-backward "^|\n") (setq beg (point))
11325 (org-table-goto-column c2)
11326 (skip-chars-forward "^|\n") (setq end (point))
11327 (org-table-add-rectangle-overlay beg end face))
11328 (beginning-of-line 2))
11329 (goto-char b))
11330 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11332 (defun org-table-remove-rectangle-highlight (&rest ignore)
11333 "Remove the rectangle overlays."
11334 (unless org-inhibit-highlight-removal
11335 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11336 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11337 (setq org-table-rectangle-overlays nil)))
11339 (defvar org-table-coordinate-overlays nil
11340 "Collects the cooordinate grid overlays, so that they can be removed.")
11341 (make-variable-buffer-local 'org-table-coordinate-overlays)
11343 (defun org-table-overlay-coordinates ()
11344 "Add overlays to the table at point, to show row/column coordinates."
11345 (interactive)
11346 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11347 (setq org-table-coordinate-overlays nil)
11348 (save-excursion
11349 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11350 (goto-char (org-table-begin))
11351 (while (org-at-table-p)
11352 (setq eol (point-at-eol))
11353 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11354 (push ov org-table-coordinate-overlays)
11355 (setq hline (looking-at org-table-hline-regexp))
11356 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11357 (format "%4d" (setq id (1+ id)))))
11358 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11359 (when hline
11360 (setq ic 0)
11361 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11362 (setq beg (1+ (match-beginning 0))
11363 ic (1+ ic)
11364 s1 (concat "$" (int-to-string ic))
11365 s2 (org-number-to-letters ic)
11366 str (if (eq org-table-use-standard-references t) s2 s1))
11367 (setq ov (org-make-overlay beg (+ beg (length str))))
11368 (push ov org-table-coordinate-overlays)
11369 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11370 (beginning-of-line 2)))))
11372 (defun org-table-toggle-coordinate-overlays ()
11373 "Toggle the display of Row/Column numbers in tables."
11374 (interactive)
11375 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11376 (message "Row/Column number display turned %s"
11377 (if org-table-overlay-coordinates "on" "off"))
11378 (if (and (org-at-table-p) org-table-overlay-coordinates)
11379 (org-table-align))
11380 (unless org-table-overlay-coordinates
11381 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11382 (setq org-table-coordinate-overlays nil)))
11384 (defun org-table-toggle-formula-debugger ()
11385 "Toggle the formula debugger in tables."
11386 (interactive)
11387 (setq org-table-formula-debug (not org-table-formula-debug))
11388 (message "Formula debugging has been turned %s"
11389 (if org-table-formula-debug "on" "off")))
11391 ;;; The orgtbl minor mode
11393 ;; Define a minor mode which can be used in other modes in order to
11394 ;; integrate the org-mode table editor.
11396 ;; This is really a hack, because the org-mode table editor uses several
11397 ;; keys which normally belong to the major mode, for example the TAB and
11398 ;; RET keys. Here is how it works: The minor mode defines all the keys
11399 ;; necessary to operate the table editor, but wraps the commands into a
11400 ;; function which tests if the cursor is currently inside a table. If that
11401 ;; is the case, the table editor command is executed. However, when any of
11402 ;; those keys is used outside a table, the function uses `key-binding' to
11403 ;; look up if the key has an associated command in another currently active
11404 ;; keymap (minor modes, major mode, global), and executes that command.
11405 ;; There might be problems if any of the keys used by the table editor is
11406 ;; otherwise used as a prefix key.
11408 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11409 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11410 ;; addresses this by checking explicitly for both bindings.
11412 ;; The optimized version (see variable `orgtbl-optimized') takes over
11413 ;; all keys which are bound to `self-insert-command' in the *global map*.
11414 ;; Some modes bind other commands to simple characters, for example
11415 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11416 ;; active, this binding is ignored inside tables and replaced with a
11417 ;; modified self-insert.
11419 (defvar orgtbl-mode nil
11420 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11421 table editor in arbitrary modes.")
11422 (make-variable-buffer-local 'orgtbl-mode)
11424 (defvar orgtbl-mode-map (make-keymap)
11425 "Keymap for `orgtbl-mode'.")
11427 ;;;###autoload
11428 (defun turn-on-orgtbl ()
11429 "Unconditionally turn on `orgtbl-mode'."
11430 (orgtbl-mode 1))
11432 (defvar org-old-auto-fill-inhibit-regexp nil
11433 "Local variable used by `orgtbl-mode'")
11435 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11436 "Matches a line belonging to an orgtbl.")
11438 (defconst orgtbl-extra-font-lock-keywords
11439 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11440 0 (quote 'org-table) 'prepend))
11441 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11443 ;;;###autoload
11444 (defun orgtbl-mode (&optional arg)
11445 "The `org-mode' table editor as a minor mode for use in other modes."
11446 (interactive)
11447 (org-load-modules-maybe)
11448 (if (org-mode-p)
11449 ;; Exit without error, in case some hook functions calls this
11450 ;; by accident in org-mode.
11451 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11452 (setq orgtbl-mode
11453 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11454 (if orgtbl-mode
11455 (progn
11456 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11457 ;; Make sure we are first in minor-mode-map-alist
11458 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11459 (and c (setq minor-mode-map-alist
11460 (cons c (delq c minor-mode-map-alist)))))
11461 (org-set-local (quote org-table-may-need-update) t)
11462 (org-add-hook 'before-change-functions 'org-before-change-function
11463 nil 'local)
11464 (org-set-local 'org-old-auto-fill-inhibit-regexp
11465 auto-fill-inhibit-regexp)
11466 (org-set-local 'auto-fill-inhibit-regexp
11467 (if auto-fill-inhibit-regexp
11468 (concat orgtbl-line-start-regexp "\\|"
11469 auto-fill-inhibit-regexp)
11470 orgtbl-line-start-regexp))
11471 (org-add-to-invisibility-spec '(org-cwidth))
11472 (when (fboundp 'font-lock-add-keywords)
11473 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11474 (org-restart-font-lock))
11475 (easy-menu-add orgtbl-mode-menu)
11476 (run-hooks 'orgtbl-mode-hook))
11477 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11478 (org-cleanup-narrow-column-properties)
11479 (org-remove-from-invisibility-spec '(org-cwidth))
11480 (remove-hook 'before-change-functions 'org-before-change-function t)
11481 (when (fboundp 'font-lock-remove-keywords)
11482 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11483 (org-restart-font-lock))
11484 (easy-menu-remove orgtbl-mode-menu)
11485 (force-mode-line-update 'all))))
11487 (defun org-cleanup-narrow-column-properties ()
11488 "Remove all properties related to narrow-column invisibility."
11489 (let ((s 1))
11490 (while (setq s (text-property-any s (point-max)
11491 'display org-narrow-column-arrow))
11492 (remove-text-properties s (1+ s) '(display t)))
11493 (setq s 1)
11494 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11495 (remove-text-properties s (1+ s) '(org-cwidth t)))
11496 (setq s 1)
11497 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11498 (remove-text-properties s (1+ s) '(invisible t)))))
11500 ;; Install it as a minor mode.
11501 (put 'orgtbl-mode :included t)
11502 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11503 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11505 (defun orgtbl-make-binding (fun n &rest keys)
11506 "Create a function for binding in the table minor mode.
11507 FUN is the command to call inside a table. N is used to create a unique
11508 command name. KEYS are keys that should be checked in for a command
11509 to execute outside of tables."
11510 (eval
11511 (list 'defun
11512 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11513 '(arg)
11514 (concat "In tables, run `" (symbol-name fun) "'.\n"
11515 "Outside of tables, run the binding of `"
11516 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11517 "'.")
11518 '(interactive "p")
11519 (list 'if
11520 '(org-at-table-p)
11521 (list 'call-interactively (list 'quote fun))
11522 (list 'let '(orgtbl-mode)
11523 (list 'call-interactively
11524 (append '(or)
11525 (mapcar (lambda (k)
11526 (list 'key-binding k))
11527 keys)
11528 '('orgtbl-error))))))))
11530 (defun orgtbl-error ()
11531 "Error when there is no default binding for a table key."
11532 (interactive)
11533 (error "This key has no function outside tables"))
11535 (defun orgtbl-setup ()
11536 "Setup orgtbl keymaps."
11537 (let ((nfunc 0)
11538 (bindings
11539 (list
11540 '([(meta shift left)] org-table-delete-column)
11541 '([(meta left)] org-table-move-column-left)
11542 '([(meta right)] org-table-move-column-right)
11543 '([(meta shift right)] org-table-insert-column)
11544 '([(meta shift up)] org-table-kill-row)
11545 '([(meta shift down)] org-table-insert-row)
11546 '([(meta up)] org-table-move-row-up)
11547 '([(meta down)] org-table-move-row-down)
11548 '("\C-c\C-w" org-table-cut-region)
11549 '("\C-c\M-w" org-table-copy-region)
11550 '("\C-c\C-y" org-table-paste-rectangle)
11551 '("\C-c-" org-table-insert-hline)
11552 '("\C-c}" org-table-toggle-coordinate-overlays)
11553 '("\C-c{" org-table-toggle-formula-debugger)
11554 '("\C-m" org-table-next-row)
11555 '([(shift return)] org-table-copy-down)
11556 '("\C-c\C-q" org-table-wrap-region)
11557 '("\C-c?" org-table-field-info)
11558 '("\C-c " org-table-blank-field)
11559 '("\C-c+" org-table-sum)
11560 '("\C-c=" org-table-eval-formula)
11561 '("\C-c'" org-table-edit-formulas)
11562 '("\C-c`" org-table-edit-field)
11563 '("\C-c*" org-table-recalculate)
11564 '("\C-c|" org-table-create-or-convert-from-region)
11565 '("\C-c^" org-table-sort-lines)
11566 '([(control ?#)] org-table-rotate-recalc-marks)))
11567 elt key fun cmd)
11568 (while (setq elt (pop bindings))
11569 (setq nfunc (1+ nfunc))
11570 (setq key (org-key (car elt))
11571 fun (nth 1 elt)
11572 cmd (orgtbl-make-binding fun nfunc key))
11573 (org-defkey orgtbl-mode-map key cmd))
11575 ;; Special treatment needed for TAB and RET
11576 (org-defkey orgtbl-mode-map [(return)]
11577 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11578 (org-defkey orgtbl-mode-map "\C-m"
11579 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11581 (org-defkey orgtbl-mode-map [(tab)]
11582 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11583 (org-defkey orgtbl-mode-map "\C-i"
11584 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11586 (org-defkey orgtbl-mode-map [(shift tab)]
11587 (orgtbl-make-binding 'org-table-previous-field 104
11588 [(shift tab)] [(tab)] "\C-i"))
11590 (org-defkey orgtbl-mode-map "\M-\C-m"
11591 (orgtbl-make-binding 'org-table-wrap-region 105
11592 "\M-\C-m" [(meta return)]))
11593 (org-defkey orgtbl-mode-map [(meta return)]
11594 (orgtbl-make-binding 'org-table-wrap-region 106
11595 [(meta return)] "\M-\C-m"))
11597 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11598 (when orgtbl-optimized
11599 ;; If the user wants maximum table support, we need to hijack
11600 ;; some standard editing functions
11601 (org-remap orgtbl-mode-map
11602 'self-insert-command 'orgtbl-self-insert-command
11603 'delete-char 'org-delete-char
11604 'delete-backward-char 'org-delete-backward-char)
11605 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11606 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11607 '("OrgTbl"
11608 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11609 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11610 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11611 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11612 "--"
11613 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11614 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11615 ["Copy Field from Above"
11616 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11617 "--"
11618 ("Column"
11619 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11620 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11621 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11622 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11623 ("Row"
11624 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11625 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11626 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11627 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11628 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
11629 "--"
11630 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11631 ("Rectangle"
11632 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11633 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11634 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11635 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11636 "--"
11637 ("Radio tables"
11638 ["Insert table template" orgtbl-insert-radio-table
11639 (assq major-mode orgtbl-radio-table-templates)]
11640 ["Comment/uncomment table" orgtbl-toggle-comment t])
11641 "--"
11642 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11643 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11644 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11645 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11646 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11647 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11648 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11649 ["Sum Column/Rectangle" org-table-sum
11650 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11651 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11652 ["Debug Formulas"
11653 org-table-toggle-formula-debugger :active (org-at-table-p)
11654 :keys "C-c {"
11655 :style toggle :selected org-table-formula-debug]
11656 ["Show Col/Row Numbers"
11657 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11658 :keys "C-c }"
11659 :style toggle :selected org-table-overlay-coordinates]
11663 (defun orgtbl-ctrl-c-ctrl-c (arg)
11664 "If the cursor is inside a table, realign the table.
11665 It it is a table to be sent away to a receiver, do it.
11666 With prefix arg, also recompute table."
11667 (interactive "P")
11668 (let ((pos (point)) action)
11669 (save-excursion
11670 (beginning-of-line 1)
11671 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11672 ((looking-at "[ \t]*|") pos)
11673 ((looking-at "#\\+TBLFM:") 'recalc))))
11674 (cond
11675 ((integerp action)
11676 (goto-char action)
11677 (org-table-maybe-eval-formula)
11678 (if arg
11679 (call-interactively 'org-table-recalculate)
11680 (org-table-maybe-recalculate-line))
11681 (call-interactively 'org-table-align)
11682 (orgtbl-send-table 'maybe))
11683 ((eq action 'recalc)
11684 (save-excursion
11685 (beginning-of-line 1)
11686 (skip-chars-backward " \r\n\t")
11687 (if (org-at-table-p)
11688 (org-call-with-arg 'org-table-recalculate t))))
11689 (t (let (orgtbl-mode)
11690 (call-interactively (key-binding "\C-c\C-c")))))))
11692 (defun orgtbl-tab (arg)
11693 "Justification and field motion for `orgtbl-mode'."
11694 (interactive "P")
11695 (if arg (org-table-edit-field t)
11696 (org-table-justify-field-maybe)
11697 (org-table-next-field)))
11699 (defun orgtbl-ret ()
11700 "Justification and field motion for `orgtbl-mode'."
11701 (interactive)
11702 (org-table-justify-field-maybe)
11703 (org-table-next-row))
11705 (defun orgtbl-self-insert-command (N)
11706 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11707 If the cursor is in a table looking at whitespace, the whitespace is
11708 overwritten, and the table is not marked as requiring realignment."
11709 (interactive "p")
11710 (if (and (org-at-table-p)
11712 (and org-table-auto-blank-field
11713 (member last-command
11714 '(orgtbl-hijacker-command-100
11715 orgtbl-hijacker-command-101
11716 orgtbl-hijacker-command-102
11717 orgtbl-hijacker-command-103
11718 orgtbl-hijacker-command-104
11719 orgtbl-hijacker-command-105))
11720 (org-table-blank-field))
11722 (eq N 1)
11723 (looking-at "[^|\n]* +|"))
11724 (let (org-table-may-need-update)
11725 (goto-char (1- (match-end 0)))
11726 (delete-backward-char 1)
11727 (goto-char (match-beginning 0))
11728 (self-insert-command N))
11729 (setq org-table-may-need-update t)
11730 (let (orgtbl-mode)
11731 (call-interactively (key-binding (vector last-input-event))))))
11733 (defun org-force-self-insert (N)
11734 "Needed to enforce self-insert under remapping."
11735 (interactive "p")
11736 (self-insert-command N))
11738 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11739 "Regula expression matching exponentials as produced by calc.")
11741 (defvar org-table-clean-did-remove-column nil)
11743 (defun orgtbl-export (table target)
11744 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11745 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11746 org-table-last-alignment org-table-last-column-widths
11747 maxcol column)
11748 (if (not (fboundp func))
11749 (error "Cannot export orgtbl table to %s" target))
11750 (setq lines (org-table-clean-before-export lines))
11751 (setq table
11752 (mapcar
11753 (lambda (x)
11754 (if (string-match org-table-hline-regexp x)
11755 'hline
11756 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11757 lines))
11758 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11759 table)))
11760 (loop for i from (1- maxcol) downto 0 do
11761 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11762 (setq column (delq nil column))
11763 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11764 (push (> (/ (apply '+ (mapcar (lambda (x) (if (string-match org-table-number-regexp x) 1 0)) column)) maxcol) org-table-number-fraction) org-table-last-alignment))
11765 (funcall func table nil)))
11767 (defun orgtbl-send-table (&optional maybe)
11768 "Send a tranformed version of this table to the receiver position.
11769 With argument MAYBE, fail quietly if no transformation is defined for
11770 this table."
11771 (interactive)
11772 (catch 'exit
11773 (unless (org-at-table-p) (error "Not at a table"))
11774 ;; when non-interactive, we assume align has just happened.
11775 (when (interactive-p) (org-table-align))
11776 (save-excursion
11777 (goto-char (org-table-begin))
11778 (beginning-of-line 0)
11779 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11780 (if maybe
11781 (throw 'exit nil)
11782 (error "Don't know how to transform this table."))))
11783 (let* ((name (match-string 1))
11785 (transform (intern (match-string 2)))
11786 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11787 (skip (plist-get params :skip))
11788 (skipcols (plist-get params :skipcols))
11789 (txt (buffer-substring-no-properties
11790 (org-table-begin) (org-table-end)))
11791 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11792 (lines (org-table-clean-before-export lines))
11793 (i0 (if org-table-clean-did-remove-column 2 1))
11794 (table (mapcar
11795 (lambda (x)
11796 (if (string-match org-table-hline-regexp x)
11797 'hline
11798 (org-remove-by-index
11799 (org-split-string (org-trim x) "\\s-*|\\s-*")
11800 skipcols i0)))
11801 lines))
11802 (fun (if (= i0 2) 'cdr 'identity))
11803 (org-table-last-alignment
11804 (org-remove-by-index (funcall fun org-table-last-alignment)
11805 skipcols i0))
11806 (org-table-last-column-widths
11807 (org-remove-by-index (funcall fun org-table-last-column-widths)
11808 skipcols i0)))
11810 (unless (fboundp transform)
11811 (error "No such transformation function %s" transform))
11812 (setq txt (funcall transform table params))
11813 ;; Find the insertion place
11814 (save-excursion
11815 (goto-char (point-min))
11816 (unless (re-search-forward
11817 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11818 (error "Don't know where to insert translated table"))
11819 (goto-char (match-beginning 0))
11820 (beginning-of-line 2)
11821 (setq beg (point))
11822 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11823 (error "Cannot find end of insertion region"))
11824 (beginning-of-line 1)
11825 (delete-region beg (point))
11826 (goto-char beg)
11827 (insert txt "\n"))
11828 (message "Table converted and installed at receiver location"))))
11830 (defun org-remove-by-index (list indices &optional i0)
11831 "Remove the elements in LIST with indices in INDICES.
11832 First element has index 0, or I0 if given."
11833 (if (not indices)
11834 list
11835 (if (integerp indices) (setq indices (list indices)))
11836 (setq i0 (1- (or i0 0)))
11837 (delq :rm (mapcar (lambda (x)
11838 (setq i0 (1+ i0))
11839 (if (memq i0 indices) :rm x))
11840 list))))
11842 (defun orgtbl-toggle-comment ()
11843 "Comment or uncomment the orgtbl at point."
11844 (interactive)
11845 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11846 (re2 (concat "^" orgtbl-line-start-regexp))
11847 (commented (save-excursion (beginning-of-line 1)
11848 (cond ((looking-at re1) t)
11849 ((looking-at re2) nil)
11850 (t (error "Not at an org table")))))
11851 (re (if commented re1 re2))
11852 beg end)
11853 (save-excursion
11854 (beginning-of-line 1)
11855 (while (looking-at re) (beginning-of-line 0))
11856 (beginning-of-line 2)
11857 (setq beg (point))
11858 (while (looking-at re) (beginning-of-line 2))
11859 (setq end (point)))
11860 (comment-region beg end (if commented '(4) nil))))
11862 (defun orgtbl-insert-radio-table ()
11863 "Insert a radio table template appropriate for this major mode."
11864 (interactive)
11865 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11866 (txt (nth 1 e))
11867 name pos)
11868 (unless e (error "No radio table setup defined for %s" major-mode))
11869 (setq name (read-string "Table name: "))
11870 (while (string-match "%n" txt)
11871 (setq txt (replace-match name t t txt)))
11872 (or (bolp) (insert "\n"))
11873 (setq pos (point))
11874 (insert txt)
11875 (goto-char pos)))
11877 (defun org-get-param (params header i sym &optional hsym)
11878 "Get parameter value for symbol SYM.
11879 If this is a header line, actually get the value for the symbol with an
11880 additional \"h\" inserted after the colon.
11881 If the value is a protperty list, get the element for the current column.
11882 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11883 (let ((val (plist-get params sym)))
11884 (and hsym header (setq val (or (plist-get params hsym) val)))
11885 (if (consp val) (plist-get val i) val)))
11887 (defun orgtbl-to-generic (table params)
11888 "Convert the orgtbl-mode TABLE to some other format.
11889 This generic routine can be used for many standard cases.
11890 TABLE is a list, each entry either the symbol `hline' for a horizontal
11891 separator line, or a list of fields for that line.
11892 PARAMS is a property list of parameters that can influence the conversion.
11893 For the generic converter, some parameters are obligatory: You need to
11894 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11895 :splice, you must have :tstart and :tend.
11897 Valid parameters are
11899 :tstart String to start the table. Ignored when :splice is t.
11900 :tend String to end the table. Ignored when :splice is t.
11902 :splice When set to t, return only table body lines, don't wrap
11903 them into :tstart and :tend. Default is nil.
11905 :hline String to be inserted on horizontal separation lines.
11906 May be nil to ignore hlines.
11908 :lstart String to start a new table line.
11909 :lend String to end a table line
11910 :sep Separator between two fields
11911 :lfmt Format for entire line, with enough %s to capture all fields.
11912 If this is present, :lstart, :lend, and :sep are ignored.
11913 :fmt A format to be used to wrap the field, should contain
11914 %s for the original field value. For example, to wrap
11915 everything in dollars, you could use :fmt \"$%s$\".
11916 This may also be a property list with column numbers and
11917 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11919 :hlstart :hlend :hlsep :hlfmt :hfmt
11920 Same as above, specific for the header lines in the table.
11921 All lines before the first hline are treated as header.
11922 If any of these is not present, the data line value is used.
11924 :efmt Use this format to print numbers with exponentials.
11925 The format should have %s twice for inserting mantissa
11926 and exponent, for example \"%s\\\\times10^{%s}\". This
11927 may also be a property list with column numbers and
11928 formats. :fmt will still be applied after :efmt.
11930 In addition to this, the parameters :skip and :skipcols are always handled
11931 directly by `orgtbl-send-table'. See manual."
11932 (interactive)
11933 (let* ((p params)
11934 (splicep (plist-get p :splice))
11935 (hline (plist-get p :hline))
11936 rtn line i fm efm lfmt h)
11938 ;; Do we have a header?
11939 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11940 (setq h t))
11942 ;; Put header
11943 (unless splicep
11944 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11946 ;; Now loop over all lines
11947 (while (setq line (pop table))
11948 (if (eq line 'hline)
11949 ;; A horizontal separator line
11950 (progn (if hline (push hline rtn))
11951 (setq h nil)) ; no longer in header
11952 ;; A normal line. Convert the fields, push line onto the result list
11953 (setq i 0)
11954 (setq line
11955 (mapcar
11956 (lambda (f)
11957 (setq i (1+ i)
11958 fm (org-get-param p h i :fmt :hfmt)
11959 efm (org-get-param p h i :efmt))
11960 (if (and efm (string-match orgtbl-exp-regexp f))
11961 (setq f (format
11962 efm (match-string 1 f) (match-string 2 f))))
11963 (if fm (setq f (format fm f)))
11965 line))
11966 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11967 (push (apply 'format lfmt line) rtn)
11968 (push (concat
11969 (org-get-param p h i :lstart :hlstart)
11970 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11971 (org-get-param p h i :lend :hlend))
11972 rtn))))
11974 (unless splicep
11975 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11977 (mapconcat 'identity (nreverse rtn) "\n")))
11979 (defun orgtbl-to-latex (table params)
11980 "Convert the orgtbl-mode TABLE to LaTeX.
11981 TABLE is a list, each entry either the symbol `hline' for a horizontal
11982 separator line, or a list of fields for that line.
11983 PARAMS is a property list of parameters that can influence the conversion.
11984 Supports all parameters from `orgtbl-to-generic'. Most important for
11985 LaTeX are:
11987 :splice When set to t, return only table body lines, don't wrap
11988 them into a tabular environment. Default is nil.
11990 :fmt A format to be used to wrap the field, should contain %s for the
11991 original field value. For example, to wrap everything in dollars,
11992 use :fmt \"$%s$\". This may also be a property list with column
11993 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11995 :efmt Format for transforming numbers with exponentials. The format
11996 should have %s twice for inserting mantissa and exponent, for
11997 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11998 This may also be a property list with column numbers and formats.
12000 The general parameters :skip and :skipcols have already been applied when
12001 this function is called."
12002 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
12003 org-table-last-alignment ""))
12004 (params2
12005 (list
12006 :tstart (concat "\\begin{tabular}{" alignment "}")
12007 :tend "\\end{tabular}"
12008 :lstart "" :lend " \\\\" :sep " & "
12009 :efmt "%s\\,(%s)" :hline "\\hline")))
12010 (orgtbl-to-generic table (org-combine-plists params2 params))))
12012 (defun orgtbl-to-html (table params)
12013 "Convert the orgtbl-mode TABLE to LaTeX.
12014 TABLE is a list, each entry either the symbol `hline' for a horizontal
12015 separator line, or a list of fields for that line.
12016 PARAMS is a property list of parameters that can influence the conversion.
12017 Currently this function recognizes the following parameters:
12019 :splice When set to t, return only table body lines, don't wrap
12020 them into a <table> environment. Default is nil.
12022 The general parameters :skip and :skipcols have already been applied when
12023 this function is called. The function does *not* use `orgtbl-to-generic',
12024 so you cannot specify parameters for it."
12025 (let* ((splicep (plist-get params :splice))
12026 html)
12027 ;; Just call the formatter we already have
12028 ;; We need to make text lines for it, so put the fields back together.
12029 (setq html (org-format-org-table-html
12030 (mapcar
12031 (lambda (x)
12032 (if (eq x 'hline)
12033 "|----+----|"
12034 (concat "| " (mapconcat 'identity x " | ") " |")))
12035 table)
12036 splicep))
12037 (if (string-match "\n+\\'" html)
12038 (setq html (replace-match "" t t html)))
12039 html))
12041 (defun orgtbl-to-texinfo (table params)
12042 "Convert the orgtbl-mode TABLE to TeXInfo.
12043 TABLE is a list, each entry either the symbol `hline' for a horizontal
12044 separator line, or a list of fields for that line.
12045 PARAMS is a property list of parameters that can influence the conversion.
12046 Supports all parameters from `orgtbl-to-generic'. Most important for
12047 TeXInfo are:
12049 :splice nil/t When set to t, return only table body lines, don't wrap
12050 them into a multitable environment. Default is nil.
12052 :fmt fmt A format to be used to wrap the field, should contain
12053 %s for the original field value. For example, to wrap
12054 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
12055 This may also be a property list with column numbers and
12056 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
12058 :cf \"f1 f2..\" The column fractions for the table. By default these
12059 are computed automatically from the width of the columns
12060 under org-mode.
12062 The general parameters :skip and :skipcols have already been applied when
12063 this function is called."
12064 (let* ((total (float (apply '+ org-table-last-column-widths)))
12065 (colfrac (or (plist-get params :cf)
12066 (mapconcat
12067 (lambda (x) (format "%.3f" (/ (float x) total)))
12068 org-table-last-column-widths " ")))
12069 (params2
12070 (list
12071 :tstart (concat "@multitable @columnfractions " colfrac)
12072 :tend "@end multitable"
12073 :lstart "@item " :lend "" :sep " @tab "
12074 :hlstart "@headitem ")))
12075 (orgtbl-to-generic table (org-combine-plists params2 params))))
12077 ;;;; Link Stuff
12079 ;;; Link abbreviations
12081 (defun org-link-expand-abbrev (link)
12082 "Apply replacements as defined in `org-link-abbrev-alist."
12083 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
12084 (let* ((key (match-string 1 link))
12085 (as (or (assoc key org-link-abbrev-alist-local)
12086 (assoc key org-link-abbrev-alist)))
12087 (tag (and (match-end 2) (match-string 3 link)))
12088 rpl)
12089 (if (not as)
12090 link
12091 (setq rpl (cdr as))
12092 (cond
12093 ((symbolp rpl) (funcall rpl tag))
12094 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
12095 (t (concat rpl tag)))))
12096 link))
12098 ;;; Storing and inserting links
12100 (defvar org-insert-link-history nil
12101 "Minibuffer history for links inserted with `org-insert-link'.")
12103 (defvar org-stored-links nil
12104 "Contains the links stored with `org-store-link'.")
12106 (defvar org-store-link-plist nil
12107 "Plist with info about the most recently link created with `org-store-link'.")
12109 (defvar org-link-protocols nil
12110 "Link protocols added to Org-mode using `org-add-link-type'.")
12112 (defvar org-store-link-functions nil
12113 "List of functions that are called to create and store a link.
12114 Each function will be called in turn until one returns a non-nil
12115 value. Each function should check if it is responsible for creating
12116 this link (for example by looking at the major mode).
12117 If not, it must exit and return nil.
12118 If yes, it should return a non-nil value after a calling
12119 `org-store-link-props' with a list of properties and values.
12120 Special properties are:
12122 :type The link prefix. like \"http\". This must be given.
12123 :link The link, like \"http://www.astro.uva.nl/~dominik\".
12124 This is obligatory as well.
12125 :description Optional default description for the second pair
12126 of brackets in an Org-mode link. The user can still change
12127 this when inserting this link into an Org-mode buffer.
12129 In addition to these, any additional properties can be specified
12130 and then used in remember templates.")
12132 (defun org-add-link-type (type &optional follow export)
12133 "Add TYPE to the list of `org-link-types'.
12134 Re-compute all regular expressions depending on `org-link-types'
12136 FOLLOW and EXPORT are two functions.
12138 FOLLOW should take the link path as the single argument and do whatever
12139 is necessary to follow the link, for example find a file or display
12140 a mail message.
12142 EXPORT should format the link path for export to one of the export formats.
12143 It should be a function accepting three arguments:
12145 path the path of the link, the text after the prefix (like \"http:\")
12146 desc the description of the link, if any, nil if there was no descripton
12147 format the export format, a symbol like `html' or `latex'.
12149 The function may use the FORMAT information to return different values
12150 depending on the format. The return value will be put literally into
12151 the exported file.
12152 Org-mode has a built-in default for exporting links. If you are happy with
12153 this default, there is no need to define an export function for the link
12154 type. For a simple example of an export function, see `org-bbdb.el'."
12155 (add-to-list 'org-link-types type t)
12156 (org-make-link-regexps)
12157 (if (assoc type org-link-protocols)
12158 (setcdr (assoc type org-link-protocols) (list follow export))
12159 (push (list type follow export) org-link-protocols)))
12162 (defun org-add-agenda-custom-command (entry)
12163 "Replace or add a command in `org-agenda-custom-commands'.
12164 This is mostly for hacking and trying a new command - once the command
12165 works you probably want to add it to `org-agenda-custom-commands' for good."
12166 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
12167 (if ass
12168 (setcdr ass (cdr entry))
12169 (push entry org-agenda-custom-commands))))
12171 ;;;###autoload
12172 (defun org-store-link (arg)
12173 "\\<org-mode-map>Store an org-link to the current location.
12174 This link is added to `org-stored-links' and can later be inserted
12175 into an org-buffer with \\[org-insert-link].
12177 For some link types, a prefix arg is interpreted:
12178 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
12179 For file links, arg negates `org-context-in-file-links'."
12180 (interactive "P")
12181 (org-load-modules-maybe)
12182 (setq org-store-link-plist nil) ; reset
12183 (let (link cpltxt desc description search txt)
12184 (cond
12186 ((run-hook-with-args-until-success 'org-store-link-functions)
12187 (setq link (plist-get org-store-link-plist :link)
12188 desc (or (plist-get org-store-link-plist :description) link)))
12190 ((eq major-mode 'calendar-mode)
12191 (let ((cd (calendar-cursor-to-date)))
12192 (setq link
12193 (format-time-string
12194 (car org-time-stamp-formats)
12195 (apply 'encode-time
12196 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
12197 nil nil nil))))
12198 (org-store-link-props :type "calendar" :date cd)))
12200 ((eq major-mode 'w3-mode)
12201 (setq cpltxt (url-view-url t)
12202 link (org-make-link cpltxt))
12203 (org-store-link-props :type "w3" :url (url-view-url t)))
12205 ((eq major-mode 'w3m-mode)
12206 (setq cpltxt (or w3m-current-title w3m-current-url)
12207 link (org-make-link w3m-current-url))
12208 (org-store-link-props :type "w3m" :url (url-view-url t)))
12210 ((setq search (run-hook-with-args-until-success
12211 'org-create-file-search-functions))
12212 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12213 "::" search))
12214 (setq cpltxt (or description link)))
12216 ((eq major-mode 'image-mode)
12217 (setq cpltxt (concat "file:"
12218 (abbreviate-file-name buffer-file-name))
12219 link (org-make-link cpltxt))
12220 (org-store-link-props :type "image" :file buffer-file-name))
12222 ((eq major-mode 'dired-mode)
12223 ;; link to the file in the current line
12224 (setq cpltxt (concat "file:"
12225 (abbreviate-file-name
12226 (expand-file-name
12227 (dired-get-filename nil t))))
12228 link (org-make-link cpltxt)))
12230 ((and buffer-file-name (org-mode-p))
12231 ;; Just link to current headline
12232 (setq cpltxt (concat "file:"
12233 (abbreviate-file-name buffer-file-name)))
12234 ;; Add a context search string
12235 (when (org-xor org-context-in-file-links arg)
12236 ;; Check if we are on a target
12237 (if (org-in-regexp "<<\\(.*?\\)>>")
12238 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12239 (setq txt (cond
12240 ((org-on-heading-p) nil)
12241 ((org-region-active-p)
12242 (buffer-substring (region-beginning) (region-end)))
12243 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12244 (when (or (null txt) (string-match "\\S-" txt))
12245 (setq cpltxt
12246 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12247 desc "NONE"))))
12248 (if (string-match "::\\'" cpltxt)
12249 (setq cpltxt (substring cpltxt 0 -2)))
12250 (setq link (org-make-link cpltxt)))
12252 ((buffer-file-name (buffer-base-buffer))
12253 ;; Just link to this file here.
12254 (setq cpltxt (concat "file:"
12255 (abbreviate-file-name
12256 (buffer-file-name (buffer-base-buffer)))))
12257 ;; Add a context string
12258 (when (org-xor org-context-in-file-links arg)
12259 (setq txt (if (org-region-active-p)
12260 (buffer-substring (region-beginning) (region-end))
12261 (buffer-substring (point-at-bol) (point-at-eol))))
12262 ;; Only use search option if there is some text.
12263 (when (string-match "\\S-" txt)
12264 (setq cpltxt
12265 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12266 desc "NONE")))
12267 (setq link (org-make-link cpltxt)))
12269 ((interactive-p)
12270 (error "Cannot link to a buffer which is not visiting a file"))
12272 (t (setq link nil)))
12274 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12275 (setq link (or link cpltxt)
12276 desc (or desc cpltxt))
12277 (if (equal desc "NONE") (setq desc nil))
12279 (if (and (interactive-p) link)
12280 (progn
12281 (setq org-stored-links
12282 (cons (list link desc) org-stored-links))
12283 (message "Stored: %s" (or desc link)))
12284 (and link (org-make-link-string link desc)))))
12286 (defun org-store-link-props (&rest plist)
12287 "Store link properties, extract names and addresses."
12288 (let (x adr)
12289 (when (setq x (plist-get plist :from))
12290 (setq adr (mail-extract-address-components x))
12291 (plist-put plist :fromname (car adr))
12292 (plist-put plist :fromaddress (nth 1 adr)))
12293 (when (setq x (plist-get plist :to))
12294 (setq adr (mail-extract-address-components x))
12295 (plist-put plist :toname (car adr))
12296 (plist-put plist :toaddress (nth 1 adr))))
12297 (let ((from (plist-get plist :from))
12298 (to (plist-get plist :to)))
12299 (when (and from to org-from-is-user-regexp)
12300 (plist-put plist :fromto
12301 (if (string-match org-from-is-user-regexp from)
12302 (concat "to %t")
12303 (concat "from %f")))))
12304 (setq org-store-link-plist plist))
12306 (defun org-add-link-props (&rest plist)
12307 "Add these properties to the link property list."
12308 (let (key value)
12309 (while plist
12310 (setq key (pop plist) value (pop plist))
12311 (setq org-store-link-plist
12312 (plist-put org-store-link-plist key value)))))
12314 (defun org-email-link-description (&optional fmt)
12315 "Return the description part of an email link.
12316 This takes information from `org-store-link-plist' and formats it
12317 according to FMT (default from `org-email-link-description-format')."
12318 (setq fmt (or fmt org-email-link-description-format))
12319 (let* ((p org-store-link-plist)
12320 (to (plist-get p :toaddress))
12321 (from (plist-get p :fromaddress))
12322 (table
12323 (list
12324 (cons "%c" (plist-get p :fromto))
12325 (cons "%F" (plist-get p :from))
12326 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12327 (cons "%T" (plist-get p :to))
12328 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12329 (cons "%s" (plist-get p :subject))
12330 (cons "%m" (plist-get p :message-id)))))
12331 (when (string-match "%c" fmt)
12332 ;; Check if the user wrote this message
12333 (if (and org-from-is-user-regexp from to
12334 (save-match-data (string-match org-from-is-user-regexp from)))
12335 (setq fmt (replace-match "to %t" t t fmt))
12336 (setq fmt (replace-match "from %f" t t fmt))))
12337 (org-replace-escapes fmt table)))
12339 (defun org-make-org-heading-search-string (&optional string heading)
12340 "Make search string for STRING or current headline."
12341 (interactive)
12342 (let ((s (or string (org-get-heading))))
12343 (unless (and string (not heading))
12344 ;; We are using a headline, clean up garbage in there.
12345 (if (string-match org-todo-regexp s)
12346 (setq s (replace-match "" t t s)))
12347 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12348 (setq s (replace-match "" t t s)))
12349 (setq s (org-trim s))
12350 (if (string-match (concat "^\\(" org-quote-string "\\|"
12351 org-comment-string "\\)") s)
12352 (setq s (replace-match "" t t s)))
12353 (while (string-match org-ts-regexp s)
12354 (setq s (replace-match "" t t s))))
12355 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12356 (setq s (replace-match " " t t s)))
12357 (or string (setq s (concat "*" s))) ; Add * for headlines
12358 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12360 (defun org-make-link (&rest strings)
12361 "Concatenate STRINGS."
12362 (apply 'concat strings))
12364 (defun org-make-link-string (link &optional description)
12365 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12366 (unless (string-match "\\S-" link)
12367 (error "Empty link"))
12368 (when (stringp description)
12369 ;; Remove brackets from the description, they are fatal.
12370 (while (string-match "\\[" description)
12371 (setq description (replace-match "{" t t description)))
12372 (while (string-match "\\]" description)
12373 (setq description (replace-match "}" t t description))))
12374 (when (equal (org-link-escape link) description)
12375 ;; No description needed, it is identical
12376 (setq description nil))
12377 (when (and (not description)
12378 (not (equal link (org-link-escape link))))
12379 (setq description link))
12380 (concat "[[" (org-link-escape link) "]"
12381 (if description (concat "[" description "]") "")
12382 "]"))
12384 (defconst org-link-escape-chars
12385 '((?\ . "%20")
12386 (?\[ . "%5B")
12387 (?\] . "%5D")
12388 (?\340 . "%E0") ; `a
12389 (?\342 . "%E2") ; ^a
12390 (?\347 . "%E7") ; ,c
12391 (?\350 . "%E8") ; `e
12392 (?\351 . "%E9") ; 'e
12393 (?\352 . "%EA") ; ^e
12394 (?\356 . "%EE") ; ^i
12395 (?\364 . "%F4") ; ^o
12396 (?\371 . "%F9") ; `u
12397 (?\373 . "%FB") ; ^u
12398 (?\; . "%3B")
12399 (?? . "%3F")
12400 (?= . "%3D")
12401 (?+ . "%2B")
12403 "Association list of escapes for some characters problematic in links.
12404 This is the list that is used for internal purposes.")
12406 (defconst org-link-escape-chars-browser
12407 '((?\ . "%20")) ; 32 for the SPC char
12408 "Association list of escapes for some characters problematic in links.
12409 This is the list that is used before handing over to the browser.")
12411 (defun org-link-escape (text &optional table)
12412 "Escape charaters in TEXT that are problematic for links."
12413 (setq table (or table org-link-escape-chars))
12414 (when text
12415 (let ((re (mapconcat (lambda (x) (regexp-quote
12416 (char-to-string (car x))))
12417 table "\\|")))
12418 (while (string-match re text)
12419 (setq text
12420 (replace-match
12421 (cdr (assoc (string-to-char (match-string 0 text))
12422 table))
12423 t t text)))
12424 text)))
12426 (defun org-link-unescape (text &optional table)
12427 "Reverse the action of `org-link-escape'."
12428 (setq table (or table org-link-escape-chars))
12429 (when text
12430 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12431 table "\\|")))
12432 (while (string-match re text)
12433 (setq text
12434 (replace-match
12435 (char-to-string (car (rassoc (match-string 0 text) table)))
12436 t t text)))
12437 text)))
12439 (defun org-xor (a b)
12440 "Exclusive or."
12441 (if a (not b) b))
12443 (defun org-get-header (header)
12444 "Find a header field in the current buffer."
12445 (save-excursion
12446 (goto-char (point-min))
12447 (let ((case-fold-search t) s)
12448 (cond
12449 ((eq header 'from)
12450 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12451 (setq s (match-string 1)))
12452 (while (string-match "\"" s)
12453 (setq s (replace-match "" t t s)))
12454 (if (string-match "[<(].*" s)
12455 (setq s (replace-match "" t t s))))
12456 ((eq header 'message-id)
12457 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12458 (setq s (match-string 1))))
12459 ((eq header 'subject)
12460 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12461 (setq s (match-string 1)))))
12462 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12463 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12464 s)))
12467 (defun org-fixup-message-id-for-http (s)
12468 "Replace special characters in a message id, so it can be used in an http query."
12469 (while (string-match "<" s)
12470 (setq s (replace-match "%3C" t t s)))
12471 (while (string-match ">" s)
12472 (setq s (replace-match "%3E" t t s)))
12473 (while (string-match "@" s)
12474 (setq s (replace-match "%40" t t s)))
12477 ;;;###autoload
12478 (defun org-insert-link-global ()
12479 "Insert a link like Org-mode does.
12480 This command can be called in any mode to insert a link in Org-mode syntax."
12481 (interactive)
12482 (org-load-modules-maybe)
12483 (org-run-like-in-org-mode 'org-insert-link))
12485 (defun org-insert-link (&optional complete-file)
12486 "Insert a link. At the prompt, enter the link.
12488 Completion can be used to select a link previously stored with
12489 `org-store-link'. When the empty string is entered (i.e. if you just
12490 press RET at the prompt), the link defaults to the most recently
12491 stored link. As SPC triggers completion in the minibuffer, you need to
12492 use M-SPC or C-q SPC to force the insertion of a space character.
12494 You will also be prompted for a description, and if one is given, it will
12495 be displayed in the buffer instead of the link.
12497 If there is already a link at point, this command will allow you to edit link
12498 and description parts.
12500 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12501 selected using completion. The path to the file will be relative to
12502 the current directory if the file is in the current directory or a
12503 subdirectory. Otherwise, the link will be the absolute path as
12504 completed in the minibuffer (i.e. normally ~/path/to/file).
12506 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12507 is in the current directory or below.
12508 With three \\[universal-argument] prefixes, negate the meaning of
12509 `org-keep-stored-link-after-insertion'."
12510 (interactive "P")
12511 (let* ((wcf (current-window-configuration))
12512 (region (if (org-region-active-p)
12513 (buffer-substring (region-beginning) (region-end))))
12514 (remove (and region (list (region-beginning) (region-end))))
12515 (desc region)
12516 tmphist ; byte-compile incorrectly complains about this
12517 link entry file)
12518 (cond
12519 ((org-in-regexp org-bracket-link-regexp 1)
12520 ;; We do have a link at point, and we are going to edit it.
12521 (setq remove (list (match-beginning 0) (match-end 0)))
12522 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12523 (setq link (read-string "Link: "
12524 (org-link-unescape
12525 (org-match-string-no-properties 1)))))
12526 ((or (org-in-regexp org-angle-link-re)
12527 (org-in-regexp org-plain-link-re))
12528 ;; Convert to bracket link
12529 (setq remove (list (match-beginning 0) (match-end 0))
12530 link (read-string "Link: "
12531 (org-remove-angle-brackets (match-string 0)))))
12532 ((equal complete-file '(4))
12533 ;; Completing read for file names.
12534 (setq file (read-file-name "File: "))
12535 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12536 (pwd1 (file-name-as-directory (abbreviate-file-name
12537 (expand-file-name ".")))))
12538 (cond
12539 ((equal complete-file '(16))
12540 (setq link (org-make-link
12541 "file:"
12542 (abbreviate-file-name (expand-file-name file)))))
12543 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12544 (setq link (org-make-link "file:" (match-string 1 file))))
12545 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12546 (expand-file-name file))
12547 (setq link (org-make-link
12548 "file:" (match-string 1 (expand-file-name file)))))
12549 (t (setq link (org-make-link "file:" file))))))
12551 ;; Read link, with completion for stored links.
12552 (with-output-to-temp-buffer "*Org Links*"
12553 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12554 (when org-stored-links
12555 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12556 (princ (mapconcat
12557 (lambda (x)
12558 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12559 (reverse org-stored-links) "\n"))))
12560 (let ((cw (selected-window)))
12561 (select-window (get-buffer-window "*Org Links*"))
12562 (shrink-window-if-larger-than-buffer)
12563 (setq truncate-lines t)
12564 (select-window cw))
12565 ;; Fake a link history, containing the stored links.
12566 (setq tmphist (append (mapcar 'car org-stored-links)
12567 org-insert-link-history))
12568 (unwind-protect
12569 (setq link (org-completing-read
12570 "Link: "
12571 (append
12572 (mapcar (lambda (x) (list (concat (car x) ":")))
12573 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12574 (mapcar (lambda (x) (list (concat x ":")))
12575 org-link-types))
12576 nil nil nil
12577 'tmphist
12578 (or (car (car org-stored-links)))))
12579 (set-window-configuration wcf)
12580 (kill-buffer "*Org Links*"))
12581 (setq entry (assoc link org-stored-links))
12582 (or entry (push link org-insert-link-history))
12583 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12584 (not org-keep-stored-link-after-insertion))
12585 (setq org-stored-links (delq (assoc link org-stored-links)
12586 org-stored-links)))
12587 (setq desc (or desc (nth 1 entry)))))
12589 (if (string-match org-plain-link-re link)
12590 ;; URL-like link, normalize the use of angular brackets.
12591 (setq link (org-make-link (org-remove-angle-brackets link))))
12593 ;; Check if we are linking to the current file with a search option
12594 ;; If yes, simplify the link by using only the search option.
12595 (when (and buffer-file-name
12596 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12597 (let* ((path (match-string 1 link))
12598 (case-fold-search nil)
12599 (search (match-string 2 link)))
12600 (save-match-data
12601 (if (equal (file-truename buffer-file-name) (file-truename path))
12602 ;; We are linking to this same file, with a search option
12603 (setq link search)))))
12605 ;; Check if we can/should use a relative path. If yes, simplify the link
12606 (when (string-match "\\<file:\\(.*\\)" link)
12607 (let* ((path (match-string 1 link))
12608 (origpath path)
12609 (case-fold-search nil))
12610 (cond
12611 ((eq org-link-file-path-type 'absolute)
12612 (setq path (abbreviate-file-name (expand-file-name path))))
12613 ((eq org-link-file-path-type 'noabbrev)
12614 (setq path (expand-file-name path)))
12615 ((eq org-link-file-path-type 'relative)
12616 (setq path (file-relative-name path)))
12618 (save-match-data
12619 (if (string-match (concat "^" (regexp-quote
12620 (file-name-as-directory
12621 (expand-file-name "."))))
12622 (expand-file-name path))
12623 ;; We are linking a file with relative path name.
12624 (setq path (substring (expand-file-name path)
12625 (match-end 0)))))))
12626 (setq link (concat "file:" path))
12627 (if (equal desc origpath)
12628 (setq desc path))))
12630 (setq desc (read-string "Description: " desc))
12631 (unless (string-match "\\S-" desc) (setq desc nil))
12632 (if remove (apply 'delete-region remove))
12633 (insert (org-make-link-string link desc))))
12635 (defun org-completing-read (&rest args)
12636 (let ((minibuffer-local-completion-map
12637 (copy-keymap minibuffer-local-completion-map)))
12638 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12639 (apply 'completing-read args)))
12641 ;;; Opening/following a link
12642 (defvar org-link-search-failed nil)
12644 (defun org-next-link ()
12645 "Move forward to the next link.
12646 If the link is in hidden text, expose it."
12647 (interactive)
12648 (when (and org-link-search-failed (eq this-command last-command))
12649 (goto-char (point-min))
12650 (message "Link search wrapped back to beginning of buffer"))
12651 (setq org-link-search-failed nil)
12652 (let* ((pos (point))
12653 (ct (org-context))
12654 (a (assoc :link ct)))
12655 (if a (goto-char (nth 2 a)))
12656 (if (re-search-forward org-any-link-re nil t)
12657 (progn
12658 (goto-char (match-beginning 0))
12659 (if (org-invisible-p) (org-show-context)))
12660 (goto-char pos)
12661 (setq org-link-search-failed t)
12662 (error "No further link found"))))
12664 (defun org-previous-link ()
12665 "Move backward to the previous link.
12666 If the link is in hidden text, expose it."
12667 (interactive)
12668 (when (and org-link-search-failed (eq this-command last-command))
12669 (goto-char (point-max))
12670 (message "Link search wrapped back to end of buffer"))
12671 (setq org-link-search-failed nil)
12672 (let* ((pos (point))
12673 (ct (org-context))
12674 (a (assoc :link ct)))
12675 (if a (goto-char (nth 1 a)))
12676 (if (re-search-backward org-any-link-re nil t)
12677 (progn
12678 (goto-char (match-beginning 0))
12679 (if (org-invisible-p) (org-show-context)))
12680 (goto-char pos)
12681 (setq org-link-search-failed t)
12682 (error "No further link found"))))
12684 (defun org-find-file-at-mouse (ev)
12685 "Open file link or URL at mouse."
12686 (interactive "e")
12687 (mouse-set-point ev)
12688 (org-open-at-point 'in-emacs))
12690 (defun org-open-at-mouse (ev)
12691 "Open file link or URL at mouse."
12692 (interactive "e")
12693 (mouse-set-point ev)
12694 (org-open-at-point))
12696 (defvar org-window-config-before-follow-link nil
12697 "The window configuration before following a link.
12698 This is saved in case the need arises to restore it.")
12700 (defvar org-open-link-marker (make-marker)
12701 "Marker pointing to the location where `org-open-at-point; was called.")
12703 ;;;###autoload
12704 (defun org-open-at-point-global ()
12705 "Follow a link like Org-mode does.
12706 This command can be called in any mode to follow a link that has
12707 Org-mode syntax."
12708 (interactive)
12709 (org-run-like-in-org-mode 'org-open-at-point))
12711 (defun org-open-at-point (&optional in-emacs)
12712 "Open link at or after point.
12713 If there is no link at point, this function will search forward up to
12714 the end of the current subtree.
12715 Normally, files will be opened by an appropriate application. If the
12716 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12717 (interactive "P")
12718 (org-load-modules-maybe)
12719 (move-marker org-open-link-marker (point))
12720 (setq org-window-config-before-follow-link (current-window-configuration))
12721 (org-remove-occur-highlights nil nil t)
12722 (if (org-at-timestamp-p t)
12723 (org-follow-timestamp-link)
12724 (let (type path link line search (pos (point)))
12725 (catch 'match
12726 (save-excursion
12727 (skip-chars-forward "^]\n\r")
12728 (when (org-in-regexp org-bracket-link-regexp)
12729 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12730 (while (string-match " *\n *" link)
12731 (setq link (replace-match " " t t link)))
12732 (setq link (org-link-expand-abbrev link))
12733 (if (string-match org-link-re-with-space2 link)
12734 (setq type (match-string 1 link) path (match-string 2 link))
12735 (setq type "thisfile" path link))
12736 (throw 'match t)))
12738 (when (get-text-property (point) 'org-linked-text)
12739 (setq type "thisfile"
12740 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12741 (1+ (point)) (point))
12742 path (buffer-substring
12743 (previous-single-property-change pos 'org-linked-text)
12744 (next-single-property-change pos 'org-linked-text)))
12745 (throw 'match t))
12747 (save-excursion
12748 (when (or (org-in-regexp org-angle-link-re)
12749 (org-in-regexp org-plain-link-re))
12750 (setq type (match-string 1) path (match-string 2))
12751 (throw 'match t)))
12752 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12753 (setq type "tree-match"
12754 path (match-string 1))
12755 (throw 'match t))
12756 (save-excursion
12757 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12758 (setq type "tags"
12759 path (match-string 1))
12760 (while (string-match ":" path)
12761 (setq path (replace-match "+" t t path)))
12762 (throw 'match t))))
12763 (unless path
12764 (error "No link found"))
12765 ;; Remove any trailing spaces in path
12766 (if (string-match " +\\'" path)
12767 (setq path (replace-match "" t t path)))
12769 (cond
12771 ((assoc type org-link-protocols)
12772 (funcall (nth 1 (assoc type org-link-protocols)) path))
12774 ((equal type "mailto")
12775 (let ((cmd (car org-link-mailto-program))
12776 (args (cdr org-link-mailto-program)) args1
12777 (address path) (subject "") a)
12778 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12779 (setq address (match-string 1 path)
12780 subject (org-link-escape (match-string 2 path))))
12781 (while args
12782 (cond
12783 ((not (stringp (car args))) (push (pop args) args1))
12784 (t (setq a (pop args))
12785 (if (string-match "%a" a)
12786 (setq a (replace-match address t t a)))
12787 (if (string-match "%s" a)
12788 (setq a (replace-match subject t t a)))
12789 (push a args1))))
12790 (apply cmd (nreverse args1))))
12792 ((member type '("http" "https" "ftp" "news"))
12793 (browse-url (concat type ":" (org-link-escape
12794 path org-link-escape-chars-browser))))
12796 ((member type '("message"))
12797 (browse-url (concat type ":" path)))
12799 ((string= type "tags")
12800 (org-tags-view in-emacs path))
12801 ((string= type "thisfile")
12802 (if in-emacs
12803 (switch-to-buffer-other-window
12804 (org-get-buffer-for-internal-link (current-buffer)))
12805 (org-mark-ring-push))
12806 (let ((cmd `(org-link-search
12807 ,path
12808 ,(cond ((equal in-emacs '(4)) 'occur)
12809 ((equal in-emacs '(16)) 'org-occur)
12810 (t nil))
12811 ,pos)))
12812 (condition-case nil (eval cmd)
12813 (error (progn (widen) (eval cmd))))))
12815 ((string= type "tree-match")
12816 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12818 ((string= type "file")
12819 (if (string-match "::\\([0-9]+\\)\\'" path)
12820 (setq line (string-to-number (match-string 1 path))
12821 path (substring path 0 (match-beginning 0)))
12822 (if (string-match "::\\(.+\\)\\'" path)
12823 (setq search (match-string 1 path)
12824 path (substring path 0 (match-beginning 0)))))
12825 (if (string-match "[*?{]" (file-name-nondirectory path))
12826 (dired path)
12827 (org-open-file path in-emacs line search)))
12829 ((string= type "news")
12830 (require 'org-gnus)
12831 (org-gnus-follow-link path))
12833 ((string= type "shell")
12834 (let ((cmd path))
12835 (if (or (not org-confirm-shell-link-function)
12836 (funcall org-confirm-shell-link-function
12837 (format "Execute \"%s\" in shell? "
12838 (org-add-props cmd nil
12839 'face 'org-warning))))
12840 (progn
12841 (message "Executing %s" cmd)
12842 (shell-command cmd))
12843 (error "Abort"))))
12845 ((string= type "elisp")
12846 (let ((cmd path))
12847 (if (or (not org-confirm-elisp-link-function)
12848 (funcall org-confirm-elisp-link-function
12849 (format "Execute \"%s\" as elisp? "
12850 (org-add-props cmd nil
12851 'face 'org-warning))))
12852 (message "%s => %s" cmd (eval (read cmd)))
12853 (error "Abort"))))
12856 (browse-url-at-point)))))
12857 (move-marker org-open-link-marker nil)
12858 (run-hook-with-args 'org-follow-link-hook))
12860 ;;; File search
12862 (defvar org-create-file-search-functions nil
12863 "List of functions to construct the right search string for a file link.
12864 These functions are called in turn with point at the location to
12865 which the link should point.
12867 A function in the hook should first test if it would like to
12868 handle this file type, for example by checking the major-mode or
12869 the file extension. If it decides not to handle this file, it
12870 should just return nil to give other functions a chance. If it
12871 does handle the file, it must return the search string to be used
12872 when following the link. The search string will be part of the
12873 file link, given after a double colon, and `org-open-at-point'
12874 will automatically search for it. If special measures must be
12875 taken to make the search successful, another function should be
12876 added to the companion hook `org-execute-file-search-functions',
12877 which see.
12879 A function in this hook may also use `setq' to set the variable
12880 `description' to provide a suggestion for the descriptive text to
12881 be used for this link when it gets inserted into an Org-mode
12882 buffer with \\[org-insert-link].")
12884 (defvar org-execute-file-search-functions nil
12885 "List of functions to execute a file search triggered by a link.
12887 Functions added to this hook must accept a single argument, the
12888 search string that was part of the file link, the part after the
12889 double colon. The function must first check if it would like to
12890 handle this search, for example by checking the major-mode or the
12891 file extension. If it decides not to handle this search, it
12892 should just return nil to give other functions a chance. If it
12893 does handle the search, it must return a non-nil value to keep
12894 other functions from trying.
12896 Each function can access the current prefix argument through the
12897 variable `current-prefix-argument'. Note that a single prefix is
12898 used to force opening a link in Emacs, so it may be good to only
12899 use a numeric or double prefix to guide the search function.
12901 In case this is needed, a function in this hook can also restore
12902 the window configuration before `org-open-at-point' was called using:
12904 (set-window-configuration org-window-config-before-follow-link)")
12906 (defun org-link-search (s &optional type avoid-pos)
12907 "Search for a link search option.
12908 If S is surrounded by forward slashes, it is interpreted as a
12909 regular expression. In org-mode files, this will create an `org-occur'
12910 sparse tree. In ordinary files, `occur' will be used to list matches.
12911 If the current buffer is in `dired-mode', grep will be used to search
12912 in all files. If AVOID-POS is given, ignore matches near that position."
12913 (let ((case-fold-search t)
12914 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12915 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12916 (append '(("") (" ") ("\t") ("\n"))
12917 org-emphasis-alist)
12918 "\\|") "\\)"))
12919 (pos (point))
12920 (pre "") (post "")
12921 words re0 re1 re2 re3 re4 re5 re2a reall)
12922 (cond
12923 ;; First check if there are any special
12924 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12925 ;; Now try the builtin stuff
12926 ((save-excursion
12927 (goto-char (point-min))
12928 (and
12929 (re-search-forward
12930 (concat "<<" (regexp-quote s0) ">>") nil t)
12931 (setq pos (match-beginning 0))))
12932 ;; There is an exact target for this
12933 (goto-char pos))
12934 ((string-match "^/\\(.*\\)/$" s)
12935 ;; A regular expression
12936 (cond
12937 ((org-mode-p)
12938 (org-occur (match-string 1 s)))
12939 ;;((eq major-mode 'dired-mode)
12940 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12941 (t (org-do-occur (match-string 1 s)))))
12943 ;; A normal search strings
12944 (when (equal (string-to-char s) ?*)
12945 ;; Anchor on headlines, post may include tags.
12946 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12947 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12948 s (substring s 1)))
12949 (remove-text-properties
12950 0 (length s)
12951 '(face nil mouse-face nil keymap nil fontified nil) s)
12952 ;; Make a series of regular expressions to find a match
12953 (setq words (org-split-string s "[ \n\r\t]+")
12954 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12955 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12956 "\\)" markers)
12957 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12958 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12959 re1 (concat pre re2 post)
12960 re3 (concat pre re4 post)
12961 re5 (concat pre ".*" re4)
12962 re2 (concat pre re2)
12963 re2a (concat pre re2a)
12964 re4 (concat pre re4)
12965 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12966 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12967 re5 "\\)"
12969 (cond
12970 ((eq type 'org-occur) (org-occur reall))
12971 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12972 (t (goto-char (point-min))
12973 (if (or (org-search-not-self 1 re0 nil t)
12974 (org-search-not-self 1 re1 nil t)
12975 (org-search-not-self 1 re2 nil t)
12976 (org-search-not-self 1 re2a nil t)
12977 (org-search-not-self 1 re3 nil t)
12978 (org-search-not-self 1 re4 nil t)
12979 (org-search-not-self 1 re5 nil t)
12981 (goto-char (match-beginning 1))
12982 (goto-char pos)
12983 (error "No match")))))
12985 ;; Normal string-search
12986 (goto-char (point-min))
12987 (if (search-forward s nil t)
12988 (goto-char (match-beginning 0))
12989 (error "No match"))))
12990 (and (org-mode-p) (org-show-context 'link-search))))
12992 (defun org-search-not-self (group &rest args)
12993 "Execute `re-search-forward', but only accept matches that do not
12994 enclose the position of `org-open-link-marker'."
12995 (let ((m org-open-link-marker))
12996 (catch 'exit
12997 (while (apply 're-search-forward args)
12998 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12999 (goto-char (match-end group))
13000 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
13001 (> (match-beginning 0) (marker-position m))
13002 (< (match-end 0) (marker-position m)))
13003 (save-match-data
13004 (or (not (org-in-regexp
13005 org-bracket-link-analytic-regexp 1))
13006 (not (match-end 4)) ; no description
13007 (and (<= (match-beginning 4) (point))
13008 (>= (match-end 4) (point))))))
13009 (throw 'exit (point))))))))
13011 (defun org-get-buffer-for-internal-link (buffer)
13012 "Return a buffer to be used for displaying the link target of internal links."
13013 (cond
13014 ((not org-display-internal-link-with-indirect-buffer)
13015 buffer)
13016 ((string-match "(Clone)$" (buffer-name buffer))
13017 (message "Buffer is already a clone, not making another one")
13018 ;; we also do not modify visibility in this case
13019 buffer)
13020 (t ; make a new indirect buffer for displaying the link
13021 (let* ((bn (buffer-name buffer))
13022 (ibn (concat bn "(Clone)"))
13023 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
13024 (with-current-buffer ib (org-overview))
13025 ib))))
13027 (defun org-do-occur (regexp &optional cleanup)
13028 "Call the Emacs command `occur'.
13029 If CLEANUP is non-nil, remove the printout of the regular expression
13030 in the *Occur* buffer. This is useful if the regex is long and not useful
13031 to read."
13032 (occur regexp)
13033 (when cleanup
13034 (let ((cwin (selected-window)) win beg end)
13035 (when (setq win (get-buffer-window "*Occur*"))
13036 (select-window win))
13037 (goto-char (point-min))
13038 (when (re-search-forward "match[a-z]+" nil t)
13039 (setq beg (match-end 0))
13040 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
13041 (setq end (1- (match-beginning 0)))))
13042 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
13043 (goto-char (point-min))
13044 (select-window cwin))))
13046 ;;; The mark ring for links jumps
13048 (defvar org-mark-ring nil
13049 "Mark ring for positions before jumps in Org-mode.")
13050 (defvar org-mark-ring-last-goto nil
13051 "Last position in the mark ring used to go back.")
13052 ;; Fill and close the ring
13053 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
13054 (loop for i from 1 to org-mark-ring-length do
13055 (push (make-marker) org-mark-ring))
13056 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
13057 org-mark-ring)
13059 (defun org-mark-ring-push (&optional pos buffer)
13060 "Put the current position or POS into the mark ring and rotate it."
13061 (interactive)
13062 (setq pos (or pos (point)))
13063 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
13064 (move-marker (car org-mark-ring)
13065 (or pos (point))
13066 (or buffer (current-buffer)))
13067 (message "%s"
13068 (substitute-command-keys
13069 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
13071 (defun org-mark-ring-goto (&optional n)
13072 "Jump to the previous position in the mark ring.
13073 With prefix arg N, jump back that many stored positions. When
13074 called several times in succession, walk through the entire ring.
13075 Org-mode commands jumping to a different position in the current file,
13076 or to another Org-mode file, automatically push the old position
13077 onto the ring."
13078 (interactive "p")
13079 (let (p m)
13080 (if (eq last-command this-command)
13081 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
13082 (setq p org-mark-ring))
13083 (setq org-mark-ring-last-goto p)
13084 (setq m (car p))
13085 (switch-to-buffer (marker-buffer m))
13086 (goto-char m)
13087 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
13089 (defun org-remove-angle-brackets (s)
13090 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
13091 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
13093 (defun org-add-angle-brackets (s)
13094 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
13095 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
13098 ;;; Following specific links
13100 (defun org-follow-timestamp-link ()
13101 (cond
13102 ((org-at-date-range-p t)
13103 (let ((org-agenda-start-on-weekday)
13104 (t1 (match-string 1))
13105 (t2 (match-string 2)))
13106 (setq t1 (time-to-days (org-time-string-to-time t1))
13107 t2 (time-to-days (org-time-string-to-time t2)))
13108 (org-agenda-list nil t1 (1+ (- t2 t1)))))
13109 ((org-at-timestamp-p t)
13110 (org-agenda-list nil (time-to-days (org-time-string-to-time
13111 (substring (match-string 1) 0 10)))
13113 (t (error "This should not happen"))))
13116 ;;; BibTeX links
13118 ;; Use the custom search meachnism to construct and use search strings for
13119 ;; file links to BibTeX database entries.
13121 (defun org-create-file-search-in-bibtex ()
13122 "Create the search string and description for a BibTeX database entry."
13123 (when (eq major-mode 'bibtex-mode)
13124 ;; yes, we want to construct this search string.
13125 ;; Make a good description for this entry, using names, year and the title
13126 ;; Put it into the `description' variable which is dynamically scoped.
13127 (let ((bibtex-autokey-names 1)
13128 (bibtex-autokey-names-stretch 1)
13129 (bibtex-autokey-name-case-convert-function 'identity)
13130 (bibtex-autokey-name-separator " & ")
13131 (bibtex-autokey-additional-names " et al.")
13132 (bibtex-autokey-year-length 4)
13133 (bibtex-autokey-name-year-separator " ")
13134 (bibtex-autokey-titlewords 3)
13135 (bibtex-autokey-titleword-separator " ")
13136 (bibtex-autokey-titleword-case-convert-function 'identity)
13137 (bibtex-autokey-titleword-length 'infty)
13138 (bibtex-autokey-year-title-separator ": "))
13139 (setq description (bibtex-generate-autokey)))
13140 ;; Now parse the entry, get the key and return it.
13141 (save-excursion
13142 (bibtex-beginning-of-entry)
13143 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13145 (defun org-execute-file-search-in-bibtex (s)
13146 "Find the link search string S as a key for a database entry."
13147 (when (eq major-mode 'bibtex-mode)
13148 ;; Yes, we want to do the search in this file.
13149 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13150 (goto-char (point-min))
13151 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13152 (regexp-quote s) "[ \t\n]*,") nil t)
13153 (goto-char (match-beginning 0)))
13154 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13155 ;; Use double prefix to indicate that any web link should be browsed
13156 (let ((b (current-buffer)) (p (point)))
13157 ;; Restore the window configuration because we just use the web link
13158 (set-window-configuration org-window-config-before-follow-link)
13159 (save-excursion (set-buffer b) (goto-char p)
13160 (bibtex-url)))
13161 (recenter 0)) ; Move entry start to beginning of window
13162 ;; return t to indicate that the search is done.
13165 ;; Finally add the functions to the right hooks.
13166 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13167 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13169 ;; end of Bibtex link setup
13171 ;;; Following file links
13173 (defun org-open-file (path &optional in-emacs line search)
13174 "Open the file at PATH.
13175 First, this expands any special file name abbreviations. Then the
13176 configuration variable `org-file-apps' is checked if it contains an
13177 entry for this file type, and if yes, the corresponding command is launched.
13178 If no application is found, Emacs simply visits the file.
13179 With optional argument IN-EMACS, Emacs will visit the file.
13180 Optional LINE specifies a line to go to, optional SEARCH a string to
13181 search for. If LINE or SEARCH is given, the file will always be
13182 opened in Emacs.
13183 If the file does not exist, an error is thrown."
13184 (setq in-emacs (or in-emacs line search))
13185 (let* ((file (if (equal path "")
13186 buffer-file-name
13187 (substitute-in-file-name (expand-file-name path))))
13188 (apps (append org-file-apps (org-default-apps)))
13189 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13190 (dirp (if remp nil (file-directory-p file)))
13191 (dfile (downcase file))
13192 (old-buffer (current-buffer))
13193 (old-pos (point))
13194 (old-mode major-mode)
13195 ext cmd)
13196 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13197 (setq ext (match-string 1 dfile))
13198 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13199 (setq ext (match-string 1 dfile))))
13200 (if in-emacs
13201 (setq cmd 'emacs)
13202 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13203 (and dirp (cdr (assoc 'directory apps)))
13204 (cdr (assoc ext apps))
13205 (cdr (assoc t apps)))))
13206 (when (eq cmd 'mailcap)
13207 (require 'mailcap)
13208 (mailcap-parse-mailcaps)
13209 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13210 (command (mailcap-mime-info mime-type)))
13211 (if (stringp command)
13212 (setq cmd command)
13213 (setq cmd 'emacs))))
13214 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13215 (not (file-exists-p file))
13216 (not org-open-non-existing-files))
13217 (error "No such file: %s" file))
13218 (cond
13219 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13220 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13221 (while (string-match "['\"]%s['\"]" cmd)
13222 (setq cmd (replace-match "%s" t t cmd)))
13223 (while (string-match "%s" cmd)
13224 (setq cmd (replace-match
13225 (save-match-data (shell-quote-argument file))
13226 t t cmd)))
13227 (save-window-excursion
13228 (start-process-shell-command cmd nil cmd)))
13229 ((or (stringp cmd)
13230 (eq cmd 'emacs))
13231 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13232 (widen)
13233 (if line (goto-line line)
13234 (if search (org-link-search search))))
13235 ((consp cmd)
13236 (eval cmd))
13237 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13238 (and (org-mode-p) (eq old-mode 'org-mode)
13239 (or (not (equal old-buffer (current-buffer)))
13240 (not (equal old-pos (point))))
13241 (org-mark-ring-push old-pos old-buffer))))
13243 (defun org-default-apps ()
13244 "Return the default applications for this operating system."
13245 (cond
13246 ((eq system-type 'darwin)
13247 org-file-apps-defaults-macosx)
13248 ((eq system-type 'windows-nt)
13249 org-file-apps-defaults-windowsnt)
13250 (t org-file-apps-defaults-gnu)))
13252 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13253 (defun org-file-remote-p (file)
13254 "Test whether FILE specifies a location on a remote system.
13255 Return non-nil if the location is indeed remote.
13257 For example, the filename \"/user@host:/foo\" specifies a location
13258 on the system \"/user@host:\"."
13259 (cond ((fboundp 'file-remote-p)
13260 (file-remote-p file))
13261 ((fboundp 'tramp-handle-file-remote-p)
13262 (tramp-handle-file-remote-p file))
13263 ((and (boundp 'ange-ftp-name-format)
13264 (string-match (car ange-ftp-name-format) file))
13266 (t nil)))
13269 ;;;; Hooks for remember.el, and refiling
13271 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13272 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13274 ;;;###autoload
13275 (defun org-remember-insinuate ()
13276 "Setup remember.el for use wiht Org-mode."
13277 (require 'remember)
13278 (setq remember-annotation-functions '(org-remember-annotation))
13279 (setq remember-handler-functions '(org-remember-handler))
13280 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13282 ;;;###autoload
13283 (defun org-remember-annotation ()
13284 "Return a link to the current location as an annotation for remember.el.
13285 If you are using Org-mode files as target for data storage with
13286 remember.el, then the annotations should include a link compatible with the
13287 conventions in Org-mode. This function returns such a link."
13288 (org-store-link nil))
13290 (defconst org-remember-help
13291 "Select a destination location for the note.
13292 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13293 RET on headline -> Store as sublevel entry to current headline
13294 RET at beg-of-buf -> Append to file as level 2 headline
13295 <left>/<right> -> before/after current headline, same headings level")
13297 (defvar org-remember-previous-location nil)
13298 (defvar org-force-remember-template-char) ;; dynamically scoped
13300 ;; Save the major mode of the buffer we called remember from
13301 (defvar org-select-template-temp-major-mode nil)
13303 ;; Temporary store the buffer where remember was called from
13304 (defvar org-select-template-original-buffer nil)
13306 (defun org-select-remember-template (&optional use-char)
13307 (when org-remember-templates
13308 (let* ((pre-selected-templates
13309 (mapcar
13310 (lambda (tpl)
13311 (let ((ctxt (nth 5 tpl))
13312 (mode org-select-template-temp-major-mode)
13313 (buf org-select-template-original-buffer))
13314 (and (or (not ctxt) (eq ctxt t)
13315 (and (listp ctxt) (memq mode ctxt))
13316 (and (functionp ctxt)
13317 (with-current-buffer buf
13318 ;; Protect the user-defined function from error
13319 (condition-case nil (funcall ctxt) (error nil)))))
13320 tpl)))
13321 org-remember-templates))
13322 ;; If no template at this point, add the default templates:
13323 (pre-selected-templates1
13324 (if (not (delq nil pre-selected-templates))
13325 (mapcar (lambda(x) (if (not (nth 5 x)) x))
13326 org-remember-templates)
13327 pre-selected-templates))
13328 ;; Then unconditionnally add template for any contexts
13329 (pre-selected-templates2
13330 (append (mapcar (lambda(x) (if (eq (nth 5 x) t) x))
13331 org-remember-templates)
13332 (delq nil pre-selected-templates1)))
13333 (templates (mapcar (lambda (x)
13334 (if (stringp (car x))
13335 (append (list (nth 1 x) (car x)) (cddr x))
13336 (append (list (car x) "") (cdr x))))
13337 (delq nil pre-selected-templates2)))
13338 (char (or use-char
13339 (cond
13340 ((= (length templates) 1)
13341 (caar templates))
13342 ((and (boundp 'org-force-remember-template-char)
13343 org-force-remember-template-char)
13344 (if (stringp org-force-remember-template-char)
13345 (string-to-char org-force-remember-template-char)
13346 org-force-remember-template-char))
13348 (message "Select template: %s"
13349 (mapconcat
13350 (lambda (x)
13351 (cond
13352 ((not (string-match "\\S-" (nth 1 x)))
13353 (format "[%c]" (car x)))
13354 ((equal (downcase (car x))
13355 (downcase (aref (nth 1 x) 0)))
13356 (format "[%c]%s" (car x)
13357 (substring (nth 1 x) 1)))
13358 (t (format "[%c]%s" (car x) (nth 1 x)))))
13359 templates " "))
13360 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13361 (when (equal char0 ?\C-g)
13362 (jump-to-register remember-register)
13363 (kill-buffer remember-buffer))
13364 char0))))))
13365 (cddr (assoc char templates)))))
13367 (defvar x-last-selected-text)
13368 (defvar x-last-selected-text-primary)
13370 ;;;###autoload
13371 (defun org-remember-apply-template (&optional use-char skip-interactive)
13372 "Initialize *remember* buffer with template, invoke `org-mode'.
13373 This function should be placed into `remember-mode-hook' and in fact requires
13374 to be run from that hook to function properly."
13375 (if org-remember-templates
13376 (let* ((entry (org-select-remember-template use-char))
13377 (tpl (car entry))
13378 (plist-p (if org-store-link-plist t nil))
13379 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13380 (string-match "\\S-" (nth 1 entry)))
13381 (nth 1 entry)
13382 org-default-notes-file))
13383 (headline (nth 2 entry))
13384 (v-c (or (and (eq window-system 'x)
13385 (fboundp 'x-cut-buffer-or-selection-value)
13386 (x-cut-buffer-or-selection-value))
13387 (org-bound-and-true-p x-last-selected-text)
13388 (org-bound-and-true-p x-last-selected-text-primary)
13389 (and (> (length kill-ring) 0) (current-kill 0))))
13390 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13391 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13392 (v-u (concat "[" (substring v-t 1 -1) "]"))
13393 (v-U (concat "[" (substring v-T 1 -1) "]"))
13394 ;; `initial' and `annotation' are bound in `remember'
13395 (v-i (if (boundp 'initial) initial))
13396 (v-a (if (and (boundp 'annotation) annotation)
13397 (if (equal annotation "[[]]") "" annotation)
13398 ""))
13399 (v-A (if (and v-a
13400 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13401 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13402 v-a))
13403 (v-n user-full-name)
13404 (org-startup-folded nil)
13405 org-time-was-given org-end-time-was-given x
13406 prompt completions char time pos default histvar)
13407 (when (and file (not (file-name-absolute-p file)))
13408 (setq file (expand-file-name file org-directory)))
13409 (setq org-store-link-plist
13410 (append (list :annotation v-a :initial v-i)
13411 org-store-link-plist))
13412 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13413 (erase-buffer)
13414 (insert (substitute-command-keys
13415 (format
13416 "## Filing location: Select interactively, default, or last used:
13417 ## %s to select file and header location interactively.
13418 ## %s \"%s\" -> \"* %s\"
13419 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13420 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13421 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13422 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13423 (abbreviate-file-name (or file org-default-notes-file))
13424 (or headline "")
13425 (or (car org-remember-previous-location) "???")
13426 (or (cdr org-remember-previous-location) "???"))))
13427 (insert tpl) (goto-char (point-min))
13428 ;; Simple %-escapes
13429 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13430 (when (and initial (equal (match-string 0) "%i"))
13431 (save-match-data
13432 (let* ((lead (buffer-substring
13433 (point-at-bol) (match-beginning 0))))
13434 (setq v-i (mapconcat 'identity
13435 (org-split-string initial "\n")
13436 (concat "\n" lead))))))
13437 (replace-match
13438 (or (eval (intern (concat "v-" (match-string 1)))) "")
13439 t t))
13441 ;; %[] Insert contents of a file.
13442 (goto-char (point-min))
13443 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13444 (let ((start (match-beginning 0))
13445 (end (match-end 0))
13446 (filename (expand-file-name (match-string 1))))
13447 (goto-char start)
13448 (delete-region start end)
13449 (condition-case error
13450 (insert-file-contents filename)
13451 (error (insert (format "%%![Couldn't insert %s: %s]"
13452 filename error))))))
13453 ;; %() embedded elisp
13454 (goto-char (point-min))
13455 (while (re-search-forward "%\\((.+)\\)" nil t)
13456 (goto-char (match-beginning 0))
13457 (let ((template-start (point)))
13458 (forward-char 1)
13459 (let ((result
13460 (condition-case error
13461 (eval (read (current-buffer)))
13462 (error (format "%%![Error: %s]" error)))))
13463 (delete-region template-start (point))
13464 (insert result))))
13466 ;; From the property list
13467 (when plist-p
13468 (goto-char (point-min))
13469 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13470 (and (setq x (or (plist-get org-store-link-plist
13471 (intern (match-string 1))) ""))
13472 (replace-match x t t))))
13474 ;; Turn on org-mode in the remember buffer, set local variables
13475 (org-mode)
13476 (org-set-local 'org-finish-function 'org-remember-finalize)
13477 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13478 (org-set-local 'org-default-notes-file file))
13479 (if (and headline (stringp headline) (string-match "\\S-" headline))
13480 (org-set-local 'org-remember-default-headline headline))
13481 ;; Interactive template entries
13482 (goto-char (point-min))
13483 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13484 (setq char (if (match-end 3) (match-string 3))
13485 prompt (if (match-end 2) (match-string 2)))
13486 (goto-char (match-beginning 0))
13487 (replace-match "")
13488 (setq completions nil default nil)
13489 (when prompt
13490 (setq completions (org-split-string prompt "|")
13491 prompt (pop completions)
13492 default (car completions)
13493 histvar (intern (concat
13494 "org-remember-template-prompt-history::"
13495 (or prompt "")))
13496 completions (mapcar 'list completions)))
13497 (cond
13498 ((member char '("G" "g"))
13499 (let* ((org-last-tags-completion-table
13500 (org-global-tags-completion-table
13501 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13502 (org-add-colon-after-tag-completion t)
13503 (ins (completing-read
13504 (if prompt (concat prompt ": ") "Tags: ")
13505 'org-tags-completion-function nil nil nil
13506 'org-tags-history)))
13507 (setq ins (mapconcat 'identity
13508 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13509 ":"))
13510 (when (string-match "\\S-" ins)
13511 (or (equal (char-before) ?:) (insert ":"))
13512 (insert ins)
13513 (or (equal (char-after) ?:) (insert ":")))))
13514 (char
13515 (setq org-time-was-given (equal (upcase char) char))
13516 (setq time (org-read-date (equal (upcase char) "U") t nil
13517 prompt))
13518 (org-insert-time-stamp time org-time-was-given
13519 (member char '("u" "U"))
13520 nil nil (list org-end-time-was-given)))
13522 (insert (org-completing-read
13523 (concat (if prompt prompt "Enter string")
13524 (if default (concat " [" default "]"))
13525 ": ")
13526 completions nil nil nil histvar default)))))
13527 (goto-char (point-min))
13528 (if (re-search-forward "%\\?" nil t)
13529 (replace-match "")
13530 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13531 (org-mode)
13532 (org-set-local 'org-finish-function 'org-remember-finalize))
13533 (when (save-excursion
13534 (goto-char (point-min))
13535 (re-search-forward "%!" nil t))
13536 (replace-match "")
13537 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13539 (defun org-remember-finish-immediately ()
13540 "File remember note immediately.
13541 This should be run in `post-command-hook' and will remove itself
13542 from that hook."
13543 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13544 (when org-finish-function
13545 (funcall org-finish-function)))
13547 (defvar org-clock-marker) ; Defined below
13548 (defun org-remember-finalize ()
13549 "Finalize the remember process."
13550 (unless (fboundp 'remember-finalize)
13551 (defalias 'remember-finalize 'remember-buffer))
13552 (when (and org-clock-marker
13553 (equal (marker-buffer org-clock-marker) (current-buffer)))
13554 ;; FIXME: test this, this is w/o notetaking!
13555 (let (org-log-note-clock-out) (org-clock-out)))
13556 (when buffer-file-name
13557 (save-buffer)
13558 (setq buffer-file-name nil))
13559 (remember-finalize))
13561 ;;;###autoload
13562 (defun org-remember (&optional goto org-force-remember-template-char)
13563 "Call `remember'. If this is already a remember buffer, re-apply template.
13564 If there is an active region, make sure remember uses it as initial content
13565 of the remember buffer.
13567 When called interactively with a `C-u' prefix argument GOTO, don't remember
13568 anything, just go to the file/headline where the selected template usually
13569 stores its notes. With a double prefix arg `C-u C-u', go to the last
13570 note stored by remember.
13572 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13573 associated with a template in `org-remember-templates'."
13574 (interactive "P")
13575 (cond
13576 ((equal goto '(4)) (org-go-to-remember-target))
13577 ((equal goto '(16)) (org-remember-goto-last-stored))
13579 ;; set temporary variables that will be needed in
13580 ;; `org-select-remember-template'
13581 (setq org-select-template-temp-major-mode major-mode)
13582 (setq org-select-template-original-buffer (current-buffer))
13583 (if (memq org-finish-function '(remember-buffer remember-finalize))
13584 (progn
13585 (when (< (length org-remember-templates) 2)
13586 (error "No other template available"))
13587 (erase-buffer)
13588 (let ((annotation (plist-get org-store-link-plist :annotation))
13589 (initial (plist-get org-store-link-plist :initial)))
13590 (org-remember-apply-template))
13591 (message "Press C-c C-c to remember data"))
13592 (if (org-region-active-p)
13593 (remember (buffer-substring (point) (mark)))
13594 (call-interactively 'remember))))))
13596 (defun org-remember-goto-last-stored ()
13597 "Go to the location where the last remember note was stored."
13598 (interactive)
13599 (bookmark-jump "org-remember-last-stored")
13600 (message "This is the last note stored by remember"))
13602 (defun org-go-to-remember-target (&optional template-key)
13603 "Go to the target location of a remember template.
13604 The user is queried for the template."
13605 (interactive)
13606 (let* (org-select-template-temp-major-mode
13607 (entry (org-select-remember-template template-key))
13608 (file (nth 1 entry))
13609 (heading (nth 2 entry))
13610 visiting)
13611 (unless (and file (stringp file) (string-match "\\S-" file))
13612 (setq file org-default-notes-file))
13613 (when (and file (not (file-name-absolute-p file)))
13614 (setq file (expand-file-name file org-directory)))
13615 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13616 (setq heading org-remember-default-headline))
13617 (setq visiting (org-find-base-buffer-visiting file))
13618 (if (not visiting) (find-file-noselect file))
13619 (switch-to-buffer (or visiting (get-file-buffer file)))
13620 (widen)
13621 (goto-char (point-min))
13622 (if (re-search-forward
13623 (concat "^\\*+[ \t]+" (regexp-quote heading)
13624 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13625 nil t)
13626 (goto-char (match-beginning 0))
13627 (error "Target headline not found: %s" heading))))
13629 (defvar org-note-abort nil) ; dynamically scoped
13631 ;;;###autoload
13632 (defun org-remember-handler ()
13633 "Store stuff from remember.el into an org file.
13634 First prompts for an org file. If the user just presses return, the value
13635 of `org-default-notes-file' is used.
13636 Then the command offers the headings tree of the selected file in order to
13637 file the text at a specific location.
13638 You can either immediately press RET to get the note appended to the
13639 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13640 find a better place. Then press RET or <left> or <right> in insert the note.
13642 Key Cursor position Note gets inserted
13643 -----------------------------------------------------------------------------
13644 RET buffer-start as level 1 heading at end of file
13645 RET on headline as sublevel of the heading at cursor
13646 RET no heading at cursor position, level taken from context.
13647 Or use prefix arg to specify level manually.
13648 <left> on headline as same level, before current heading
13649 <right> on headline as same level, after current heading
13651 So the fastest way to store the note is to press RET RET to append it to
13652 the default file. This way your current train of thought is not
13653 interrupted, in accordance with the principles of remember.el.
13654 You can also get the fast execution without prompting by using
13655 C-u C-c C-c to exit the remember buffer. See also the variable
13656 `org-remember-store-without-prompt'.
13658 Before being stored away, the function ensures that the text has a
13659 headline, i.e. a first line that starts with a \"*\". If not, a headline
13660 is constructed from the current date and some additional data.
13662 If the variable `org-adapt-indentation' is non-nil, the entire text is
13663 also indented so that it starts in the same column as the headline
13664 \(i.e. after the stars).
13666 See also the variable `org-reverse-note-order'."
13667 (goto-char (point-min))
13668 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13669 (replace-match ""))
13670 (goto-char (point-max))
13671 (beginning-of-line 1)
13672 (while (looking-at "[ \t]*$\\|##.*")
13673 (delete-region (1- (point)) (point-max))
13674 (beginning-of-line 1))
13675 (catch 'quit
13676 (if org-note-abort (throw 'quit nil))
13677 (let* ((txt (buffer-substring (point-min) (point-max)))
13678 (fastp (org-xor (equal current-prefix-arg '(4))
13679 org-remember-store-without-prompt))
13680 (file (cond
13681 (fastp org-default-notes-file)
13682 ((and (eq org-remember-interactive-interface 'refile)
13683 org-refile-targets)
13684 org-default-notes-file)
13685 ((not (and (equal current-prefix-arg '(16))
13686 org-remember-previous-location))
13687 (org-get-org-file))))
13688 (heading org-remember-default-headline)
13689 (visiting (and file (org-find-base-buffer-visiting file)))
13690 (org-startup-folded nil)
13691 (org-startup-align-all-tables nil)
13692 (org-goto-start-pos 1)
13693 spos exitcmd level indent reversed)
13694 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13695 (setq file (car org-remember-previous-location)
13696 heading (cdr org-remember-previous-location)
13697 fastp t))
13698 (setq current-prefix-arg nil)
13699 (if (string-match "[ \t\n]+\\'" txt)
13700 (setq txt (replace-match "" t t txt)))
13701 ;; Modify text so that it becomes a nice subtree which can be inserted
13702 ;; into an org tree.
13703 (let* ((lines (split-string txt "\n"))
13704 first)
13705 (setq first (car lines) lines (cdr lines))
13706 (if (string-match "^\\*+ " first)
13707 ;; Is already a headline
13708 (setq indent nil)
13709 ;; We need to add a headline: Use time and first buffer line
13710 (setq lines (cons first lines)
13711 first (concat "* " (current-time-string)
13712 " (" (remember-buffer-desc) ")")
13713 indent " "))
13714 (if (and org-adapt-indentation indent)
13715 (setq lines (mapcar
13716 (lambda (x)
13717 (if (string-match "\\S-" x)
13718 (concat indent x) x))
13719 lines)))
13720 (setq txt (concat first "\n"
13721 (mapconcat 'identity lines "\n"))))
13722 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13723 (setq txt (replace-match "\n\n" t t txt))
13724 (if (string-match "[ \t\n]*\\'" txt)
13725 (setq txt (replace-match "\n" t t txt))))
13726 ;; Put the modified text back into the remember buffer, for refile.
13727 (erase-buffer)
13728 (insert txt)
13729 (goto-char (point-min))
13730 (when (and (eq org-remember-interactive-interface 'refile)
13731 (not fastp))
13732 (org-refile nil (or visiting (find-file-noselect file)))
13733 (throw 'quit t))
13734 ;; Find the file
13735 (if (not visiting) (find-file-noselect file))
13736 (with-current-buffer (or visiting (get-file-buffer file))
13737 (unless (org-mode-p)
13738 (error "Target files for remember notes must be in Org-mode"))
13739 (save-excursion
13740 (save-restriction
13741 (widen)
13742 (and (goto-char (point-min))
13743 (not (re-search-forward "^\\* " nil t))
13744 (insert "\n* " (or heading "Notes") "\n"))
13745 (setq reversed (org-notes-order-reversed-p))
13747 ;; Find the default location
13748 (when (and heading (stringp heading) (string-match "\\S-" heading))
13749 (goto-char (point-min))
13750 (if (re-search-forward
13751 (concat "^\\*+[ \t]+" (regexp-quote heading)
13752 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13753 nil t)
13754 (setq org-goto-start-pos (match-beginning 0))
13755 (when fastp
13756 (goto-char (point-max))
13757 (unless (bolp) (newline))
13758 (insert "* " heading "\n")
13759 (setq org-goto-start-pos (point-at-bol 0)))))
13761 ;; Ask the User for a location, using the appropriate interface
13762 (cond
13763 (fastp (setq spos org-goto-start-pos
13764 exitcmd 'return))
13765 ((eq org-remember-interactive-interface 'outline)
13766 (setq spos (org-get-location (current-buffer)
13767 org-remember-help)
13768 exitcmd (cdr spos)
13769 spos (car spos)))
13770 ((eq org-remember-interactive-interface 'outline-path-completion)
13771 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
13772 (org-refile-use-outline-path t))
13773 (setq spos (org-refile-get-location "Heading: ")
13774 exitcmd 'return
13775 spos (nth 3 spos))))
13776 (t (error "this should not hapen")))
13777 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13778 ; not handle this note
13779 (goto-char spos)
13780 (cond ((org-on-heading-p t)
13781 (org-back-to-heading t)
13782 (setq level (funcall outline-level))
13783 (cond
13784 ((eq exitcmd 'return)
13785 ;; sublevel of current
13786 (setq org-remember-previous-location
13787 (cons (abbreviate-file-name file)
13788 (org-get-heading 'notags)))
13789 (if reversed
13790 (outline-next-heading)
13791 (org-end-of-subtree t)
13792 (if (not (bolp))
13793 (if (looking-at "[ \t]*\n")
13794 (beginning-of-line 2)
13795 (end-of-line 1)
13796 (insert "\n"))))
13797 (bookmark-set "org-remember-last-stored")
13798 (org-paste-subtree (org-get-valid-level level 1) txt))
13799 ((eq exitcmd 'left)
13800 ;; before current
13801 (bookmark-set "org-remember-last-stored")
13802 (org-paste-subtree level txt))
13803 ((eq exitcmd 'right)
13804 ;; after current
13805 (org-end-of-subtree t)
13806 (bookmark-set "org-remember-last-stored")
13807 (org-paste-subtree level txt))
13808 (t (error "This should not happen"))))
13810 ((and (bobp) (not reversed))
13811 ;; Put it at the end, one level below level 1
13812 (save-restriction
13813 (widen)
13814 (goto-char (point-max))
13815 (if (not (bolp)) (newline))
13816 (bookmark-set "org-remember-last-stored")
13817 (org-paste-subtree (org-get-valid-level 1 1) txt)))
13819 ((and (bobp) reversed)
13820 ;; Put it at the start, as level 1
13821 (save-restriction
13822 (widen)
13823 (goto-char (point-min))
13824 (re-search-forward "^\\*+ " nil t)
13825 (beginning-of-line 1)
13826 (bookmark-set "org-remember-last-stored")
13827 (org-paste-subtree 1 txt)))
13829 ;; Put it right there, with automatic level determined by
13830 ;; org-paste-subtree or from prefix arg
13831 (bookmark-set "org-remember-last-stored")
13832 (org-paste-subtree
13833 (if (numberp current-prefix-arg) current-prefix-arg)
13834 txt)))
13835 (when remember-save-after-remembering
13836 (save-buffer)
13837 (if (not visiting) (kill-buffer (current-buffer)))))))))
13839 t) ;; return t to indicate that we took care of this note.
13841 (defun org-get-org-file ()
13842 "Read a filename, with default directory `org-directory'."
13843 (let ((default (or org-default-notes-file remember-data-file)))
13844 (read-file-name (format "File name [%s]: " default)
13845 (file-name-as-directory org-directory)
13846 default)))
13848 (defun org-notes-order-reversed-p ()
13849 "Check if the current file should receive notes in reversed order."
13850 (cond
13851 ((not org-reverse-note-order) nil)
13852 ((eq t org-reverse-note-order) t)
13853 ((not (listp org-reverse-note-order)) nil)
13854 (t (catch 'exit
13855 (let ((all org-reverse-note-order)
13856 entry)
13857 (while (setq entry (pop all))
13858 (if (string-match (car entry) buffer-file-name)
13859 (throw 'exit (cdr entry))))
13860 nil)))))
13862 ;;; Refiling
13864 (defvar org-refile-target-table nil
13865 "The list of refile targets, created by `org-refile'.")
13867 (defvar org-agenda-new-buffers nil
13868 "Buffers created to visit agenda files.")
13870 (defun org-get-refile-targets (&optional default-buffer)
13871 "Produce a table with refile targets."
13872 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
13873 targets txt re files f desc descre)
13874 (with-current-buffer (or default-buffer (current-buffer))
13875 (while (setq entry (pop entries))
13876 (setq files (car entry) desc (cdr entry))
13877 (cond
13878 ((null files) (setq files (list (current-buffer))))
13879 ((eq files 'org-agenda-files)
13880 (setq files (org-agenda-files 'unrestricted)))
13881 ((and (symbolp files) (fboundp files))
13882 (setq files (funcall files)))
13883 ((and (symbolp files) (boundp files))
13884 (setq files (symbol-value files))))
13885 (if (stringp files) (setq files (list files)))
13886 (cond
13887 ((eq (car desc) :tag)
13888 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
13889 ((eq (car desc) :todo)
13890 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
13891 ((eq (car desc) :regexp)
13892 (setq descre (cdr desc)))
13893 ((eq (car desc) :level)
13894 (setq descre (concat "^\\*\\{" (number-to-string
13895 (if org-odd-levels-only
13896 (1- (* 2 (cdr desc)))
13897 (cdr desc)))
13898 "\\}[ \t]")))
13899 ((eq (car desc) :maxlevel)
13900 (setq descre (concat "^\\*\\{1," (number-to-string
13901 (if org-odd-levels-only
13902 (1- (* 2 (cdr desc)))
13903 (cdr desc)))
13904 "\\}[ \t]")))
13905 (t (error "Bad refiling target description %s" desc)))
13906 (while (setq f (pop files))
13907 (save-excursion
13908 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
13909 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
13910 (save-excursion
13911 (save-restriction
13912 (widen)
13913 (goto-char (point-min))
13914 (while (re-search-forward descre nil t)
13915 (goto-char (point-at-bol))
13916 (when (looking-at org-complex-heading-regexp)
13917 (setq txt (match-string 4)
13918 re (concat "^" (regexp-quote
13919 (buffer-substring (match-beginning 1)
13920 (match-end 4)))))
13921 (if (match-end 5) (setq re (concat re "[ \t]+"
13922 (regexp-quote
13923 (match-string 5)))))
13924 (setq re (concat re "[ \t]*$"))
13925 (when org-refile-use-outline-path
13926 (setq txt (mapconcat 'identity
13927 (append
13928 (if (eq org-refile-use-outline-path 'file)
13929 (list (file-name-nondirectory
13930 (buffer-file-name (buffer-base-buffer))))
13931 (if (eq org-refile-use-outline-path 'full-file-path)
13932 (list (buffer-file-name (buffer-base-buffer)))))
13933 (org-get-outline-path)
13934 (list txt))
13935 "/")))
13936 (push (list txt f re (point)) targets))
13937 (goto-char (point-at-eol))))))))
13938 (nreverse targets))))
13940 (defun org-get-outline-path ()
13941 "Return the outline path to the current entry, as a list."
13942 (let (rtn)
13943 (save-excursion
13944 (while (org-up-heading-safe)
13945 (when (looking-at org-complex-heading-regexp)
13946 (push (org-match-string-no-properties 4) rtn)))
13947 rtn)))
13949 (defvar org-refile-history nil
13950 "History for refiling operations.")
13952 (defun org-refile (&optional goto default-buffer)
13953 "Move the entry at point to another heading.
13954 The list of target headings is compiled using the information in
13955 `org-refile-targets', which see. This list is created upon first use, and
13956 you can update it by calling this command with a double prefix (`C-u C-u').
13957 FIXME: Can we find a better way of updating?
13959 At the target location, the entry is filed as a subitem of the target heading.
13960 Depending on `org-reverse-note-order', the new subitem will either be the
13961 first of the last subitem.
13963 With prefix arg GOTO, the command will only visit the target location,
13964 not actually move anything.
13965 With a double prefix `C-c C-c', go to the location where the last refiling
13966 operation has put the subtree.
13968 With a double prefix argument, the command can be used to jump to any
13969 heading in the current buffer."
13970 (interactive "P")
13971 (let* ((cbuf (current-buffer))
13972 (filename (buffer-file-name (buffer-base-buffer cbuf)))
13973 pos it nbuf file re level reversed)
13974 (if (equal goto '(16))
13975 (org-refile-goto-last-stored)
13976 (when (setq it (org-refile-get-location
13977 (if goto "Goto: " "Refile to: ") default-buffer))
13978 (setq file (nth 1 it)
13979 re (nth 2 it)
13980 pos (nth 3 it))
13981 (setq nbuf (or (find-buffer-visiting file)
13982 (find-file-noselect file)))
13983 (if goto
13984 (progn
13985 (switch-to-buffer nbuf)
13986 (goto-char pos)
13987 (org-show-context 'org-goto))
13988 (org-copy-special)
13989 (save-excursion
13990 (set-buffer (setq nbuf (or (find-buffer-visiting file)
13991 (find-file-noselect file))))
13992 (setq reversed (org-notes-order-reversed-p))
13993 (save-excursion
13994 (save-restriction
13995 (widen)
13996 (goto-char pos)
13997 (looking-at outline-regexp)
13998 (setq level (org-get-valid-level (funcall outline-level) 1))
13999 (goto-char
14000 (if reversed
14001 (outline-next-heading)
14002 (or (save-excursion (outline-get-next-sibling))
14003 (org-end-of-subtree t t)
14004 (point-max))))
14005 (bookmark-set "org-refile-last-stored")
14006 (org-paste-subtree level))))
14007 (org-cut-special)
14008 (message "Entry refiled to \"%s\"" (car it)))))))
14010 (defun org-refile-goto-last-stored ()
14011 "Go to the location where the last refile was stored."
14012 (interactive)
14013 (bookmark-jump "org-refile-last-stored")
14014 (message "This is the location of the last refile"))
14016 (defun org-refile-get-location (&optional prompt default-buffer)
14017 "Prompt the user for a refile location, using PROMPT."
14018 (let ((org-refile-targets org-refile-targets)
14019 (org-refile-use-outline-path org-refile-use-outline-path))
14020 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14021 (unless org-refile-target-table
14022 (error "No refile targets"))
14023 (let* ((cbuf (current-buffer))
14024 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14025 (fname (and filename (file-truename filename)))
14026 (tbl (mapcar
14027 (lambda (x)
14028 (if (not (equal fname (file-truename (nth 1 x))))
14029 (cons (concat (car x) " (" (file-name-nondirectory
14030 (nth 1 x)) ")")
14031 (cdr x))
14033 org-refile-target-table))
14034 (completion-ignore-case t))
14035 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14036 tbl)))
14038 ;;;; Dynamic blocks
14040 (defun org-find-dblock (name)
14041 "Find the first dynamic block with name NAME in the buffer.
14042 If not found, stay at current position and return nil."
14043 (let (pos)
14044 (save-excursion
14045 (goto-char (point-min))
14046 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14047 nil t)
14048 (match-beginning 0))))
14049 (if pos (goto-char pos))
14050 pos))
14052 (defconst org-dblock-start-re
14053 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14054 "Matches the startline of a dynamic block, with parameters.")
14056 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14057 "Matches the end of a dyhamic block.")
14059 (defun org-create-dblock (plist)
14060 "Create a dynamic block section, with parameters taken from PLIST.
14061 PLIST must containe a :name entry which is used as name of the block."
14062 (unless (bolp) (newline))
14063 (let ((name (plist-get plist :name)))
14064 (insert "#+BEGIN: " name)
14065 (while plist
14066 (if (eq (car plist) :name)
14067 (setq plist (cddr plist))
14068 (insert " " (prin1-to-string (pop plist)))))
14069 (insert "\n\n#+END:\n")
14070 (beginning-of-line -2)))
14072 (defun org-prepare-dblock ()
14073 "Prepare dynamic block for refresh.
14074 This empties the block, puts the cursor at the insert position and returns
14075 the property list including an extra property :name with the block name."
14076 (unless (looking-at org-dblock-start-re)
14077 (error "Not at a dynamic block"))
14078 (let* ((begdel (1+ (match-end 0)))
14079 (name (org-no-properties (match-string 1)))
14080 (params (append (list :name name)
14081 (read (concat "(" (match-string 3) ")")))))
14082 (unless (re-search-forward org-dblock-end-re nil t)
14083 (error "Dynamic block not terminated"))
14084 (setq params
14085 (append params
14086 (list :content (buffer-substring
14087 begdel (match-beginning 0)))))
14088 (delete-region begdel (match-beginning 0))
14089 (goto-char begdel)
14090 (open-line 1)
14091 params))
14093 (defun org-map-dblocks (&optional command)
14094 "Apply COMMAND to all dynamic blocks in the current buffer.
14095 If COMMAND is not given, use `org-update-dblock'."
14096 (let ((cmd (or command 'org-update-dblock))
14097 pos)
14098 (save-excursion
14099 (goto-char (point-min))
14100 (while (re-search-forward org-dblock-start-re nil t)
14101 (goto-char (setq pos (match-beginning 0)))
14102 (condition-case nil
14103 (funcall cmd)
14104 (error (message "Error during update of dynamic block")))
14105 (goto-char pos)
14106 (unless (re-search-forward org-dblock-end-re nil t)
14107 (error "Dynamic block not terminated"))))))
14109 (defun org-dblock-update (&optional arg)
14110 "User command for updating dynamic blocks.
14111 Update the dynamic block at point. With prefix ARG, update all dynamic
14112 blocks in the buffer."
14113 (interactive "P")
14114 (if arg
14115 (org-update-all-dblocks)
14116 (or (looking-at org-dblock-start-re)
14117 (org-beginning-of-dblock))
14118 (org-update-dblock)))
14120 (defun org-update-dblock ()
14121 "Update the dynamic block at point
14122 This means to empty the block, parse for parameters and then call
14123 the correct writing function."
14124 (save-window-excursion
14125 (let* ((pos (point))
14126 (line (org-current-line))
14127 (params (org-prepare-dblock))
14128 (name (plist-get params :name))
14129 (cmd (intern (concat "org-dblock-write:" name))))
14130 (message "Updating dynamic block `%s' at line %d..." name line)
14131 (funcall cmd params)
14132 (message "Updating dynamic block `%s' at line %d...done" name line)
14133 (goto-char pos))))
14135 (defun org-beginning-of-dblock ()
14136 "Find the beginning of the dynamic block at point.
14137 Error if there is no scuh block at point."
14138 (let ((pos (point))
14139 beg)
14140 (end-of-line 1)
14141 (if (and (re-search-backward org-dblock-start-re nil t)
14142 (setq beg (match-beginning 0))
14143 (re-search-forward org-dblock-end-re nil t)
14144 (> (match-end 0) pos))
14145 (goto-char beg)
14146 (goto-char pos)
14147 (error "Not in a dynamic block"))))
14149 (defun org-update-all-dblocks ()
14150 "Update all dynamic blocks in the buffer.
14151 This function can be used in a hook."
14152 (when (org-mode-p)
14153 (org-map-dblocks 'org-update-dblock)))
14156 ;;;; Completion
14158 (defconst org-additional-option-like-keywords
14159 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14160 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
14161 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14163 (defun org-complete (&optional arg)
14164 "Perform completion on word at point.
14165 At the beginning of a headline, this completes TODO keywords as given in
14166 `org-todo-keywords'.
14167 If the current word is preceded by a backslash, completes the TeX symbols
14168 that are supported for HTML support.
14169 If the current word is preceded by \"#+\", completes special words for
14170 setting file options.
14171 In the line after \"#+STARTUP:, complete valid keywords.\"
14172 At all other locations, this simply calls the value of
14173 `org-completion-fallback-command'."
14174 (interactive "P")
14175 (org-without-partial-completion
14176 (catch 'exit
14177 (let* ((end (point))
14178 (beg1 (save-excursion
14179 (skip-chars-backward (org-re "[:alnum:]_@"))
14180 (point)))
14181 (beg (save-excursion
14182 (skip-chars-backward "a-zA-Z0-9_:$")
14183 (point)))
14184 (confirm (lambda (x) (stringp (car x))))
14185 (searchhead (equal (char-before beg) ?*))
14186 (tag (and (equal (char-before beg1) ?:)
14187 (equal (char-after (point-at-bol)) ?*)))
14188 (prop (and (equal (char-before beg1) ?:)
14189 (not (equal (char-after (point-at-bol)) ?*))))
14190 (texp (equal (char-before beg) ?\\))
14191 (link (equal (char-before beg) ?\[))
14192 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14193 beg)
14194 "#+"))
14195 (startup (string-match "^#\\+STARTUP:.*"
14196 (buffer-substring (point-at-bol) (point))))
14197 (completion-ignore-case opt)
14198 (type nil)
14199 (tbl nil)
14200 (table (cond
14201 (opt
14202 (setq type :opt)
14203 (append
14204 (mapcar
14205 (lambda (x)
14206 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14207 (cons (match-string 2 x) (match-string 1 x)))
14208 (org-split-string (org-get-current-options) "\n"))
14209 (mapcar 'list org-additional-option-like-keywords)))
14210 (startup
14211 (setq type :startup)
14212 org-startup-options)
14213 (link (append org-link-abbrev-alist-local
14214 org-link-abbrev-alist))
14215 (texp
14216 (setq type :tex)
14217 org-html-entities)
14218 ((string-match "\\`\\*+[ \t]+\\'"
14219 (buffer-substring (point-at-bol) beg))
14220 (setq type :todo)
14221 (mapcar 'list org-todo-keywords-1))
14222 (searchhead
14223 (setq type :searchhead)
14224 (save-excursion
14225 (goto-char (point-min))
14226 (while (re-search-forward org-todo-line-regexp nil t)
14227 (push (list
14228 (org-make-org-heading-search-string
14229 (match-string 3) t))
14230 tbl)))
14231 tbl)
14232 (tag (setq type :tag beg beg1)
14233 (or org-tag-alist (org-get-buffer-tags)))
14234 (prop (setq type :prop beg beg1)
14235 (mapcar 'list (org-buffer-property-keys nil t t)))
14236 (t (progn
14237 (call-interactively org-completion-fallback-command)
14238 (throw 'exit nil)))))
14239 (pattern (buffer-substring-no-properties beg end))
14240 (completion (try-completion pattern table confirm)))
14241 (cond ((eq completion t)
14242 (if (not (assoc (upcase pattern) table))
14243 (message "Already complete")
14244 (if (and (equal type :opt)
14245 (not (member (car (assoc (upcase pattern) table))
14246 org-additional-option-like-keywords)))
14247 (insert (substring (cdr (assoc (upcase pattern) table))
14248 (length pattern)))
14249 (if (memq type '(:tag :prop)) (insert ":")))))
14250 ((null completion)
14251 (message "Can't find completion for \"%s\"" pattern)
14252 (ding))
14253 ((not (string= pattern completion))
14254 (delete-region beg end)
14255 (if (string-match " +$" completion)
14256 (setq completion (replace-match "" t t completion)))
14257 (insert completion)
14258 (if (get-buffer-window "*Completions*")
14259 (delete-window (get-buffer-window "*Completions*")))
14260 (if (assoc completion table)
14261 (if (eq type :todo) (insert " ")
14262 (if (memq type '(:tag :prop)) (insert ":"))))
14263 (if (and (equal type :opt) (assoc completion table))
14264 (message "%s" (substitute-command-keys
14265 "Press \\[org-complete] again to insert example settings"))))
14267 (message "Making completion list...")
14268 (let ((list (sort (all-completions pattern table confirm)
14269 'string<)))
14270 (with-output-to-temp-buffer "*Completions*"
14271 (condition-case nil
14272 ;; Protection needed for XEmacs and emacs 21
14273 (display-completion-list list pattern)
14274 (error (display-completion-list list)))))
14275 (message "Making completion list...%s" "done")))))))
14277 ;;;; TODO, DEADLINE, Comments
14279 (defun org-toggle-comment ()
14280 "Change the COMMENT state of an entry."
14281 (interactive)
14282 (save-excursion
14283 (org-back-to-heading)
14284 (let (case-fold-search)
14285 (if (looking-at (concat outline-regexp
14286 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14287 (replace-match "" t t nil 1)
14288 (if (looking-at outline-regexp)
14289 (progn
14290 (goto-char (match-end 0))
14291 (insert org-comment-string " ")))))))
14293 (defvar org-last-todo-state-is-todo nil
14294 "This is non-nil when the last TODO state change led to a TODO state.
14295 If the last change removed the TODO tag or switched to DONE, then
14296 this is nil.")
14298 (defvar org-setting-tags nil) ; dynamically skiped
14300 ;; FIXME: better place
14301 (defun org-property-or-variable-value (var &optional inherit)
14302 "Check if there is a property fixing the value of VAR.
14303 If yes, return this value. If not, return the current value of the variable."
14304 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14305 (if (and prop (stringp prop) (string-match "\\S-" prop))
14306 (read prop)
14307 (symbol-value var))))
14309 (defun org-parse-local-options (string var)
14310 "Parse STRING for startup setting relevant for variable VAR."
14311 (let ((rtn (symbol-value var))
14312 e opts)
14313 (save-match-data
14314 (if (or (not string) (not (string-match "\\S-" string)))
14316 (setq opts (delq nil (mapcar (lambda (x)
14317 (setq e (assoc x org-startup-options))
14318 (if (eq (nth 1 e) var) e nil))
14319 (org-split-string string "[ \t]+"))))
14320 (if (not opts)
14322 (setq rtn nil)
14323 (while (setq e (pop opts))
14324 (if (not (nth 3 e))
14325 (setq rtn (nth 2 e))
14326 (if (not (listp rtn)) (setq rtn nil))
14327 (push (nth 2 e) rtn)))
14328 rtn)))))
14330 (defvar org-blocker-hook nil
14331 "Hook for functions that are allowed to block a state change.
14333 Each function gets as its single argument a property list, see
14334 `org-trigger-hook' for more information about this list.
14336 If any of the functions in this hook returns nil, the state change
14337 is blocked.")
14339 (defvar org-trigger-hook nil
14340 "Hook for functions that are triggered by a state change.
14342 Each function gets as its single argument a property list with at least
14343 the following elements:
14345 (:type type-of-change :position pos-at-entry-start
14346 :from old-state :to new-state)
14348 Depending on the type, more properties may be present.
14350 This mechanism is currently implemented for:
14352 TODO state changes
14353 ------------------
14354 :type todo-state-change
14355 :from previous state (keyword as a string), or nil
14356 :to new state (keyword as a string), or nil")
14359 (defun org-todo (&optional arg)
14360 "Change the TODO state of an item.
14361 The state of an item is given by a keyword at the start of the heading,
14362 like
14363 *** TODO Write paper
14364 *** DONE Call mom
14366 The different keywords are specified in the variable `org-todo-keywords'.
14367 By default the available states are \"TODO\" and \"DONE\".
14368 So for this example: when the item starts with TODO, it is changed to DONE.
14369 When it starts with DONE, the DONE is removed. And when neither TODO nor
14370 DONE are present, add TODO at the beginning of the heading.
14372 With C-u prefix arg, use completion to determine the new state.
14373 With numeric prefix arg, switch to that state.
14375 For calling through lisp, arg is also interpreted in the following way:
14376 'none -> empty state
14377 \"\"(empty string) -> switch to empty state
14378 'done -> switch to DONE
14379 'nextset -> switch to the next set of keywords
14380 'previousset -> switch to the previous set of keywords
14381 \"WAITING\" -> switch to the specified keyword, but only if it
14382 really is a member of `org-todo-keywords'."
14383 (interactive "P")
14384 (save-excursion
14385 (catch 'exit
14386 (org-back-to-heading)
14387 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14388 (or (looking-at (concat " +" org-todo-regexp " *"))
14389 (looking-at " *"))
14390 (let* ((match-data (match-data))
14391 (startpos (point-at-bol))
14392 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14393 (org-log-done org-log-done)
14394 (org-log-repeat org-log-repeat)
14395 (org-todo-log-states org-todo-log-states)
14396 (this (match-string 1))
14397 (hl-pos (match-beginning 0))
14398 (head (org-get-todo-sequence-head this))
14399 (ass (assoc head org-todo-kwd-alist))
14400 (interpret (nth 1 ass))
14401 (done-word (nth 3 ass))
14402 (final-done-word (nth 4 ass))
14403 (last-state (or this ""))
14404 (completion-ignore-case t)
14405 (member (member this org-todo-keywords-1))
14406 (tail (cdr member))
14407 (state (cond
14408 ((and org-todo-key-trigger
14409 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14410 (and (not arg) org-use-fast-todo-selection
14411 (not (eq org-use-fast-todo-selection 'prefix)))))
14412 ;; Use fast selection
14413 (org-fast-todo-selection))
14414 ((and (equal arg '(4))
14415 (or (not org-use-fast-todo-selection)
14416 (not org-todo-key-trigger)))
14417 ;; Read a state with completion
14418 (completing-read "State: " (mapcar (lambda(x) (list x))
14419 org-todo-keywords-1)
14420 nil t))
14421 ((eq arg 'right)
14422 (if this
14423 (if tail (car tail) nil)
14424 (car org-todo-keywords-1)))
14425 ((eq arg 'left)
14426 (if (equal member org-todo-keywords-1)
14428 (if this
14429 (nth (- (length org-todo-keywords-1) (length tail) 2)
14430 org-todo-keywords-1)
14431 (org-last org-todo-keywords-1))))
14432 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14433 (setq arg nil))) ; hack to fall back to cycling
14434 (arg
14435 ;; user or caller requests a specific state
14436 (cond
14437 ((equal arg "") nil)
14438 ((eq arg 'none) nil)
14439 ((eq arg 'done) (or done-word (car org-done-keywords)))
14440 ((eq arg 'nextset)
14441 (or (car (cdr (member head org-todo-heads)))
14442 (car org-todo-heads)))
14443 ((eq arg 'previousset)
14444 (let ((org-todo-heads (reverse org-todo-heads)))
14445 (or (car (cdr (member head org-todo-heads)))
14446 (car org-todo-heads))))
14447 ((car (member arg org-todo-keywords-1)))
14448 ((nth (1- (prefix-numeric-value arg))
14449 org-todo-keywords-1))))
14450 ((null member) (or head (car org-todo-keywords-1)))
14451 ((equal this final-done-word) nil) ;; -> make empty
14452 ((null tail) nil) ;; -> first entry
14453 ((eq interpret 'sequence)
14454 (car tail))
14455 ((memq interpret '(type priority))
14456 (if (eq this-command last-command)
14457 (car tail)
14458 (if (> (length tail) 0)
14459 (or done-word (car org-done-keywords))
14460 nil)))
14461 (t nil)))
14462 (next (if state (concat " " state " ") " "))
14463 (change-plist (list :type 'todo-state-change :from this :to state
14464 :position startpos))
14465 dolog now-done-p)
14466 (when org-blocker-hook
14467 (unless (save-excursion
14468 (save-match-data
14469 (run-hook-with-args-until-failure
14470 'org-blocker-hook change-plist)))
14471 (if (interactive-p)
14472 (error "TODO state change from %s to %s blocked" this state)
14473 ;; fail silently
14474 (message "TODO state change from %s to %s blocked" this state)
14475 (throw 'exit nil))))
14476 (store-match-data match-data)
14477 (replace-match next t t)
14478 (unless (pos-visible-in-window-p hl-pos)
14479 (message "TODO state changed to %s" (org-trim next)))
14480 (unless head
14481 (setq head (org-get-todo-sequence-head state)
14482 ass (assoc head org-todo-kwd-alist)
14483 interpret (nth 1 ass)
14484 done-word (nth 3 ass)
14485 final-done-word (nth 4 ass)))
14486 (when (memq arg '(nextset previousset))
14487 (message "Keyword-Set %d/%d: %s"
14488 (- (length org-todo-sets) -1
14489 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14490 (length org-todo-sets)
14491 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14492 (setq org-last-todo-state-is-todo
14493 (not (member state org-done-keywords)))
14494 (setq now-done-p (and (member state org-done-keywords)
14495 (not (member this org-done-keywords))))
14496 (and logging (org-local-logging logging))
14497 (when (and (or org-todo-log-states org-log-done)
14498 (not (memq arg '(nextset previousset))))
14499 ;; we need to look at recording a time and note
14500 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
14501 (nth 2 (assoc this org-todo-log-states))))
14502 (when (and state
14503 (member state org-not-done-keywords)
14504 (not (member this org-not-done-keywords)))
14505 ;; This is now a todo state and was not one before
14506 ;; If there was a CLOSED time stamp, get rid of it.
14507 (org-add-planning-info nil nil 'closed))
14508 (when (and now-done-p org-log-done)
14509 ;; It is now done, and it was not done before
14510 (org-add-planning-info 'closed (org-current-time))
14511 (if (and (not dolog) (eq 'note org-log-done))
14512 (org-add-log-maybe 'done state 'findpos 'note)))
14513 (when (and state dolog)
14514 ;; This is a non-nil state, and we need to log it
14515 (org-add-log-maybe 'state state 'findpos dolog)))
14516 ;; Fixup tag positioning
14517 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14518 (run-hooks 'org-after-todo-state-change-hook)
14519 (if (and arg (not (member state org-done-keywords)))
14520 (setq head (org-get-todo-sequence-head state)))
14521 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14522 ;; Do we need to trigger a repeat?
14523 (when now-done-p (org-auto-repeat-maybe state))
14524 ;; Fixup cursor location if close to the keyword
14525 (if (and (outline-on-heading-p)
14526 (not (bolp))
14527 (save-excursion (beginning-of-line 1)
14528 (looking-at org-todo-line-regexp))
14529 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14530 (progn
14531 (goto-char (or (match-end 2) (match-end 1)))
14532 (just-one-space)))
14533 (when org-trigger-hook
14534 (save-excursion
14535 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14537 (defun org-local-logging (value)
14538 "Get logging settings from a property VALUE."
14539 (let* (words w a)
14540 ;; directly set the variables, they are already local.
14541 (setq org-log-done nil
14542 org-log-repeat nil
14543 org-todo-log-states nil)
14544 (setq words (org-split-string value))
14545 (while (setq w (pop words))
14546 (cond
14547 ((setq a (assoc w org-startup-options))
14548 (and (member (nth 1 a) '(org-log-done org-log-repeat))
14549 (set (nth 1 a) (nth 2 a))))
14550 ((setq a (org-extract-log-state-settings w))
14551 (and (member (car a) org-todo-keywords-1)
14552 (push a org-todo-log-states)))))))
14554 (defun org-get-todo-sequence-head (kwd)
14555 "Return the head of the TODO sequence to which KWD belongs.
14556 If KWD is not set, check if there is a text property remembering the
14557 right sequence."
14558 (let (p)
14559 (cond
14560 ((not kwd)
14561 (or (get-text-property (point-at-bol) 'org-todo-head)
14562 (progn
14563 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14564 nil (point-at-eol)))
14565 (get-text-property p 'org-todo-head))))
14566 ((not (member kwd org-todo-keywords-1))
14567 (car org-todo-keywords-1))
14568 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14570 (defun org-fast-todo-selection ()
14571 "Fast TODO keyword selection with single keys.
14572 Returns the new TODO keyword, or nil if no state change should occur."
14573 (let* ((fulltable org-todo-key-alist)
14574 (done-keywords org-done-keywords) ;; needed for the faces.
14575 (maxlen (apply 'max (mapcar
14576 (lambda (x)
14577 (if (stringp (car x)) (string-width (car x)) 0))
14578 fulltable)))
14579 (expert nil)
14580 (fwidth (+ maxlen 3 1 3))
14581 (ncol (/ (- (window-width) 4) fwidth))
14582 tg cnt e c tbl
14583 groups ingroup)
14584 (save-window-excursion
14585 (if expert
14586 (set-buffer (get-buffer-create " *Org todo*"))
14587 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14588 (erase-buffer)
14589 (org-set-local 'org-done-keywords done-keywords)
14590 (setq tbl fulltable cnt 0)
14591 (while (setq e (pop tbl))
14592 (cond
14593 ((equal e '(:startgroup))
14594 (push '() groups) (setq ingroup t)
14595 (when (not (= cnt 0))
14596 (setq cnt 0)
14597 (insert "\n"))
14598 (insert "{ "))
14599 ((equal e '(:endgroup))
14600 (setq ingroup nil cnt 0)
14601 (insert "}\n"))
14603 (setq tg (car e) c (cdr e))
14604 (if ingroup (push tg (car groups)))
14605 (setq tg (org-add-props tg nil 'face
14606 (org-get-todo-face tg)))
14607 (if (and (= cnt 0) (not ingroup)) (insert " "))
14608 (insert "[" c "] " tg (make-string
14609 (- fwidth 4 (length tg)) ?\ ))
14610 (when (= (setq cnt (1+ cnt)) ncol)
14611 (insert "\n")
14612 (if ingroup (insert " "))
14613 (setq cnt 0)))))
14614 (insert "\n")
14615 (goto-char (point-min))
14616 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14617 (fit-window-to-buffer))
14618 (message "[a-z..]:Set [SPC]:clear")
14619 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14620 (cond
14621 ((or (= c ?\C-g)
14622 (and (= c ?q) (not (rassoc c fulltable))))
14623 (setq quit-flag t))
14624 ((= c ?\ ) nil)
14625 ((setq e (rassoc c fulltable) tg (car e))
14627 (t (setq quit-flag t))))))
14629 (defun org-get-repeat ()
14630 "Check if tere is a deadline/schedule with repeater in this entry."
14631 (save-match-data
14632 (save-excursion
14633 (org-back-to-heading t)
14634 (if (re-search-forward
14635 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14636 (match-string 1)))))
14638 (defvar org-last-changed-timestamp)
14639 (defvar org-log-post-message)
14640 (defvar org-log-note-purpose)
14641 (defun org-auto-repeat-maybe (done-word)
14642 "Check if the current headline contains a repeated deadline/schedule.
14643 If yes, set TODO state back to what it was and change the base date
14644 of repeating deadline/scheduled time stamps to new date.
14645 This function is run automatically after each state change to a DONE state."
14646 ;; last-state is dynamically scoped into this function
14647 (let* ((repeat (org-get-repeat))
14648 (aa (assoc last-state org-todo-kwd-alist))
14649 (interpret (nth 1 aa))
14650 (head (nth 2 aa))
14651 (whata '(("d" . day) ("m" . month) ("y" . year)))
14652 (msg "Entry repeats: ")
14653 (org-log-done nil)
14654 (org-todo-log-states nil)
14655 (nshiftmax 10) (nshift 0)
14656 re type n what ts mb0 time)
14657 (when repeat
14658 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
14659 (org-todo (if (eq interpret 'type) last-state head))
14660 (when (and org-log-repeat
14661 (or (not (memq 'org-add-log-note
14662 (default-value 'post-command-hook)))
14663 (eq org-log-note-purpose 'done)))
14664 ;; Make sure a note is taken;
14665 (org-add-log-maybe 'state (or done-word (car org-done-keywords))
14666 'findpos org-log-repeat))
14667 (org-back-to-heading t)
14668 (org-add-planning-info nil nil 'closed)
14669 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14670 org-deadline-time-regexp "\\)\\|\\("
14671 org-ts-regexp "\\)"))
14672 (while (re-search-forward
14673 re (save-excursion (outline-next-heading) (point)) t)
14674 (setq type (if (match-end 1) org-scheduled-string
14675 (if (match-end 3) org-deadline-string "Plain:"))
14676 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
14677 mb0 (match-beginning 0))
14678 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
14679 (setq n (string-to-number (match-string 2 ts))
14680 what (match-string 3 ts))
14681 (if (equal what "w") (setq n (* n 7) what "d"))
14682 ;; Preparation, see if we need to modify the start date for the change
14683 (when (match-end 1)
14684 (setq time (save-match-data (org-time-string-to-time ts)))
14685 (cond
14686 ((equal (match-string 1 ts) ".")
14687 ;; Shift starting date to today
14688 (org-timestamp-change
14689 (- (time-to-days (current-time)) (time-to-days time))
14690 'day))
14691 ((equal (match-string 1 ts) "+")
14692 (while (< (time-to-days time) (time-to-days (current-time)))
14693 (when (= (incf nshift) nshiftmax)
14694 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
14695 (error "Abort")))
14696 (org-timestamp-change n (cdr (assoc what whata)))
14697 (sit-for .0001) ;; so we can watch the date shifting
14698 (org-at-timestamp-p t)
14699 (setq ts (match-string 1))
14700 (setq time (save-match-data (org-time-string-to-time ts))))
14701 (org-timestamp-change (- n) (cdr (assoc what whata)))
14702 ;; rematch, so that we have everything in place for the real shift
14703 (org-at-timestamp-p t)
14704 (setq ts (match-string 1))
14705 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
14706 (org-timestamp-change n (cdr (assoc what whata)))
14707 (setq msg (concat msg type org-last-changed-timestamp " "))))
14708 (setq org-log-post-message msg)
14709 (message "%s" msg))))
14711 (defun org-show-todo-tree (arg)
14712 "Make a compact tree which shows all headlines marked with TODO.
14713 The tree will show the lines where the regexp matches, and all higher
14714 headlines above the match.
14715 With a \\[universal-argument] prefix, also show the DONE entries.
14716 With a numeric prefix N, construct a sparse tree for the Nth element
14717 of `org-todo-keywords-1'."
14718 (interactive "P")
14719 (let ((case-fold-search nil)
14720 (kwd-re
14721 (cond ((null arg) org-not-done-regexp)
14722 ((equal arg '(4))
14723 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14724 (mapcar 'list org-todo-keywords-1))))
14725 (concat "\\("
14726 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14727 "\\)\\>")))
14728 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14729 (regexp-quote (nth (1- (prefix-numeric-value arg))
14730 org-todo-keywords-1)))
14731 (t (error "Invalid prefix argument: %s" arg)))))
14732 (message "%d TODO entries found"
14733 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14735 (defun org-deadline (&optional remove)
14736 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14737 With argument REMOVE, remove any deadline from the item."
14738 (interactive "P")
14739 (if remove
14740 (progn
14741 (org-remove-timestamp-with-keyword org-deadline-string)
14742 (message "Item no longer has a deadline."))
14743 (org-add-planning-info 'deadline nil 'closed)))
14745 (defun org-schedule (&optional remove)
14746 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14747 With argument REMOVE, remove any scheduling date from the item."
14748 (interactive "P")
14749 (if remove
14750 (progn
14751 (org-remove-timestamp-with-keyword org-scheduled-string)
14752 (message "Item is no longer scheduled."))
14753 (org-add-planning-info 'scheduled nil 'closed)))
14755 (defun org-remove-timestamp-with-keyword (keyword)
14756 "Remove all time stamps with KEYWORD in the current entry."
14757 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
14758 beg)
14759 (save-excursion
14760 (org-back-to-heading t)
14761 (setq beg (point))
14762 (org-end-of-subtree t t)
14763 (while (re-search-backward re beg t)
14764 (replace-match "")
14765 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
14766 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
14768 (defun org-add-planning-info (what &optional time &rest remove)
14769 "Insert new timestamp with keyword in the line directly after the headline.
14770 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14771 If non is given, the user is prompted for a date.
14772 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14773 be removed."
14774 (interactive)
14775 (let (org-time-was-given org-end-time-was-given ts
14776 end default-time default-input)
14778 (when (and (not time) (memq what '(scheduled deadline)))
14779 ;; Try to get a default date/time from existing timestamp
14780 (save-excursion
14781 (org-back-to-heading t)
14782 (setq end (save-excursion (outline-next-heading) (point)))
14783 (when (re-search-forward (if (eq what 'scheduled)
14784 org-scheduled-time-regexp
14785 org-deadline-time-regexp)
14786 end t)
14787 (setq ts (match-string 1)
14788 default-time
14789 (apply 'encode-time (org-parse-time-string ts))
14790 default-input (and ts (org-get-compact-tod ts))))))
14791 (when what
14792 ;; If necessary, get the time from the user
14793 (setq time (or time (org-read-date nil 'to-time nil nil
14794 default-time default-input))))
14796 (when (and org-insert-labeled-timestamps-at-point
14797 (member what '(scheduled deadline)))
14798 (insert
14799 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14800 (org-insert-time-stamp time org-time-was-given
14801 nil nil nil (list org-end-time-was-given))
14802 (setq what nil))
14803 (save-excursion
14804 (save-restriction
14805 (let (col list elt ts buffer-invisibility-spec)
14806 (org-back-to-heading t)
14807 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14808 (goto-char (match-end 1))
14809 (setq col (current-column))
14810 (goto-char (match-end 0))
14811 (if (eobp) (insert "\n") (forward-char 1))
14812 (if (and (not (looking-at outline-regexp))
14813 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14814 "[^\r\n]*"))
14815 (not (equal (match-string 1) org-clock-string)))
14816 (narrow-to-region (match-beginning 0) (match-end 0))
14817 (insert-before-markers "\n")
14818 (backward-char 1)
14819 (narrow-to-region (point) (point))
14820 (indent-to-column col))
14821 ;; Check if we have to remove something.
14822 (setq list (cons what remove))
14823 (while list
14824 (setq elt (pop list))
14825 (goto-char (point-min))
14826 (when (or (and (eq elt 'scheduled)
14827 (re-search-forward org-scheduled-time-regexp nil t))
14828 (and (eq elt 'deadline)
14829 (re-search-forward org-deadline-time-regexp nil t))
14830 (and (eq elt 'closed)
14831 (re-search-forward org-closed-time-regexp nil t)))
14832 (replace-match "")
14833 (if (looking-at "--+<[^>]+>") (replace-match ""))
14834 (if (looking-at " +") (replace-match ""))))
14835 (goto-char (point-max))
14836 (when what
14837 (insert
14838 (if (not (equal (char-before) ?\ )) " " "")
14839 (cond ((eq what 'scheduled) org-scheduled-string)
14840 ((eq what 'deadline) org-deadline-string)
14841 ((eq what 'closed) org-closed-string))
14842 " ")
14843 (setq ts (org-insert-time-stamp
14844 time
14845 (or org-time-was-given
14846 (and (eq what 'closed) org-log-done-with-time))
14847 (eq what 'closed)
14848 nil nil (list org-end-time-was-given)))
14849 (end-of-line 1))
14850 (goto-char (point-min))
14851 (widen)
14852 (if (looking-at "[ \t]+\r?\n")
14853 (replace-match ""))
14854 ts)))))
14856 (defvar org-log-note-marker (make-marker))
14857 (defvar org-log-note-purpose nil)
14858 (defvar org-log-note-state nil)
14859 (defvar org-log-note-how nil)
14860 (defvar org-log-note-window-configuration nil)
14861 (defvar org-log-note-return-to (make-marker))
14862 (defvar org-log-post-message nil
14863 "Message to be displayed after a log note has been stored.
14864 The auto-repeater uses this.")
14866 (defun org-add-log-maybe (&optional purpose state findpos how)
14867 "Set up the post command hook to take a note.
14868 If this is about to TODO state change, the new state is expected in STATE.
14869 When FINDPOS is non-nil, find the correct position for the note in
14870 the current entry. If not, assume that it can be inserted at point."
14871 (save-excursion
14872 (when findpos
14873 (org-back-to-heading t)
14874 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
14875 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
14876 "[^\r\n]*\\)?"))
14877 (goto-char (match-end 0))
14878 (unless org-log-states-order-reversed
14879 (and (= (char-after) ?\n) (forward-char 1))
14880 (org-skip-over-state-notes)
14881 (skip-chars-backward " \t\n\r")))
14882 (move-marker org-log-note-marker (point))
14883 (setq org-log-note-purpose purpose
14884 org-log-note-state state
14885 org-log-note-how how)
14886 (add-hook 'post-command-hook 'org-add-log-note 'append)))
14888 (defun org-skip-over-state-notes ()
14889 "Skip past the list of State notes in an entry."
14890 (if (looking-at "\n[ \t]*- State") (forward-char 1))
14891 (while (looking-at "[ \t]*- State")
14892 (condition-case nil
14893 (org-next-item)
14894 (error (org-end-of-item)))))
14896 (defun org-add-log-note (&optional purpose)
14897 "Pop up a window for taking a note, and add this note later at point."
14898 (remove-hook 'post-command-hook 'org-add-log-note)
14899 (setq org-log-note-window-configuration (current-window-configuration))
14900 (delete-other-windows)
14901 (move-marker org-log-note-return-to (point))
14902 (switch-to-buffer (marker-buffer org-log-note-marker))
14903 (goto-char org-log-note-marker)
14904 (org-switch-to-buffer-other-window "*Org Note*")
14905 (erase-buffer)
14906 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
14907 (org-store-log-note)
14908 (let ((org-inhibit-startup t)) (org-mode))
14909 (insert (format "# Insert note for %s.
14910 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
14911 (cond
14912 ((eq org-log-note-purpose 'clock-out) "stopped clock")
14913 ((eq org-log-note-purpose 'done) "closed todo item")
14914 ((eq org-log-note-purpose 'state)
14915 (format "state change to \"%s\"" org-log-note-state))
14916 (t (error "This should not happen")))))
14917 (org-set-local 'org-finish-function 'org-store-log-note)))
14919 (defun org-store-log-note ()
14920 "Finish taking a log note, and insert it to where it belongs."
14921 (let ((txt (buffer-string))
14922 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
14923 lines ind)
14924 (kill-buffer (current-buffer))
14925 (while (string-match "\\`#.*\n[ \t\n]*" txt)
14926 (setq txt (replace-match "" t t txt)))
14927 (if (string-match "\\s-+\\'" txt)
14928 (setq txt (replace-match "" t t txt)))
14929 (setq lines (org-split-string txt "\n"))
14930 (when (and note (string-match "\\S-" note))
14931 (setq note
14932 (org-replace-escapes
14933 note
14934 (list (cons "%u" (user-login-name))
14935 (cons "%U" user-full-name)
14936 (cons "%t" (format-time-string
14937 (org-time-stamp-format 'long 'inactive)
14938 (current-time)))
14939 (cons "%s" (if org-log-note-state
14940 (concat "\"" org-log-note-state "\"")
14941 "")))))
14942 (if lines (setq note (concat note " \\\\")))
14943 (push note lines))
14944 (when (or current-prefix-arg org-note-abort) (setq lines nil))
14945 (when lines
14946 (save-excursion
14947 (set-buffer (marker-buffer org-log-note-marker))
14948 (save-excursion
14949 (goto-char org-log-note-marker)
14950 (move-marker org-log-note-marker nil)
14951 (end-of-line 1)
14952 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
14953 (indent-relative nil)
14954 (insert "- " (pop lines))
14955 (org-indent-line-function)
14956 (beginning-of-line 1)
14957 (looking-at "[ \t]*")
14958 (setq ind (concat (match-string 0) " "))
14959 (end-of-line 1)
14960 (while lines (insert "\n" ind (pop lines)))))))
14961 (set-window-configuration org-log-note-window-configuration)
14962 (with-current-buffer (marker-buffer org-log-note-return-to)
14963 (goto-char org-log-note-return-to))
14964 (move-marker org-log-note-return-to nil)
14965 (and org-log-post-message (message "%s" org-log-post-message)))
14967 ;; FIXME: what else would be useful?
14968 ;; - priority
14969 ;; - date
14971 (defun org-sparse-tree (&optional arg)
14972 "Create a sparse tree, prompt for the details.
14973 This command can create sparse trees. You first need to select the type
14974 of match used to create the tree:
14976 t Show entries with a specific TODO keyword.
14977 T Show entries selected by a tags match.
14978 p Enter a property name and its value (both with completion on existing
14979 names/values) and show entries with that property.
14980 r Show entries matching a regular expression
14981 d Show deadlines due within `org-deadline-warning-days'."
14982 (interactive "P")
14983 (let (ans kwd value)
14984 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
14985 (setq ans (read-char-exclusive))
14986 (cond
14987 ((equal ans ?d)
14988 (call-interactively 'org-check-deadlines))
14989 ((equal ans ?b)
14990 (call-interactively 'org-check-before-date))
14991 ((equal ans ?t)
14992 (org-show-todo-tree '(4)))
14993 ((equal ans ?T)
14994 (call-interactively 'org-tags-sparse-tree))
14995 ((member ans '(?p ?P))
14996 (setq kwd (completing-read "Property: "
14997 (mapcar 'list (org-buffer-property-keys))))
14998 (setq value (completing-read "Value: "
14999 (mapcar 'list (org-property-values kwd))))
15000 (unless (string-match "\\`{.*}\\'" value)
15001 (setq value (concat "\"" value "\"")))
15002 (org-tags-sparse-tree arg (concat kwd "=" value)))
15003 ((member ans '(?r ?R ?/))
15004 (call-interactively 'org-occur))
15005 (t (error "No such sparse tree command \"%c\"" ans)))))
15007 (defvar org-occur-highlights nil
15008 "List of overlays used for occur matches.")
15009 (make-variable-buffer-local 'org-occur-highlights)
15010 (defvar org-occur-parameters nil
15011 "Parameters of the active org-occur calls.
15012 This is a list, each call to org-occur pushes as cons cell,
15013 containing the regular expression and the callback, onto the list.
15014 The list can contain several entries if `org-occur' has been called
15015 several time with the KEEP-PREVIOUS argument. Otherwise, this list
15016 will only contain one set of parameters. When the highlights are
15017 removed (for example with `C-c C-c', or with the next edit (depending
15018 on `org-remove-highlights-with-change'), this variable is emptied
15019 as well.")
15020 (make-variable-buffer-local 'org-occur-parameters)
15022 (defun org-occur (regexp &optional keep-previous callback)
15023 "Make a compact tree which shows all matches of REGEXP.
15024 The tree will show the lines where the regexp matches, and all higher
15025 headlines above the match. It will also show the heading after the match,
15026 to make sure editing the matching entry is easy.
15027 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15028 call to `org-occur' will be kept, to allow stacking of calls to this
15029 command.
15030 If CALLBACK is non-nil, it is a function which is called to confirm
15031 that the match should indeed be shown."
15032 (interactive "sRegexp: \nP")
15033 (unless keep-previous
15034 (org-remove-occur-highlights nil nil t))
15035 (push (cons regexp callback) org-occur-parameters)
15036 (let ((cnt 0))
15037 (save-excursion
15038 (goto-char (point-min))
15039 (if (or (not keep-previous) ; do not want to keep
15040 (not org-occur-highlights)) ; no previous matches
15041 ;; hide everything
15042 (org-overview))
15043 (while (re-search-forward regexp nil t)
15044 (when (or (not callback)
15045 (save-match-data (funcall callback)))
15046 (setq cnt (1+ cnt))
15047 (when org-highlight-sparse-tree-matches
15048 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15049 (org-show-context 'occur-tree))))
15050 (when org-remove-highlights-with-change
15051 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15052 nil 'local))
15053 (unless org-sparse-tree-open-archived-trees
15054 (org-hide-archived-subtrees (point-min) (point-max)))
15055 (run-hooks 'org-occur-hook)
15056 (if (interactive-p)
15057 (message "%d match(es) for regexp %s" cnt regexp))
15058 cnt))
15060 (defun org-show-context (&optional key)
15061 "Make sure point and context and visible.
15062 How much context is shown depends upon the variables
15063 `org-show-hierarchy-above', `org-show-following-heading'. and
15064 `org-show-siblings'."
15065 (let ((heading-p (org-on-heading-p t))
15066 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15067 (following-p (org-get-alist-option org-show-following-heading key))
15068 (entry-p (org-get-alist-option org-show-entry-below key))
15069 (siblings-p (org-get-alist-option org-show-siblings key)))
15070 (catch 'exit
15071 ;; Show heading or entry text
15072 (if (and heading-p (not entry-p))
15073 (org-flag-heading nil) ; only show the heading
15074 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15075 (org-show-hidden-entry))) ; show entire entry
15076 (when following-p
15077 ;; Show next sibling, or heading below text
15078 (save-excursion
15079 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15080 (org-flag-heading nil))))
15081 (when siblings-p (org-show-siblings))
15082 (when hierarchy-p
15083 ;; show all higher headings, possibly with siblings
15084 (save-excursion
15085 (while (and (condition-case nil
15086 (progn (org-up-heading-all 1) t)
15087 (error nil))
15088 (not (bobp)))
15089 (org-flag-heading nil)
15090 (when siblings-p (org-show-siblings))))))))
15092 (defun org-reveal (&optional siblings)
15093 "Show current entry, hierarchy above it, and the following headline.
15094 This can be used to show a consistent set of context around locations
15095 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15096 not t for the search context.
15098 With optional argument SIBLINGS, on each level of the hierarchy all
15099 siblings are shown. This repairs the tree structure to what it would
15100 look like when opened with hierarchical calls to `org-cycle'."
15101 (interactive "P")
15102 (let ((org-show-hierarchy-above t)
15103 (org-show-following-heading t)
15104 (org-show-siblings (if siblings t org-show-siblings)))
15105 (org-show-context nil)))
15107 (defun org-highlight-new-match (beg end)
15108 "Highlight from BEG to END and mark the highlight is an occur headline."
15109 (let ((ov (org-make-overlay beg end)))
15110 (org-overlay-put ov 'face 'secondary-selection)
15111 (push ov org-occur-highlights)))
15113 (defun org-remove-occur-highlights (&optional beg end noremove)
15114 "Remove the occur highlights from the buffer.
15115 BEG and END are ignored. If NOREMOVE is nil, remove this function
15116 from the `before-change-functions' in the current buffer."
15117 (interactive)
15118 (unless org-inhibit-highlight-removal
15119 (mapc 'org-delete-overlay org-occur-highlights)
15120 (setq org-occur-highlights nil)
15121 (setq org-occur-parameters nil)
15122 (unless noremove
15123 (remove-hook 'before-change-functions
15124 'org-remove-occur-highlights 'local))))
15126 ;;;; Priorities
15128 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15129 "Regular expression matching the priority indicator.")
15131 (defvar org-remove-priority-next-time nil)
15133 (defun org-priority-up ()
15134 "Increase the priority of the current item."
15135 (interactive)
15136 (org-priority 'up))
15138 (defun org-priority-down ()
15139 "Decrease the priority of the current item."
15140 (interactive)
15141 (org-priority 'down))
15143 (defun org-priority (&optional action)
15144 "Change the priority of an item by ARG.
15145 ACTION can be `set', `up', `down', or a character."
15146 (interactive)
15147 (setq action (or action 'set))
15148 (let (current new news have remove)
15149 (save-excursion
15150 (org-back-to-heading)
15151 (if (looking-at org-priority-regexp)
15152 (setq current (string-to-char (match-string 2))
15153 have t)
15154 (setq current org-default-priority))
15155 (cond
15156 ((or (eq action 'set) (integerp action))
15157 (if (integerp action)
15158 (setq new action)
15159 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15160 (setq new (read-char-exclusive)))
15161 (if (and (= (upcase org-highest-priority) org-highest-priority)
15162 (= (upcase org-lowest-priority) org-lowest-priority))
15163 (setq new (upcase new)))
15164 (cond ((equal new ?\ ) (setq remove t))
15165 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15166 (error "Priority must be between `%c' and `%c'"
15167 org-highest-priority org-lowest-priority))))
15168 ((eq action 'up)
15169 (if (and (not have) (eq last-command this-command))
15170 (setq new org-lowest-priority)
15171 (setq new (if (and org-priority-start-cycle-with-default (not have))
15172 org-default-priority (1- current)))))
15173 ((eq action 'down)
15174 (if (and (not have) (eq last-command this-command))
15175 (setq new org-highest-priority)
15176 (setq new (if (and org-priority-start-cycle-with-default (not have))
15177 org-default-priority (1+ current)))))
15178 (t (error "Invalid action")))
15179 (if (or (< (upcase new) org-highest-priority)
15180 (> (upcase new) org-lowest-priority))
15181 (setq remove t))
15182 (setq news (format "%c" new))
15183 (if have
15184 (if remove
15185 (replace-match "" t t nil 1)
15186 (replace-match news t t nil 2))
15187 (if remove
15188 (error "No priority cookie found in line")
15189 (looking-at org-todo-line-regexp)
15190 (if (match-end 2)
15191 (progn
15192 (goto-char (match-end 2))
15193 (insert " [#" news "]"))
15194 (goto-char (match-beginning 3))
15195 (insert "[#" news "] ")))))
15196 (org-preserve-lc (org-set-tags nil 'align))
15197 (if remove
15198 (message "Priority removed")
15199 (message "Priority of current item set to %s" news))))
15202 (defun org-get-priority (s)
15203 "Find priority cookie and return priority."
15204 (save-match-data
15205 (if (not (string-match org-priority-regexp s))
15206 (* 1000 (- org-lowest-priority org-default-priority))
15207 (* 1000 (- org-lowest-priority
15208 (string-to-char (match-string 2 s)))))))
15210 ;;;; Tags
15212 (defun org-scan-tags (action matcher &optional todo-only)
15213 "Scan headline tags with inheritance and produce output ACTION.
15214 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15215 evaluated, testing if a given set of tags qualifies a headline for
15216 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15217 are included in the output."
15218 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15219 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15220 (org-re
15221 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15222 (props (list 'face nil
15223 'done-face 'org-done
15224 'undone-face nil
15225 'mouse-face 'highlight
15226 'org-not-done-regexp org-not-done-regexp
15227 'org-todo-regexp org-todo-regexp
15228 'keymap org-agenda-keymap
15229 'help-echo
15230 (format "mouse-2 or RET jump to org file %s"
15231 (abbreviate-file-name
15232 (or (buffer-file-name (buffer-base-buffer))
15233 (buffer-name (buffer-base-buffer)))))))
15234 (case-fold-search nil)
15235 lspos
15236 tags tags-list tags-alist (llast 0) rtn level category i txt
15237 todo marker entry priority)
15238 (save-excursion
15239 (goto-char (point-min))
15240 (when (eq action 'sparse-tree)
15241 (org-overview)
15242 (org-remove-occur-highlights))
15243 (while (re-search-forward re nil t)
15244 (catch :skip
15245 (setq todo (if (match-end 1) (match-string 2))
15246 tags (if (match-end 4) (match-string 4)))
15247 (goto-char (setq lspos (1+ (match-beginning 0))))
15248 (setq level (org-reduced-level (funcall outline-level))
15249 category (org-get-category))
15250 (setq i llast llast level)
15251 ;; remove tag lists from same and sublevels
15252 (while (>= i level)
15253 (when (setq entry (assoc i tags-alist))
15254 (setq tags-alist (delete entry tags-alist)))
15255 (setq i (1- i)))
15256 ;; add the nex tags
15257 (when tags
15258 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15259 tags-alist
15260 (cons (cons level tags) tags-alist)))
15261 ;; compile tags for current headline
15262 (setq tags-list
15263 (if org-use-tag-inheritance
15264 (apply 'append (mapcar 'cdr tags-alist))
15265 tags))
15266 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15267 (eval matcher)
15268 (or (not org-agenda-skip-archived-trees)
15269 (not (member org-archive-tag tags-list))))
15270 (and (eq action 'agenda) (org-agenda-skip))
15271 ;; list this headline
15273 (if (eq action 'sparse-tree)
15274 (progn
15275 (and org-highlight-sparse-tree-matches
15276 (org-get-heading) (match-end 0)
15277 (org-highlight-new-match
15278 (match-beginning 0) (match-beginning 1)))
15279 (org-show-context 'tags-tree))
15280 (setq txt (org-format-agenda-item
15282 (concat
15283 (if org-tags-match-list-sublevels
15284 (make-string (1- level) ?.) "")
15285 (org-get-heading))
15286 category tags-list)
15287 priority (org-get-priority txt))
15288 (goto-char lspos)
15289 (setq marker (org-agenda-new-marker))
15290 (org-add-props txt props
15291 'org-marker marker 'org-hd-marker marker 'org-category category
15292 'priority priority 'type "tagsmatch")
15293 (push txt rtn))
15294 ;; if we are to skip sublevels, jump to end of subtree
15295 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15296 (when (and (eq action 'sparse-tree)
15297 (not org-sparse-tree-open-archived-trees))
15298 (org-hide-archived-subtrees (point-min) (point-max)))
15299 (nreverse rtn)))
15301 (defvar todo-only) ;; dynamically scoped
15303 (defun org-tags-sparse-tree (&optional todo-only match)
15304 "Create a sparse tree according to tags string MATCH.
15305 MATCH can contain positive and negative selection of tags, like
15306 \"+WORK+URGENT-WITHBOSS\".
15307 If optional argument TODO_ONLY is non-nil, only select lines that are
15308 also TODO lines."
15309 (interactive "P")
15310 (org-prepare-agenda-buffers (list (current-buffer)))
15311 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15313 (defvar org-cached-props nil)
15314 (defun org-cached-entry-get (pom property)
15315 (if (or (eq t org-use-property-inheritance)
15316 (member property org-use-property-inheritance))
15317 ;; Caching is not possible, check it directly
15318 (org-entry-get pom property 'inherit)
15319 ;; Get all properties, so that we can do complicated checks easily
15320 (cdr (assoc property (or org-cached-props
15321 (setq org-cached-props
15322 (org-entry-properties pom)))))))
15324 (defun org-global-tags-completion-table (&optional files)
15325 "Return the list of all tags in all agenda buffer/files."
15326 (save-excursion
15327 (org-uniquify
15328 (delq nil
15329 (apply 'append
15330 (mapcar
15331 (lambda (file)
15332 (set-buffer (find-file-noselect file))
15333 (append (org-get-buffer-tags)
15334 (mapcar (lambda (x) (if (stringp (car-safe x))
15335 (list (car-safe x)) nil))
15336 org-tag-alist)))
15337 (if (and files (car files))
15338 files
15339 (org-agenda-files))))))))
15341 (defun org-make-tags-matcher (match)
15342 "Create the TAGS//TODO matcher form for the selection string MATCH."
15343 ;; todo-only is scoped dynamically into this function, and the function
15344 ;; may change it it the matcher asksk for it.
15345 (unless match
15346 ;; Get a new match request, with completion
15347 (let ((org-last-tags-completion-table
15348 (org-global-tags-completion-table)))
15349 (setq match (completing-read
15350 "Match: " 'org-tags-completion-function nil nil nil
15351 'org-tags-history))))
15353 ;; Parse the string and create a lisp form
15354 (let ((match0 match)
15355 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15356 minus tag mm
15357 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15358 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15359 (if (string-match "/+" match)
15360 ;; match contains also a todo-matching request
15361 (progn
15362 (setq tagsmatch (substring match 0 (match-beginning 0))
15363 todomatch (substring match (match-end 0)))
15364 (if (string-match "^!" todomatch)
15365 (setq todo-only t todomatch (substring todomatch 1)))
15366 (if (string-match "^\\s-*$" todomatch)
15367 (setq todomatch nil)))
15368 ;; only matching tags
15369 (setq tagsmatch match todomatch nil))
15371 ;; Make the tags matcher
15372 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15373 (setq tagsmatcher t)
15374 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15375 (while (setq term (pop orterms))
15376 (while (and (equal (substring term -1) "\\") orterms)
15377 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15378 (while (string-match re term)
15379 (setq minus (and (match-end 1)
15380 (equal (match-string 1 term) "-"))
15381 tag (match-string 2 term)
15382 re-p (equal (string-to-char tag) ?{)
15383 level-p (match-end 3)
15384 prop-p (match-end 4)
15385 mm (cond
15386 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15387 (level-p `(= level ,(string-to-number
15388 (match-string 3 term))))
15389 (prop-p
15390 (setq pn (match-string 4 term)
15391 pv (match-string 5 term)
15392 cat-p (equal pn "CATEGORY")
15393 re-p (equal (string-to-char pv) ?{)
15394 pv (substring pv 1 -1))
15395 (if (equal pn "CATEGORY")
15396 (setq gv '(get-text-property (point) 'org-category))
15397 (setq gv `(org-cached-entry-get nil ,pn)))
15398 (if re-p
15399 `(string-match ,pv (or ,gv ""))
15400 `(equal ,pv (or ,gv ""))))
15401 (t `(member ,(downcase tag) tags-list)))
15402 mm (if minus (list 'not mm) mm)
15403 term (substring term (match-end 0)))
15404 (push mm tagsmatcher))
15405 (push (if (> (length tagsmatcher) 1)
15406 (cons 'and tagsmatcher)
15407 (car tagsmatcher))
15408 orlist)
15409 (setq tagsmatcher nil))
15410 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15411 (setq tagsmatcher
15412 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15414 ;; Make the todo matcher
15415 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15416 (setq todomatcher t)
15417 (setq orterms (org-split-string todomatch "|") orlist nil)
15418 (while (setq term (pop orterms))
15419 (while (string-match re term)
15420 (setq minus (and (match-end 1)
15421 (equal (match-string 1 term) "-"))
15422 kwd (match-string 2 term)
15423 re-p (equal (string-to-char kwd) ?{)
15424 term (substring term (match-end 0))
15425 mm (if re-p
15426 `(string-match ,(substring kwd 1 -1) todo)
15427 (list 'equal 'todo kwd))
15428 mm (if minus (list 'not mm) mm))
15429 (push mm todomatcher))
15430 (push (if (> (length todomatcher) 1)
15431 (cons 'and todomatcher)
15432 (car todomatcher))
15433 orlist)
15434 (setq todomatcher nil))
15435 (setq todomatcher (if (> (length orlist) 1)
15436 (cons 'or orlist) (car orlist))))
15438 ;; Return the string and lisp forms of the matcher
15439 (setq matcher (if todomatcher
15440 (list 'and tagsmatcher todomatcher)
15441 tagsmatcher))
15442 (cons match0 matcher)))
15444 (defun org-match-any-p (re list)
15445 "Does re match any element of list?"
15446 (setq list (mapcar (lambda (x) (string-match re x)) list))
15447 (delq nil list))
15449 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15450 (defvar org-tags-overlay (org-make-overlay 1 1))
15451 (org-detach-overlay org-tags-overlay)
15453 (defun org-align-tags-here (to-col)
15454 ;; Assumes that this is a headline
15455 (let ((pos (point)) (col (current-column)) tags)
15456 (beginning-of-line 1)
15457 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15458 (< pos (match-beginning 2)))
15459 (progn
15460 (setq tags (match-string 2))
15461 (goto-char (match-beginning 1))
15462 (insert " ")
15463 (delete-region (point) (1+ (match-end 0)))
15464 (backward-char 1)
15465 (move-to-column
15466 (max (1+ (current-column))
15467 (1+ col)
15468 (if (> to-col 0)
15469 to-col
15470 (- (abs to-col) (length tags))))
15472 (insert tags)
15473 (move-to-column (min (current-column) col) t))
15474 (goto-char pos))))
15476 (defun org-set-tags (&optional arg just-align)
15477 "Set the tags for the current headline.
15478 With prefix ARG, realign all tags in headings in the current buffer."
15479 (interactive "P")
15480 (let* ((re (concat "^" outline-regexp))
15481 (current (org-get-tags-string))
15482 (col (current-column))
15483 (org-setting-tags t)
15484 table current-tags inherited-tags ; computed below when needed
15485 tags p0 c0 c1 rpl)
15486 (if arg
15487 (save-excursion
15488 (goto-char (point-min))
15489 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15490 (while (re-search-forward re nil t)
15491 (org-set-tags nil t)
15492 (end-of-line 1)))
15493 (message "All tags realigned to column %d" org-tags-column))
15494 (if just-align
15495 (setq tags current)
15496 ;; Get a new set of tags from the user
15497 (save-excursion
15498 (setq table (or org-tag-alist (org-get-buffer-tags))
15499 org-last-tags-completion-table table
15500 current-tags (org-split-string current ":")
15501 inherited-tags (nreverse
15502 (nthcdr (length current-tags)
15503 (nreverse (org-get-tags-at))))
15504 tags
15505 (if (or (eq t org-use-fast-tag-selection)
15506 (and org-use-fast-tag-selection
15507 (delq nil (mapcar 'cdr table))))
15508 (org-fast-tag-selection
15509 current-tags inherited-tags table
15510 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15511 (let ((org-add-colon-after-tag-completion t))
15512 (org-trim
15513 (org-without-partial-completion
15514 (completing-read "Tags: " 'org-tags-completion-function
15515 nil nil current 'org-tags-history)))))))
15516 (while (string-match "[-+&]+" tags)
15517 ;; No boolean logic, just a list
15518 (setq tags (replace-match ":" t t tags))))
15520 (if (string-match "\\`[\t ]*\\'" tags)
15521 (setq tags "")
15522 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15523 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15525 ;; Insert new tags at the correct column
15526 (beginning-of-line 1)
15527 (cond
15528 ((and (equal current "") (equal tags "")))
15529 ((re-search-forward
15530 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15531 (point-at-eol) t)
15532 (if (equal tags "")
15533 (setq rpl "")
15534 (goto-char (match-beginning 0))
15535 (setq c0 (current-column) p0 (point)
15536 c1 (max (1+ c0) (if (> org-tags-column 0)
15537 org-tags-column
15538 (- (- org-tags-column) (length tags))))
15539 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15540 (replace-match rpl t t)
15541 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15542 tags)
15543 (t (error "Tags alignment failed")))
15544 (move-to-column col)
15545 (unless just-align
15546 (run-hooks 'org-after-tags-change-hook)))))
15548 (defun org-change-tag-in-region (beg end tag off)
15549 "Add or remove TAG for each entry in the region.
15550 This works in the agenda, and also in an org-mode buffer."
15551 (interactive
15552 (list (region-beginning) (region-end)
15553 (let ((org-last-tags-completion-table
15554 (if (org-mode-p)
15555 (org-get-buffer-tags)
15556 (org-global-tags-completion-table))))
15557 (completing-read
15558 "Tag: " 'org-tags-completion-function nil nil nil
15559 'org-tags-history))
15560 (progn
15561 (message "[s]et or [r]emove? ")
15562 (equal (read-char-exclusive) ?r))))
15563 (if (fboundp 'deactivate-mark) (deactivate-mark))
15564 (let ((agendap (equal major-mode 'org-agenda-mode))
15565 l1 l2 m buf pos newhead (cnt 0))
15566 (goto-char end)
15567 (setq l2 (1- (org-current-line)))
15568 (goto-char beg)
15569 (setq l1 (org-current-line))
15570 (loop for l from l1 to l2 do
15571 (goto-line l)
15572 (setq m (get-text-property (point) 'org-hd-marker))
15573 (when (or (and (org-mode-p) (org-on-heading-p))
15574 (and agendap m))
15575 (setq buf (if agendap (marker-buffer m) (current-buffer))
15576 pos (if agendap m (point)))
15577 (with-current-buffer buf
15578 (save-excursion
15579 (save-restriction
15580 (goto-char pos)
15581 (setq cnt (1+ cnt))
15582 (org-toggle-tag tag (if off 'off 'on))
15583 (setq newhead (org-get-heading)))))
15584 (and agendap (org-agenda-change-all-lines newhead m))))
15585 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15587 (defun org-tags-completion-function (string predicate &optional flag)
15588 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15589 (confirm (lambda (x) (stringp (car x)))))
15590 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15591 (setq s1 (match-string 1 string)
15592 s2 (match-string 2 string))
15593 (setq s1 "" s2 string))
15594 (cond
15595 ((eq flag nil)
15596 ;; try completion
15597 (setq rtn (try-completion s2 ctable confirm))
15598 (if (stringp rtn)
15599 (setq rtn
15600 (concat s1 s2 (substring rtn (length s2))
15601 (if (and org-add-colon-after-tag-completion
15602 (assoc rtn ctable))
15603 ":" ""))))
15604 rtn)
15605 ((eq flag t)
15606 ;; all-completions
15607 (all-completions s2 ctable confirm)
15609 ((eq flag 'lambda)
15610 ;; exact match?
15611 (assoc s2 ctable)))
15614 (defun org-fast-tag-insert (kwd tags face &optional end)
15615 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15616 (insert (format "%-12s" (concat kwd ":"))
15617 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15618 (or end "")))
15620 (defun org-fast-tag-show-exit (flag)
15621 (save-excursion
15622 (goto-line 3)
15623 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15624 (replace-match ""))
15625 (when flag
15626 (end-of-line 1)
15627 (move-to-column (- (window-width) 19) t)
15628 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15630 (defun org-set-current-tags-overlay (current prefix)
15631 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15632 (if (featurep 'xemacs)
15633 (org-overlay-display org-tags-overlay (concat prefix s)
15634 'secondary-selection)
15635 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15636 (org-overlay-display org-tags-overlay (concat prefix s)))))
15638 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15639 "Fast tag selection with single keys.
15640 CURRENT is the current list of tags in the headline, INHERITED is the
15641 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15642 possibly with grouping information. TODO-TABLE is a similar table with
15643 TODO keywords, should these have keys assigned to them.
15644 If the keys are nil, a-z are automatically assigned.
15645 Returns the new tags string, or nil to not change the current settings."
15646 (let* ((fulltable (append table todo-table))
15647 (maxlen (apply 'max (mapcar
15648 (lambda (x)
15649 (if (stringp (car x)) (string-width (car x)) 0))
15650 fulltable)))
15651 (buf (current-buffer))
15652 (expert (eq org-fast-tag-selection-single-key 'expert))
15653 (buffer-tags nil)
15654 (fwidth (+ maxlen 3 1 3))
15655 (ncol (/ (- (window-width) 4) fwidth))
15656 (i-face 'org-done)
15657 (c-face 'org-todo)
15658 tg cnt e c char c1 c2 ntable tbl rtn
15659 ov-start ov-end ov-prefix
15660 (exit-after-next org-fast-tag-selection-single-key)
15661 (done-keywords org-done-keywords)
15662 groups ingroup)
15663 (save-excursion
15664 (beginning-of-line 1)
15665 (if (looking-at
15666 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15667 (setq ov-start (match-beginning 1)
15668 ov-end (match-end 1)
15669 ov-prefix "")
15670 (setq ov-start (1- (point-at-eol))
15671 ov-end (1+ ov-start))
15672 (skip-chars-forward "^\n\r")
15673 (setq ov-prefix
15674 (concat
15675 (buffer-substring (1- (point)) (point))
15676 (if (> (current-column) org-tags-column)
15678 (make-string (- org-tags-column (current-column)) ?\ ))))))
15679 (org-move-overlay org-tags-overlay ov-start ov-end)
15680 (save-window-excursion
15681 (if expert
15682 (set-buffer (get-buffer-create " *Org tags*"))
15683 (delete-other-windows)
15684 (split-window-vertically)
15685 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15686 (erase-buffer)
15687 (org-set-local 'org-done-keywords done-keywords)
15688 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15689 (org-fast-tag-insert "Current" current c-face "\n\n")
15690 (org-fast-tag-show-exit exit-after-next)
15691 (org-set-current-tags-overlay current ov-prefix)
15692 (setq tbl fulltable char ?a cnt 0)
15693 (while (setq e (pop tbl))
15694 (cond
15695 ((equal e '(:startgroup))
15696 (push '() groups) (setq ingroup t)
15697 (when (not (= cnt 0))
15698 (setq cnt 0)
15699 (insert "\n"))
15700 (insert "{ "))
15701 ((equal e '(:endgroup))
15702 (setq ingroup nil cnt 0)
15703 (insert "}\n"))
15705 (setq tg (car e) c2 nil)
15706 (if (cdr e)
15707 (setq c (cdr e))
15708 ;; automatically assign a character.
15709 (setq c1 (string-to-char
15710 (downcase (substring
15711 tg (if (= (string-to-char tg) ?@) 1 0)))))
15712 (if (or (rassoc c1 ntable) (rassoc c1 table))
15713 (while (or (rassoc char ntable) (rassoc char table))
15714 (setq char (1+ char)))
15715 (setq c2 c1))
15716 (setq c (or c2 char)))
15717 (if ingroup (push tg (car groups)))
15718 (setq tg (org-add-props tg nil 'face
15719 (cond
15720 ((not (assoc tg table))
15721 (org-get-todo-face tg))
15722 ((member tg current) c-face)
15723 ((member tg inherited) i-face)
15724 (t nil))))
15725 (if (and (= cnt 0) (not ingroup)) (insert " "))
15726 (insert "[" c "] " tg (make-string
15727 (- fwidth 4 (length tg)) ?\ ))
15728 (push (cons tg c) ntable)
15729 (when (= (setq cnt (1+ cnt)) ncol)
15730 (insert "\n")
15731 (if ingroup (insert " "))
15732 (setq cnt 0)))))
15733 (setq ntable (nreverse ntable))
15734 (insert "\n")
15735 (goto-char (point-min))
15736 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15737 (fit-window-to-buffer))
15738 (setq rtn
15739 (catch 'exit
15740 (while t
15741 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15742 (if groups " [!] no groups" " [!]groups")
15743 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15744 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15745 (cond
15746 ((= c ?\r) (throw 'exit t))
15747 ((= c ?!)
15748 (setq groups (not groups))
15749 (goto-char (point-min))
15750 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15751 ((= c ?\C-c)
15752 (if (not expert)
15753 (org-fast-tag-show-exit
15754 (setq exit-after-next (not exit-after-next)))
15755 (setq expert nil)
15756 (delete-other-windows)
15757 (split-window-vertically)
15758 (org-switch-to-buffer-other-window " *Org tags*")
15759 (and (fboundp 'fit-window-to-buffer)
15760 (fit-window-to-buffer))))
15761 ((or (= c ?\C-g)
15762 (and (= c ?q) (not (rassoc c ntable))))
15763 (org-detach-overlay org-tags-overlay)
15764 (setq quit-flag t))
15765 ((= c ?\ )
15766 (setq current nil)
15767 (if exit-after-next (setq exit-after-next 'now)))
15768 ((= c ?\t)
15769 (condition-case nil
15770 (setq tg (completing-read
15771 "Tag: "
15772 (or buffer-tags
15773 (with-current-buffer buf
15774 (org-get-buffer-tags)))))
15775 (quit (setq tg "")))
15776 (when (string-match "\\S-" tg)
15777 (add-to-list 'buffer-tags (list tg))
15778 (if (member tg current)
15779 (setq current (delete tg current))
15780 (push tg current)))
15781 (if exit-after-next (setq exit-after-next 'now)))
15782 ((setq e (rassoc c todo-table) tg (car e))
15783 (with-current-buffer buf
15784 (save-excursion (org-todo tg)))
15785 (if exit-after-next (setq exit-after-next 'now)))
15786 ((setq e (rassoc c ntable) tg (car e))
15787 (if (member tg current)
15788 (setq current (delete tg current))
15789 (loop for g in groups do
15790 (if (member tg g)
15791 (mapc (lambda (x)
15792 (setq current (delete x current)))
15793 g)))
15794 (push tg current))
15795 (if exit-after-next (setq exit-after-next 'now))))
15797 ;; Create a sorted list
15798 (setq current
15799 (sort current
15800 (lambda (a b)
15801 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15802 (if (eq exit-after-next 'now) (throw 'exit t))
15803 (goto-char (point-min))
15804 (beginning-of-line 2)
15805 (delete-region (point) (point-at-eol))
15806 (org-fast-tag-insert "Current" current c-face)
15807 (org-set-current-tags-overlay current ov-prefix)
15808 (while (re-search-forward
15809 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15810 (setq tg (match-string 1))
15811 (add-text-properties
15812 (match-beginning 1) (match-end 1)
15813 (list 'face
15814 (cond
15815 ((member tg current) c-face)
15816 ((member tg inherited) i-face)
15817 (t (get-text-property (match-beginning 1) 'face))))))
15818 (goto-char (point-min)))))
15819 (org-detach-overlay org-tags-overlay)
15820 (if rtn
15821 (mapconcat 'identity current ":")
15822 nil))))
15824 (defun org-get-tags-string ()
15825 "Get the TAGS string in the current headline."
15826 (unless (org-on-heading-p t)
15827 (error "Not on a heading"))
15828 (save-excursion
15829 (beginning-of-line 1)
15830 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15831 (org-match-string-no-properties 1)
15832 "")))
15834 (defun org-get-tags ()
15835 "Get the list of tags specified in the current headline."
15836 (org-split-string (org-get-tags-string) ":"))
15838 (defun org-get-buffer-tags ()
15839 "Get a table of all tags used in the buffer, for completion."
15840 (let (tags)
15841 (save-excursion
15842 (goto-char (point-min))
15843 (while (re-search-forward
15844 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15845 (when (equal (char-after (point-at-bol 0)) ?*)
15846 (mapc (lambda (x) (add-to-list 'tags x))
15847 (org-split-string (org-match-string-no-properties 1) ":")))))
15848 (mapcar 'list tags)))
15851 ;;;; Properties
15853 ;;; Setting and retrieving properties
15855 (defconst org-special-properties
15856 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15857 "TIMESTAMP" "TIMESTAMP_IA")
15858 "The special properties valid in Org-mode.
15860 These are properties that are not defined in the property drawer,
15861 but in some other way.")
15863 (defconst org-default-properties
15864 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15865 "LOCATION" "LOGGING" "COLUMNS")
15866 "Some properties that are used by Org-mode for various purposes.
15867 Being in this list makes sure that they are offered for completion.")
15869 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15870 "Regular expression matching the first line of a property drawer.")
15872 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15873 "Regular expression matching the first line of a property drawer.")
15875 (defun org-property-action ()
15876 "Do an action on properties."
15877 (interactive)
15878 (let (c)
15879 (org-at-property-p)
15880 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15881 (setq c (read-char-exclusive))
15882 (cond
15883 ((equal c ?s)
15884 (call-interactively 'org-set-property))
15885 ((equal c ?d)
15886 (call-interactively 'org-delete-property))
15887 ((equal c ?D)
15888 (call-interactively 'org-delete-property-globally))
15889 ((equal c ?c)
15890 (call-interactively 'org-compute-property-at-point))
15891 (t (error "No such property action %c" c)))))
15893 (defun org-at-property-p ()
15894 "Is the cursor in a property line?"
15895 ;; FIXME: Does not check if we are actually in the drawer.
15896 ;; FIXME: also returns true on any drawers.....
15897 ;; This is used by C-c C-c for property action.
15898 (save-excursion
15899 (beginning-of-line 1)
15900 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
15902 (defmacro org-with-point-at (pom &rest body)
15903 "Move to buffer and point of point-or-marker POM for the duration of BODY."
15904 (declare (indent 1) (debug t))
15905 `(save-excursion
15906 (if (markerp pom) (set-buffer (marker-buffer pom)))
15907 (save-excursion
15908 (goto-char (or pom (point)))
15909 ,@body)))
15911 (defun org-get-property-block (&optional beg end force)
15912 "Return the (beg . end) range of the body of the property drawer.
15913 BEG and END can be beginning and end of subtree, if not given
15914 they will be found.
15915 If the drawer does not exist and FORCE is non-nil, create the drawer."
15916 (catch 'exit
15917 (save-excursion
15918 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
15919 (end (or end (progn (outline-next-heading) (point)))))
15920 (goto-char beg)
15921 (if (re-search-forward org-property-start-re end t)
15922 (setq beg (1+ (match-end 0)))
15923 (if force
15924 (save-excursion
15925 (org-insert-property-drawer)
15926 (setq end (progn (outline-next-heading) (point))))
15927 (throw 'exit nil))
15928 (goto-char beg)
15929 (if (re-search-forward org-property-start-re end t)
15930 (setq beg (1+ (match-end 0)))))
15931 (if (re-search-forward org-property-end-re end t)
15932 (setq end (match-beginning 0))
15933 (or force (throw 'exit nil))
15934 (goto-char beg)
15935 (setq end beg)
15936 (org-indent-line-function)
15937 (insert ":END:\n"))
15938 (cons beg end)))))
15940 (defun org-entry-properties (&optional pom which)
15941 "Get all properties of the entry at point-or-marker POM.
15942 This includes the TODO keyword, the tags, time strings for deadline,
15943 scheduled, and clocking, and any additional properties defined in the
15944 entry. The return value is an alist, keys may occur multiple times
15945 if the property key was used several times.
15946 POM may also be nil, in which case the current entry is used.
15947 If WHICH is nil or `all', get all properties. If WHICH is
15948 `special' or `standard', only get that subclass."
15949 (setq which (or which 'all))
15950 (org-with-point-at pom
15951 (let ((clockstr (substring org-clock-string 0 -1))
15952 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
15953 beg end range props sum-props key value string clocksum)
15954 (save-excursion
15955 (when (condition-case nil (org-back-to-heading t) (error nil))
15956 (setq beg (point))
15957 (setq sum-props (get-text-property (point) 'org-summaries))
15958 (setq clocksum (get-text-property (point) :org-clock-minutes))
15959 (outline-next-heading)
15960 (setq end (point))
15961 (when (memq which '(all special))
15962 ;; Get the special properties, like TODO and tags
15963 (goto-char beg)
15964 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15965 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15966 (when (looking-at org-priority-regexp)
15967 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15968 (when (and (setq value (org-get-tags-string))
15969 (string-match "\\S-" value))
15970 (push (cons "TAGS" value) props))
15971 (when (setq value (org-get-tags-at))
15972 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
15973 props))
15974 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15975 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
15976 string (if (equal key clockstr)
15977 (org-no-properties
15978 (org-trim
15979 (buffer-substring
15980 (match-beginning 3) (goto-char (point-at-eol)))))
15981 (substring (org-match-string-no-properties 3) 1 -1)))
15982 (unless key
15983 (if (= (char-after (match-beginning 3)) ?\[)
15984 (setq key "TIMESTAMP_IA")
15985 (setq key "TIMESTAMP")))
15986 (when (or (equal key clockstr) (not (assoc key props)))
15987 (push (cons key string) props)))
15991 (when (memq which '(all standard))
15992 ;; Get the standard properties, like :PORP: ...
15993 (setq range (org-get-property-block beg end))
15994 (when range
15995 (goto-char (car range))
15996 (while (re-search-forward
15997 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15998 (cdr range) t)
15999 (setq key (org-match-string-no-properties 1)
16000 value (org-trim (or (org-match-string-no-properties 2) "")))
16001 (unless (member key excluded)
16002 (push (cons key (or value "")) props)))))
16003 (if clocksum
16004 (push (cons "CLOCKSUM"
16005 (org-column-number-to-string (/ (float clocksum) 60.)
16006 'add_times))
16007 props))
16008 (append sum-props (nreverse props)))))))
16010 (defun org-entry-get (pom property &optional inherit)
16011 "Get value of PROPERTY for entry at point-or-marker POM.
16012 If INHERIT is non-nil and the entry does not have the property,
16013 then also check higher levels of the hierarchy.
16014 If the property is present but empty, the return value is the empty string.
16015 If the property is not present at all, nil is returned."
16016 (org-with-point-at pom
16017 (if inherit
16018 (org-entry-get-with-inheritance property)
16019 (if (member property org-special-properties)
16020 ;; We need a special property. Use brute force, get all properties.
16021 (cdr (assoc property (org-entry-properties nil 'special)))
16022 (let ((range (org-get-property-block)))
16023 (if (and range
16024 (goto-char (car range))
16025 (re-search-forward
16026 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16027 (cdr range) t))
16028 ;; Found the property, return it.
16029 (if (match-end 1)
16030 (org-match-string-no-properties 1)
16031 "")))))))
16033 (defun org-entry-delete (pom property)
16034 "Delete the property PROPERTY from entry at point-or-marker POM."
16035 (org-with-point-at pom
16036 (if (member property org-special-properties)
16037 nil ; cannot delete these properties.
16038 (let ((range (org-get-property-block)))
16039 (if (and range
16040 (goto-char (car range))
16041 (re-search-forward
16042 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16043 (cdr range) t))
16044 (progn
16045 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16047 nil)))))
16049 ;; Multi-values properties are properties that contain multiple values
16050 ;; These values are assumed to be single words, separated by whitespace.
16051 (defun org-entry-add-to-multivalued-property (pom property value)
16052 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16053 (let* ((old (org-entry-get pom property))
16054 (values (and old (org-split-string old "[ \t]"))))
16055 (unless (member value values)
16056 (setq values (cons value values))
16057 (org-entry-put pom property
16058 (mapconcat 'identity values " ")))))
16060 (defun org-entry-remove-from-multivalued-property (pom property value)
16061 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16062 (let* ((old (org-entry-get pom property))
16063 (values (and old (org-split-string old "[ \t]"))))
16064 (when (member value values)
16065 (setq values (delete value values))
16066 (org-entry-put pom property
16067 (mapconcat 'identity values " ")))))
16069 (defun org-entry-member-in-multivalued-property (pom property value)
16070 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16071 (let* ((old (org-entry-get pom property))
16072 (values (and old (org-split-string old "[ \t]"))))
16073 (member value values)))
16075 (defvar org-entry-property-inherited-from (make-marker))
16077 (defun org-entry-get-with-inheritance (property)
16078 "Get entry property, and search higher levels if not present."
16079 (let (tmp)
16080 (save-excursion
16081 (save-restriction
16082 (widen)
16083 (catch 'ex
16084 (while t
16085 (when (setq tmp (org-entry-get nil property))
16086 (org-back-to-heading t)
16087 (move-marker org-entry-property-inherited-from (point))
16088 (throw 'ex tmp))
16089 (or (org-up-heading-safe) (throw 'ex nil)))))
16090 (or tmp (cdr (assoc property org-local-properties))
16091 (cdr (assoc property org-global-properties))))))
16093 (defun org-entry-put (pom property value)
16094 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16095 (org-with-point-at pom
16096 (org-back-to-heading t)
16097 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16098 range)
16099 (cond
16100 ((equal property "TODO")
16101 (when (and (stringp value) (string-match "\\S-" value)
16102 (not (member value org-todo-keywords-1)))
16103 (error "\"%s\" is not a valid TODO state" value))
16104 (if (or (not value)
16105 (not (string-match "\\S-" value)))
16106 (setq value 'none))
16107 (org-todo value)
16108 (org-set-tags nil 'align))
16109 ((equal property "PRIORITY")
16110 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16111 (string-to-char value) ?\ ))
16112 (org-set-tags nil 'align))
16113 ((equal property "SCHEDULED")
16114 (if (re-search-forward org-scheduled-time-regexp end t)
16115 (cond
16116 ((eq value 'earlier) (org-timestamp-change -1 'day))
16117 ((eq value 'later) (org-timestamp-change 1 'day))
16118 (t (call-interactively 'org-schedule)))
16119 (call-interactively 'org-schedule)))
16120 ((equal property "DEADLINE")
16121 (if (re-search-forward org-deadline-time-regexp end t)
16122 (cond
16123 ((eq value 'earlier) (org-timestamp-change -1 'day))
16124 ((eq value 'later) (org-timestamp-change 1 'day))
16125 (t (call-interactively 'org-deadline)))
16126 (call-interactively 'org-deadline)))
16127 ((member property org-special-properties)
16128 (error "The %s property can not yet be set with `org-entry-put'"
16129 property))
16130 (t ; a non-special property
16131 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16132 (setq range (org-get-property-block beg end 'force))
16133 (goto-char (car range))
16134 (if (re-search-forward
16135 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16136 (progn
16137 (delete-region (match-beginning 1) (match-end 1))
16138 (goto-char (match-beginning 1)))
16139 (goto-char (cdr range))
16140 (insert "\n")
16141 (backward-char 1)
16142 (org-indent-line-function)
16143 (insert ":" property ":"))
16144 (and value (insert " " value))
16145 (org-indent-line-function)))))))
16147 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16148 "Get all property keys in the current buffer.
16149 With INCLUDE-SPECIALS, also list the special properties that relect things
16150 like tags and TODO state.
16151 With INCLUDE-DEFAULTS, also include properties that has special meaning
16152 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16153 With INCLUDE-COLUMNS, also include property names given in COLUMN
16154 formats in the current buffer."
16155 (let (rtn range cfmt cols s p)
16156 (save-excursion
16157 (save-restriction
16158 (widen)
16159 (goto-char (point-min))
16160 (while (re-search-forward org-property-start-re nil t)
16161 (setq range (org-get-property-block))
16162 (goto-char (car range))
16163 (while (re-search-forward
16164 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16165 (cdr range) t)
16166 (add-to-list 'rtn (org-match-string-no-properties 1)))
16167 (outline-next-heading))))
16169 (when include-specials
16170 (setq rtn (append org-special-properties rtn)))
16172 (when include-defaults
16173 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16175 (when include-columns
16176 (save-excursion
16177 (save-restriction
16178 (widen)
16179 (goto-char (point-min))
16180 (while (re-search-forward
16181 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16182 nil t)
16183 (setq cfmt (match-string 2) s 0)
16184 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16185 cfmt s)
16186 (setq s (match-end 0)
16187 p (match-string 1 cfmt))
16188 (unless (or (equal p "ITEM")
16189 (member p org-special-properties))
16190 (add-to-list 'rtn (match-string 1 cfmt))))))))
16192 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16194 (defun org-property-values (key)
16195 "Return a list of all values of property KEY."
16196 (save-excursion
16197 (save-restriction
16198 (widen)
16199 (goto-char (point-min))
16200 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16201 values)
16202 (while (re-search-forward re nil t)
16203 (add-to-list 'values (org-trim (match-string 1))))
16204 (delete "" values)))))
16206 (defun org-insert-property-drawer ()
16207 "Insert a property drawer into the current entry."
16208 (interactive)
16209 (org-back-to-heading t)
16210 (looking-at outline-regexp)
16211 (let ((indent (- (match-end 0)(match-beginning 0)))
16212 (beg (point))
16213 (re (concat "^[ \t]*" org-keyword-time-regexp))
16214 end hiddenp)
16215 (outline-next-heading)
16216 (setq end (point))
16217 (goto-char beg)
16218 (while (re-search-forward re end t))
16219 (setq hiddenp (org-invisible-p))
16220 (end-of-line 1)
16221 (and (equal (char-after) ?\n) (forward-char 1))
16222 (org-skip-over-state-notes)
16223 (skip-chars-backward " \t\n\r")
16224 (if (eq (char-before) ?*) (forward-char 1))
16225 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16226 (beginning-of-line 0)
16227 (indent-to-column indent)
16228 (beginning-of-line 2)
16229 (indent-to-column indent)
16230 (beginning-of-line 0)
16231 (if hiddenp
16232 (save-excursion
16233 (org-back-to-heading t)
16234 (hide-entry))
16235 (org-flag-drawer t))))
16237 (defun org-set-property (property value)
16238 "In the current entry, set PROPERTY to VALUE.
16239 When called interactively, this will prompt for a property name, offering
16240 completion on existing and default properties. And then it will prompt
16241 for a value, offering competion either on allowed values (via an inherited
16242 xxx_ALL property) or on existing values in other instances of this property
16243 in the current file."
16244 (interactive
16245 (let* ((prop (completing-read
16246 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16247 (cur (org-entry-get nil prop))
16248 (allowed (org-property-get-allowed-values nil prop 'table))
16249 (existing (mapcar 'list (org-property-values prop)))
16250 (val (if allowed
16251 (completing-read "Value: " allowed nil 'req-match)
16252 (completing-read
16253 (concat "Value" (if (and cur (string-match "\\S-" cur))
16254 (concat "[" cur "]") "")
16255 ": ")
16256 existing nil nil "" nil cur))))
16257 (list prop (if (equal val "") cur val))))
16258 (unless (equal (org-entry-get nil property) value)
16259 (org-entry-put nil property value)))
16261 (defun org-delete-property (property)
16262 "In the current entry, delete PROPERTY."
16263 (interactive
16264 (let* ((prop (completing-read
16265 "Property: " (org-entry-properties nil 'standard))))
16266 (list prop)))
16267 (message "Property %s %s" property
16268 (if (org-entry-delete nil property)
16269 "deleted"
16270 "was not present in the entry")))
16272 (defun org-delete-property-globally (property)
16273 "Remove PROPERTY globally, from all entries."
16274 (interactive
16275 (let* ((prop (completing-read
16276 "Globally remove property: "
16277 (mapcar 'list (org-buffer-property-keys)))))
16278 (list prop)))
16279 (save-excursion
16280 (save-restriction
16281 (widen)
16282 (goto-char (point-min))
16283 (let ((cnt 0))
16284 (while (re-search-forward
16285 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16286 nil t)
16287 (setq cnt (1+ cnt))
16288 (replace-match ""))
16289 (message "Property \"%s\" removed from %d entries" property cnt)))))
16291 (defvar org-columns-current-fmt-compiled) ; defined below
16293 (defun org-compute-property-at-point ()
16294 "Compute the property at point.
16295 This looks for an enclosing column format, extracts the operator and
16296 then applies it to the proerty in the column format's scope."
16297 (interactive)
16298 (unless (org-at-property-p)
16299 (error "Not at a property"))
16300 (let ((prop (org-match-string-no-properties 2)))
16301 (org-columns-get-format-and-top-level)
16302 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16303 (error "No operator defined for property %s" prop))
16304 (org-columns-compute prop)))
16306 (defun org-property-get-allowed-values (pom property &optional table)
16307 "Get allowed values for the property PROPERTY.
16308 When TABLE is non-nil, return an alist that can directly be used for
16309 completion."
16310 (let (vals)
16311 (cond
16312 ((equal property "TODO")
16313 (setq vals (org-with-point-at pom
16314 (append org-todo-keywords-1 '("")))))
16315 ((equal property "PRIORITY")
16316 (let ((n org-lowest-priority))
16317 (while (>= n org-highest-priority)
16318 (push (char-to-string n) vals)
16319 (setq n (1- n)))))
16320 ((member property org-special-properties))
16322 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16324 (when (and vals (string-match "\\S-" vals))
16325 (setq vals (car (read-from-string (concat "(" vals ")"))))
16326 (setq vals (mapcar (lambda (x)
16327 (cond ((stringp x) x)
16328 ((numberp x) (number-to-string x))
16329 ((symbolp x) (symbol-name x))
16330 (t "???")))
16331 vals)))))
16332 (if table (mapcar 'list vals) vals)))
16334 (defun org-property-previous-allowed-value (&optional previous)
16335 "Switch to the next allowed value for this property."
16336 (interactive)
16337 (org-property-next-allowed-value t))
16339 (defun org-property-next-allowed-value (&optional previous)
16340 "Switch to the next allowed value for this property."
16341 (interactive)
16342 (unless (org-at-property-p)
16343 (error "Not at a property"))
16344 (let* ((key (match-string 2))
16345 (value (match-string 3))
16346 (allowed (or (org-property-get-allowed-values (point) key)
16347 (and (member value '("[ ]" "[-]" "[X]"))
16348 '("[ ]" "[X]"))))
16349 nval)
16350 (unless allowed
16351 (error "Allowed values for this property have not been defined"))
16352 (if previous (setq allowed (reverse allowed)))
16353 (if (member value allowed)
16354 (setq nval (car (cdr (member value allowed)))))
16355 (setq nval (or nval (car allowed)))
16356 (if (equal nval value)
16357 (error "Only one allowed value for this property"))
16358 (org-at-property-p)
16359 (replace-match (concat " :" key ": " nval) t t)
16360 (org-indent-line-function)
16361 (beginning-of-line 1)
16362 (skip-chars-forward " \t")))
16364 (defun org-find-entry-with-id (ident)
16365 "Locate the entry that contains the ID property with exact value IDENT.
16366 IDENT can be a string, a symbol or a number, this function will search for
16367 the string representation of it.
16368 Return the position where this entry starts, or nil if there is no such entry."
16369 (let ((id (cond
16370 ((stringp ident) ident)
16371 ((symbol-name ident) (symbol-name ident))
16372 ((numberp ident) (number-to-string ident))
16373 (t (error "IDENT %s must be a string, symbol or number" ident))))
16374 (case-fold-search nil))
16375 (save-excursion
16376 (save-restriction
16377 (widen)
16378 (goto-char (point-min))
16379 (when (re-search-forward
16380 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16381 nil t)
16382 (org-back-to-heading)
16383 (point))))))
16385 ;;; Column View
16387 (defvar org-columns-overlays nil
16388 "Holds the list of current column overlays.")
16390 (defvar org-columns-current-fmt nil
16391 "Local variable, holds the currently active column format.")
16392 (defvar org-columns-current-fmt-compiled nil
16393 "Local variable, holds the currently active column format.
16394 This is the compiled version of the format.")
16395 (defvar org-columns-current-widths nil
16396 "Loval variable, holds the currently widths of fields.")
16397 (defvar org-columns-current-maxwidths nil
16398 "Loval variable, holds the currently active maximum column widths.")
16399 (defvar org-columns-begin-marker (make-marker)
16400 "Points to the position where last a column creation command was called.")
16401 (defvar org-columns-top-level-marker (make-marker)
16402 "Points to the position where current columns region starts.")
16404 (defvar org-columns-map (make-sparse-keymap)
16405 "The keymap valid in column display.")
16407 (defun org-columns-content ()
16408 "Switch to contents view while in columns view."
16409 (interactive)
16410 (org-overview)
16411 (org-content))
16413 (org-defkey org-columns-map "c" 'org-columns-content)
16414 (org-defkey org-columns-map "o" 'org-overview)
16415 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16416 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16417 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16418 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16419 (org-defkey org-columns-map "v" 'org-columns-show-value)
16420 (org-defkey org-columns-map "q" 'org-columns-quit)
16421 (org-defkey org-columns-map "r" 'org-columns-redo)
16422 (org-defkey org-columns-map "g" 'org-columns-redo)
16423 (org-defkey org-columns-map [left] 'backward-char)
16424 (org-defkey org-columns-map "\M-b" 'backward-char)
16425 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16426 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16427 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16428 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16429 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16430 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16431 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16432 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16433 (org-defkey org-columns-map "<" 'org-columns-narrow)
16434 (org-defkey org-columns-map ">" 'org-columns-widen)
16435 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16436 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16437 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16438 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16440 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16441 '("Column"
16442 ["Edit property" org-columns-edit-value t]
16443 ["Next allowed value" org-columns-next-allowed-value t]
16444 ["Previous allowed value" org-columns-previous-allowed-value t]
16445 ["Show full value" org-columns-show-value t]
16446 ["Edit allowed values" org-columns-edit-allowed t]
16447 "--"
16448 ["Edit column attributes" org-columns-edit-attributes t]
16449 ["Increase column width" org-columns-widen t]
16450 ["Decrease column width" org-columns-narrow t]
16451 "--"
16452 ["Move column right" org-columns-move-right t]
16453 ["Move column left" org-columns-move-left t]
16454 ["Add column" org-columns-new t]
16455 ["Delete column" org-columns-delete t]
16456 "--"
16457 ["CONTENTS" org-columns-content t]
16458 ["OVERVIEW" org-overview t]
16459 ["Refresh columns display" org-columns-redo t]
16460 "--"
16461 ["Open link" org-columns-open-link t]
16462 "--"
16463 ["Quit" org-columns-quit t]))
16465 (defun org-columns-new-overlay (beg end &optional string face)
16466 "Create a new column overlay and add it to the list."
16467 (let ((ov (org-make-overlay beg end)))
16468 (org-overlay-put ov 'face (or face 'secondary-selection))
16469 (org-overlay-display ov string face)
16470 (push ov org-columns-overlays)
16471 ov))
16473 (defun org-columns-display-here (&optional props)
16474 "Overlay the current line with column display."
16475 (interactive)
16476 (let* ((fmt org-columns-current-fmt-compiled)
16477 (beg (point-at-bol))
16478 (level-face (save-excursion
16479 (beginning-of-line 1)
16480 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16481 (org-get-level-face 2))))
16482 (color (list :foreground
16483 (face-attribute (or level-face 'default) :foreground)))
16484 props pom property ass width f string ov column val modval)
16485 ;; Check if the entry is in another buffer.
16486 (unless props
16487 (if (eq major-mode 'org-agenda-mode)
16488 (setq pom (or (get-text-property (point) 'org-hd-marker)
16489 (get-text-property (point) 'org-marker))
16490 props (if pom (org-entry-properties pom) nil))
16491 (setq props (org-entry-properties nil))))
16492 ;; Walk the format
16493 (while (setq column (pop fmt))
16494 (setq property (car column)
16495 ass (if (equal property "ITEM")
16496 (cons "ITEM"
16497 (save-match-data
16498 (org-no-properties
16499 (org-remove-tabs
16500 (buffer-substring-no-properties
16501 (point-at-bol) (point-at-eol))))))
16502 (assoc property props))
16503 width (or (cdr (assoc property org-columns-current-maxwidths))
16504 (nth 2 column)
16505 (length property))
16506 f (format "%%-%d.%ds | " width width)
16507 val (or (cdr ass) "")
16508 modval (if (equal property "ITEM")
16509 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16510 string (format f (or modval val)))
16511 ;; Create the overlay
16512 (org-unmodified
16513 (setq ov (org-columns-new-overlay
16514 beg (setq beg (1+ beg)) string
16515 (list color 'org-column)))
16516 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16517 (org-overlay-put ov 'keymap org-columns-map)
16518 (org-overlay-put ov 'org-columns-key property)
16519 (org-overlay-put ov 'org-columns-value (cdr ass))
16520 (org-overlay-put ov 'org-columns-value-modified modval)
16521 (org-overlay-put ov 'org-columns-pom pom)
16522 (org-overlay-put ov 'org-columns-format f))
16523 (if (or (not (char-after beg))
16524 (equal (char-after beg) ?\n))
16525 (let ((inhibit-read-only t))
16526 (save-excursion
16527 (goto-char beg)
16528 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16529 ;; Make the rest of the line disappear.
16530 (org-unmodified
16531 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16532 (org-overlay-put ov 'invisible t)
16533 (org-overlay-put ov 'keymap org-columns-map)
16534 (org-overlay-put ov 'intangible t)
16535 (push ov org-columns-overlays)
16536 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16537 (org-overlay-put ov 'keymap org-columns-map)
16538 (push ov org-columns-overlays)
16539 (let ((inhibit-read-only t))
16540 (put-text-property (max (point-min) (1- (point-at-bol)))
16541 (min (point-max) (1+ (point-at-eol)))
16542 'read-only "Type `e' to edit property")))))
16544 (defvar org-previous-header-line-format nil
16545 "The header line format before column view was turned on.")
16546 (defvar org-columns-inhibit-recalculation nil
16547 "Inhibit recomputing of columns on column view startup.")
16550 (defvar header-line-format)
16551 (defun org-columns-display-here-title ()
16552 "Overlay the newline before the current line with the table title."
16553 (interactive)
16554 (let ((fmt org-columns-current-fmt-compiled)
16555 string (title "")
16556 property width f column str widths)
16557 (while (setq column (pop fmt))
16558 (setq property (car column)
16559 str (or (nth 1 column) property)
16560 width (or (cdr (assoc property org-columns-current-maxwidths))
16561 (nth 2 column)
16562 (length str))
16563 widths (push width widths)
16564 f (format "%%-%d.%ds | " width width)
16565 string (format f str)
16566 title (concat title string)))
16567 (setq title (concat
16568 (org-add-props " " nil 'display '(space :align-to 0))
16569 (org-add-props title nil 'face '(:weight bold :underline t))))
16570 (org-set-local 'org-previous-header-line-format header-line-format)
16571 (org-set-local 'org-columns-current-widths (nreverse widths))
16572 (setq header-line-format title)))
16574 (defun org-columns-remove-overlays ()
16575 "Remove all currently active column overlays."
16576 (interactive)
16577 (when (marker-buffer org-columns-begin-marker)
16578 (with-current-buffer (marker-buffer org-columns-begin-marker)
16579 (when (local-variable-p 'org-previous-header-line-format)
16580 (setq header-line-format org-previous-header-line-format)
16581 (kill-local-variable 'org-previous-header-line-format))
16582 (move-marker org-columns-begin-marker nil)
16583 (move-marker org-columns-top-level-marker nil)
16584 (org-unmodified
16585 (mapc 'org-delete-overlay org-columns-overlays)
16586 (setq org-columns-overlays nil)
16587 (let ((inhibit-read-only t))
16588 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16590 (defun org-columns-cleanup-item (item fmt)
16591 "Remove from ITEM what is a column in the format FMT."
16592 (if (not org-complex-heading-regexp)
16593 item
16594 (when (string-match org-complex-heading-regexp item)
16595 (concat
16596 (org-add-props (concat (match-string 1 item) " ") nil
16597 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16598 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16599 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16600 " " (match-string 4 item)
16601 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16603 (defun org-columns-show-value ()
16604 "Show the full value of the property."
16605 (interactive)
16606 (let ((value (get-char-property (point) 'org-columns-value)))
16607 (message "Value is: %s" (or value ""))))
16609 (defun org-columns-quit ()
16610 "Remove the column overlays and in this way exit column editing."
16611 (interactive)
16612 (org-unmodified
16613 (org-columns-remove-overlays)
16614 (let ((inhibit-read-only t))
16615 (remove-text-properties (point-min) (point-max) '(read-only t))))
16616 (when (eq major-mode 'org-agenda-mode)
16617 (message
16618 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16620 (defun org-columns-check-computed ()
16621 "Check if this column value is computed.
16622 If yes, throw an error indicating that changing it does not make sense."
16623 (let ((val (get-char-property (point) 'org-columns-value)))
16624 (when (and (stringp val)
16625 (get-char-property 0 'org-computed val))
16626 (error "This value is computed from the entry's children"))))
16628 (defun org-columns-todo (&optional arg)
16629 "Change the TODO state during column view."
16630 (interactive "P")
16631 (org-columns-edit-value "TODO"))
16633 (defun org-columns-set-tags-or-toggle (&optional arg)
16634 "Toggle checkbox at point, or set tags for current headline."
16635 (interactive "P")
16636 (if (string-match "\\`\\[[ xX-]\\]\\'"
16637 (get-char-property (point) 'org-columns-value))
16638 (org-columns-next-allowed-value)
16639 (org-columns-edit-value "TAGS")))
16641 (defun org-columns-edit-value (&optional key)
16642 "Edit the value of the property at point in column view.
16643 Where possible, use the standard interface for changing this line."
16644 (interactive)
16645 (org-columns-check-computed)
16646 (let* ((external-key key)
16647 (col (current-column))
16648 (key (or key (get-char-property (point) 'org-columns-key)))
16649 (value (get-char-property (point) 'org-columns-value))
16650 (bol (point-at-bol)) (eol (point-at-eol))
16651 (pom (or (get-text-property bol 'org-hd-marker)
16652 (point))) ; keep despite of compiler waring
16653 (line-overlays
16654 (delq nil (mapcar (lambda (x)
16655 (and (eq (overlay-buffer x) (current-buffer))
16656 (>= (overlay-start x) bol)
16657 (<= (overlay-start x) eol)
16659 org-columns-overlays)))
16660 nval eval allowed)
16661 (cond
16662 ((equal key "CLOCKSUM")
16663 (error "This special column cannot be edited"))
16664 ((equal key "ITEM")
16665 (setq eval '(org-with-point-at pom
16666 (org-edit-headline))))
16667 ((equal key "TODO")
16668 (setq eval '(org-with-point-at pom
16669 (let ((current-prefix-arg
16670 (if external-key current-prefix-arg '(4))))
16671 (call-interactively 'org-todo)))))
16672 ((equal key "PRIORITY")
16673 (setq eval '(org-with-point-at pom
16674 (call-interactively 'org-priority))))
16675 ((equal key "TAGS")
16676 (setq eval '(org-with-point-at pom
16677 (let ((org-fast-tag-selection-single-key
16678 (if (eq org-fast-tag-selection-single-key 'expert)
16679 t org-fast-tag-selection-single-key)))
16680 (call-interactively 'org-set-tags)))))
16681 ((equal key "DEADLINE")
16682 (setq eval '(org-with-point-at pom
16683 (call-interactively 'org-deadline))))
16684 ((equal key "SCHEDULED")
16685 (setq eval '(org-with-point-at pom
16686 (call-interactively 'org-schedule))))
16688 (setq allowed (org-property-get-allowed-values pom key 'table))
16689 (if allowed
16690 (setq nval (completing-read "Value: " allowed nil t))
16691 (setq nval (read-string "Edit: " value)))
16692 (setq nval (org-trim nval))
16693 (when (not (equal nval value))
16694 (setq eval '(org-entry-put pom key nval)))))
16695 (when eval
16696 (let ((inhibit-read-only t))
16697 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16698 (unwind-protect
16699 (progn
16700 (setq org-columns-overlays
16701 (org-delete-all line-overlays org-columns-overlays))
16702 (mapc 'org-delete-overlay line-overlays)
16703 (org-columns-eval eval))
16704 (org-columns-display-here))))
16705 (move-to-column col)
16706 (if (and (org-mode-p)
16707 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16708 (org-columns-update key))))
16710 (defun org-edit-headline () ; FIXME: this is not columns specific
16711 "Edit the current headline, the part without TODO keyword, TAGS."
16712 (org-back-to-heading)
16713 (when (looking-at org-todo-line-regexp)
16714 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16715 (txt (match-string 3))
16716 (post "")
16717 txt2)
16718 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16719 (setq post (match-string 0 txt)
16720 txt (substring txt 0 (match-beginning 0))))
16721 (setq txt2 (read-string "Edit: " txt))
16722 (when (not (equal txt txt2))
16723 (beginning-of-line 1)
16724 (insert pre txt2 post)
16725 (delete-region (point) (point-at-eol))
16726 (org-set-tags nil t)))))
16728 (defun org-columns-edit-allowed ()
16729 "Edit the list of allowed values for the current property."
16730 (interactive)
16731 (let* ((key (get-char-property (point) 'org-columns-key))
16732 (key1 (concat key "_ALL"))
16733 (allowed (org-entry-get (point) key1 t))
16734 nval)
16735 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16736 (setq nval (read-string "Allowed: " allowed))
16737 (org-entry-put
16738 (cond ((marker-position org-entry-property-inherited-from)
16739 org-entry-property-inherited-from)
16740 ((marker-position org-columns-top-level-marker)
16741 org-columns-top-level-marker))
16742 key1 nval)))
16744 (defmacro org-no-warnings (&rest body)
16745 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16747 (defun org-columns-eval (form)
16748 (let (hidep)
16749 (save-excursion
16750 (beginning-of-line 1)
16751 ;; `next-line' is needed here, because it skips invisible line.
16752 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16753 (setq hidep (org-on-heading-p 1)))
16754 (eval form)
16755 (and hidep (hide-entry))))
16757 (defun org-columns-previous-allowed-value ()
16758 "Switch to the previous allowed value for this column."
16759 (interactive)
16760 (org-columns-next-allowed-value t))
16762 (defun org-columns-next-allowed-value (&optional previous)
16763 "Switch to the next allowed value for this column."
16764 (interactive)
16765 (org-columns-check-computed)
16766 (let* ((col (current-column))
16767 (key (get-char-property (point) 'org-columns-key))
16768 (value (get-char-property (point) 'org-columns-value))
16769 (bol (point-at-bol)) (eol (point-at-eol))
16770 (pom (or (get-text-property bol 'org-hd-marker)
16771 (point))) ; keep despite of compiler waring
16772 (line-overlays
16773 (delq nil (mapcar (lambda (x)
16774 (and (eq (overlay-buffer x) (current-buffer))
16775 (>= (overlay-start x) bol)
16776 (<= (overlay-start x) eol)
16778 org-columns-overlays)))
16779 (allowed (or (org-property-get-allowed-values pom key)
16780 (and (memq
16781 (nth 4 (assoc key org-columns-current-fmt-compiled))
16782 '(checkbox checkbox-n-of-m checkbox-percent))
16783 '("[ ]" "[X]"))))
16784 nval)
16785 (when (equal key "ITEM")
16786 (error "Cannot edit item headline from here"))
16787 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16788 (error "Allowed values for this property have not been defined"))
16789 (if (member key '("SCHEDULED" "DEADLINE"))
16790 (setq nval (if previous 'earlier 'later))
16791 (if previous (setq allowed (reverse allowed)))
16792 (if (member value allowed)
16793 (setq nval (car (cdr (member value allowed)))))
16794 (setq nval (or nval (car allowed)))
16795 (if (equal nval value)
16796 (error "Only one allowed value for this property")))
16797 (let ((inhibit-read-only t))
16798 (remove-text-properties (1- bol) eol '(read-only t))
16799 (unwind-protect
16800 (progn
16801 (setq org-columns-overlays
16802 (org-delete-all line-overlays org-columns-overlays))
16803 (mapc 'org-delete-overlay line-overlays)
16804 (org-columns-eval '(org-entry-put pom key nval)))
16805 (org-columns-display-here)))
16806 (move-to-column col)
16807 (if (and (org-mode-p)
16808 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16809 (org-columns-update key))))
16811 (defun org-verify-version (task)
16812 (cond
16813 ((eq task 'columns)
16814 (if (or (featurep 'xemacs)
16815 (< emacs-major-version 22))
16816 (error "Emacs 22 is required for the columns feature")))))
16818 (defun org-columns-open-link (&optional arg)
16819 (interactive "P")
16820 (let ((value (get-char-property (point) 'org-columns-value)))
16821 (org-open-link-from-string value arg)))
16823 (defun org-open-link-from-string (s &optional arg)
16824 "Open a link in the string S, as if it was in Org-mode."
16825 (interactive)
16826 (with-temp-buffer
16827 (let ((org-inhibit-startup t))
16828 (org-mode)
16829 (insert s)
16830 (goto-char (point-min))
16831 (org-open-at-point arg))))
16833 (defun org-columns-get-format-and-top-level ()
16834 (let (fmt)
16835 (when (condition-case nil (org-back-to-heading) (error nil))
16836 (move-marker org-entry-property-inherited-from nil)
16837 (setq fmt (org-entry-get nil "COLUMNS" t)))
16838 (setq fmt (or fmt org-columns-default-format))
16839 (org-set-local 'org-columns-current-fmt fmt)
16840 (org-columns-compile-format fmt)
16841 (if (marker-position org-entry-property-inherited-from)
16842 (move-marker org-columns-top-level-marker
16843 org-entry-property-inherited-from)
16844 (move-marker org-columns-top-level-marker (point)))
16845 fmt))
16847 (defun org-columns ()
16848 "Turn on column view on an org-mode file."
16849 (interactive)
16850 (org-verify-version 'columns)
16851 (org-columns-remove-overlays)
16852 (move-marker org-columns-begin-marker (point))
16853 (let (beg end fmt cache maxwidths)
16854 (setq fmt (org-columns-get-format-and-top-level))
16855 (save-excursion
16856 (goto-char org-columns-top-level-marker)
16857 (setq beg (point))
16858 (unless org-columns-inhibit-recalculation
16859 (org-columns-compute-all))
16860 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16861 (point-max)))
16862 ;; Get and cache the properties
16863 (goto-char beg)
16864 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
16865 (save-excursion
16866 (save-restriction
16867 (narrow-to-region beg end)
16868 (org-clock-sum))))
16869 (while (re-search-forward (concat "^" outline-regexp) end t)
16870 (push (cons (org-current-line) (org-entry-properties)) cache))
16871 (when cache
16872 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16873 (org-set-local 'org-columns-current-maxwidths maxwidths)
16874 (org-columns-display-here-title)
16875 (mapc (lambda (x)
16876 (goto-line (car x))
16877 (org-columns-display-here (cdr x)))
16878 cache)))))
16880 (defun org-columns-new (&optional prop title width op fmt &rest rest)
16881 "Insert a new column, to the left of the current column."
16882 (interactive)
16883 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
16884 cell)
16885 (setq prop (completing-read
16886 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
16887 nil nil prop))
16888 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
16889 (setq width (read-string "Column width: " (if width (number-to-string width))))
16890 (if (string-match "\\S-" width)
16891 (setq width (string-to-number width))
16892 (setq width nil))
16893 (setq fmt (completing-read "Summary [none]: "
16894 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
16895 nil t))
16896 (if (string-match "\\S-" fmt)
16897 (setq fmt (intern fmt))
16898 (setq fmt nil))
16899 (if (eq fmt 'none) (setq fmt nil))
16900 (if editp
16901 (progn
16902 (setcar editp prop)
16903 (setcdr editp (list title width nil fmt)))
16904 (setq cell (nthcdr (1- (current-column))
16905 org-columns-current-fmt-compiled))
16906 (setcdr cell (cons (list prop title width nil fmt)
16907 (cdr cell))))
16908 (org-columns-store-format)
16909 (org-columns-redo)))
16911 (defun org-columns-delete ()
16912 "Delete the column at point from columns view."
16913 (interactive)
16914 (let* ((n (current-column))
16915 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
16916 (when (y-or-n-p
16917 (format "Are you sure you want to remove column \"%s\"? " title))
16918 (setq org-columns-current-fmt-compiled
16919 (delq (nth n org-columns-current-fmt-compiled)
16920 org-columns-current-fmt-compiled))
16921 (org-columns-store-format)
16922 (org-columns-redo)
16923 (if (>= (current-column) (length org-columns-current-fmt-compiled))
16924 (backward-char 1)))))
16926 (defun org-columns-edit-attributes ()
16927 "Edit the attributes of the current column."
16928 (interactive)
16929 (let* ((n (current-column))
16930 (info (nth n org-columns-current-fmt-compiled)))
16931 (apply 'org-columns-new info)))
16933 (defun org-columns-widen (arg)
16934 "Make the column wider by ARG characters."
16935 (interactive "p")
16936 (let* ((n (current-column))
16937 (entry (nth n org-columns-current-fmt-compiled))
16938 (width (or (nth 2 entry)
16939 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
16940 (setq width (max 1 (+ width arg)))
16941 (setcar (nthcdr 2 entry) width)
16942 (org-columns-store-format)
16943 (org-columns-redo)))
16945 (defun org-columns-narrow (arg)
16946 "Make the column nrrower by ARG characters."
16947 (interactive "p")
16948 (org-columns-widen (- arg)))
16950 (defun org-columns-move-right ()
16951 "Swap this column with the one to the right."
16952 (interactive)
16953 (let* ((n (current-column))
16954 (cell (nthcdr n org-columns-current-fmt-compiled))
16956 (when (>= n (1- (length org-columns-current-fmt-compiled)))
16957 (error "Cannot shift this column further to the right"))
16958 (setq e (car cell))
16959 (setcar cell (car (cdr cell)))
16960 (setcdr cell (cons e (cdr (cdr cell))))
16961 (org-columns-store-format)
16962 (org-columns-redo)
16963 (forward-char 1)))
16965 (defun org-columns-move-left ()
16966 "Swap this column with the one to the left."
16967 (interactive)
16968 (let* ((n (current-column)))
16969 (when (= n 0)
16970 (error "Cannot shift this column further to the left"))
16971 (backward-char 1)
16972 (org-columns-move-right)
16973 (backward-char 1)))
16975 (defun org-columns-store-format ()
16976 "Store the text version of the current columns format in appropriate place.
16977 This is either in the COLUMNS property of the node starting the current column
16978 display, or in the #+COLUMNS line of the current buffer."
16979 (let (fmt (cnt 0))
16980 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
16981 (org-set-local 'org-columns-current-fmt fmt)
16982 (if (marker-position org-columns-top-level-marker)
16983 (save-excursion
16984 (goto-char org-columns-top-level-marker)
16985 (if (and (org-at-heading-p)
16986 (org-entry-get nil "COLUMNS"))
16987 (org-entry-put nil "COLUMNS" fmt)
16988 (goto-char (point-min))
16989 ;; Overwrite all #+COLUMNS lines....
16990 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
16991 (setq cnt (1+ cnt))
16992 (replace-match (concat "#+COLUMNS: " fmt) t t))
16993 (unless (> cnt 0)
16994 (goto-char (point-min))
16995 (or (org-on-heading-p t) (outline-next-heading))
16996 (let ((inhibit-read-only t))
16997 (insert-before-markers "#+COLUMNS: " fmt "\n")))
16998 (org-set-local 'org-columns-default-format fmt))))))
17000 (defvar org-overriding-columns-format nil
17001 "When set, overrides any other definition.")
17002 (defvar org-agenda-view-columns-initially nil
17003 "When set, switch to columns view immediately after creating the agenda.")
17005 (defun org-agenda-columns ()
17006 "Turn on column view in the agenda."
17007 (interactive)
17008 (org-verify-version 'columns)
17009 (org-columns-remove-overlays)
17010 (move-marker org-columns-begin-marker (point))
17011 (let (fmt cache maxwidths m)
17012 (cond
17013 ((and (local-variable-p 'org-overriding-columns-format)
17014 org-overriding-columns-format)
17015 (setq fmt org-overriding-columns-format))
17016 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
17017 (setq fmt (org-entry-get m "COLUMNS" t)))
17018 ((and (boundp 'org-columns-current-fmt)
17019 (local-variable-p 'org-columns-current-fmt)
17020 org-columns-current-fmt)
17021 (setq fmt org-columns-current-fmt))
17022 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
17023 (setq m (get-text-property m 'org-hd-marker))
17024 (setq fmt (org-entry-get m "COLUMNS" t))))
17025 (setq fmt (or fmt org-columns-default-format))
17026 (org-set-local 'org-columns-current-fmt fmt)
17027 (org-columns-compile-format fmt)
17028 (save-excursion
17029 ;; Get and cache the properties
17030 (goto-char (point-min))
17031 (while (not (eobp))
17032 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17033 (get-text-property (point) 'org-marker)))
17034 (push (cons (org-current-line) (org-entry-properties m)) cache))
17035 (beginning-of-line 2))
17036 (when cache
17037 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17038 (org-set-local 'org-columns-current-maxwidths maxwidths)
17039 (org-columns-display-here-title)
17040 (mapc (lambda (x)
17041 (goto-line (car x))
17042 (org-columns-display-here (cdr x)))
17043 cache)))))
17045 (defun org-columns-get-autowidth-alist (s cache)
17046 "Derive the maximum column widths from the format and the cache."
17047 (let ((start 0) rtn)
17048 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
17049 (push (cons (match-string 1 s) 1) rtn)
17050 (setq start (match-end 0)))
17051 (mapc (lambda (x)
17052 (setcdr x (apply 'max
17053 (mapcar
17054 (lambda (y)
17055 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17056 cache))))
17057 rtn)
17058 rtn))
17060 (defun org-columns-compute-all ()
17061 "Compute all columns that have operators defined."
17062 (org-unmodified
17063 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17064 (let ((columns org-columns-current-fmt-compiled) col)
17065 (while (setq col (pop columns))
17066 (when (nth 3 col)
17067 (save-excursion
17068 (org-columns-compute (car col)))))))
17070 (defun org-columns-update (property)
17071 "Recompute PROPERTY, and update the columns display for it."
17072 (org-columns-compute property)
17073 (let (fmt val pos)
17074 (save-excursion
17075 (mapc (lambda (ov)
17076 (when (equal (org-overlay-get ov 'org-columns-key) property)
17077 (setq pos (org-overlay-start ov))
17078 (goto-char pos)
17079 (when (setq val (cdr (assoc property
17080 (get-text-property
17081 (point-at-bol) 'org-summaries))))
17082 (setq fmt (org-overlay-get ov 'org-columns-format))
17083 (org-overlay-put ov 'org-columns-value val)
17084 (org-overlay-put ov 'display (format fmt val)))))
17085 org-columns-overlays))))
17087 (defun org-columns-compute (property)
17088 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17089 (interactive)
17090 (let* ((re (concat "^" outline-regexp))
17091 (lmax 30) ; Does anyone use deeper levels???
17092 (lsum (make-vector lmax 0))
17093 (lflag (make-vector lmax nil))
17094 (level 0)
17095 (ass (assoc property org-columns-current-fmt-compiled))
17096 (format (nth 4 ass))
17097 (printf (nth 5 ass))
17098 (beg org-columns-top-level-marker)
17099 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17100 (save-excursion
17101 ;; Find the region to compute
17102 (goto-char beg)
17103 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17104 (goto-char end)
17105 ;; Walk the tree from the back and do the computations
17106 (while (re-search-backward re beg t)
17107 (setq sumpos (match-beginning 0)
17108 last-level level
17109 level (org-outline-level)
17110 val (org-entry-get nil property)
17111 valflag (and val (string-match "\\S-" val)))
17112 (cond
17113 ((< level last-level)
17114 ;; put the sum of lower levels here as a property
17115 (setq sum (aref lsum last-level) ; current sum
17116 flag (aref lflag last-level) ; any valid entries from children?
17117 str (org-column-number-to-string sum format printf)
17118 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17119 useval (if flag str1 (if valflag val ""))
17120 sum-alist (get-text-property sumpos 'org-summaries))
17121 (if (assoc property sum-alist)
17122 (setcdr (assoc property sum-alist) useval)
17123 (push (cons property useval) sum-alist)
17124 (org-unmodified
17125 (add-text-properties sumpos (1+ sumpos)
17126 (list 'org-summaries sum-alist))))
17127 (when val
17128 (org-entry-put nil property (if flag str val)))
17129 ;; add current to current level accumulator
17130 (when (or flag valflag)
17131 (aset lsum level (+ (aref lsum level)
17132 (if flag sum (org-column-string-to-number
17133 (if flag str val) format))))
17134 (aset lflag level t))
17135 ;; clear accumulators for deeper levels
17136 (loop for l from (1+ level) to (1- lmax) do
17137 (aset lsum l 0)
17138 (aset lflag l nil)))
17139 ((>= level last-level)
17140 ;; add what we have here to the accumulator for this level
17141 (aset lsum level (+ (aref lsum level)
17142 (org-column-string-to-number (or val "0") format)))
17143 (and valflag (aset lflag level t)))
17144 (t (error "This should not happen")))))))
17146 (defun org-columns-redo ()
17147 "Construct the column display again."
17148 (interactive)
17149 (message "Recomputing columns...")
17150 (save-excursion
17151 (if (marker-position org-columns-begin-marker)
17152 (goto-char org-columns-begin-marker))
17153 (org-columns-remove-overlays)
17154 (if (org-mode-p)
17155 (call-interactively 'org-columns)
17156 (call-interactively 'org-agenda-columns)))
17157 (message "Recomputing columns...done"))
17159 (defun org-columns-not-in-agenda ()
17160 (if (eq major-mode 'org-agenda-mode)
17161 (error "This command is only allowed in Org-mode buffers")))
17164 (defun org-string-to-number (s)
17165 "Convert string to number, and interpret hh:mm:ss."
17166 (if (not (string-match ":" s))
17167 (string-to-number s)
17168 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17169 (while l
17170 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17171 sum)))
17173 (defun org-column-number-to-string (n fmt &optional printf)
17174 "Convert a computed column number to a string value, according to FMT."
17175 (cond
17176 ((eq fmt 'add_times)
17177 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17178 (format "%d:%02d" h m)))
17179 ((eq fmt 'checkbox)
17180 (cond ((= n (floor n)) "[X]")
17181 ((> n 1.) "[-]")
17182 (t "[ ]")))
17183 ((memq fmt '(checkbox-n-of-m checkbox-percent))
17184 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
17185 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
17186 (printf (format printf n))
17187 ((eq fmt 'currency)
17188 (format "%.2f" n))
17189 (t (number-to-string n))))
17191 (defun org-nofm-to-completion (n m &optional percent)
17192 (if (not percent)
17193 (format "[%d/%d]" n m)
17194 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
17196 (defun org-column-string-to-number (s fmt)
17197 "Convert a column value to a number that can be used for column computing."
17198 (cond
17199 ((string-match ":" s)
17200 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17201 (while l
17202 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17203 sum))
17204 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
17205 (if (equal s "[X]") 1. 0.000001))
17206 (t (string-to-number s))))
17208 (defun org-columns-uncompile-format (cfmt)
17209 "Turn the compiled columns format back into a string representation."
17210 (let ((rtn "") e s prop title op width fmt printf)
17211 (while (setq e (pop cfmt))
17212 (setq prop (car e)
17213 title (nth 1 e)
17214 width (nth 2 e)
17215 op (nth 3 e)
17216 fmt (nth 4 e)
17217 printf (nth 5 e))
17218 (cond
17219 ((eq fmt 'add_times) (setq op ":"))
17220 ((eq fmt 'checkbox) (setq op "X"))
17221 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
17222 ((eq fmt 'checkbox-percent) (setq op "X%"))
17223 ((eq fmt 'add_numbers) (setq op "+"))
17224 ((eq fmt 'currency) (setq op "$")))
17225 (if (and op printf) (setq op (concat op ";" printf)))
17226 (if (equal title prop) (setq title nil))
17227 (setq s (concat "%" (if width (number-to-string width))
17228 prop
17229 (if title (concat "(" title ")"))
17230 (if op (concat "{" op "}"))))
17231 (setq rtn (concat rtn " " s)))
17232 (org-trim rtn)))
17234 (defun org-columns-compile-format (fmt)
17235 "Turn a column format string into an alist of specifications.
17236 The alist has one entry for each column in the format. The elements of
17237 that list are:
17238 property the property
17239 title the title field for the columns
17240 width the column width in characters, can be nil for automatic
17241 operator the operator if any
17242 format the output format for computed results, derived from operator
17243 printf a printf format for computed values"
17244 (let ((start 0) width prop title op f printf)
17245 (setq org-columns-current-fmt-compiled nil)
17246 (while (string-match
17247 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17248 fmt start)
17249 (setq start (match-end 0)
17250 width (match-string 1 fmt)
17251 prop (match-string 2 fmt)
17252 title (or (match-string 3 fmt) prop)
17253 op (match-string 4 fmt)
17254 f nil
17255 printf nil)
17256 (if width (setq width (string-to-number width)))
17257 (when (and op (string-match ";" op))
17258 (setq printf (substring op (match-end 0))
17259 op (substring op 0 (match-beginning 0))))
17260 (cond
17261 ((equal op "+") (setq f 'add_numbers))
17262 ((equal op "$") (setq f 'currency))
17263 ((equal op ":") (setq f 'add_times))
17264 ((equal op "X") (setq f 'checkbox))
17265 ((equal op "X/") (setq f 'checkbox-n-of-m))
17266 ((equal op "X%") (setq f 'checkbox-percent))
17268 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17269 (setq org-columns-current-fmt-compiled
17270 (nreverse org-columns-current-fmt-compiled))))
17273 ;;; Dynamic block for Column view
17275 (defun org-columns-capture-view (&optional maxlevel skip-empty-rows)
17276 "Get the column view of the current buffer or subtree.
17277 The first optional argument MAXLEVEL sets the level limit. A
17278 second optional argument SKIP-EMPTY-ROWS tells whether to skip
17279 empty rows, an empty row being one where all the column view
17280 specifiers except ITEM are empty. This function returns a list
17281 containing the title row and all other rows. Each row is a list
17282 of fields."
17283 (save-excursion
17284 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17285 (n (length title)) row tbl)
17286 (goto-char (point-min))
17287 (while (and (re-search-forward "^\\(\\*+\\) " nil t)
17288 (or (null maxlevel)
17289 (>= maxlevel
17290 (if org-odd-levels-only
17291 (/ (1+ (length (match-string 1))) 2)
17292 (length (match-string 1))))))
17293 (when (get-char-property (match-beginning 0) 'org-columns-key)
17294 (setq row nil)
17295 (loop for i from 0 to (1- n) do
17296 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17297 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17299 row))
17300 (setq row (nreverse row))
17301 (unless (and skip-empty-rows
17302 (eq 1 (length (delete "" (delete-dups row)))))
17303 (push row tbl))))
17304 (append (list title 'hline) (nreverse tbl)))))
17306 (defun org-dblock-write:columnview (params)
17307 "Write the column view table.
17308 PARAMS is a property list of parameters:
17310 :width enforce same column widths with <N> specifiers.
17311 :id the :ID: property of the entry where the columns view
17312 should be built, as a string. When `local', call locally.
17313 When `global' call column view with the cursor at the beginning
17314 of the buffer (usually this means that the whole buffer switches
17315 to column view).
17316 :hlines When t, insert a hline before each item. When a number, insert
17317 a hline before each level <= that number.
17318 :vlines When t, make each column a colgroup to enforce vertical lines.
17319 :maxlevel When set to a number, don't capture headlines below this level.
17320 :skip-empty-rows
17321 When t, skip rows where all specifiers other than ITEM are empty."
17322 (let ((pos (move-marker (make-marker) (point)))
17323 (hlines (plist-get params :hlines))
17324 (vlines (plist-get params :vlines))
17325 (maxlevel (plist-get params :maxlevel))
17326 (skip-empty-rows (plist-get params :skip-empty-rows))
17327 tbl id idpos nfields tmp)
17328 (save-excursion
17329 (save-restriction
17330 (when (setq id (plist-get params :id))
17331 (cond ((not id) nil)
17332 ((eq id 'global) (goto-char (point-min)))
17333 ((eq id 'local) nil)
17334 ((setq idpos (org-find-entry-with-id id))
17335 (goto-char idpos))
17336 (t (error "Cannot find entry with :ID: %s" id))))
17337 (org-columns)
17338 (setq tbl (org-columns-capture-view maxlevel skip-empty-rows))
17339 (setq nfields (length (car tbl)))
17340 (org-columns-quit)))
17341 (goto-char pos)
17342 (move-marker pos nil)
17343 (when tbl
17344 (when (plist-get params :hlines)
17345 (setq tmp nil)
17346 (while tbl
17347 (if (eq (car tbl) 'hline)
17348 (push (pop tbl) tmp)
17349 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17350 (if (and (not (eq (car tmp) 'hline))
17351 (or (eq hlines t)
17352 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17353 (push 'hline tmp)))
17354 (push (pop tbl) tmp)))
17355 (setq tbl (nreverse tmp)))
17356 (when vlines
17357 (setq tbl (mapcar (lambda (x)
17358 (if (eq 'hline x) x (cons "" x)))
17359 tbl))
17360 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17361 (setq pos (point))
17362 (insert (org-listtable-to-string tbl))
17363 (when (plist-get params :width)
17364 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17365 org-columns-current-widths "|")))
17366 (goto-char pos)
17367 (org-table-align))))
17369 (defun org-listtable-to-string (tbl)
17370 "Convert a listtable TBL to a string that contains the Org-mode table.
17371 The table still need to be alligned. The resulting string has no leading
17372 and tailing newline characters."
17373 (mapconcat
17374 (lambda (x)
17375 (cond
17376 ((listp x)
17377 (concat "|" (mapconcat 'identity x "|") "|"))
17378 ((eq x 'hline) "|-|")
17379 (t (error "Garbage in listtable: %s" x))))
17380 tbl "\n"))
17382 (defun org-insert-columns-dblock ()
17383 "Create a dynamic block capturing a column view table."
17384 (interactive)
17385 (let ((defaults '(:name "columnview" :hlines 1))
17386 (id (completing-read
17387 "Capture columns (local, global, entry with :ID: property) [local]: "
17388 (append '(("global") ("local"))
17389 (mapcar 'list (org-property-values "ID"))))))
17390 (if (equal id "") (setq id 'local))
17391 (if (equal id "global") (setq id 'global))
17392 (setq defaults (append defaults (list :id id)))
17393 (org-create-dblock defaults)
17394 (org-update-dblock)))
17396 ;;;; Timestamps
17398 (defvar org-last-changed-timestamp nil)
17399 (defvar org-time-was-given) ; dynamically scoped parameter
17400 (defvar org-end-time-was-given) ; dynamically scoped parameter
17401 (defvar org-ts-what) ; dynamically scoped parameter
17403 (defun org-time-stamp (arg)
17404 "Prompt for a date/time and insert a time stamp.
17405 If the user specifies a time like HH:MM, or if this command is called
17406 with a prefix argument, the time stamp will contain date and time.
17407 Otherwise, only the date will be included. All parts of a date not
17408 specified by the user will be filled in from the current date/time.
17409 So if you press just return without typing anything, the time stamp
17410 will represent the current date/time. If there is already a timestamp
17411 at the cursor, it will be modified."
17412 (interactive "P")
17413 (let* ((ts nil)
17414 (default-time
17415 ;; Default time is either today, or, when entering a range,
17416 ;; the range start.
17417 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17418 (save-excursion
17419 (re-search-backward
17420 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17421 (- (point) 20) t)))
17422 (apply 'encode-time (org-parse-time-string (match-string 1)))
17423 (current-time)))
17424 (default-input (and ts (org-get-compact-tod ts)))
17425 org-time-was-given org-end-time-was-given time)
17426 (cond
17427 ((and (org-at-timestamp-p)
17428 (eq last-command 'org-time-stamp)
17429 (eq this-command 'org-time-stamp))
17430 (insert "--")
17431 (setq time (let ((this-command this-command))
17432 (org-read-date arg 'totime nil nil default-time default-input)))
17433 (org-insert-time-stamp time (or org-time-was-given arg)))
17434 ((org-at-timestamp-p)
17435 (setq time (let ((this-command this-command))
17436 (org-read-date arg 'totime nil nil default-time default-input)))
17437 (when (org-at-timestamp-p) ; just to get the match data
17438 (replace-match "")
17439 (setq org-last-changed-timestamp
17440 (org-insert-time-stamp
17441 time (or org-time-was-given arg)
17442 nil nil nil (list org-end-time-was-given))))
17443 (message "Timestamp updated"))
17445 (setq time (let ((this-command this-command))
17446 (org-read-date arg 'totime nil nil default-time default-input)))
17447 (org-insert-time-stamp time (or org-time-was-given arg)
17448 nil nil nil (list org-end-time-was-given))))))
17450 ;; FIXME: can we use this for something else????
17451 ;; like computing time differences?????
17452 (defun org-get-compact-tod (s)
17453 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17454 (let* ((t1 (match-string 1 s))
17455 (h1 (string-to-number (match-string 2 s)))
17456 (m1 (string-to-number (match-string 3 s)))
17457 (t2 (and (match-end 4) (match-string 5 s)))
17458 (h2 (and t2 (string-to-number (match-string 6 s))))
17459 (m2 (and t2 (string-to-number (match-string 7 s))))
17460 dh dm)
17461 (if (not t2)
17463 (setq dh (- h2 h1) dm (- m2 m1))
17464 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17465 (concat t1 "+" (number-to-string dh)
17466 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17468 (defun org-time-stamp-inactive (&optional arg)
17469 "Insert an inactive time stamp.
17470 An inactive time stamp is enclosed in square brackets instead of angle
17471 brackets. It is inactive in the sense that it does not trigger agenda entries,
17472 does not link to the calendar and cannot be changed with the S-cursor keys.
17473 So these are more for recording a certain time/date."
17474 (interactive "P")
17475 (let (org-time-was-given org-end-time-was-given time)
17476 (setq time (org-read-date arg 'totime))
17477 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17478 nil nil (list org-end-time-was-given))))
17480 (defvar org-date-ovl (org-make-overlay 1 1))
17481 (org-overlay-put org-date-ovl 'face 'org-warning)
17482 (org-detach-overlay org-date-ovl)
17484 (defvar org-ans1) ; dynamically scoped parameter
17485 (defvar org-ans2) ; dynamically scoped parameter
17487 (defvar org-plain-time-of-day-regexp) ; defined below
17489 (defvar org-read-date-overlay nil)
17490 (defvar org-dcst nil) ; dynamically scoped
17492 (defun org-read-date (&optional with-time to-time from-string prompt
17493 default-time default-input)
17494 "Read a date, possibly a time, and make things smooth for the user.
17495 The prompt will suggest to enter an ISO date, but you can also enter anything
17496 which will at least partially be understood by `parse-time-string'.
17497 Unrecognized parts of the date will default to the current day, month, year,
17498 hour and minute. If this command is called to replace a timestamp at point,
17499 of to enter the second timestamp of a range, the default time is taken from the
17500 existing stamp. For example,
17501 3-2-5 --> 2003-02-05
17502 feb 15 --> currentyear-02-15
17503 sep 12 9 --> 2009-09-12
17504 12:45 --> today 12:45
17505 22 sept 0:34 --> currentyear-09-22 0:34
17506 12 --> currentyear-currentmonth-12
17507 Fri --> nearest Friday (today or later)
17508 etc.
17510 Furthermore you can specify a relative date by giving, as the *first* thing
17511 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17512 change in days weeks, months, years.
17513 With a single plus or minus, the date is relative to today. With a double
17514 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17515 +4d --> four days from today
17516 +4 --> same as above
17517 +2w --> two weeks from today
17518 ++5 --> five days from default date
17520 The function understands only English month and weekday abbreviations,
17521 but this can be configured with the variables `parse-time-months' and
17522 `parse-time-weekdays'.
17524 While prompting, a calendar is popped up - you can also select the
17525 date with the mouse (button 1). The calendar shows a period of three
17526 months. To scroll it to other months, use the keys `>' and `<'.
17527 If you don't like the calendar, turn it off with
17528 \(setq org-read-date-popup-calendar nil)
17530 With optional argument TO-TIME, the date will immediately be converted
17531 to an internal time.
17532 With an optional argument WITH-TIME, the prompt will suggest to also
17533 insert a time. Note that when WITH-TIME is not set, you can still
17534 enter a time, and this function will inform the calling routine about
17535 this change. The calling routine may then choose to change the format
17536 used to insert the time stamp into the buffer to include the time.
17537 With optional argument FROM-STRING, read from this string instead from
17538 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17539 the time/date that is used for everything that is not specified by the
17540 user."
17541 (require 'parse-time)
17542 (let* ((org-time-stamp-rounding-minutes
17543 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
17544 (org-dcst org-display-custom-times)
17545 (ct (org-current-time))
17546 (def (or default-time ct))
17547 (defdecode (decode-time def))
17548 (dummy (progn
17549 (when (< (nth 2 defdecode) org-extend-today-until)
17550 (setcar (nthcdr 2 defdecode) -1)
17551 (setcar (nthcdr 1 defdecode) 59)
17552 (setq def (apply 'encode-time defdecode)
17553 defdecode (decode-time def)))))
17554 (calendar-move-hook nil)
17555 (view-diary-entries-initially nil)
17556 (view-calendar-holidays-initially nil)
17557 (timestr (format-time-string
17558 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17559 (prompt (concat (if prompt (concat prompt " ") "")
17560 (format "Date+time [%s]: " timestr)))
17561 ans (org-ans0 "") org-ans1 org-ans2 final)
17563 (cond
17564 (from-string (setq ans from-string))
17565 (org-read-date-popup-calendar
17566 (save-excursion
17567 (save-window-excursion
17568 (calendar)
17569 (calendar-forward-day (- (time-to-days def)
17570 (calendar-absolute-from-gregorian
17571 (calendar-current-date))))
17572 (org-eval-in-calendar nil t)
17573 (let* ((old-map (current-local-map))
17574 (map (copy-keymap calendar-mode-map))
17575 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17576 (org-defkey map (kbd "RET") 'org-calendar-select)
17577 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17578 'org-calendar-select-mouse)
17579 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17580 'org-calendar-select-mouse)
17581 (org-defkey minibuffer-local-map [(meta shift left)]
17582 (lambda () (interactive)
17583 (org-eval-in-calendar '(calendar-backward-month 1))))
17584 (org-defkey minibuffer-local-map [(meta shift right)]
17585 (lambda () (interactive)
17586 (org-eval-in-calendar '(calendar-forward-month 1))))
17587 (org-defkey minibuffer-local-map [(meta shift up)]
17588 (lambda () (interactive)
17589 (org-eval-in-calendar '(calendar-backward-year 1))))
17590 (org-defkey minibuffer-local-map [(meta shift down)]
17591 (lambda () (interactive)
17592 (org-eval-in-calendar '(calendar-forward-year 1))))
17593 (org-defkey minibuffer-local-map [(shift up)]
17594 (lambda () (interactive)
17595 (org-eval-in-calendar '(calendar-backward-week 1))))
17596 (org-defkey minibuffer-local-map [(shift down)]
17597 (lambda () (interactive)
17598 (org-eval-in-calendar '(calendar-forward-week 1))))
17599 (org-defkey minibuffer-local-map [(shift left)]
17600 (lambda () (interactive)
17601 (org-eval-in-calendar '(calendar-backward-day 1))))
17602 (org-defkey minibuffer-local-map [(shift right)]
17603 (lambda () (interactive)
17604 (org-eval-in-calendar '(calendar-forward-day 1))))
17605 (org-defkey minibuffer-local-map ">"
17606 (lambda () (interactive)
17607 (org-eval-in-calendar '(scroll-calendar-left 1))))
17608 (org-defkey minibuffer-local-map "<"
17609 (lambda () (interactive)
17610 (org-eval-in-calendar '(scroll-calendar-right 1))))
17611 (unwind-protect
17612 (progn
17613 (use-local-map map)
17614 (add-hook 'post-command-hook 'org-read-date-display)
17615 (setq org-ans0 (read-string prompt default-input nil nil))
17616 ;; org-ans0: from prompt
17617 ;; org-ans1: from mouse click
17618 ;; org-ans2: from calendar motion
17619 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17620 (remove-hook 'post-command-hook 'org-read-date-display)
17621 (use-local-map old-map)
17622 (when org-read-date-overlay
17623 (org-delete-overlay org-read-date-overlay)
17624 (setq org-read-date-overlay nil)))))))
17626 (t ; Naked prompt only
17627 (unwind-protect
17628 (setq ans (read-string prompt default-input nil timestr))
17629 (when org-read-date-overlay
17630 (org-delete-overlay org-read-date-overlay)
17631 (setq org-read-date-overlay nil)))))
17633 (setq final (org-read-date-analyze ans def defdecode))
17635 (if to-time
17636 (apply 'encode-time final)
17637 (if (and (boundp 'org-time-was-given) org-time-was-given)
17638 (format "%04d-%02d-%02d %02d:%02d"
17639 (nth 5 final) (nth 4 final) (nth 3 final)
17640 (nth 2 final) (nth 1 final))
17641 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17642 (defvar def)
17643 (defvar defdecode)
17644 (defvar with-time)
17645 (defun org-read-date-display ()
17646 "Display the currrent date prompt interpretation in the minibuffer."
17647 (when org-read-date-display-live
17648 (when org-read-date-overlay
17649 (org-delete-overlay org-read-date-overlay))
17650 (let ((p (point)))
17651 (end-of-line 1)
17652 (while (not (equal (buffer-substring
17653 (max (point-min) (- (point) 4)) (point))
17654 " "))
17655 (insert " "))
17656 (goto-char p))
17657 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17658 " " (or org-ans1 org-ans2)))
17659 (org-end-time-was-given nil)
17660 (f (org-read-date-analyze ans def defdecode))
17661 (fmts (if org-dcst
17662 org-time-stamp-custom-formats
17663 org-time-stamp-formats))
17664 (fmt (if (or with-time
17665 (and (boundp 'org-time-was-given) org-time-was-given))
17666 (cdr fmts)
17667 (car fmts)))
17668 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17669 (when (and org-end-time-was-given
17670 (string-match org-plain-time-of-day-regexp txt))
17671 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17672 org-end-time-was-given
17673 (substring txt (match-end 0)))))
17674 (setq org-read-date-overlay
17675 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17676 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17678 (defun org-read-date-analyze (ans def defdecode)
17679 "Analyze the combined answer of the date prompt."
17680 ;; FIXME: cleanup and comment
17681 (let (delta deltan deltaw deltadef year month day
17682 hour minute second wday pm h2 m2 tl wday1
17683 iso-year iso-weekday iso-week iso-year iso-date)
17685 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17686 (setq ans (replace-match "" t t ans)
17687 deltan (car delta)
17688 deltaw (nth 1 delta)
17689 deltadef (nth 2 delta)))
17691 ;; Check if there is an iso week date in there
17692 ;; If yes, sore the info and ostpone interpreting it until the rest
17693 ;; of the parsing is done
17694 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17695 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
17696 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
17697 iso-week (string-to-number (match-string 2 ans)))
17698 (setq ans (replace-match "" t t ans)))
17700 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17701 (when (string-match
17702 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17703 (setq year (if (match-end 2)
17704 (string-to-number (match-string 2 ans))
17705 (string-to-number (format-time-string "%Y")))
17706 month (string-to-number (match-string 3 ans))
17707 day (string-to-number (match-string 4 ans)))
17708 (if (< year 100) (setq year (+ 2000 year)))
17709 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17710 t nil ans)))
17711 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17712 ;; If there is a time with am/pm, and *no* time without it, we convert
17713 ;; so that matching will be successful.
17714 (loop for i from 1 to 2 do ; twice, for end time as well
17715 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17716 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17717 (setq hour (string-to-number (match-string 1 ans))
17718 minute (if (match-end 3)
17719 (string-to-number (match-string 3 ans))
17721 pm (equal ?p
17722 (string-to-char (downcase (match-string 4 ans)))))
17723 (if (and (= hour 12) (not pm))
17724 (setq hour 0)
17725 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17726 (setq ans (replace-match (format "%02d:%02d" hour minute)
17727 t t ans))))
17729 ;; Check if a time range is given as a duration
17730 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17731 (setq hour (string-to-number (match-string 1 ans))
17732 h2 (+ hour (string-to-number (match-string 3 ans)))
17733 minute (string-to-number (match-string 2 ans))
17734 m2 (+ minute (if (match-end 5) (string-to-number
17735 (match-string 5 ans))0)))
17736 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17737 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17738 t t ans)))
17740 ;; Check if there is a time range
17741 (when (boundp 'org-end-time-was-given)
17742 (setq org-time-was-given nil)
17743 (when (and (string-match org-plain-time-of-day-regexp ans)
17744 (match-end 8))
17745 (setq org-end-time-was-given (match-string 8 ans))
17746 (setq ans (concat (substring ans 0 (match-beginning 7))
17747 (substring ans (match-end 7))))))
17749 (setq tl (parse-time-string ans)
17750 day (or (nth 3 tl) (nth 3 defdecode))
17751 month (or (nth 4 tl)
17752 (if (and org-read-date-prefer-future
17753 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17754 (1+ (nth 4 defdecode))
17755 (nth 4 defdecode)))
17756 year (or (nth 5 tl)
17757 (if (and org-read-date-prefer-future
17758 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17759 (1+ (nth 5 defdecode))
17760 (nth 5 defdecode)))
17761 hour (or (nth 2 tl) (nth 2 defdecode))
17762 minute (or (nth 1 tl) (nth 1 defdecode))
17763 second (or (nth 0 tl) 0)
17764 wday (nth 6 tl))
17766 ;; Special date definitions below
17767 (cond
17768 (iso-week
17769 ;; There was an iso week
17770 (setq year (or iso-year year)
17771 day (or iso-weekday wday 1)
17772 wday nil ; to make sure that the trigger below does not match
17773 iso-date (calendar-gregorian-from-absolute
17774 (calendar-absolute-from-iso
17775 (list iso-week day year))))
17776 ; FIXME: Should we also push ISO weeks into the future?
17777 ; (when (and org-read-date-prefer-future
17778 ; (not iso-year)
17779 ; (< (calendar-absolute-from-gregorian iso-date)
17780 ; (time-to-days (current-time))))
17781 ; (setq year (1+ year)
17782 ; iso-date (calendar-gregorian-from-absolute
17783 ; (calendar-absolute-from-iso
17784 ; (list iso-week day year)))))
17785 (setq month (car iso-date)
17786 year (nth 2 iso-date)
17787 day (nth 1 iso-date)))
17788 (deltan
17789 (unless deltadef
17790 (let ((now (decode-time (current-time))))
17791 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17792 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17793 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17794 ((equal deltaw "m") (setq month (+ month deltan)))
17795 ((equal deltaw "y") (setq year (+ year deltan)))))
17796 ((and wday (not (nth 3 tl)))
17797 ;; Weekday was given, but no day, so pick that day in the week
17798 ;; on or after the derived date.
17799 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17800 (unless (equal wday wday1)
17801 (setq day (+ day (% (- wday wday1 -7) 7))))))
17802 (if (and (boundp 'org-time-was-given)
17803 (nth 2 tl))
17804 (setq org-time-was-given t))
17805 (if (< year 100) (setq year (+ 2000 year)))
17806 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17807 (list second minute hour day month year)))
17809 (defvar parse-time-weekdays)
17811 (defun org-read-date-get-relative (s today default)
17812 "Check string S for special relative date string.
17813 TODAY and DEFAULT are internal times, for today and for a default.
17814 Return shift list (N what def-flag)
17815 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17816 N is the number of WHATs to shift.
17817 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17818 the DEFAULT date rather than TODAY."
17819 (when (string-match
17820 (concat
17821 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17822 "\\([0-9]+\\)?"
17823 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17824 "\\([ \t]\\|$\\)") s)
17825 (let* ((dir (if (match-end 1)
17826 (string-to-char (substring (match-string 1 s) -1))
17827 ?+))
17828 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17829 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17830 (what (if (match-end 3) (match-string 3 s) "d"))
17831 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17832 (date (if rel default today))
17833 (wday (nth 6 (decode-time date)))
17834 delta)
17835 (if wday1
17836 (progn
17837 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17838 (if (= dir ?-) (setq delta (- delta 7)))
17839 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17840 (list delta "d" rel))
17841 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17843 (defun org-eval-in-calendar (form &optional keepdate)
17844 "Eval FORM in the calendar window and return to current window.
17845 Also, store the cursor date in variable org-ans2."
17846 (let ((sw (selected-window)))
17847 (select-window (get-buffer-window "*Calendar*"))
17848 (eval form)
17849 (when (and (not keepdate) (calendar-cursor-to-date))
17850 (let* ((date (calendar-cursor-to-date))
17851 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17852 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17853 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17854 (select-window sw)))
17856 ; ;; Update the prompt to show new default date
17857 ; (save-excursion
17858 ; (goto-char (point-min))
17859 ; (when (and org-ans2
17860 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17861 ; (get-text-property (match-end 0) 'field))
17862 ; (let ((inhibit-read-only t))
17863 ; (replace-match (concat "[" org-ans2 "]") t t)
17864 ; (add-text-properties (point-min) (1+ (match-end 0))
17865 ; (text-properties-at (1+ (point-min)))))))))
17867 (defun org-calendar-select ()
17868 "Return to `org-read-date' with the date currently selected.
17869 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17870 (interactive)
17871 (when (calendar-cursor-to-date)
17872 (let* ((date (calendar-cursor-to-date))
17873 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17874 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17875 (if (active-minibuffer-window) (exit-minibuffer))))
17877 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17878 "Insert a date stamp for the date given by the internal TIME.
17879 WITH-HM means, use the stamp format that includes the time of the day.
17880 INACTIVE means use square brackets instead of angular ones, so that the
17881 stamp will not contribute to the agenda.
17882 PRE and POST are optional strings to be inserted before and after the
17883 stamp.
17884 The command returns the inserted time stamp."
17885 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17886 stamp)
17887 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17888 (insert-before-markers (or pre ""))
17889 (insert-before-markers (setq stamp (format-time-string fmt time)))
17890 (when (listp extra)
17891 (setq extra (car extra))
17892 (if (and (stringp extra)
17893 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17894 (setq extra (format "-%02d:%02d"
17895 (string-to-number (match-string 1 extra))
17896 (string-to-number (match-string 2 extra))))
17897 (setq extra nil)))
17898 (when extra
17899 (backward-char 1)
17900 (insert-before-markers extra)
17901 (forward-char 1))
17902 (insert-before-markers (or post ""))
17903 stamp))
17905 (defun org-toggle-time-stamp-overlays ()
17906 "Toggle the use of custom time stamp formats."
17907 (interactive)
17908 (setq org-display-custom-times (not org-display-custom-times))
17909 (unless org-display-custom-times
17910 (let ((p (point-min)) (bmp (buffer-modified-p)))
17911 (while (setq p (next-single-property-change p 'display))
17912 (if (and (get-text-property p 'display)
17913 (eq (get-text-property p 'face) 'org-date))
17914 (remove-text-properties
17915 p (setq p (next-single-property-change p 'display))
17916 '(display t))))
17917 (set-buffer-modified-p bmp)))
17918 (if (featurep 'xemacs)
17919 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17920 (org-restart-font-lock)
17921 (setq org-table-may-need-update t)
17922 (if org-display-custom-times
17923 (message "Time stamps are overlayed with custom format")
17924 (message "Time stamp overlays removed")))
17926 (defun org-display-custom-time (beg end)
17927 "Overlay modified time stamp format over timestamp between BED and END."
17928 (let* ((ts (buffer-substring beg end))
17929 t1 w1 with-hm tf time str w2 (off 0))
17930 (save-match-data
17931 (setq t1 (org-parse-time-string ts t))
17932 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
17933 (setq off (- (match-end 0) (match-beginning 0)))))
17934 (setq end (- end off))
17935 (setq w1 (- end beg)
17936 with-hm (and (nth 1 t1) (nth 2 t1))
17937 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17938 time (org-fix-decoded-time t1)
17939 str (org-add-props
17940 (format-time-string
17941 (substring tf 1 -1) (apply 'encode-time time))
17942 nil 'mouse-face 'highlight)
17943 w2 (length str))
17944 (if (not (= w2 w1))
17945 (add-text-properties (1+ beg) (+ 2 beg)
17946 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17947 (if (featurep 'xemacs)
17948 (progn
17949 (put-text-property beg end 'invisible t)
17950 (put-text-property beg end 'end-glyph (make-glyph str)))
17951 (put-text-property beg end 'display str))))
17953 (defun org-translate-time (string)
17954 "Translate all timestamps in STRING to custom format.
17955 But do this only if the variable `org-display-custom-times' is set."
17956 (when org-display-custom-times
17957 (save-match-data
17958 (let* ((start 0)
17959 (re org-ts-regexp-both)
17960 t1 with-hm inactive tf time str beg end)
17961 (while (setq start (string-match re string start))
17962 (setq beg (match-beginning 0)
17963 end (match-end 0)
17964 t1 (save-match-data
17965 (org-parse-time-string (substring string beg end) t))
17966 with-hm (and (nth 1 t1) (nth 2 t1))
17967 inactive (equal (substring string beg (1+ beg)) "[")
17968 tf (funcall (if with-hm 'cdr 'car)
17969 org-time-stamp-custom-formats)
17970 time (org-fix-decoded-time t1)
17971 str (format-time-string
17972 (concat
17973 (if inactive "[" "<") (substring tf 1 -1)
17974 (if inactive "]" ">"))
17975 (apply 'encode-time time))
17976 string (replace-match str t t string)
17977 start (+ start (length str)))))))
17978 string)
17980 (defun org-fix-decoded-time (time)
17981 "Set 0 instead of nil for the first 6 elements of time.
17982 Don't touch the rest."
17983 (let ((n 0))
17984 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17986 (defun org-days-to-time (timestamp-string)
17987 "Difference between TIMESTAMP-STRING and now in days."
17988 (- (time-to-days (org-time-string-to-time timestamp-string))
17989 (time-to-days (current-time))))
17991 (defun org-deadline-close (timestamp-string &optional ndays)
17992 "Is the time in TIMESTAMP-STRING close to the current date?"
17993 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17994 (and (< (org-days-to-time timestamp-string) ndays)
17995 (not (org-entry-is-done-p))))
17997 (defun org-get-wdays (ts)
17998 "Get the deadline lead time appropriate for timestring TS."
17999 (cond
18000 ((<= org-deadline-warning-days 0)
18001 ;; 0 or negative, enforce this value no matter what
18002 (- org-deadline-warning-days))
18003 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
18004 ;; lead time is specified.
18005 (floor (* (string-to-number (match-string 1 ts))
18006 (cdr (assoc (match-string 2 ts)
18007 '(("d" . 1) ("w" . 7)
18008 ("m" . 30.4) ("y" . 365.25)))))))
18009 ;; go for the default.
18010 (t org-deadline-warning-days)))
18012 (defun org-calendar-select-mouse (ev)
18013 "Return to `org-read-date' with the date currently selected.
18014 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18015 (interactive "e")
18016 (mouse-set-point ev)
18017 (when (calendar-cursor-to-date)
18018 (let* ((date (calendar-cursor-to-date))
18019 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18020 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18021 (if (active-minibuffer-window) (exit-minibuffer))))
18023 (defun org-check-deadlines (ndays)
18024 "Check if there are any deadlines due or past due.
18025 A deadline is considered due if it happens within `org-deadline-warning-days'
18026 days from today's date. If the deadline appears in an entry marked DONE,
18027 it is not shown. The prefix arg NDAYS can be used to test that many
18028 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
18029 (interactive "P")
18030 (let* ((org-warn-days
18031 (cond
18032 ((equal ndays '(4)) 100000)
18033 (ndays (prefix-numeric-value ndays))
18034 (t (abs org-deadline-warning-days))))
18035 (case-fold-search nil)
18036 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
18037 (callback
18038 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
18040 (message "%d deadlines past-due or due within %d days"
18041 (org-occur regexp nil callback)
18042 org-warn-days)))
18044 (defun org-check-before-date (date)
18045 "Check if there are deadlines or scheduled entries before DATE."
18046 (interactive (list (org-read-date)))
18047 (let ((case-fold-search nil)
18048 (regexp (concat "\\<\\(" org-deadline-string
18049 "\\|" org-scheduled-string
18050 "\\) *<\\([^>]+\\)>"))
18051 (callback
18052 (lambda () (time-less-p
18053 (org-time-string-to-time (match-string 2))
18054 (org-time-string-to-time date)))))
18055 (message "%d entries before %s"
18056 (org-occur regexp nil callback) date)))
18058 (defun org-evaluate-time-range (&optional to-buffer)
18059 "Evaluate a time range by computing the difference between start and end.
18060 Normally the result is just printed in the echo area, but with prefix arg
18061 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
18062 If the time range is actually in a table, the result is inserted into the
18063 next column.
18064 For time difference computation, a year is assumed to be exactly 365
18065 days in order to avoid rounding problems."
18066 (interactive "P")
18068 (org-clock-update-time-maybe)
18069 (save-excursion
18070 (unless (org-at-date-range-p t)
18071 (goto-char (point-at-bol))
18072 (re-search-forward org-tr-regexp-both (point-at-eol) t))
18073 (if (not (org-at-date-range-p t))
18074 (error "Not at a time-stamp range, and none found in current line")))
18075 (let* ((ts1 (match-string 1))
18076 (ts2 (match-string 2))
18077 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
18078 (match-end (match-end 0))
18079 (time1 (org-time-string-to-time ts1))
18080 (time2 (org-time-string-to-time ts2))
18081 (t1 (time-to-seconds time1))
18082 (t2 (time-to-seconds time2))
18083 (diff (abs (- t2 t1)))
18084 (negative (< (- t2 t1) 0))
18085 ;; (ys (floor (* 365 24 60 60)))
18086 (ds (* 24 60 60))
18087 (hs (* 60 60))
18088 (fy "%dy %dd %02d:%02d")
18089 (fy1 "%dy %dd")
18090 (fd "%dd %02d:%02d")
18091 (fd1 "%dd")
18092 (fh "%02d:%02d")
18093 y d h m align)
18094 (if havetime
18095 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18097 d (floor (/ diff ds)) diff (mod diff ds)
18098 h (floor (/ diff hs)) diff (mod diff hs)
18099 m (floor (/ diff 60)))
18100 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18102 d (floor (+ (/ diff ds) 0.5))
18103 h 0 m 0))
18104 (if (not to-buffer)
18105 (message "%s" (org-make-tdiff-string y d h m))
18106 (if (org-at-table-p)
18107 (progn
18108 (goto-char match-end)
18109 (setq align t)
18110 (and (looking-at " *|") (goto-char (match-end 0))))
18111 (goto-char match-end))
18112 (if (looking-at
18113 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18114 (replace-match ""))
18115 (if negative (insert " -"))
18116 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18117 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18118 (insert " " (format fh h m))))
18119 (if align (org-table-align))
18120 (message "Time difference inserted")))))
18122 (defun org-make-tdiff-string (y d h m)
18123 (let ((fmt "")
18124 (l nil))
18125 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18126 l (push y l)))
18127 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18128 l (push d l)))
18129 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18130 l (push h l)))
18131 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18132 l (push m l)))
18133 (apply 'format fmt (nreverse l))))
18135 (defun org-time-string-to-time (s)
18136 (apply 'encode-time (org-parse-time-string s)))
18138 (defun org-time-string-to-absolute (s &optional daynr prefer)
18139 "Convert a time stamp to an absolute day number.
18140 If there is a specifyer for a cyclic time stamp, get the closest date to
18141 DAYNR."
18142 (cond
18143 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18144 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18145 daynr
18146 (+ daynr 1000)))
18147 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18148 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18149 (time-to-days (current-time))) (match-string 0 s)
18150 prefer))
18151 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18153 (defun org-time-from-absolute (d)
18154 "Return the time corresponding to date D.
18155 D may be an absolute day number, or a calendar-type list (month day year)."
18156 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18157 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18159 (defun org-calendar-holiday ()
18160 "List of holidays, for Diary display in Org-mode."
18161 (require 'holidays)
18162 (let ((hl (funcall
18163 (if (fboundp 'calendar-check-holidays)
18164 'calendar-check-holidays 'check-calendar-holidays) date)))
18165 (if hl (mapconcat 'identity hl "; "))))
18167 (defun org-diary-sexp-entry (sexp entry date)
18168 "Process a SEXP diary ENTRY for DATE."
18169 (require 'diary-lib)
18170 (let ((result (if calendar-debug-sexp
18171 (let ((stack-trace-on-error t))
18172 (eval (car (read-from-string sexp))))
18173 (condition-case nil
18174 (eval (car (read-from-string sexp)))
18175 (error
18176 (beep)
18177 (message "Bad sexp at line %d in %s: %s"
18178 (org-current-line)
18179 (buffer-file-name) sexp)
18180 (sleep-for 2))))))
18181 (cond ((stringp result) result)
18182 ((and (consp result)
18183 (stringp (cdr result))) (cdr result))
18184 (result entry)
18185 (t nil))))
18187 (defun org-diary-to-ical-string (frombuf)
18188 "Get iCalendar entries from diary entries in buffer FROMBUF.
18189 This uses the icalendar.el library."
18190 (let* ((tmpdir (if (featurep 'xemacs)
18191 (temp-directory)
18192 temporary-file-directory))
18193 (tmpfile (make-temp-name
18194 (expand-file-name "orgics" tmpdir)))
18195 buf rtn b e)
18196 (save-excursion
18197 (set-buffer frombuf)
18198 (icalendar-export-region (point-min) (point-max) tmpfile)
18199 (setq buf (find-buffer-visiting tmpfile))
18200 (set-buffer buf)
18201 (goto-char (point-min))
18202 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18203 (setq b (match-beginning 0)))
18204 (goto-char (point-max))
18205 (if (re-search-backward "^END:VEVENT" nil t)
18206 (setq e (match-end 0)))
18207 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18208 (kill-buffer buf)
18209 (kill-buffer frombuf)
18210 (delete-file tmpfile)
18211 rtn))
18213 (defun org-closest-date (start current change prefer)
18214 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18215 When PREFER is `past' return a date that is either CURRENT or past.
18216 When PREFER is `future', return a date that is either CURRENT or future."
18217 ;; Make the proper lists from the dates
18218 (catch 'exit
18219 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18220 dn dw sday cday n1 n2
18221 d m y y1 y2 date1 date2 nmonths nm ny m2)
18223 (setq start (org-date-to-gregorian start)
18224 current (org-date-to-gregorian
18225 (if org-agenda-repeating-timestamp-show-all
18226 current
18227 (time-to-days (current-time))))
18228 sday (calendar-absolute-from-gregorian start)
18229 cday (calendar-absolute-from-gregorian current))
18231 (if (<= cday sday) (throw 'exit sday))
18233 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18234 (setq dn (string-to-number (match-string 1 change))
18235 dw (cdr (assoc (match-string 2 change) a1)))
18236 (error "Invalid change specifyer: %s" change))
18237 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18238 (cond
18239 ((eq dw 'day)
18240 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18241 n2 (+ n1 dn)))
18242 ((eq dw 'year)
18243 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18244 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18245 (setq date1 (list m d y1)
18246 n1 (calendar-absolute-from-gregorian date1)
18247 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18248 n2 (calendar-absolute-from-gregorian date2)))
18249 ((eq dw 'month)
18250 ;; approx number of month between the tow dates
18251 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18252 ;; How often does dn fit in there?
18253 (setq d (nth 1 start) m (car start) y (nth 2 start)
18254 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18255 m (+ m nm)
18256 ny (floor (/ m 12))
18257 y (+ y ny)
18258 m (- m (* ny 12)))
18259 (while (> m 12) (setq m (- m 12) y (1+ y)))
18260 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18261 (setq m2 (+ m dn) y2 y)
18262 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18263 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18264 (while (< n2 cday)
18265 (setq n1 n2 m m2 y y2)
18266 (setq m2 (+ m dn) y2 y)
18267 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18268 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18270 (if org-agenda-repeating-timestamp-show-all
18271 (cond
18272 ((eq prefer 'past) n1)
18273 ((eq prefer 'future) (if (= cday n1) n1 n2))
18274 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18275 (cond
18276 ((eq prefer 'past) n1)
18277 ((eq prefer 'future) (if (= cday n1) n1 n2))
18278 (t (if (= cday n1) n1 n2)))))))
18280 (defun org-date-to-gregorian (date)
18281 "Turn any specification of DATE into a gregorian date for the calendar."
18282 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18283 ((and (listp date) (= (length date) 3)) date)
18284 ((stringp date)
18285 (setq date (org-parse-time-string date))
18286 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18287 ((listp date)
18288 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18290 (defun org-parse-time-string (s &optional nodefault)
18291 "Parse the standard Org-mode time string.
18292 This should be a lot faster than the normal `parse-time-string'.
18293 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18294 hour and minute fields will be nil if not given."
18295 (if (string-match org-ts-regexp0 s)
18296 (list 0
18297 (if (or (match-beginning 8) (not nodefault))
18298 (string-to-number (or (match-string 8 s) "0")))
18299 (if (or (match-beginning 7) (not nodefault))
18300 (string-to-number (or (match-string 7 s) "0")))
18301 (string-to-number (match-string 4 s))
18302 (string-to-number (match-string 3 s))
18303 (string-to-number (match-string 2 s))
18304 nil nil nil)
18305 (make-list 9 0)))
18307 (defun org-timestamp-up (&optional arg)
18308 "Increase the date item at the cursor by one.
18309 If the cursor is on the year, change the year. If it is on the month or
18310 the day, change that.
18311 With prefix ARG, change by that many units."
18312 (interactive "p")
18313 (org-timestamp-change (prefix-numeric-value arg)))
18315 (defun org-timestamp-down (&optional arg)
18316 "Decrease the date item at the cursor by one.
18317 If the cursor is on the year, change the year. If it is on the month or
18318 the day, change that.
18319 With prefix ARG, change by that many units."
18320 (interactive "p")
18321 (org-timestamp-change (- (prefix-numeric-value arg))))
18323 (defun org-timestamp-up-day (&optional arg)
18324 "Increase the date in the time stamp by one day.
18325 With prefix ARG, change that many days."
18326 (interactive "p")
18327 (if (and (not (org-at-timestamp-p t))
18328 (org-on-heading-p))
18329 (org-todo 'up)
18330 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18332 (defun org-timestamp-down-day (&optional arg)
18333 "Decrease the date in the time stamp by one day.
18334 With prefix ARG, change that many days."
18335 (interactive "p")
18336 (if (and (not (org-at-timestamp-p t))
18337 (org-on-heading-p))
18338 (org-todo 'down)
18339 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18341 (defsubst org-pos-in-match-range (pos n)
18342 (and (match-beginning n)
18343 (<= (match-beginning n) pos)
18344 (>= (match-end n) pos)))
18346 (defun org-at-timestamp-p (&optional inactive-ok)
18347 "Determine if the cursor is in or at a timestamp."
18348 (interactive)
18349 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18350 (pos (point))
18351 (ans (or (looking-at tsr)
18352 (save-excursion
18353 (skip-chars-backward "^[<\n\r\t")
18354 (if (> (point) (point-min)) (backward-char 1))
18355 (and (looking-at tsr)
18356 (> (- (match-end 0) pos) -1))))))
18357 (and ans
18358 (boundp 'org-ts-what)
18359 (setq org-ts-what
18360 (cond
18361 ((= pos (match-beginning 0)) 'bracket)
18362 ((= pos (1- (match-end 0))) 'bracket)
18363 ((org-pos-in-match-range pos 2) 'year)
18364 ((org-pos-in-match-range pos 3) 'month)
18365 ((org-pos-in-match-range pos 7) 'hour)
18366 ((org-pos-in-match-range pos 8) 'minute)
18367 ((or (org-pos-in-match-range pos 4)
18368 (org-pos-in-match-range pos 5)) 'day)
18369 ((and (> pos (or (match-end 8) (match-end 5)))
18370 (< pos (match-end 0)))
18371 (- pos (or (match-end 8) (match-end 5))))
18372 (t 'day))))
18373 ans))
18375 (defun org-toggle-timestamp-type ()
18376 "Toggle the type (<active> or [inactive]) of a time stamp."
18377 (interactive)
18378 (when (org-at-timestamp-p t)
18379 (save-excursion
18380 (goto-char (match-beginning 0))
18381 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18382 (goto-char (1- (match-end 0)))
18383 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18384 (message "Timestamp is now %sactive"
18385 (if (equal (char-before) ?>) "in" ""))))
18387 (defun org-timestamp-change (n &optional what)
18388 "Change the date in the time stamp at point.
18389 The date will be changed by N times WHAT. WHAT can be `day', `month',
18390 `year', `minute', `second'. If WHAT is not given, the cursor position
18391 in the timestamp determines what will be changed."
18392 (let ((pos (point))
18393 with-hm inactive
18394 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18395 org-ts-what
18396 extra rem
18397 ts time time0)
18398 (if (not (org-at-timestamp-p t))
18399 (error "Not at a timestamp"))
18400 (if (and (not what) (eq org-ts-what 'bracket))
18401 (org-toggle-timestamp-type)
18402 (if (and (not what) (not (eq org-ts-what 'day))
18403 org-display-custom-times
18404 (get-text-property (point) 'display)
18405 (not (get-text-property (1- (point)) 'display)))
18406 (setq org-ts-what 'day))
18407 (setq org-ts-what (or what org-ts-what)
18408 inactive (= (char-after (match-beginning 0)) ?\[)
18409 ts (match-string 0))
18410 (replace-match "")
18411 (if (string-match
18412 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
18414 (setq extra (match-string 1 ts)))
18415 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18416 (setq with-hm t))
18417 (setq time0 (org-parse-time-string ts))
18418 (when (and (eq org-ts-what 'minute)
18419 (eq current-prefix-arg nil))
18420 (setq n (* dm (org-no-warnings (signum n))))
18421 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
18422 (setcar (cdr time0) (+ (nth 1 time0)
18423 (if (> n 0) (- rem) (- dm rem))))))
18424 (setq time
18425 (encode-time (or (car time0) 0)
18426 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18427 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18428 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18429 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18430 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18431 (nthcdr 6 time0)))
18432 (when (integerp org-ts-what)
18433 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18434 (if (eq what 'calendar)
18435 (let ((cal-date (org-get-date-from-calendar)))
18436 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18437 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18438 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18439 (setcar time0 (or (car time0) 0))
18440 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18441 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18442 (setq time (apply 'encode-time time0))))
18443 (setq org-last-changed-timestamp
18444 (org-insert-time-stamp time with-hm inactive nil nil extra))
18445 (org-clock-update-time-maybe)
18446 (goto-char pos)
18447 ;; Try to recenter the calendar window, if any
18448 (if (and org-calendar-follow-timestamp-change
18449 (get-buffer-window "*Calendar*" t)
18450 (memq org-ts-what '(day month year)))
18451 (org-recenter-calendar (time-to-days time))))))
18453 ;; FIXME: does not yet work for lead times
18454 (defun org-modify-ts-extra (s pos n dm)
18455 "Change the different parts of the lead-time and repeat fields in timestamp."
18456 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18457 ng h m new rem)
18458 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18459 (cond
18460 ((or (org-pos-in-match-range pos 2)
18461 (org-pos-in-match-range pos 3))
18462 (setq m (string-to-number (match-string 3 s))
18463 h (string-to-number (match-string 2 s)))
18464 (if (org-pos-in-match-range pos 2)
18465 (setq h (+ h n))
18466 (setq n (* dm (org-no-warnings (signum n))))
18467 (when (not (= 0 (setq rem (% m dm))))
18468 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18469 (setq m (+ m n)))
18470 (if (< m 0) (setq m (+ m 60) h (1- h)))
18471 (if (> m 59) (setq m (- m 60) h (1+ h)))
18472 (setq h (min 24 (max 0 h)))
18473 (setq ng 1 new (format "-%02d:%02d" h m)))
18474 ((org-pos-in-match-range pos 6)
18475 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18476 ((org-pos-in-match-range pos 5)
18477 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18479 ((org-pos-in-match-range pos 9)
18480 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18481 ((org-pos-in-match-range pos 8)
18482 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18484 (when ng
18485 (setq s (concat
18486 (substring s 0 (match-beginning ng))
18488 (substring s (match-end ng))))))
18491 (defun org-recenter-calendar (date)
18492 "If the calendar is visible, recenter it to DATE."
18493 (let* ((win (selected-window))
18494 (cwin (get-buffer-window "*Calendar*" t))
18495 (calendar-move-hook nil))
18496 (when cwin
18497 (select-window cwin)
18498 (calendar-goto-date (if (listp date) date
18499 (calendar-gregorian-from-absolute date)))
18500 (select-window win))))
18502 (defun org-goto-calendar (&optional arg)
18503 "Go to the Emacs calendar at the current date.
18504 If there is a time stamp in the current line, go to that date.
18505 A prefix ARG can be used to force the current date."
18506 (interactive "P")
18507 (let ((tsr org-ts-regexp) diff
18508 (calendar-move-hook nil)
18509 (view-calendar-holidays-initially nil)
18510 (view-diary-entries-initially nil))
18511 (if (or (org-at-timestamp-p)
18512 (save-excursion
18513 (beginning-of-line 1)
18514 (looking-at (concat ".*" tsr))))
18515 (let ((d1 (time-to-days (current-time)))
18516 (d2 (time-to-days
18517 (org-time-string-to-time (match-string 1)))))
18518 (setq diff (- d2 d1))))
18519 (calendar)
18520 (calendar-goto-today)
18521 (if (and diff (not arg)) (calendar-forward-day diff))))
18523 (defun org-get-date-from-calendar ()
18524 "Return a list (month day year) of date at point in calendar."
18525 (with-current-buffer "*Calendar*"
18526 (save-match-data
18527 (calendar-cursor-to-date))))
18529 (defun org-date-from-calendar ()
18530 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18531 If there is already a time stamp at the cursor position, update it."
18532 (interactive)
18533 (if (org-at-timestamp-p t)
18534 (org-timestamp-change 0 'calendar)
18535 (let ((cal-date (org-get-date-from-calendar)))
18536 (org-insert-time-stamp
18537 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18539 (defvar appt-time-msg-list)
18541 ;;;###autoload
18542 (defun org-agenda-to-appt (&optional refresh filter)
18543 "Activate appointments found in `org-agenda-files'.
18544 With a \\[universal-argument] prefix, refresh the list of
18545 appointements.
18547 If FILTER is t, interactively prompt the user for a regular
18548 expression, and filter out entries that don't match it.
18550 If FILTER is a string, use this string as a regular expression
18551 for filtering entries out.
18553 FILTER can also be an alist with the car of each cell being
18554 either 'headline or 'category. For example:
18556 '((headline \"IMPORTANT\")
18557 (category \"Work\"))
18559 will only add headlines containing IMPORTANT or headlines
18560 belonging to the \"Work\" category."
18561 (interactive "P")
18562 (require 'calendar)
18563 (if refresh (setq appt-time-msg-list nil))
18564 (if (eq filter t)
18565 (setq filter (read-from-minibuffer "Regexp filter: ")))
18566 (let* ((cnt 0) ; count added events
18567 (org-agenda-new-buffers nil)
18568 (org-deadline-warning-days 0)
18569 (today (org-date-to-gregorian
18570 (time-to-days (current-time))))
18571 (files (org-agenda-files)) entries file)
18572 ;; Get all entries which may contain an appt
18573 (while (setq file (pop files))
18574 (setq entries
18575 (append entries
18576 (org-agenda-get-day-entries
18577 file today :timestamp :scheduled :deadline))))
18578 (setq entries (delq nil entries))
18579 ;; Map thru entries and find if we should filter them out
18580 (mapc
18581 (lambda(x)
18582 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18583 (cat (get-text-property 1 'org-category x))
18584 (tod (get-text-property 1 'time-of-day x))
18585 (ok (or (null filter)
18586 (and (stringp filter) (string-match filter evt))
18587 (and (listp filter)
18588 (or (string-match
18589 (cadr (assoc 'category filter)) cat)
18590 (string-match
18591 (cadr (assoc 'headline filter)) evt))))))
18592 ;; FIXME: Shall we remove text-properties for the appt text?
18593 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18594 (when (and ok tod)
18595 (setq tod (number-to-string tod)
18596 tod (when (string-match
18597 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18598 (concat (match-string 1 tod) ":"
18599 (match-string 2 tod))))
18600 (appt-add tod evt)
18601 (setq cnt (1+ cnt))))) entries)
18602 (org-release-buffers org-agenda-new-buffers)
18603 (if (eq cnt 0)
18604 (message "No event to add")
18605 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" "")))))
18607 ;;; The clock for measuring work time.
18609 (defvar org-mode-line-string "")
18610 (put 'org-mode-line-string 'risky-local-variable t)
18612 (defvar org-mode-line-timer nil)
18613 (defvar org-clock-heading "")
18614 (defvar org-clock-start-time "")
18616 (defun org-update-mode-line ()
18617 (let* ((delta (- (time-to-seconds (current-time))
18618 (time-to-seconds org-clock-start-time)))
18619 (h (floor delta 3600))
18620 (m (floor (- delta (* 3600 h)) 60)))
18621 (setq org-mode-line-string
18622 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18623 'help-echo "Org-mode clock is running"))
18624 (force-mode-line-update)))
18626 (defvar org-clock-marker (make-marker)
18627 "Marker recording the last clock-in.")
18628 (defvar org-clock-mode-line-entry nil
18629 "Information for the modeline about the running clock.")
18631 (defun org-clock-in ()
18632 "Start the clock on the current item.
18633 If necessary, clock-out of the currently active clock."
18634 (interactive)
18635 (org-clock-out t)
18636 (let (ts)
18637 (save-excursion
18638 (org-back-to-heading t)
18639 (when (and org-clock-in-switch-to-state
18640 (not (looking-at (concat outline-regexp "[ \t]*"
18641 org-clock-in-switch-to-state
18642 "\\>"))))
18643 (org-todo org-clock-in-switch-to-state))
18644 (if (and org-clock-heading-function
18645 (functionp org-clock-heading-function))
18646 (setq org-clock-heading (funcall org-clock-heading-function))
18647 (if (looking-at org-complex-heading-regexp)
18648 (setq org-clock-heading (match-string 4))
18649 (setq org-clock-heading "???")))
18650 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18651 (org-clock-find-position)
18653 (insert "\n") (backward-char 1)
18654 (indent-relative)
18655 (insert org-clock-string " ")
18656 (setq org-clock-start-time (current-time))
18657 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18658 (move-marker org-clock-marker (point) (buffer-base-buffer))
18659 (or global-mode-string (setq global-mode-string '("")))
18660 (or (memq 'org-mode-line-string global-mode-string)
18661 (setq global-mode-string
18662 (append global-mode-string '(org-mode-line-string))))
18663 (org-update-mode-line)
18664 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18665 (message "Clock started at %s" ts))))
18667 (defun org-clock-find-position ()
18668 "Find the location where the next clock line should be inserted."
18669 (org-back-to-heading t)
18670 (catch 'exit
18671 (let ((beg (save-excursion
18672 (beginning-of-line 2)
18673 (or (bolp) (newline))
18674 (point)))
18675 (end (progn (outline-next-heading) (point)))
18676 (re (concat "^[ \t]*" org-clock-string))
18677 (cnt 0)
18678 first last)
18679 (goto-char beg)
18680 (when (eobp) (newline) (setq end (max (point) end)))
18681 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18682 ;; we seem to have a CLOCK drawer, so go there.
18683 (beginning-of-line 2)
18684 (throw 'exit t))
18685 ;; Lets count the CLOCK lines
18686 (goto-char beg)
18687 (while (re-search-forward re end t)
18688 (setq first (or first (match-beginning 0))
18689 last (match-beginning 0)
18690 cnt (1+ cnt)))
18691 (when (and (integerp org-clock-into-drawer)
18692 (>= (1+ cnt) org-clock-into-drawer))
18693 ;; Wrap current entries into a new drawer
18694 (goto-char last)
18695 (beginning-of-line 2)
18696 (if (org-at-item-p) (org-end-of-item))
18697 (insert ":END:\n")
18698 (beginning-of-line 0)
18699 (org-indent-line-function)
18700 (goto-char first)
18701 (insert ":CLOCK:\n")
18702 (beginning-of-line 0)
18703 (org-indent-line-function)
18704 (org-flag-drawer t)
18705 (beginning-of-line 2)
18706 (throw 'exit nil))
18708 (goto-char beg)
18709 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18710 (not (equal (match-string 1) org-clock-string)))
18711 ;; Planning info, skip to after it
18712 (beginning-of-line 2)
18713 (or (bolp) (newline)))
18714 (when (eq t org-clock-into-drawer)
18715 (insert ":CLOCK:\n:END:\n")
18716 (beginning-of-line -1)
18717 (org-indent-line-function)
18718 (org-flag-drawer t)
18719 (beginning-of-line 2)
18720 (org-indent-line-function)))))
18722 (defun org-clock-out (&optional fail-quietly)
18723 "Stop the currently running clock.
18724 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18725 (interactive)
18726 (catch 'exit
18727 (if (not (marker-buffer org-clock-marker))
18728 (if fail-quietly (throw 'exit t) (error "No active clock")))
18729 (let (ts te s h m)
18730 (save-excursion
18731 (set-buffer (marker-buffer org-clock-marker))
18732 (goto-char org-clock-marker)
18733 (beginning-of-line 1)
18734 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18735 (equal (match-string 1) org-clock-string))
18736 (setq ts (match-string 2))
18737 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18738 (goto-char (match-end 0))
18739 (delete-region (point) (point-at-eol))
18740 (insert "--")
18741 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18742 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18743 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18744 h (floor (/ s 3600))
18745 s (- s (* 3600 h))
18746 m (floor (/ s 60))
18747 s (- s (* 60 s)))
18748 (insert " => " (format "%2d:%02d" h m))
18749 (move-marker org-clock-marker nil)
18750 (when org-log-note-clock-out
18751 (org-add-log-maybe 'clock-out))
18752 (when org-mode-line-timer
18753 (cancel-timer org-mode-line-timer)
18754 (setq org-mode-line-timer nil))
18755 (setq global-mode-string
18756 (delq 'org-mode-line-string global-mode-string))
18757 (force-mode-line-update)
18758 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18760 (defun org-clock-cancel ()
18761 "Cancel the running clock be removing the start timestamp."
18762 (interactive)
18763 (if (not (marker-buffer org-clock-marker))
18764 (error "No active clock"))
18765 (save-excursion
18766 (set-buffer (marker-buffer org-clock-marker))
18767 (goto-char org-clock-marker)
18768 (delete-region (1- (point-at-bol)) (point-at-eol)))
18769 (setq global-mode-string
18770 (delq 'org-mode-line-string global-mode-string))
18771 (force-mode-line-update)
18772 (message "Clock canceled"))
18774 (defun org-clock-goto (&optional delete-windows)
18775 "Go to the currently clocked-in entry."
18776 (interactive "P")
18777 (if (not (marker-buffer org-clock-marker))
18778 (error "No active clock"))
18779 (switch-to-buffer-other-window
18780 (marker-buffer org-clock-marker))
18781 (if delete-windows (delete-other-windows))
18782 (goto-char org-clock-marker)
18783 (org-show-entry)
18784 (org-back-to-heading)
18785 (recenter))
18787 (defvar org-clock-file-total-minutes nil
18788 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18789 (make-variable-buffer-local 'org-clock-file-total-minutes)
18791 (defun org-clock-sum (&optional tstart tend)
18792 "Sum the times for each subtree.
18793 Puts the resulting times in minutes as a text property on each headline."
18794 (interactive)
18795 (let* ((bmp (buffer-modified-p))
18796 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18797 org-clock-string
18798 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18799 (lmax 30)
18800 (ltimes (make-vector lmax 0))
18801 (t1 0)
18802 (level 0)
18803 ts te dt
18804 time)
18805 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18806 (save-excursion
18807 (goto-char (point-max))
18808 (while (re-search-backward re nil t)
18809 (cond
18810 ((match-end 2)
18811 ;; Two time stamps
18812 (setq ts (match-string 2)
18813 te (match-string 3)
18814 ts (time-to-seconds
18815 (apply 'encode-time (org-parse-time-string ts)))
18816 te (time-to-seconds
18817 (apply 'encode-time (org-parse-time-string te)))
18818 ts (if tstart (max ts tstart) ts)
18819 te (if tend (min te tend) te)
18820 dt (- te ts)
18821 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18822 ((match-end 4)
18823 ;; A naket time
18824 (setq t1 (+ t1 (string-to-number (match-string 5))
18825 (* 60 (string-to-number (match-string 4))))))
18826 (t ;; A headline
18827 (setq level (- (match-end 1) (match-beginning 1)))
18828 (when (or (> t1 0) (> (aref ltimes level) 0))
18829 (loop for l from 0 to level do
18830 (aset ltimes l (+ (aref ltimes l) t1)))
18831 (setq t1 0 time (aref ltimes level))
18832 (loop for l from level to (1- lmax) do
18833 (aset ltimes l 0))
18834 (goto-char (match-beginning 0))
18835 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18836 (setq org-clock-file-total-minutes (aref ltimes 0)))
18837 (set-buffer-modified-p bmp)))
18839 (defun org-clock-display (&optional total-only)
18840 "Show subtree times in the entire buffer.
18841 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18842 in the echo area."
18843 (interactive)
18844 (org-remove-clock-overlays)
18845 (let (time h m p)
18846 (org-clock-sum)
18847 (unless total-only
18848 (save-excursion
18849 (goto-char (point-min))
18850 (while (or (and (equal (setq p (point)) (point-min))
18851 (get-text-property p :org-clock-minutes))
18852 (setq p (next-single-property-change
18853 (point) :org-clock-minutes)))
18854 (goto-char p)
18855 (when (setq time (get-text-property p :org-clock-minutes))
18856 (org-put-clock-overlay time (funcall outline-level))))
18857 (setq h (/ org-clock-file-total-minutes 60)
18858 m (- org-clock-file-total-minutes (* 60 h)))
18859 ;; Arrange to remove the overlays upon next change.
18860 (when org-remove-highlights-with-change
18861 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18862 nil 'local))))
18863 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18865 (defvar org-clock-overlays nil)
18866 (make-variable-buffer-local 'org-clock-overlays)
18868 (defun org-put-clock-overlay (time &optional level)
18869 "Put an overlays on the current line, displaying TIME.
18870 If LEVEL is given, prefix time with a corresponding number of stars.
18871 This creates a new overlay and stores it in `org-clock-overlays', so that it
18872 will be easy to remove."
18873 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18874 (l (if level (org-get-valid-level level 0) 0))
18875 (off 0)
18876 ov tx)
18877 (move-to-column c)
18878 (unless (eolp) (skip-chars-backward "^ \t"))
18879 (skip-chars-backward " \t")
18880 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18881 tx (concat (buffer-substring (1- (point)) (point))
18882 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18883 (org-add-props (format "%s %2d:%02d%s"
18884 (make-string l ?*) h m
18885 (make-string (- 16 l) ?\ ))
18886 '(face secondary-selection))
18887 ""))
18888 (if (not (featurep 'xemacs))
18889 (org-overlay-put ov 'display tx)
18890 (org-overlay-put ov 'invisible t)
18891 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18892 (push ov org-clock-overlays)))
18894 (defun org-remove-clock-overlays (&optional beg end noremove)
18895 "Remove the occur highlights from the buffer.
18896 BEG and END are ignored. If NOREMOVE is nil, remove this function
18897 from the `before-change-functions' in the current buffer."
18898 (interactive)
18899 (unless org-inhibit-highlight-removal
18900 (mapc 'org-delete-overlay org-clock-overlays)
18901 (setq org-clock-overlays nil)
18902 (unless noremove
18903 (remove-hook 'before-change-functions
18904 'org-remove-clock-overlays 'local))))
18906 (defun org-clock-out-if-current ()
18907 "Clock out if the current entry contains the running clock.
18908 This is used to stop the clock after a TODO entry is marked DONE,
18909 and is only done if the variable `org-clock-out-when-done' is not nil."
18910 (when (and org-clock-out-when-done
18911 (member state org-done-keywords)
18912 (equal (marker-buffer org-clock-marker) (current-buffer))
18913 (< (point) org-clock-marker)
18914 (> (save-excursion (outline-next-heading) (point))
18915 org-clock-marker))
18916 ;; Clock out, but don't accept a logging message for this.
18917 (let ((org-log-note-clock-out nil))
18918 (org-clock-out))))
18920 (add-hook 'org-after-todo-state-change-hook
18921 'org-clock-out-if-current)
18923 (defun org-check-running-clock ()
18924 "Check if the current buffer contains the running clock.
18925 If yes, offer to stop it and to save the buffer with the changes."
18926 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
18927 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
18928 (buffer-name))))
18929 (org-clock-out)
18930 (when (y-or-n-p "Save changed buffer?")
18931 (save-buffer))))
18933 (defun org-clock-report (&optional arg)
18934 "Create a table containing a report about clocked time.
18935 If the cursor is inside an existing clocktable block, then the table
18936 will be updated. If not, a new clocktable will be inserted.
18937 When called with a prefix argument, move to the first clock table in the
18938 buffer and update it."
18939 (interactive "P")
18940 (org-remove-clock-overlays)
18941 (when arg
18942 (org-find-dblock "clocktable")
18943 (org-show-entry))
18944 (if (org-in-clocktable-p)
18945 (goto-char (org-in-clocktable-p))
18946 (org-create-dblock (list :name "clocktable"
18947 :maxlevel 2 :scope 'file)))
18948 (org-update-dblock))
18950 (defun org-in-clocktable-p ()
18951 "Check if the cursor is in a clocktable."
18952 (let ((pos (point)) start)
18953 (save-excursion
18954 (end-of-line 1)
18955 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
18956 (setq start (match-beginning 0))
18957 (re-search-forward "^#\\+END:.*" nil t)
18958 (>= (match-end 0) pos)
18959 start))))
18961 (defun org-clock-update-time-maybe ()
18962 "If this is a CLOCK line, update it and return t.
18963 Otherwise, return nil."
18964 (interactive)
18965 (save-excursion
18966 (beginning-of-line 1)
18967 (skip-chars-forward " \t")
18968 (when (looking-at org-clock-string)
18969 (let ((re (concat "[ \t]*" org-clock-string
18970 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
18971 "\\([ \t]*=>.*\\)?"))
18972 ts te h m s)
18973 (if (not (looking-at re))
18975 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
18976 (end-of-line 1)
18977 (setq ts (match-string 1)
18978 te (match-string 2))
18979 (setq s (- (time-to-seconds
18980 (apply 'encode-time (org-parse-time-string te)))
18981 (time-to-seconds
18982 (apply 'encode-time (org-parse-time-string ts))))
18983 h (floor (/ s 3600))
18984 s (- s (* 3600 h))
18985 m (floor (/ s 60))
18986 s (- s (* 60 s)))
18987 (insert " => " (format "%2d:%02d" h m))
18988 t)))))
18990 (defun org-clock-special-range (key &optional time as-strings)
18991 "Return two times bordering a special time range.
18992 Key is a symbol specifying the range and can be one of `today', `yesterday',
18993 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
18994 A week starts Monday 0:00 and ends Sunday 24:00.
18995 The range is determined relative to TIME. TIME defaults to the current time.
18996 The return value is a cons cell with two internal times like the ones
18997 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
18998 the returned times will be formatted strings."
18999 (let* ((tm (decode-time (or time (current-time))))
19000 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
19001 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
19002 (dow (nth 6 tm))
19003 s1 m1 h1 d1 month1 y1 diff ts te fm)
19004 (cond
19005 ((eq key 'today)
19006 (setq h 0 m 0 h1 24 m1 0))
19007 ((eq key 'yesterday)
19008 (setq d (1- d) h 0 m 0 h1 24 m1 0))
19009 ((eq key 'thisweek)
19010 (setq diff (if (= dow 0) 6 (1- dow))
19011 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19012 ((eq key 'lastweek)
19013 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
19014 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19015 ((eq key 'thismonth)
19016 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
19017 ((eq key 'lastmonth)
19018 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
19019 ((eq key 'thisyear)
19020 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
19021 ((eq key 'lastyear)
19022 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
19023 (t (error "No such time block %s" key)))
19024 (setq ts (encode-time s m h d month y)
19025 te (encode-time (or s1 s) (or m1 m) (or h1 h)
19026 (or d1 d) (or month1 month) (or y1 y)))
19027 (setq fm (cdr org-time-stamp-formats))
19028 (if as-strings
19029 (cons (format-time-string fm ts) (format-time-string fm te))
19030 (cons ts te))))
19032 (defun org-dblock-write:clocktable (params)
19033 "Write the standard clocktable."
19034 (catch 'exit
19035 (let* ((hlchars '((1 . "*") (2 . "/")))
19036 (ins (make-marker))
19037 (total-time nil)
19038 (scope (plist-get params :scope))
19039 (tostring (plist-get params :tostring))
19040 (multifile (plist-get params :multifile))
19041 (header (plist-get params :header))
19042 (maxlevel (or (plist-get params :maxlevel) 3))
19043 (step (plist-get params :step))
19044 (emph (plist-get params :emphasize))
19045 (ts (plist-get params :tstart))
19046 (te (plist-get params :tend))
19047 (block (plist-get params :block))
19048 (link (plist-get params :link))
19049 ipos time h m p level hlc hdl
19050 cc beg end pos tbl)
19051 (when step
19052 (org-clocktable-steps params)
19053 (throw 'exit nil))
19054 (when block
19055 (setq cc (org-clock-special-range block nil t)
19056 ts (car cc) te (cdr cc)))
19057 (if ts (setq ts (time-to-seconds
19058 (apply 'encode-time (org-parse-time-string ts)))))
19059 (if te (setq te (time-to-seconds
19060 (apply 'encode-time (org-parse-time-string te)))))
19061 (move-marker ins (point))
19062 (setq ipos (point))
19064 ;; Get the right scope
19065 (setq pos (point))
19066 (save-restriction
19067 (cond
19068 ((not scope))
19069 ((eq scope 'file) (widen))
19070 ((eq scope 'subtree) (org-narrow-to-subtree))
19071 ((eq scope 'tree)
19072 (while (org-up-heading-safe))
19073 (org-narrow-to-subtree))
19074 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
19075 (symbol-name scope)))
19076 (setq level (string-to-number (match-string 1 (symbol-name scope))))
19077 (catch 'exit
19078 (while (org-up-heading-safe)
19079 (looking-at outline-regexp)
19080 (if (<= (org-reduced-level (funcall outline-level)) level)
19081 (throw 'exit nil))))
19082 (org-narrow-to-subtree))
19083 ((or (listp scope) (eq scope 'agenda))
19084 (let* ((files (if (listp scope) scope (org-agenda-files)))
19085 (scope 'agenda)
19086 (p1 (copy-sequence params))
19087 file)
19088 (plist-put p1 :tostring t)
19089 (plist-put p1 :multifile t)
19090 (plist-put p1 :scope 'file)
19091 (org-prepare-agenda-buffers files)
19092 (while (setq file (pop files))
19093 (with-current-buffer (find-buffer-visiting file)
19094 (push (org-clocktable-add-file
19095 file (org-dblock-write:clocktable p1)) tbl)
19096 (setq total-time (+ (or total-time 0)
19097 org-clock-file-total-minutes)))))))
19098 (goto-char pos)
19100 (unless (eq scope 'agenda)
19101 (org-clock-sum ts te)
19102 (goto-char (point-min))
19103 (while (setq p (next-single-property-change (point) :org-clock-minutes))
19104 (goto-char p)
19105 (when (setq time (get-text-property p :org-clock-minutes))
19106 (save-excursion
19107 (beginning-of-line 1)
19108 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19109 (setq level (org-reduced-level
19110 (- (match-end 1) (match-beginning 1))))
19111 (<= level maxlevel))
19112 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19113 hdl (if (not link)
19114 (match-string 2)
19115 (org-make-link-string
19116 (format "file:%s::%s"
19117 (buffer-file-name)
19118 (save-match-data
19119 (org-make-org-heading-search-string
19120 (match-string 2))))
19121 (match-string 2)))
19122 h (/ time 60)
19123 m (- time (* 60 h)))
19124 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19125 (push (concat
19126 "| " (int-to-string level) "|" hlc hdl hlc " |"
19127 (make-string (1- level) ?|)
19128 hlc (format "%d:%02d" h m) hlc
19129 " |") tbl))))))
19130 (setq tbl (nreverse tbl))
19131 (if tostring
19132 (if tbl (mapconcat 'identity tbl "\n") nil)
19133 (goto-char ins)
19134 (insert-before-markers
19135 (or header
19136 (concat
19137 "Clock summary at ["
19138 (substring
19139 (format-time-string (cdr org-time-stamp-formats))
19140 1 -1)
19141 "]."
19142 (if block
19143 (format " Considered range is /%s/." block)
19145 "\n\n"))
19146 (if (eq scope 'agenda) "|File" "")
19147 "|L|Headline|Time|\n")
19148 (setq total-time (or total-time org-clock-file-total-minutes)
19149 h (/ total-time 60)
19150 m (- total-time (* 60 h)))
19151 (insert-before-markers
19152 "|-\n|"
19153 (if (eq scope 'agenda) "|" "")
19155 "*Total time*| "
19156 (format "*%d:%02d*" h m)
19157 "|\n|-\n")
19158 (setq tbl (delq nil tbl))
19159 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19160 (equal (substring (car tbl) 0 2) "|-"))
19161 (pop tbl))
19162 (insert-before-markers (mapconcat
19163 'identity (delq nil tbl)
19164 (if (eq scope 'agenda) "\n|-\n" "\n")))
19165 (backward-delete-char 1)
19166 (goto-char ipos)
19167 (skip-chars-forward "^|")
19168 (org-table-align))))))
19170 (defun org-clocktable-steps (params)
19171 (let* ((p1 (copy-sequence params))
19172 (ts (plist-get p1 :tstart))
19173 (te (plist-get p1 :tend))
19174 (step0 (plist-get p1 :step))
19175 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19176 (block (plist-get p1 :block))
19178 (when block
19179 (setq cc (org-clock-special-range block nil t)
19180 ts (car cc) te (cdr cc)))
19181 (if ts (setq ts (time-to-seconds
19182 (apply 'encode-time (org-parse-time-string ts)))))
19183 (if te (setq te (time-to-seconds
19184 (apply 'encode-time (org-parse-time-string te)))))
19185 (plist-put p1 :header "")
19186 (plist-put p1 :step nil)
19187 (plist-put p1 :block nil)
19188 (while (< ts te)
19189 (or (bolp) (insert "\n"))
19190 (plist-put p1 :tstart (format-time-string
19191 (car org-time-stamp-formats)
19192 (seconds-to-time ts)))
19193 (plist-put p1 :tend (format-time-string
19194 (car org-time-stamp-formats)
19195 (seconds-to-time (setq ts (+ ts step)))))
19196 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19197 (plist-get p1 :tstart) "\n")
19198 (org-dblock-write:clocktable p1)
19199 (re-search-forward "#\\+END:")
19200 (end-of-line 0))))
19203 (defun org-clocktable-add-file (file table)
19204 (if table
19205 (let ((lines (org-split-string table "\n"))
19206 (ff (file-name-nondirectory file)))
19207 (mapconcat 'identity
19208 (mapcar (lambda (x)
19209 (if (string-match org-table-dataline-regexp x)
19210 (concat "|" ff x)
19212 lines)
19213 "\n"))))
19215 ;; FIXME: I don't think anybody uses this, ask David
19216 (defun org-collect-clock-time-entries ()
19217 "Return an internal list with clocking information.
19218 This list has one entry for each CLOCK interval.
19219 FIXME: describe the elements."
19220 (interactive)
19221 (let ((re (concat "^[ \t]*" org-clock-string
19222 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19223 rtn beg end next cont level title total closedp leafp
19224 clockpos titlepos h m donep)
19225 (save-excursion
19226 (org-clock-sum)
19227 (goto-char (point-min))
19228 (while (re-search-forward re nil t)
19229 (setq clockpos (match-beginning 0)
19230 beg (match-string 1) end (match-string 2)
19231 cont (match-end 0))
19232 (setq beg (apply 'encode-time (org-parse-time-string beg))
19233 end (apply 'encode-time (org-parse-time-string end)))
19234 (org-back-to-heading t)
19235 (setq donep (org-entry-is-done-p))
19236 (setq titlepos (point)
19237 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19238 h (/ total 60) m (- total (* 60 h))
19239 total (cons h m))
19240 (looking-at "\\(\\*+\\) +\\(.*\\)")
19241 (setq level (- (match-end 1) (match-beginning 1))
19242 title (org-match-string-no-properties 2))
19243 (save-excursion (outline-next-heading) (setq next (point)))
19244 (setq closedp (re-search-forward org-closed-time-regexp next t))
19245 (goto-char next)
19246 (setq leafp (and (looking-at "^\\*+ ")
19247 (<= (- (match-end 0) (point)) level)))
19248 (push (list beg end clockpos closedp donep
19249 total title titlepos level leafp)
19250 rtn)
19251 (goto-char cont)))
19252 (nreverse rtn)))
19254 ;;;; Agenda, and Diary Integration
19256 ;;; Define the Org-agenda-mode
19258 (defvar org-agenda-mode-map (make-sparse-keymap)
19259 "Keymap for `org-agenda-mode'.")
19261 (defvar org-agenda-menu) ; defined later in this file.
19262 (defvar org-agenda-follow-mode nil)
19263 (defvar org-agenda-show-log nil)
19264 (defvar org-agenda-redo-command nil)
19265 (defvar org-agenda-query-string nil)
19266 (defvar org-agenda-mode-hook nil)
19267 (defvar org-agenda-type nil)
19268 (defvar org-agenda-force-single-file nil)
19270 (defun org-agenda-mode ()
19271 "Mode for time-sorted view on action items in Org-mode files.
19273 The following commands are available:
19275 \\{org-agenda-mode-map}"
19276 (interactive)
19277 (kill-all-local-variables)
19278 (setq org-agenda-undo-list nil
19279 org-agenda-pending-undo-list nil)
19280 (setq major-mode 'org-agenda-mode)
19281 ;; Keep global-font-lock-mode from turning on font-lock-mode
19282 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19283 (setq mode-name "Org-Agenda")
19284 (use-local-map org-agenda-mode-map)
19285 (easy-menu-add org-agenda-menu)
19286 (if org-startup-truncated (setq truncate-lines t))
19287 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19288 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19289 ;; Make sure properties are removed when copying text
19290 (when (boundp 'buffer-substring-filters)
19291 (org-set-local 'buffer-substring-filters
19292 (cons (lambda (x)
19293 (set-text-properties 0 (length x) nil x) x)
19294 buffer-substring-filters)))
19295 (unless org-agenda-keep-modes
19296 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19297 org-agenda-show-log nil))
19298 (easy-menu-change
19299 '("Agenda") "Agenda Files"
19300 (append
19301 (list
19302 (vector
19303 (if (get 'org-agenda-files 'org-restrict)
19304 "Restricted to single file"
19305 "Edit File List")
19306 '(org-edit-agenda-file-list)
19307 (not (get 'org-agenda-files 'org-restrict)))
19308 "--")
19309 (mapcar 'org-file-menu-entry (org-agenda-files))))
19310 (org-agenda-set-mode-name)
19311 (apply
19312 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19313 (list 'org-agenda-mode-hook)))
19315 (substitute-key-definition 'undo 'org-agenda-undo
19316 org-agenda-mode-map global-map)
19317 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19318 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19319 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19320 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19321 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19322 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19323 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19324 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19325 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19326 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19327 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19328 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19329 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19330 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19331 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19332 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19333 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19334 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19335 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19336 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19337 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19338 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19339 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19340 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19341 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19342 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19343 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19344 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19345 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19347 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19348 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19349 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19350 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19351 (while l (org-defkey org-agenda-mode-map
19352 (int-to-string (pop l)) 'digit-argument)))
19354 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19355 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19356 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19357 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19358 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19359 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19360 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19361 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19362 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19363 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19364 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19365 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19366 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19367 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19368 (org-defkey org-agenda-mode-map "n" 'next-line)
19369 (org-defkey org-agenda-mode-map "p" 'previous-line)
19370 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19371 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19372 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19373 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19374 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19375 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19376 (eval-after-load "calendar"
19377 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19378 'org-calendar-goto-agenda))
19379 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19380 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19381 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19382 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19383 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19384 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19385 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19386 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19387 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19388 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19389 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19390 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19391 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19392 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19393 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19394 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19395 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19396 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19397 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19398 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19399 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19400 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19402 (org-defkey org-agenda-mode-map "[" 'org-agenda-manipulate-query-add)
19403 (org-defkey org-agenda-mode-map "]" 'org-agenda-manipulate-query-subtract)
19404 (org-defkey org-agenda-mode-map "{" 'org-agenda-manipulate-query-add-re)
19405 (org-defkey org-agenda-mode-map "}" 'org-agenda-manipulate-query-subtract-re)
19407 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19408 "Local keymap for agenda entries from Org-mode.")
19410 (org-defkey org-agenda-keymap
19411 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19412 (org-defkey org-agenda-keymap
19413 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19414 (when org-agenda-mouse-1-follows-link
19415 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19416 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19417 '("Agenda"
19418 ("Agenda Files")
19419 "--"
19420 ["Show" org-agenda-show t]
19421 ["Go To (other window)" org-agenda-goto t]
19422 ["Go To (this window)" org-agenda-switch-to t]
19423 ["Follow Mode" org-agenda-follow-mode
19424 :style toggle :selected org-agenda-follow-mode :active t]
19425 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19426 "--"
19427 ["Cycle TODO" org-agenda-todo t]
19428 ["Archive subtree" org-agenda-archive t]
19429 ["Delete subtree" org-agenda-kill t]
19430 "--"
19431 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19432 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19433 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19434 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19435 "--"
19436 ("Tags and Properties"
19437 ["Show all Tags" org-agenda-show-tags t]
19438 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19439 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19440 "--"
19441 ["Column View" org-columns t])
19442 ("Date/Schedule"
19443 ["Schedule" org-agenda-schedule t]
19444 ["Set Deadline" org-agenda-deadline t]
19445 "--"
19446 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19447 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19448 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19449 ("Clock"
19450 ["Clock in" org-agenda-clock-in t]
19451 ["Clock out" org-agenda-clock-out t]
19452 ["Clock cancel" org-agenda-clock-cancel t]
19453 ["Goto running clock" org-clock-goto t])
19454 ("Priority"
19455 ["Set Priority" org-agenda-priority t]
19456 ["Increase Priority" org-agenda-priority-up t]
19457 ["Decrease Priority" org-agenda-priority-down t]
19458 ["Show Priority" org-agenda-show-priority t])
19459 ("Calendar/Diary"
19460 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19461 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19462 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19463 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19464 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19465 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19466 "--"
19467 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19468 "--"
19469 ("View"
19470 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19471 :style radio :selected (equal org-agenda-ndays 1)]
19472 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19473 :style radio :selected (equal org-agenda-ndays 7)]
19474 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19475 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19476 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19477 :style radio :selected (member org-agenda-ndays '(365 366))]
19478 "--"
19479 ["Show Logbook entries" org-agenda-log-mode
19480 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19481 ["Include Diary" org-agenda-toggle-diary
19482 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19483 ["Use Time Grid" org-agenda-toggle-time-grid
19484 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19485 ["Write view to file" org-write-agenda t]
19486 ["Rebuild buffer" org-agenda-redo t]
19487 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19488 "--"
19489 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19490 "--"
19491 ["Quit" org-agenda-quit t]
19492 ["Exit and Release Buffers" org-agenda-exit t]
19495 ;;; Agenda undo
19497 (defvar org-agenda-allow-remote-undo t
19498 "Non-nil means, allow remote undo from the agenda buffer.")
19499 (defvar org-agenda-undo-list nil
19500 "List of undoable operations in the agenda since last refresh.")
19501 (defvar org-agenda-undo-has-started-in nil
19502 "Buffers that have already seen `undo-start' in the current undo sequence.")
19503 (defvar org-agenda-pending-undo-list nil
19504 "In a series of undo commands, this is the list of remaning undo items.")
19506 (defmacro org-if-unprotected (&rest body)
19507 "Execute BODY if there is no `org-protected' text property at point."
19508 (declare (debug t))
19509 `(unless (get-text-property (point) 'org-protected)
19510 ,@body))
19512 (defmacro org-with-remote-undo (_buffer &rest _body)
19513 "Execute BODY while recording undo information in two buffers."
19514 (declare (indent 1) (debug t))
19515 `(let ((_cline (org-current-line))
19516 (_cmd this-command)
19517 (_buf1 (current-buffer))
19518 (_buf2 ,_buffer)
19519 (_undo1 buffer-undo-list)
19520 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19521 _c1 _c2)
19522 ,@_body
19523 (when org-agenda-allow-remote-undo
19524 (setq _c1 (org-verify-change-for-undo
19525 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19526 _c2 (org-verify-change-for-undo
19527 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19528 (when (or _c1 _c2)
19529 ;; make sure there are undo boundaries
19530 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19531 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19532 ;; remember which buffer to undo
19533 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19534 org-agenda-undo-list)))))
19536 (defun org-agenda-undo ()
19537 "Undo a remote editing step in the agenda.
19538 This undoes changes both in the agenda buffer and in the remote buffer
19539 that have been changed along."
19540 (interactive)
19541 (or org-agenda-allow-remote-undo
19542 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19543 (if (not (eq this-command last-command))
19544 (setq org-agenda-undo-has-started-in nil
19545 org-agenda-pending-undo-list org-agenda-undo-list))
19546 (if (not org-agenda-pending-undo-list)
19547 (error "No further undo information"))
19548 (let* ((entry (pop org-agenda-pending-undo-list))
19549 buf line cmd rembuf)
19550 (setq cmd (pop entry) line (pop entry))
19551 (setq rembuf (nth 2 entry))
19552 (org-with-remote-undo rembuf
19553 (while (bufferp (setq buf (pop entry)))
19554 (if (pop entry)
19555 (with-current-buffer buf
19556 (let ((last-undo-buffer buf)
19557 (inhibit-read-only t))
19558 (unless (memq buf org-agenda-undo-has-started-in)
19559 (push buf org-agenda-undo-has-started-in)
19560 (make-local-variable 'pending-undo-list)
19561 (undo-start))
19562 (while (and pending-undo-list
19563 (listp pending-undo-list)
19564 (not (car pending-undo-list)))
19565 (pop pending-undo-list))
19566 (undo-more 1))))))
19567 (goto-line line)
19568 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19570 (defun org-verify-change-for-undo (l1 l2)
19571 "Verify that a real change occurred between the undo lists L1 and L2."
19572 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19573 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19574 (not (eq l1 l2)))
19576 ;;; Agenda dispatch
19578 (defvar org-agenda-restrict nil)
19579 (defvar org-agenda-restrict-begin (make-marker))
19580 (defvar org-agenda-restrict-end (make-marker))
19581 (defvar org-agenda-last-dispatch-buffer nil)
19582 (defvar org-agenda-overriding-restriction nil)
19584 ;;;###autoload
19585 (defun org-agenda (arg &optional keys restriction)
19586 "Dispatch agenda commands to collect entries to the agenda buffer.
19587 Prompts for a command to execute. Any prefix arg will be passed
19588 on to the selected command. The default selections are:
19590 a Call `org-agenda-list' to display the agenda for current day or week.
19591 t Call `org-todo-list' to display the global todo list.
19592 T Call `org-todo-list' to display the global todo list, select only
19593 entries with a specific TODO keyword (the user gets a prompt).
19594 m Call `org-tags-view' to display headlines with tags matching
19595 a condition (the user is prompted for the condition).
19596 M Like `m', but select only TODO entries, no ordinary headlines.
19597 L Create a timeline for the current buffer.
19598 e Export views to associated files.
19600 More commands can be added by configuring the variable
19601 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19602 searches can be pre-defined in this way.
19604 If the current buffer is in Org-mode and visiting a file, you can also
19605 first press `<' once to indicate that the agenda should be temporarily
19606 \(until the next use of \\[org-agenda]) restricted to the current file.
19607 Pressing `<' twice means to restrict to the current subtree or region
19608 \(if active)."
19609 (interactive "P")
19610 (catch 'exit
19611 (let* ((prefix-descriptions nil)
19612 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19613 (org-agenda-custom-commands
19614 ;; normalize different versions
19615 (delq nil
19616 (mapcar
19617 (lambda (x)
19618 (cond ((stringp (cdr x))
19619 (push x prefix-descriptions)
19620 nil)
19621 ((stringp (nth 1 x)) x)
19622 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19623 (t (cons (car x) (cons "" (cdr x))))))
19624 org-agenda-custom-commands)))
19625 (buf (current-buffer))
19626 (bfn (buffer-file-name (buffer-base-buffer)))
19627 entry key type match lprops ans)
19628 ;; Turn off restriction unless there is an overriding one
19629 (unless org-agenda-overriding-restriction
19630 (put 'org-agenda-files 'org-restrict nil)
19631 (setq org-agenda-restrict nil)
19632 (move-marker org-agenda-restrict-begin nil)
19633 (move-marker org-agenda-restrict-end nil))
19634 ;; Delete old local properties
19635 (put 'org-agenda-redo-command 'org-lprops nil)
19636 ;; Remember where this call originated
19637 (setq org-agenda-last-dispatch-buffer (current-buffer))
19638 (unless keys
19639 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19640 keys (car ans)
19641 restriction (cdr ans)))
19642 ;; Estabish the restriction, if any
19643 (when (and (not org-agenda-overriding-restriction) restriction)
19644 (put 'org-agenda-files 'org-restrict (list bfn))
19645 (cond
19646 ((eq restriction 'region)
19647 (setq org-agenda-restrict t)
19648 (move-marker org-agenda-restrict-begin (region-beginning))
19649 (move-marker org-agenda-restrict-end (region-end)))
19650 ((eq restriction 'subtree)
19651 (save-excursion
19652 (setq org-agenda-restrict t)
19653 (org-back-to-heading t)
19654 (move-marker org-agenda-restrict-begin (point))
19655 (move-marker org-agenda-restrict-end
19656 (progn (org-end-of-subtree t)))))))
19658 (require 'calendar) ; FIXME: can we avoid this for some commands?
19659 ;; For example the todo list should not need it (but does...)
19660 (cond
19661 ((setq entry (assoc keys org-agenda-custom-commands))
19662 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19663 (progn
19664 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19665 (put 'org-agenda-redo-command 'org-lprops lprops)
19666 (cond
19667 ((eq type 'agenda)
19668 (org-let lprops '(org-agenda-list current-prefix-arg)))
19669 ((eq type 'alltodo)
19670 (org-let lprops '(org-todo-list current-prefix-arg)))
19671 ((eq type 'search)
19672 (org-let lprops '(org-search-view current-prefix-arg match nil)))
19673 ((eq type 'stuck)
19674 (org-let lprops '(org-agenda-list-stuck-projects
19675 current-prefix-arg)))
19676 ((eq type 'tags)
19677 (org-let lprops '(org-tags-view current-prefix-arg match)))
19678 ((eq type 'tags-todo)
19679 (org-let lprops '(org-tags-view '(4) match)))
19680 ((eq type 'todo)
19681 (org-let lprops '(org-todo-list match)))
19682 ((eq type 'tags-tree)
19683 (org-check-for-org-mode)
19684 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19685 ((eq type 'todo-tree)
19686 (org-check-for-org-mode)
19687 (org-let lprops
19688 '(org-occur (concat "^" outline-regexp "[ \t]*"
19689 (regexp-quote match) "\\>"))))
19690 ((eq type 'occur-tree)
19691 (org-check-for-org-mode)
19692 (org-let lprops '(org-occur match)))
19693 ((functionp type)
19694 (org-let lprops '(funcall type match)))
19695 ((fboundp type)
19696 (org-let lprops '(funcall type match)))
19697 (t (error "Invalid custom agenda command type %s" type))))
19698 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19699 ((equal keys "C")
19700 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19701 (customize-variable 'org-agenda-custom-commands))
19702 ((equal keys "a") (call-interactively 'org-agenda-list))
19703 ((equal keys "s") (call-interactively 'org-search-view))
19704 ((equal keys "t") (call-interactively 'org-todo-list))
19705 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19706 ((equal keys "m") (call-interactively 'org-tags-view))
19707 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19708 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19709 ((equal keys "L")
19710 (unless (org-mode-p)
19711 (error "This is not an Org-mode file"))
19712 (unless restriction
19713 (put 'org-agenda-files 'org-restrict (list bfn))
19714 (org-call-with-arg 'org-timeline arg)))
19715 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19716 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19717 ((equal keys "!") (customize-variable 'org-stuck-projects))
19718 (t (error "Invalid agenda key"))))))
19720 (defun org-agenda-normalize-custom-commands (cmds)
19721 (delq nil
19722 (mapcar
19723 (lambda (x)
19724 (cond ((stringp (cdr x)) nil)
19725 ((stringp (nth 1 x)) x)
19726 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19727 (t (cons (car x) (cons "" (cdr x))))))
19728 cmds)))
19730 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19731 "The user interface for selecting an agenda command."
19732 (catch 'exit
19733 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19734 (restrict-ok (and bfn (org-mode-p)))
19735 (region-p (org-region-active-p))
19736 (custom org-agenda-custom-commands)
19737 (selstring "")
19738 restriction second-time
19739 c entry key type match prefixes rmheader header-end custom1 desc)
19740 (save-window-excursion
19741 (delete-other-windows)
19742 (org-switch-to-buffer-other-window " *Agenda Commands*")
19743 (erase-buffer)
19744 (insert (eval-when-compile
19745 (let ((header
19747 Press key for an agenda command: < Buffer,subtree/region restriction
19748 -------------------------------- > Remove restriction
19749 a Agenda for current week or day e Export agenda views
19750 t List of all TODO entries T Entries with special TODO kwd
19751 m Match a TAGS query M Like m, but only TODO entries
19752 L Timeline for current buffer # List stuck projects (!=configure)
19753 s Search for keywords C Configure custom agenda commands
19754 / Multi-occur
19756 (start 0))
19757 (while (string-match
19758 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19759 header start)
19760 (setq start (match-end 0))
19761 (add-text-properties (match-beginning 2) (match-end 2)
19762 '(face bold) header))
19763 header)))
19764 (setq header-end (move-marker (make-marker) (point)))
19765 (while t
19766 (setq custom1 custom)
19767 (when (eq rmheader t)
19768 (goto-line 1)
19769 (re-search-forward ":" nil t)
19770 (delete-region (match-end 0) (point-at-eol))
19771 (forward-char 1)
19772 (looking-at "-+")
19773 (delete-region (match-end 0) (point-at-eol))
19774 (move-marker header-end (match-end 0)))
19775 (goto-char header-end)
19776 (delete-region (point) (point-max))
19777 (while (setq entry (pop custom1))
19778 (setq key (car entry) desc (nth 1 entry)
19779 type (nth 2 entry) match (nth 3 entry))
19780 (if (> (length key) 1)
19781 (add-to-list 'prefixes (string-to-char key))
19782 (insert
19783 (format
19784 "\n%-4s%-14s: %s"
19785 (org-add-props (copy-sequence key)
19786 '(face bold))
19787 (cond
19788 ((string-match "\\S-" desc) desc)
19789 ((eq type 'agenda) "Agenda for current week or day")
19790 ((eq type 'alltodo) "List of all TODO entries")
19791 ((eq type 'search) "Word search")
19792 ((eq type 'stuck) "List of stuck projects")
19793 ((eq type 'todo) "TODO keyword")
19794 ((eq type 'tags) "Tags query")
19795 ((eq type 'tags-todo) "Tags (TODO)")
19796 ((eq type 'tags-tree) "Tags tree")
19797 ((eq type 'todo-tree) "TODO kwd tree")
19798 ((eq type 'occur-tree) "Occur tree")
19799 ((functionp type) (if (symbolp type)
19800 (symbol-name type)
19801 "Lambda expression"))
19802 (t "???"))
19803 (cond
19804 ((stringp match)
19805 (org-add-props match nil 'face 'org-warning))
19806 (match
19807 (format "set of %d commands" (length match)))
19808 (t ""))))))
19809 (when prefixes
19810 (mapc (lambda (x)
19811 (insert
19812 (format "\n%s %s"
19813 (org-add-props (char-to-string x)
19814 nil 'face 'bold)
19815 (or (cdr (assoc (concat selstring (char-to-string x))
19816 prefix-descriptions))
19817 "Prefix key"))))
19818 prefixes))
19819 (goto-char (point-min))
19820 (when (fboundp 'fit-window-to-buffer)
19821 (if second-time
19822 (if (not (pos-visible-in-window-p (point-max)))
19823 (fit-window-to-buffer))
19824 (setq second-time t)
19825 (fit-window-to-buffer)))
19826 (message "Press key for agenda command%s:"
19827 (if (or restrict-ok org-agenda-overriding-restriction)
19828 (if org-agenda-overriding-restriction
19829 " (restriction lock active)"
19830 (if restriction
19831 (format " (restricted to %s)" restriction)
19832 " (unrestricted)"))
19833 ""))
19834 (setq c (read-char-exclusive))
19835 (message "")
19836 (cond
19837 ((assoc (char-to-string c) custom)
19838 (setq selstring (concat selstring (char-to-string c)))
19839 (throw 'exit (cons selstring restriction)))
19840 ((memq c prefixes)
19841 (setq selstring (concat selstring (char-to-string c))
19842 prefixes nil
19843 rmheader (or rmheader t)
19844 custom (delq nil (mapcar
19845 (lambda (x)
19846 (if (or (= (length (car x)) 1)
19847 (/= (string-to-char (car x)) c))
19849 (cons (substring (car x) 1) (cdr x))))
19850 custom))))
19851 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19852 (message "Restriction is only possible in Org-mode buffers")
19853 (ding) (sit-for 1))
19854 ((eq c ?1)
19855 (org-agenda-remove-restriction-lock 'noupdate)
19856 (setq restriction 'buffer))
19857 ((eq c ?0)
19858 (org-agenda-remove-restriction-lock 'noupdate)
19859 (setq restriction (if region-p 'region 'subtree)))
19860 ((eq c ?<)
19861 (org-agenda-remove-restriction-lock 'noupdate)
19862 (setq restriction
19863 (cond
19864 ((eq restriction 'buffer)
19865 (if region-p 'region 'subtree))
19866 ((memq restriction '(subtree region))
19867 nil)
19868 (t 'buffer))))
19869 ((eq c ?>)
19870 (org-agenda-remove-restriction-lock 'noupdate)
19871 (setq restriction nil))
19872 ((and (equal selstring "") (memq c '(?s ?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19873 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19874 ((and (> (length selstring) 0) (eq c ?\d))
19875 (delete-window)
19876 (org-agenda-get-restriction-and-command prefix-descriptions))
19878 ((equal c ?q) (error "Abort"))
19879 (t (error "Invalid key %c" c))))))))
19881 (defun org-run-agenda-series (name series)
19882 (org-prepare-agenda name)
19883 (let* ((org-agenda-multi t)
19884 (redo (list 'org-run-agenda-series name (list 'quote series)))
19885 (cmds (car series))
19886 (gprops (nth 1 series))
19887 match ;; The byte compiler incorrectly complains about this. Keep it!
19888 cmd type lprops)
19889 (while (setq cmd (pop cmds))
19890 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19891 (cond
19892 ((eq type 'agenda)
19893 (org-let2 gprops lprops
19894 '(call-interactively 'org-agenda-list)))
19895 ((eq type 'alltodo)
19896 (org-let2 gprops lprops
19897 '(call-interactively 'org-todo-list)))
19898 ((eq type 'search)
19899 (org-let2 gprops lprops
19900 '(org-search-view current-prefix-arg match nil)))
19901 ((eq type 'stuck)
19902 (org-let2 gprops lprops
19903 '(call-interactively 'org-agenda-list-stuck-projects)))
19904 ((eq type 'tags)
19905 (org-let2 gprops lprops
19906 '(org-tags-view current-prefix-arg match)))
19907 ((eq type 'tags-todo)
19908 (org-let2 gprops lprops
19909 '(org-tags-view '(4) match)))
19910 ((eq type 'todo)
19911 (org-let2 gprops lprops
19912 '(org-todo-list match)))
19913 ((fboundp type)
19914 (org-let2 gprops lprops
19915 '(funcall type match)))
19916 (t (error "Invalid type in command series"))))
19917 (widen)
19918 (setq org-agenda-redo-command redo)
19919 (goto-char (point-min)))
19920 (org-finalize-agenda))
19922 ;;;###autoload
19923 (defmacro org-batch-agenda (cmd-key &rest parameters)
19924 "Run an agenda command in batch mode and send the result to STDOUT.
19925 If CMD-KEY is a string of length 1, it is used as a key in
19926 `org-agenda-custom-commands' and triggers this command. If it is a
19927 longer string it is used as a tags/todo match string.
19928 Paramters are alternating variable names and values that will be bound
19929 before running the agenda command."
19930 (let (pars)
19931 (while parameters
19932 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19933 (if (> (length cmd-key) 2)
19934 (eval (list 'let (nreverse pars)
19935 (list 'org-tags-view nil cmd-key)))
19936 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19937 (set-buffer org-agenda-buffer-name)
19938 (princ (org-encode-for-stdout (buffer-string)))))
19940 (defun org-encode-for-stdout (string)
19941 (if (fboundp 'encode-coding-string)
19942 (encode-coding-string string buffer-file-coding-system)
19943 string))
19945 (defvar org-agenda-info nil)
19947 ;;;###autoload
19948 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
19949 "Run an agenda command in batch mode and send the result to STDOUT.
19950 If CMD-KEY is a string of length 1, it is used as a key in
19951 `org-agenda-custom-commands' and triggers this command. If it is a
19952 longer string it is used as a tags/todo match string.
19953 Paramters are alternating variable names and values that will be bound
19954 before running the agenda command.
19956 The output gives a line for each selected agenda item. Each
19957 item is a list of comma-separated values, like this:
19959 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
19961 category The category of the item
19962 head The headline, without TODO kwd, TAGS and PRIORITY
19963 type The type of the agenda entry, can be
19964 todo selected in TODO match
19965 tagsmatch selected in tags match
19966 diary imported from diary
19967 deadline a deadline on given date
19968 scheduled scheduled on given date
19969 timestamp entry has timestamp on given date
19970 closed entry was closed on given date
19971 upcoming-deadline warning about deadline
19972 past-scheduled forwarded scheduled item
19973 block entry has date block including g. date
19974 todo The todo keyword, if any
19975 tags All tags including inherited ones, separated by colons
19976 date The relevant date, like 2007-2-14
19977 time The time, like 15:00-16:50
19978 extra Sting with extra planning info
19979 priority-l The priority letter if any was given
19980 priority-n The computed numerical priority
19981 agenda-day The day in the agenda where this is listed"
19983 (let (pars)
19984 (while parameters
19985 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19986 (push (list 'org-agenda-remove-tags t) pars)
19987 (if (> (length cmd-key) 2)
19988 (eval (list 'let (nreverse pars)
19989 (list 'org-tags-view nil cmd-key)))
19990 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19991 (set-buffer org-agenda-buffer-name)
19992 (let* ((lines (org-split-string (buffer-string) "\n"))
19993 line)
19994 (while (setq line (pop lines))
19995 (catch 'next
19996 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
19997 (setq org-agenda-info
19998 (org-fix-agenda-info (text-properties-at 0 line)))
19999 (princ
20000 (org-encode-for-stdout
20001 (mapconcat 'org-agenda-export-csv-mapper
20002 '(org-category txt type todo tags date time-of-day extra
20003 priority-letter priority agenda-day)
20004 ",")))
20005 (princ "\n"))))))
20007 (defun org-fix-agenda-info (props)
20008 "Make sure all properties on an agenda item have a canonical form,
20009 so the export commands can easily use it."
20010 (let (tmp re)
20011 (when (setq tmp (plist-get props 'tags))
20012 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
20013 (when (setq tmp (plist-get props 'date))
20014 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20015 (let ((calendar-date-display-form '(year "-" month "-" day)))
20016 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
20018 (setq tmp (calendar-date-string tmp)))
20019 (setq props (plist-put props 'date tmp)))
20020 (when (setq tmp (plist-get props 'day))
20021 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20022 (let ((calendar-date-display-form '(year "-" month "-" day)))
20023 (setq tmp (calendar-date-string tmp)))
20024 (setq props (plist-put props 'day tmp))
20025 (setq props (plist-put props 'agenda-day tmp)))
20026 (when (setq tmp (plist-get props 'txt))
20027 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
20028 (plist-put props 'priority-letter (match-string 1 tmp))
20029 (setq tmp (replace-match "" t t tmp)))
20030 (when (and (setq re (plist-get props 'org-todo-regexp))
20031 (setq re (concat "\\`\\.*" re " ?"))
20032 (string-match re tmp))
20033 (plist-put props 'todo (match-string 1 tmp))
20034 (setq tmp (replace-match "" t t tmp)))
20035 (plist-put props 'txt tmp)))
20036 props)
20038 (defun org-agenda-export-csv-mapper (prop)
20039 (let ((res (plist-get org-agenda-info prop)))
20040 (setq res
20041 (cond
20042 ((not res) "")
20043 ((stringp res) res)
20044 (t (prin1-to-string res))))
20045 (while (string-match "," res)
20046 (setq res (replace-match ";" t t res)))
20047 (org-trim res)))
20050 ;;;###autoload
20051 (defun org-store-agenda-views (&rest parameters)
20052 (interactive)
20053 (eval (list 'org-batch-store-agenda-views)))
20055 ;; FIXME, why is this a macro?????
20056 ;;;###autoload
20057 (defmacro org-batch-store-agenda-views (&rest parameters)
20058 "Run all custom agenda commands that have a file argument."
20059 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
20060 (pop-up-frames nil)
20061 (dir default-directory)
20062 pars cmd thiscmdkey files opts)
20063 (while parameters
20064 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20065 (setq pars (reverse pars))
20066 (save-window-excursion
20067 (while cmds
20068 (setq cmd (pop cmds)
20069 thiscmdkey (car cmd)
20070 opts (nth 4 cmd)
20071 files (nth 5 cmd))
20072 (if (stringp files) (setq files (list files)))
20073 (when files
20074 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20075 (list 'org-agenda nil thiscmdkey)))
20076 (set-buffer org-agenda-buffer-name)
20077 (while files
20078 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20079 (list 'org-write-agenda
20080 (expand-file-name (pop files) dir) t))))
20081 (and (get-buffer org-agenda-buffer-name)
20082 (kill-buffer org-agenda-buffer-name)))))))
20084 (defun org-write-agenda (file &optional nosettings)
20085 "Write the current buffer (an agenda view) as a file.
20086 Depending on the extension of the file name, plain text (.txt),
20087 HTML (.html or .htm) or Postscript (.ps) is produced.
20088 If the extension is .ics, run icalendar export over all files used
20089 to construct the agenda and limit the export to entries listed in the
20090 agenda now.
20091 If NOSETTINGS is given, do not scope the settings of
20092 `org-agenda-exporter-settings' into the export commands. This is used when
20093 the settings have already been scoped and we do not wish to overrule other,
20094 higher priority settings."
20095 (interactive "FWrite agenda to file: ")
20096 (if (not (file-writable-p file))
20097 (error "Cannot write agenda to file %s" file))
20098 (cond
20099 ((string-match "\\.html?\\'" file) (require 'htmlize))
20100 ((string-match "\\.ps\\'" file) (require 'ps-print)))
20101 (org-let (if nosettings nil org-agenda-exporter-settings)
20102 '(save-excursion
20103 (save-window-excursion
20104 (cond
20105 ((string-match "\\.html?\\'" file)
20106 (set-buffer (htmlize-buffer (current-buffer)))
20108 (when (and org-agenda-export-html-style
20109 (string-match "<style>" org-agenda-export-html-style))
20110 ;; replace <style> section with org-agenda-export-html-style
20111 (goto-char (point-min))
20112 (kill-region (- (search-forward "<style") 6)
20113 (search-forward "</style>"))
20114 (insert org-agenda-export-html-style))
20115 (write-file file)
20116 (kill-buffer (current-buffer))
20117 (message "HTML written to %s" file))
20118 ((string-match "\\.ps\\'" file)
20119 (ps-print-buffer-with-faces file)
20120 (message "Postscript written to %s" file))
20121 ((string-match "\\.ics\\'" file)
20122 (let ((org-agenda-marker-table
20123 (org-create-marker-find-array
20124 (org-agenda-collect-markers)))
20125 (org-icalendar-verify-function 'org-check-agenda-marker-table)
20126 (org-combined-agenda-icalendar-file file))
20127 (apply 'org-export-icalendar 'combine (org-agenda-files))))
20129 (let ((bs (buffer-string)))
20130 (find-file file)
20131 (insert bs)
20132 (save-buffer 0)
20133 (kill-buffer (current-buffer))
20134 (message "Plain text written to %s" file))))))
20135 (set-buffer org-agenda-buffer-name)))
20137 (defun org-agenda-collect-markers ()
20138 "Collect the markers pointing to entries in the agenda buffer."
20139 (let (m markers)
20140 (save-excursion
20141 (goto-char (point-min))
20142 (while (not (eobp))
20143 (when (setq m (or (get-text-property (point) 'org-hd-marker)
20144 (get-text-property (point) 'org-marker)))
20145 (push m markers))
20146 (beginning-of-line 2)))
20147 (nreverse markers)))
20149 (defun org-create-marker-find-array (marker-list)
20150 "Create a alist of files names with all marker positions in that file."
20151 (let (f tbl m a p)
20152 (while (setq m (pop marker-list))
20153 (setq p (marker-position m)
20154 f (buffer-file-name (or (buffer-base-buffer
20155 (marker-buffer m))
20156 (marker-buffer m))))
20157 (if (setq a (assoc f tbl))
20158 (push (marker-position m) (cdr a))
20159 (push (list f p) tbl)))
20160 (mapcar (lambda (x) (setcdr x (sort (copy-sequence (cdr x)) '<)) x)
20161 tbl)))
20163 (defvar org-agenda-marker-table nil) ; dyamically scoped parameter
20164 (defun org-check-agenda-marker-table ()
20165 "Check of the current entry is on the marker list."
20166 (let ((file (buffer-file-name (or (buffer-base-buffer) (current-buffer))))
20168 (and (setq a (assoc file org-agenda-marker-table))
20169 (save-match-data
20170 (save-excursion
20171 (org-back-to-heading t)
20172 (member (point) (cdr a)))))))
20174 (defmacro org-no-read-only (&rest body)
20175 "Inhibit read-only for BODY."
20176 `(let ((inhibit-read-only t)) ,@body))
20178 (defun org-check-for-org-mode ()
20179 "Make sure current buffer is in org-mode. Error if not."
20180 (or (org-mode-p)
20181 (error "Cannot execute org-mode agenda command on buffer in %s."
20182 major-mode)))
20184 (defun org-fit-agenda-window ()
20185 "Fit the window to the buffer size."
20186 (and (memq org-agenda-window-setup '(reorganize-frame))
20187 (fboundp 'fit-window-to-buffer)
20188 (fit-window-to-buffer
20190 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20191 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20193 ;;; Agenda file list
20195 (defun org-agenda-files (&optional unrestricted)
20196 "Get the list of agenda files.
20197 Optional UNRESTRICTED means return the full list even if a restriction
20198 is currently in place."
20199 (let ((files
20200 (cond
20201 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20202 ((stringp org-agenda-files) (org-read-agenda-file-list))
20203 ((listp org-agenda-files) org-agenda-files)
20204 (t (error "Invalid value of `org-agenda-files'")))))
20205 (setq files (apply 'append
20206 (mapcar (lambda (f)
20207 (if (file-directory-p f)
20208 (directory-files f t
20209 org-agenda-file-regexp)
20210 (list f)))
20211 files)))
20212 (if org-agenda-skip-unavailable-files
20213 (delq nil
20214 (mapcar (function
20215 (lambda (file)
20216 (and (file-readable-p file) file)))
20217 files))
20218 files))) ; `org-check-agenda-file' will remove them from the list
20220 (defun org-edit-agenda-file-list ()
20221 "Edit the list of agenda files.
20222 Depending on setup, this either uses customize to edit the variable
20223 `org-agenda-files', or it visits the file that is holding the list. In the
20224 latter case, the buffer is set up in a way that saving it automatically kills
20225 the buffer and restores the previous window configuration."
20226 (interactive)
20227 (if (stringp org-agenda-files)
20228 (let ((cw (current-window-configuration)))
20229 (find-file org-agenda-files)
20230 (org-set-local 'org-window-configuration cw)
20231 (org-add-hook 'after-save-hook
20232 (lambda ()
20233 (set-window-configuration
20234 (prog1 org-window-configuration
20235 (kill-buffer (current-buffer))))
20236 (org-install-agenda-files-menu)
20237 (message "New agenda file list installed"))
20238 nil 'local)
20239 (message "%s" (substitute-command-keys
20240 "Edit list and finish with \\[save-buffer]")))
20241 (customize-variable 'org-agenda-files)))
20243 (defun org-store-new-agenda-file-list (list)
20244 "Set new value for the agenda file list and save it correcly."
20245 (if (stringp org-agenda-files)
20246 (let ((f org-agenda-files) b)
20247 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20248 (with-temp-file f
20249 (insert (mapconcat 'identity list "\n") "\n")))
20250 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20251 (setq org-agenda-files list)
20252 (customize-save-variable 'org-agenda-files org-agenda-files))))
20254 (defun org-read-agenda-file-list ()
20255 "Read the list of agenda files from a file."
20256 (when (stringp org-agenda-files)
20257 (with-temp-buffer
20258 (insert-file-contents org-agenda-files)
20259 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20262 ;;;###autoload
20263 (defun org-cycle-agenda-files ()
20264 "Cycle through the files in `org-agenda-files'.
20265 If the current buffer visits an agenda file, find the next one in the list.
20266 If the current buffer does not, find the first agenda file."
20267 (interactive)
20268 (let* ((fs (org-agenda-files t))
20269 (files (append fs (list (car fs))))
20270 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20271 file)
20272 (unless files (error "No agenda files"))
20273 (catch 'exit
20274 (while (setq file (pop files))
20275 (if (equal (file-truename file) tcf)
20276 (when (car files)
20277 (find-file (car files))
20278 (throw 'exit t))))
20279 (find-file (car fs)))
20280 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20282 (defun org-agenda-file-to-front (&optional to-end)
20283 "Move/add the current file to the top of the agenda file list.
20284 If the file is not present in the list, it is added to the front. If it is
20285 present, it is moved there. With optional argument TO-END, add/move to the
20286 end of the list."
20287 (interactive "P")
20288 (let ((org-agenda-skip-unavailable-files nil)
20289 (file-alist (mapcar (lambda (x)
20290 (cons (file-truename x) x))
20291 (org-agenda-files t)))
20292 (ctf (file-truename buffer-file-name))
20293 x had)
20294 (setq x (assoc ctf file-alist) had x)
20296 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20297 (if to-end
20298 (setq file-alist (append (delq x file-alist) (list x)))
20299 (setq file-alist (cons x (delq x file-alist))))
20300 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20301 (org-install-agenda-files-menu)
20302 (message "File %s to %s of agenda file list"
20303 (if had "moved" "added") (if to-end "end" "front"))))
20305 (defun org-remove-file (&optional file)
20306 "Remove current file from the list of files in variable `org-agenda-files'.
20307 These are the files which are being checked for agenda entries.
20308 Optional argument FILE means, use this file instead of the current."
20309 (interactive)
20310 (let* ((org-agenda-skip-unavailable-files nil)
20311 (file (or file buffer-file-name))
20312 (true-file (file-truename file))
20313 (afile (abbreviate-file-name file))
20314 (files (delq nil (mapcar
20315 (lambda (x)
20316 (if (equal true-file
20317 (file-truename x))
20318 nil x))
20319 (org-agenda-files t)))))
20320 (if (not (= (length files) (length (org-agenda-files t))))
20321 (progn
20322 (org-store-new-agenda-file-list files)
20323 (org-install-agenda-files-menu)
20324 (message "Removed file: %s" afile))
20325 (message "File was not in list: %s (not removed)" afile))))
20327 (defun org-file-menu-entry (file)
20328 (vector file (list 'find-file file) t))
20330 (defun org-check-agenda-file (file)
20331 "Make sure FILE exists. If not, ask user what to do."
20332 (when (not (file-exists-p file))
20333 (message "non-existent file %s. [R]emove from list or [A]bort?"
20334 (abbreviate-file-name file))
20335 (let ((r (downcase (read-char-exclusive))))
20336 (cond
20337 ((equal r ?r)
20338 (org-remove-file file)
20339 (throw 'nextfile t))
20340 (t (error "Abort"))))))
20342 ;;; Agenda prepare and finalize
20344 (defvar org-agenda-multi nil) ; dynammically scoped
20345 (defvar org-agenda-buffer-name "*Org Agenda*")
20346 (defvar org-pre-agenda-window-conf nil)
20347 (defvar org-agenda-name nil)
20348 (defun org-prepare-agenda (&optional name)
20349 (setq org-todo-keywords-for-agenda nil)
20350 (setq org-done-keywords-for-agenda nil)
20351 (if org-agenda-multi
20352 (progn
20353 (setq buffer-read-only nil)
20354 (goto-char (point-max))
20355 (unless (or (bobp) org-agenda-compact-blocks)
20356 (insert "\n" (make-string (window-width) ?=) "\n"))
20357 (narrow-to-region (point) (point-max)))
20358 (org-agenda-reset-markers)
20359 (org-prepare-agenda-buffers (org-agenda-files))
20360 (setq org-todo-keywords-for-agenda
20361 (org-uniquify org-todo-keywords-for-agenda))
20362 (setq org-done-keywords-for-agenda
20363 (org-uniquify org-done-keywords-for-agenda))
20364 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20365 (awin (get-buffer-window abuf)))
20366 (cond
20367 ((equal (current-buffer) abuf) nil)
20368 (awin (select-window awin))
20369 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20370 ((equal org-agenda-window-setup 'current-window)
20371 (switch-to-buffer abuf))
20372 ((equal org-agenda-window-setup 'other-window)
20373 (org-switch-to-buffer-other-window abuf))
20374 ((equal org-agenda-window-setup 'other-frame)
20375 (switch-to-buffer-other-frame abuf))
20376 ((equal org-agenda-window-setup 'reorganize-frame)
20377 (delete-other-windows)
20378 (org-switch-to-buffer-other-window abuf))))
20379 (setq buffer-read-only nil)
20380 (erase-buffer)
20381 (org-agenda-mode)
20382 (and name (not org-agenda-name)
20383 (org-set-local 'org-agenda-name name)))
20384 (setq buffer-read-only nil))
20386 (defun org-finalize-agenda ()
20387 "Finishing touch for the agenda buffer, called just before displaying it."
20388 (unless org-agenda-multi
20389 (save-excursion
20390 (let ((inhibit-read-only t))
20391 (goto-char (point-min))
20392 (while (org-activate-bracket-links (point-max))
20393 (add-text-properties (match-beginning 0) (match-end 0)
20394 '(face org-link)))
20395 (org-agenda-align-tags)
20396 (unless org-agenda-with-colors
20397 (remove-text-properties (point-min) (point-max) '(face nil))))
20398 (if (and (boundp 'org-overriding-columns-format)
20399 org-overriding-columns-format)
20400 (org-set-local 'org-overriding-columns-format
20401 org-overriding-columns-format))
20402 (if (and (boundp 'org-agenda-view-columns-initially)
20403 org-agenda-view-columns-initially)
20404 (org-agenda-columns))
20405 (when org-agenda-fontify-priorities
20406 (org-fontify-priorities))
20407 (run-hooks 'org-finalize-agenda-hook)
20408 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20411 (defun org-fontify-priorities ()
20412 "Make highest priority lines bold, and lowest italic."
20413 (interactive)
20414 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20415 (org-delete-overlay o)))
20416 (org-overlays-in (point-min) (point-max)))
20417 (save-excursion
20418 (let ((inhibit-read-only t)
20419 b e p ov h l)
20420 (goto-char (point-min))
20421 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20422 (setq h (or (get-char-property (point) 'org-highest-priority)
20423 org-highest-priority)
20424 l (or (get-char-property (point) 'org-lowest-priority)
20425 org-lowest-priority)
20426 p (string-to-char (match-string 1))
20427 b (match-beginning 0) e (point-at-eol)
20428 ov (org-make-overlay b e))
20429 (org-overlay-put
20430 ov 'face
20431 (cond ((listp org-agenda-fontify-priorities)
20432 (cdr (assoc p org-agenda-fontify-priorities)))
20433 ((equal p l) 'italic)
20434 ((equal p h) 'bold)))
20435 (org-overlay-put ov 'org-type 'org-priority)))))
20437 (defun org-prepare-agenda-buffers (files)
20438 "Create buffers for all agenda files, protect archived trees and comments."
20439 (interactive)
20440 (let ((pa '(:org-archived t))
20441 (pc '(:org-comment t))
20442 (pall '(:org-archived t :org-comment t))
20443 (inhibit-read-only t)
20444 (rea (concat ":" org-archive-tag ":"))
20445 bmp file re)
20446 (save-excursion
20447 (save-restriction
20448 (while (setq file (pop files))
20449 (if (bufferp file)
20450 (set-buffer file)
20451 (org-check-agenda-file file)
20452 (set-buffer (org-get-agenda-file-buffer file)))
20453 (widen)
20454 (setq bmp (buffer-modified-p))
20455 (org-refresh-category-properties)
20456 (setq org-todo-keywords-for-agenda
20457 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20458 (setq org-done-keywords-for-agenda
20459 (append org-done-keywords-for-agenda org-done-keywords))
20460 (save-excursion
20461 (remove-text-properties (point-min) (point-max) pall)
20462 (when org-agenda-skip-archived-trees
20463 (goto-char (point-min))
20464 (while (re-search-forward rea nil t)
20465 (if (org-on-heading-p t)
20466 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20467 (goto-char (point-min))
20468 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20469 (while (re-search-forward re nil t)
20470 (add-text-properties
20471 (match-beginning 0) (org-end-of-subtree t) pc)))
20472 (set-buffer-modified-p bmp))))))
20474 (defvar org-agenda-skip-function nil
20475 "Function to be called at each match during agenda construction.
20476 If this function returns nil, the current match should not be skipped.
20477 Otherwise, the function must return a position from where the search
20478 should be continued.
20479 This may also be a Lisp form, it will be evaluated.
20480 Never set this variable using `setq' or so, because then it will apply
20481 to all future agenda commands. Instead, bind it with `let' to scope
20482 it dynamically into the agenda-constructing command. A good way to set
20483 it is through options in org-agenda-custom-commands.")
20485 (defun org-agenda-skip ()
20486 "Throw to `:skip' in places that should be skipped.
20487 Also moves point to the end of the skipped region, so that search can
20488 continue from there."
20489 (let ((p (point-at-bol)) to fp)
20490 (and org-agenda-skip-archived-trees
20491 (get-text-property p :org-archived)
20492 (org-end-of-subtree t)
20493 (throw :skip t))
20494 (and (get-text-property p :org-comment)
20495 (org-end-of-subtree t)
20496 (throw :skip t))
20497 (if (equal (char-after p) ?#) (throw :skip t))
20498 (when (and (or (setq fp (functionp org-agenda-skip-function))
20499 (consp org-agenda-skip-function))
20500 (setq to (save-excursion
20501 (save-match-data
20502 (if fp
20503 (funcall org-agenda-skip-function)
20504 (eval org-agenda-skip-function))))))
20505 (goto-char to)
20506 (throw :skip t))))
20508 (defvar org-agenda-markers nil
20509 "List of all currently active markers created by `org-agenda'.")
20510 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20511 "Creation time of the last agenda marker.")
20513 (defun org-agenda-new-marker (&optional pos)
20514 "Return a new agenda marker.
20515 Org-mode keeps a list of these markers and resets them when they are
20516 no longer in use."
20517 (let ((m (copy-marker (or pos (point)))))
20518 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20519 (push m org-agenda-markers)
20522 (defun org-agenda-reset-markers ()
20523 "Reset markers created by `org-agenda'."
20524 (while org-agenda-markers
20525 (move-marker (pop org-agenda-markers) nil)))
20527 (defun org-get-agenda-file-buffer (file)
20528 "Get a buffer visiting FILE. If the buffer needs to be created, add
20529 it to the list of buffers which might be released later."
20530 (let ((buf (org-find-base-buffer-visiting file)))
20531 (if buf
20532 buf ; just return it
20533 ;; Make a new buffer and remember it
20534 (setq buf (find-file-noselect file))
20535 (if buf (push buf org-agenda-new-buffers))
20536 buf)))
20538 (defun org-release-buffers (blist)
20539 "Release all buffers in list, asking the user for confirmation when needed.
20540 When a buffer is unmodified, it is just killed. When modified, it is saved
20541 \(if the user agrees) and then killed."
20542 (let (buf file)
20543 (while (setq buf (pop blist))
20544 (setq file (buffer-file-name buf))
20545 (when (and (buffer-modified-p buf)
20546 file
20547 (y-or-n-p (format "Save file %s? " file)))
20548 (with-current-buffer buf (save-buffer)))
20549 (kill-buffer buf))))
20551 (defun org-get-category (&optional pos)
20552 "Get the category applying to position POS."
20553 (get-text-property (or pos (point)) 'org-category))
20555 ;;; Agenda timeline
20557 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20559 (defun org-timeline (&optional include-all)
20560 "Show a time-sorted view of the entries in the current org file.
20561 Only entries with a time stamp of today or later will be listed. With
20562 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20563 under the current date.
20564 If the buffer contains an active region, only check the region for
20565 dates."
20566 (interactive "P")
20567 (require 'calendar)
20568 (org-compile-prefix-format 'timeline)
20569 (org-set-sorting-strategy 'timeline)
20570 (let* ((dopast t)
20571 (dotodo include-all)
20572 (doclosed org-agenda-show-log)
20573 (entry buffer-file-name)
20574 (date (calendar-current-date))
20575 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20576 (end (if (org-region-active-p) (region-end) (point-max)))
20577 (day-numbers (org-get-all-dates beg end 'no-ranges
20578 t doclosed ; always include today
20579 org-timeline-show-empty-dates))
20580 (org-deadline-warning-days 0)
20581 (org-agenda-only-exact-dates t)
20582 (today (time-to-days (current-time)))
20583 (past t)
20584 args
20585 s e rtn d emptyp)
20586 (setq org-agenda-redo-command
20587 (list 'progn
20588 (list 'org-switch-to-buffer-other-window (current-buffer))
20589 (list 'org-timeline (list 'quote include-all))))
20590 (if (not dopast)
20591 ;; Remove past dates from the list of dates.
20592 (setq day-numbers (delq nil (mapcar (lambda(x)
20593 (if (>= x today) x nil))
20594 day-numbers))))
20595 (org-prepare-agenda (concat "Timeline "
20596 (file-name-nondirectory buffer-file-name)))
20597 (if doclosed (push :closed args))
20598 (push :timestamp args)
20599 (push :deadline args)
20600 (push :scheduled args)
20601 (push :sexp args)
20602 (if dotodo (push :todo args))
20603 (while (setq d (pop day-numbers))
20604 (if (and (listp d) (eq (car d) :omitted))
20605 (progn
20606 (setq s (point))
20607 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20608 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20609 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20610 (if (and (>= d today)
20611 dopast
20612 past)
20613 (progn
20614 (setq past nil)
20615 (insert (make-string 79 ?-) "\n")))
20616 (setq date (calendar-gregorian-from-absolute d))
20617 (setq s (point))
20618 (setq rtn (and (not emptyp)
20619 (apply 'org-agenda-get-day-entries entry
20620 date args)))
20621 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20622 (progn
20623 (insert
20624 (if (stringp org-agenda-format-date)
20625 (format-time-string org-agenda-format-date
20626 (org-time-from-absolute date))
20627 (funcall org-agenda-format-date date))
20628 "\n")
20629 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20630 (put-text-property s (1- (point)) 'org-date-line t)
20631 (if (equal d today)
20632 (put-text-property s (1- (point)) 'org-today t))
20633 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20634 (put-text-property s (1- (point)) 'day d)))))
20635 (goto-char (point-min))
20636 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20637 (point-min)))
20638 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20639 (org-finalize-agenda)
20640 (setq buffer-read-only t)))
20642 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20643 "Return a list of all relevant day numbers from BEG to END buffer positions.
20644 If NO-RANGES is non-nil, include only the start and end dates of a range,
20645 not every single day in the range. If FORCE-TODAY is non-nil, make
20646 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20647 inactive time stamps (those in square brackets) are included.
20648 When EMPTY is non-nil, also include days without any entries."
20649 (let ((re (concat
20650 (if pre-re pre-re "")
20651 (if inactive org-ts-regexp-both org-ts-regexp)))
20652 dates dates1 date day day1 day2 ts1 ts2)
20653 (if force-today
20654 (setq dates (list (time-to-days (current-time)))))
20655 (save-excursion
20656 (goto-char beg)
20657 (while (re-search-forward re end t)
20658 (setq day (time-to-days (org-time-string-to-time
20659 (substring (match-string 1) 0 10))))
20660 (or (memq day dates) (push day dates)))
20661 (unless no-ranges
20662 (goto-char beg)
20663 (while (re-search-forward org-tr-regexp end t)
20664 (setq ts1 (substring (match-string 1) 0 10)
20665 ts2 (substring (match-string 2) 0 10)
20666 day1 (time-to-days (org-time-string-to-time ts1))
20667 day2 (time-to-days (org-time-string-to-time ts2)))
20668 (while (< (setq day1 (1+ day1)) day2)
20669 (or (memq day1 dates) (push day1 dates)))))
20670 (setq dates (sort dates '<))
20671 (when empty
20672 (while (setq day (pop dates))
20673 (setq day2 (car dates))
20674 (push day dates1)
20675 (when (and day2 empty)
20676 (if (or (eq empty t)
20677 (and (numberp empty) (<= (- day2 day) empty)))
20678 (while (< (setq day (1+ day)) day2)
20679 (push (list day) dates1))
20680 (push (cons :omitted (- day2 day)) dates1))))
20681 (setq dates (nreverse dates1)))
20682 dates)))
20684 ;;; Agenda Daily/Weekly
20686 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20687 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20688 (defvar org-agenda-last-arguments nil
20689 "The arguments of the previous call to org-agenda")
20690 (defvar org-starting-day nil) ; local variable in the agenda buffer
20691 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20692 (defvar org-include-all-loc nil) ; local variable
20693 (defvar org-agenda-remove-date nil) ; dynamically scoped FIXME: not used???
20695 ;;;###autoload
20696 (defun org-agenda-list (&optional include-all start-day ndays)
20697 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20698 The view will be for the current day or week, but from the overview buffer
20699 you will be able to go to other days/weeks.
20701 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20702 all unfinished TODO items will also be shown, before the agenda.
20703 This feature is considered obsolete, please use the TODO list or a block
20704 agenda instead.
20706 With a numeric prefix argument in an interactive call, the agenda will
20707 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20708 the number of days. NDAYS defaults to `org-agenda-ndays'.
20710 START-DAY defaults to TODAY, or to the most recent match for the weekday
20711 given in `org-agenda-start-on-weekday'."
20712 (interactive "P")
20713 (if (and (integerp include-all) (> include-all 0))
20714 (setq ndays include-all include-all nil))
20715 (setq ndays (or ndays org-agenda-ndays)
20716 start-day (or start-day org-agenda-start-day))
20717 (if org-agenda-overriding-arguments
20718 (setq include-all (car org-agenda-overriding-arguments)
20719 start-day (nth 1 org-agenda-overriding-arguments)
20720 ndays (nth 2 org-agenda-overriding-arguments)))
20721 (if (stringp start-day)
20722 ;; Convert to an absolute day number
20723 (setq start-day (time-to-days (org-read-date nil t start-day))))
20724 (setq org-agenda-last-arguments (list include-all start-day ndays))
20725 (org-compile-prefix-format 'agenda)
20726 (org-set-sorting-strategy 'agenda)
20727 (require 'calendar)
20728 (let* ((org-agenda-start-on-weekday
20729 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20730 org-agenda-start-on-weekday nil))
20731 (thefiles (org-agenda-files))
20732 (files thefiles)
20733 (today (time-to-days
20734 (time-subtract (current-time)
20735 (list 0 (* 3600 org-extend-today-until) 0))))
20736 (sd (or start-day today))
20737 (start (if (or (null org-agenda-start-on-weekday)
20738 (< org-agenda-ndays 7))
20740 (let* ((nt (calendar-day-of-week
20741 (calendar-gregorian-from-absolute sd)))
20742 (n1 org-agenda-start-on-weekday)
20743 (d (- nt n1)))
20744 (- sd (+ (if (< d 0) 7 0) d)))))
20745 (day-numbers (list start))
20746 (day-cnt 0)
20747 (inhibit-redisplay (not debug-on-error))
20748 s e rtn rtnall file date d start-pos end-pos todayp nd)
20749 (setq org-agenda-redo-command
20750 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20751 ;; Make the list of days
20752 (setq ndays (or ndays org-agenda-ndays)
20753 nd ndays)
20754 (while (> ndays 1)
20755 (push (1+ (car day-numbers)) day-numbers)
20756 (setq ndays (1- ndays)))
20757 (setq day-numbers (nreverse day-numbers))
20758 (org-prepare-agenda "Day/Week")
20759 (org-set-local 'org-starting-day (car day-numbers))
20760 (org-set-local 'org-include-all-loc include-all)
20761 (org-set-local 'org-agenda-span
20762 (org-agenda-ndays-to-span nd))
20763 (when (and (or include-all org-agenda-include-all-todo)
20764 (member today day-numbers))
20765 (setq files thefiles
20766 rtnall nil)
20767 (while (setq file (pop files))
20768 (catch 'nextfile
20769 (org-check-agenda-file file)
20770 (setq date (calendar-gregorian-from-absolute today)
20771 rtn (org-agenda-get-day-entries
20772 file date :todo))
20773 (setq rtnall (append rtnall rtn))))
20774 (when rtnall
20775 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20776 (add-text-properties (point-min) (1- (point))
20777 (list 'face 'org-agenda-structure))
20778 (insert (org-finalize-agenda-entries rtnall) "\n")))
20779 (unless org-agenda-compact-blocks
20780 (let* ((d1 (car day-numbers))
20781 (d2 (org-last day-numbers))
20782 (w1 (org-days-to-iso-week d1))
20783 (w2 (org-days-to-iso-week d2)))
20784 (setq s (point))
20785 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20786 "-agenda"
20787 (if (< (- d2 d1) 350)
20788 (if (= w1 w2)
20789 (format " (W%02d)" w1)
20790 (format " (W%02d-W%02d)" w1 w2))
20792 ":\n"))
20793 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20794 'org-date-line t)))
20795 (while (setq d (pop day-numbers))
20796 (setq date (calendar-gregorian-from-absolute d)
20797 s (point))
20798 (if (or (setq todayp (= d today))
20799 (and (not start-pos) (= d sd)))
20800 (setq start-pos (point))
20801 (if (and start-pos (not end-pos))
20802 (setq end-pos (point))))
20803 (setq files thefiles
20804 rtnall nil)
20805 (while (setq file (pop files))
20806 (catch 'nextfile
20807 (org-check-agenda-file file)
20808 (if org-agenda-show-log
20809 (setq rtn (org-agenda-get-day-entries
20810 file date
20811 :deadline :scheduled :timestamp :sexp :closed))
20812 (setq rtn (org-agenda-get-day-entries
20813 file date
20814 :deadline :scheduled :sexp :timestamp)))
20815 (setq rtnall (append rtnall rtn))))
20816 (if org-agenda-include-diary
20817 (progn
20818 (require 'diary-lib)
20819 (setq rtn (org-get-entries-from-diary date))
20820 (setq rtnall (append rtnall rtn))))
20821 (if (or rtnall org-agenda-show-all-dates)
20822 (progn
20823 (setq day-cnt (1+ day-cnt))
20824 (insert
20825 (if (stringp org-agenda-format-date)
20826 (format-time-string org-agenda-format-date
20827 (org-time-from-absolute date))
20828 (funcall org-agenda-format-date date))
20829 "\n")
20830 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20831 (put-text-property s (1- (point)) 'org-date-line t)
20832 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20833 (if todayp (put-text-property s (1- (point)) 'org-today t))
20834 (if rtnall (insert
20835 (org-finalize-agenda-entries
20836 (org-agenda-add-time-grid-maybe
20837 rtnall nd todayp))
20838 "\n"))
20839 (put-text-property s (1- (point)) 'day d)
20840 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20841 (goto-char (point-min))
20842 (org-fit-agenda-window)
20843 (unless (and (pos-visible-in-window-p (point-min))
20844 (pos-visible-in-window-p (point-max)))
20845 (goto-char (1- (point-max)))
20846 (recenter -1)
20847 (if (not (pos-visible-in-window-p (or start-pos 1)))
20848 (progn
20849 (goto-char (or start-pos 1))
20850 (recenter 1))))
20851 (goto-char (or start-pos 1))
20852 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20853 (org-finalize-agenda)
20854 (setq buffer-read-only t)
20855 (message "")))
20857 (defun org-agenda-ndays-to-span (n)
20858 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20860 ;;; Agenda word search
20862 (defvar org-agenda-search-history nil)
20863 (defvar org-todo-only nil)
20865 (defvar org-search-syntax-table nil
20866 "Special syntax table for org-mode search.
20867 In this table, we have single quotes not as word constituents, to
20868 that when \"+Ameli\" is searchd as a work, it will also match \"Ameli's\"")
20870 (defun org-search-syntax-table ()
20871 (unless org-search-syntax-table
20872 (setq org-search-syntax-table (copy-syntax-table org-mode-syntax-table))
20873 (modify-syntax-entry ?' "." org-search-syntax-table)
20874 (modify-syntax-entry ?` "." org-search-syntax-table))
20875 org-search-syntax-table)
20877 ;;;###autoload
20878 (defun org-search-view (&optional todo-only string edit-at)
20879 "Show all entries that contain words or regular expressions.
20880 If the first character of the search string is an asterisks,
20881 search only the headlines.
20883 With optional prefix argument TODO-ONLY, only consider entries that are
20884 TODO entries. The argument STRING can be used to pass a default search
20885 string into this function. If EDIT-AT is non-nil, it means that the
20886 user should get a chance to edit this string, with cursor at position
20887 EDIT-AT.
20889 The search string is broken into \"words\" by splitting at whitespace.
20890 The individual words are then interpreted as a boolean expression with
20891 logical AND. Words prefixed with a minus must not occur in the entry.
20892 Words without a prefix or prefixed with a plus must occur in the entry.
20893 Matching is case-insensitive and the words are enclosed by word delimiters.
20895 Words enclosed by curly braces are interpreted as regular expressions
20896 that must or must not match in the entry.
20898 If the search string starts with an asterisk, search only in headlines.
20899 If (possibly after the leading star) the search string starts with an
20900 exclamation mark, this also means to look at TODO entries only, an effect
20901 that can also be achieved with a prefix argument.
20903 This command searches the agenda files, and in addition the files listed
20904 in `org-agenda-text-search-extra-files'."
20905 (interactive "P")
20906 (org-compile-prefix-format 'search)
20907 (org-set-sorting-strategy 'search)
20908 (org-prepare-agenda "SEARCH")
20909 (let* ((props (list 'face nil
20910 'done-face 'org-done
20911 'org-not-done-regexp org-not-done-regexp
20912 'org-todo-regexp org-todo-regexp
20913 'mouse-face 'highlight
20914 'keymap org-agenda-keymap
20915 'help-echo (format "mouse-2 or RET jump to location")))
20916 regexp rtn rtnall files file pos
20917 marker priority category tags c neg re
20918 ee txt beg end words regexps+ regexps- hdl-only buffer beg1 str)
20919 (unless (and (not edit-at)
20920 (stringp string)
20921 (string-match "\\S-" string))
20922 (setq string (read-string "[+-]Word/{Regexp} ...: "
20923 (cond
20924 ((integerp edit-at) (cons string edit-at))
20925 (edit-at string))
20926 'org-agenda-search-history)))
20927 (org-set-local 'org-todo-only todo-only)
20928 (setq org-agenda-redo-command
20929 (list 'org-search-view (if todo-only t nil) string
20930 '(if current-prefix-arg 1 nil)))
20931 (setq org-agenda-query-string string)
20933 (if (equal (string-to-char string) ?*)
20934 (setq hdl-only t
20935 words (substring string 1))
20936 (setq words string))
20937 (when (equal (string-to-char words) ?!)
20938 (setq todo-only t
20939 words (substring words 1)))
20940 (setq words (org-split-string words))
20941 (mapc (lambda (w)
20942 (setq c (string-to-char w))
20943 (if (equal c ?-)
20944 (setq neg t w (substring w 1))
20945 (if (equal c ?+)
20946 (setq neg nil w (substring w 1))
20947 (setq neg nil)))
20948 (if (string-match "\\`{.*}\\'" w)
20949 (setq re (substring w 1 -1))
20950 (setq re (concat "\\<" (regexp-quote (downcase w)) "\\>")))
20951 (if neg (push re regexps-) (push re regexps+)))
20952 words)
20953 (setq regexps+ (sort regexps+ (lambda (a b) (> (length a) (length b)))))
20954 (if (not regexps+)
20955 (setq regexp (concat "^" org-outline-regexp))
20956 (setq regexp (pop regexps+))
20957 (if hdl-only (setq regexp (concat "^" org-outline-regexp ".*?"
20958 regexp))))
20959 (setq files (append (org-agenda-files) org-agenda-text-search-extra-files)
20960 rtnall nil)
20961 (while (setq file (pop files))
20962 (setq ee nil)
20963 (catch 'nextfile
20964 (org-check-agenda-file file)
20965 (setq buffer (if (file-exists-p file)
20966 (org-get-agenda-file-buffer file)
20967 (error "No such file %s" file)))
20968 (if (not buffer)
20969 ;; If file does not exist, make sure an error message is sent
20970 (setq rtn (list (format "ORG-AGENDA-ERROR: No such org-file %s"
20971 file))))
20972 (with-current-buffer buffer
20973 (with-syntax-table (org-search-syntax-table)
20974 (unless (org-mode-p)
20975 (error "Agenda file %s is not in `org-mode'" file))
20976 (let ((case-fold-search t))
20977 (save-excursion
20978 (save-restriction
20979 (if org-agenda-restrict
20980 (narrow-to-region org-agenda-restrict-begin
20981 org-agenda-restrict-end)
20982 (widen))
20983 (goto-char (point-min))
20984 (unless (or (org-on-heading-p)
20985 (outline-next-heading))
20986 (throw 'nextfile t))
20987 (goto-char (max (point-min) (1- (point))))
20988 (while (re-search-forward regexp nil t)
20989 (org-back-to-heading t)
20990 (skip-chars-forward "* ")
20991 (setq beg (point-at-bol)
20992 beg1 (point)
20993 end (progn (outline-next-heading) (point)))
20994 (catch :skip
20995 (goto-char beg)
20996 (org-agenda-skip)
20997 (setq str (buffer-substring-no-properties
20998 (point-at-bol)
20999 (if hdl-only (point-at-eol) end)))
21000 (mapc (lambda (wr) (when (string-match wr str)
21001 (goto-char (1- end))
21002 (throw :skip t)))
21003 regexps-)
21004 (mapc (lambda (wr) (unless (string-match wr str)
21005 (goto-char (1- end))
21006 (throw :skip t)))
21007 (if todo-only
21008 (cons (concat "^\*+[ \t]+" org-not-done-regexp)
21009 regexps+)
21010 regexps+))
21011 (goto-char beg)
21012 (setq marker (org-agenda-new-marker (point))
21013 category (org-get-category)
21014 tags (org-get-tags-at (point))
21015 txt (org-format-agenda-item
21017 (buffer-substring-no-properties
21018 beg1 (point-at-eol))
21019 category tags))
21020 (org-add-props txt props
21021 'org-marker marker 'org-hd-marker marker
21022 'org-todo-regexp org-todo-regexp
21023 'priority 1000 'org-category category
21024 'type "search")
21025 (push txt ee)
21026 (goto-char (1- end))))))))))
21027 (setq rtn (nreverse ee))
21028 (setq rtnall (append rtnall rtn)))
21029 (if org-agenda-overriding-header
21030 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21031 nil 'face 'org-agenda-structure) "\n")
21032 (insert "Search words: ")
21033 (add-text-properties (point-min) (1- (point))
21034 (list 'face 'org-agenda-structure))
21035 (setq pos (point))
21036 (insert string "\n")
21037 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21038 (setq pos (point))
21039 (unless org-agenda-multi
21040 (insert "Press `[', `]' to add/sub word, `{', `}' to add/sub regexp, `C-u r' to edit\n")
21041 (add-text-properties pos (1- (point))
21042 (list 'face 'org-agenda-structure))))
21043 (when rtnall
21044 (insert (org-finalize-agenda-entries rtnall) "\n"))
21045 (goto-char (point-min))
21046 (org-fit-agenda-window)
21047 (add-text-properties (point-min) (point-max) '(org-agenda-type search))
21048 (org-finalize-agenda)
21049 (setq buffer-read-only t)))
21051 ;;; Agenda TODO list
21053 (defvar org-select-this-todo-keyword nil)
21054 (defvar org-last-arg nil)
21056 ;;;###autoload
21057 (defun org-todo-list (arg)
21058 "Show all TODO entries from all agenda file in a single list.
21059 The prefix arg can be used to select a specific TODO keyword and limit
21060 the list to these. When using \\[universal-argument], you will be prompted
21061 for a keyword. A numeric prefix directly selects the Nth keyword in
21062 `org-todo-keywords-1'."
21063 (interactive "P")
21064 (require 'calendar)
21065 (org-compile-prefix-format 'todo)
21066 (org-set-sorting-strategy 'todo)
21067 (org-prepare-agenda "TODO")
21068 (let* ((today (time-to-days (current-time)))
21069 (date (calendar-gregorian-from-absolute today))
21070 (kwds org-todo-keywords-for-agenda)
21071 (completion-ignore-case t)
21072 (org-select-this-todo-keyword
21073 (if (stringp arg) arg
21074 (and arg (integerp arg) (> arg 0)
21075 (nth (1- arg) kwds))))
21076 rtn rtnall files file pos)
21077 (when (equal arg '(4))
21078 (setq org-select-this-todo-keyword
21079 (completing-read "Keyword (or KWD1|K2D2|...): "
21080 (mapcar 'list kwds) nil nil)))
21081 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
21082 (org-set-local 'org-last-arg arg)
21083 (setq org-agenda-redo-command
21084 '(org-todo-list (or current-prefix-arg org-last-arg)))
21085 (setq files (org-agenda-files)
21086 rtnall nil)
21087 (while (setq file (pop files))
21088 (catch 'nextfile
21089 (org-check-agenda-file file)
21090 (setq rtn (org-agenda-get-day-entries file date :todo))
21091 (setq rtnall (append rtnall rtn))))
21092 (if org-agenda-overriding-header
21093 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21094 nil 'face 'org-agenda-structure) "\n")
21095 (insert "Global list of TODO items of type: ")
21096 (add-text-properties (point-min) (1- (point))
21097 (list 'face 'org-agenda-structure))
21098 (setq pos (point))
21099 (insert (or org-select-this-todo-keyword "ALL") "\n")
21100 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21101 (setq pos (point))
21102 (unless org-agenda-multi
21103 (insert "Available with `N r': (0)ALL")
21104 (let ((n 0) s)
21105 (mapc (lambda (x)
21106 (setq s (format "(%d)%s" (setq n (1+ n)) x))
21107 (if (> (+ (current-column) (string-width s) 1) (frame-width))
21108 (insert "\n "))
21109 (insert " " s))
21110 kwds))
21111 (insert "\n"))
21112 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21113 (when rtnall
21114 (insert (org-finalize-agenda-entries rtnall) "\n"))
21115 (goto-char (point-min))
21116 (org-fit-agenda-window)
21117 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
21118 (org-finalize-agenda)
21119 (setq buffer-read-only t)))
21121 ;;; Agenda tags match
21123 ;;;###autoload
21124 (defun org-tags-view (&optional todo-only match)
21125 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
21126 The prefix arg TODO-ONLY limits the search to TODO entries."
21127 (interactive "P")
21128 (org-compile-prefix-format 'tags)
21129 (org-set-sorting-strategy 'tags)
21130 (let* ((org-tags-match-list-sublevels
21131 (if todo-only t org-tags-match-list-sublevels))
21132 (completion-ignore-case t)
21133 rtn rtnall files file pos matcher
21134 buffer)
21135 (setq matcher (org-make-tags-matcher match)
21136 match (car matcher) matcher (cdr matcher))
21137 (org-prepare-agenda (concat "TAGS " match))
21138 (setq org-agenda-query-string match)
21139 (setq org-agenda-redo-command
21140 (list 'org-tags-view (list 'quote todo-only)
21141 (list 'if 'current-prefix-arg nil 'org-agenda-query-string)))
21142 (setq files (org-agenda-files)
21143 rtnall nil)
21144 (while (setq file (pop files))
21145 (catch 'nextfile
21146 (org-check-agenda-file file)
21147 (setq buffer (if (file-exists-p file)
21148 (org-get-agenda-file-buffer file)
21149 (error "No such file %s" file)))
21150 (if (not buffer)
21151 ;; If file does not exist, merror message to agenda
21152 (setq rtn (list
21153 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21154 rtnall (append rtnall rtn))
21155 (with-current-buffer buffer
21156 (unless (org-mode-p)
21157 (error "Agenda file %s is not in `org-mode'" file))
21158 (save-excursion
21159 (save-restriction
21160 (if org-agenda-restrict
21161 (narrow-to-region org-agenda-restrict-begin
21162 org-agenda-restrict-end)
21163 (widen))
21164 (setq rtn (org-scan-tags 'agenda matcher todo-only))
21165 (setq rtnall (append rtnall rtn))))))))
21166 (if org-agenda-overriding-header
21167 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21168 nil 'face 'org-agenda-structure) "\n")
21169 (insert "Headlines with TAGS match: ")
21170 (add-text-properties (point-min) (1- (point))
21171 (list 'face 'org-agenda-structure))
21172 (setq pos (point))
21173 (insert match "\n")
21174 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21175 (setq pos (point))
21176 (unless org-agenda-multi
21177 (insert "Press `C-u r' to search again with new search string\n"))
21178 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21179 (when rtnall
21180 (insert (org-finalize-agenda-entries rtnall) "\n"))
21181 (goto-char (point-min))
21182 (org-fit-agenda-window)
21183 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
21184 (org-finalize-agenda)
21185 (setq buffer-read-only t)))
21187 ;;; Agenda Finding stuck projects
21189 (defvar org-agenda-skip-regexp nil
21190 "Regular expression used in skipping subtrees for the agenda.
21191 This is basically a temporary global variable that can be set and then
21192 used by user-defined selections using `org-agenda-skip-function'.")
21194 (defvar org-agenda-overriding-header nil
21195 "When this is set during todo and tags searches, will replace header.")
21197 (defun org-agenda-skip-subtree-when-regexp-matches ()
21198 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
21199 If yes, it returns the end position of this tree, causing agenda commands
21200 to skip this subtree. This is a function that can be put into
21201 `org-agenda-skip-function' for the duration of a command."
21202 (let ((end (save-excursion (org-end-of-subtree t)))
21203 skip)
21204 (save-excursion
21205 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
21206 (and skip end)))
21208 (defun org-agenda-skip-entry-if (&rest conditions)
21209 "Skip entry if any of CONDITIONS is true.
21210 See `org-agenda-skip-if' for details."
21211 (org-agenda-skip-if nil conditions))
21213 (defun org-agenda-skip-subtree-if (&rest conditions)
21214 "Skip entry if any of CONDITIONS is true.
21215 See `org-agenda-skip-if' for details."
21216 (org-agenda-skip-if t conditions))
21218 (defun org-agenda-skip-if (subtree conditions)
21219 "Checks current entity for CONDITIONS.
21220 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
21221 the entry, i.e. the text before the next heading is checked.
21223 CONDITIONS is a list of symbols, boolean OR is used to combine the results
21224 from different tests. Valid conditions are:
21226 scheduled Check if there is a scheduled cookie
21227 notscheduled Check if there is no scheduled cookie
21228 deadline Check if there is a deadline
21229 notdeadline Check if there is no deadline
21230 regexp Check if regexp matches
21231 notregexp Check if regexp does not match.
21233 The regexp is taken from the conditions list, it must come right after
21234 the `regexp' or `notregexp' element.
21236 If any of these conditions is met, this function returns the end point of
21237 the entity, causing the search to continue from there. This is a function
21238 that can be put into `org-agenda-skip-function' for the duration of a command."
21239 (let (beg end m)
21240 (org-back-to-heading t)
21241 (setq beg (point)
21242 end (if subtree
21243 (progn (org-end-of-subtree t) (point))
21244 (progn (outline-next-heading) (1- (point)))))
21245 (goto-char beg)
21246 (and
21248 (and (memq 'scheduled conditions)
21249 (re-search-forward org-scheduled-time-regexp end t))
21250 (and (memq 'notscheduled conditions)
21251 (not (re-search-forward org-scheduled-time-regexp end t)))
21252 (and (memq 'deadline conditions)
21253 (re-search-forward org-deadline-time-regexp end t))
21254 (and (memq 'notdeadline conditions)
21255 (not (re-search-forward org-deadline-time-regexp end t)))
21256 (and (setq m (memq 'regexp conditions))
21257 (stringp (nth 1 m))
21258 (re-search-forward (nth 1 m) end t))
21259 (and (setq m (memq 'notregexp conditions))
21260 (stringp (nth 1 m))
21261 (not (re-search-forward (nth 1 m) end t))))
21262 end)))
21264 ;;;###autoload
21265 (defun org-agenda-list-stuck-projects (&rest ignore)
21266 "Create agenda view for projects that are stuck.
21267 Stuck projects are project that have no next actions. For the definitions
21268 of what a project is and how to check if it stuck, customize the variable
21269 `org-stuck-projects'.
21270 MATCH is being ignored."
21271 (interactive)
21272 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
21273 ;; FIXME: we could have used org-agenda-skip-if here.
21274 (org-agenda-overriding-header "List of stuck projects: ")
21275 (matcher (nth 0 org-stuck-projects))
21276 (todo (nth 1 org-stuck-projects))
21277 (todo-wds (if (member "*" todo)
21278 (progn
21279 (org-prepare-agenda-buffers (org-agenda-files))
21280 (org-delete-all
21281 org-done-keywords-for-agenda
21282 (copy-sequence org-todo-keywords-for-agenda)))
21283 todo))
21284 (todo-re (concat "^\\*+[ \t]+\\("
21285 (mapconcat 'identity todo-wds "\\|")
21286 "\\)\\>"))
21287 (tags (nth 2 org-stuck-projects))
21288 (tags-re (if (member "*" tags)
21289 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
21290 (concat "^\\*+ .*:\\("
21291 (mapconcat 'identity tags "\\|")
21292 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
21293 (gen-re (nth 3 org-stuck-projects))
21294 (re-list
21295 (delq nil
21296 (list
21297 (if todo todo-re)
21298 (if tags tags-re)
21299 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
21300 gen-re)))))
21301 (setq org-agenda-skip-regexp
21302 (if re-list
21303 (mapconcat 'identity re-list "\\|")
21304 (error "No information how to identify unstuck projects")))
21305 (org-tags-view nil matcher)
21306 (with-current-buffer org-agenda-buffer-name
21307 (setq org-agenda-redo-command
21308 '(org-agenda-list-stuck-projects
21309 (or current-prefix-arg org-last-arg))))))
21311 ;;; Diary integration
21313 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
21314 (defvar list-diary-entries-hook)
21316 (defun org-get-entries-from-diary (date)
21317 "Get the (Emacs Calendar) diary entries for DATE."
21318 (require 'diary-lib)
21319 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
21320 (diary-display-hook '(fancy-diary-display))
21321 (pop-up-frames nil)
21322 (list-diary-entries-hook
21323 (cons 'org-diary-default-entry list-diary-entries-hook))
21324 (diary-file-name-prefix-function nil) ; turn this feature off
21325 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
21326 entries
21327 (org-disable-agenda-to-diary t))
21328 (save-excursion
21329 (save-window-excursion
21330 (funcall (if (fboundp 'diary-list-entries)
21331 'diary-list-entries 'list-diary-entries)
21332 date 1)))
21333 (if (not (get-buffer fancy-diary-buffer))
21334 (setq entries nil)
21335 (with-current-buffer fancy-diary-buffer
21336 (setq buffer-read-only nil)
21337 (if (zerop (buffer-size))
21338 ;; No entries
21339 (setq entries nil)
21340 ;; Omit the date and other unnecessary stuff
21341 (org-agenda-cleanup-fancy-diary)
21342 ;; Add prefix to each line and extend the text properties
21343 (if (zerop (buffer-size))
21344 (setq entries nil)
21345 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
21346 (set-buffer-modified-p nil)
21347 (kill-buffer fancy-diary-buffer)))
21348 (when entries
21349 (setq entries (org-split-string entries "\n"))
21350 (setq entries
21351 (mapcar
21352 (lambda (x)
21353 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
21354 ;; Extend the text properties to the beginning of the line
21355 (org-add-props x (text-properties-at (1- (length x)) x)
21356 'type "diary" 'date date))
21357 entries)))))
21359 (defun org-agenda-cleanup-fancy-diary ()
21360 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
21361 This gets rid of the date, the underline under the date, and
21362 the dummy entry installed by `org-mode' to ensure non-empty diary for each
21363 date. It also removes lines that contain only whitespace."
21364 (goto-char (point-min))
21365 (if (looking-at ".*?:[ \t]*")
21366 (progn
21367 (replace-match "")
21368 (re-search-forward "\n=+$" nil t)
21369 (replace-match "")
21370 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
21371 (re-search-forward "\n=+$" nil t)
21372 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
21373 (goto-char (point-min))
21374 (while (re-search-forward "^ +\n" nil t)
21375 (replace-match ""))
21376 (goto-char (point-min))
21377 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21378 (replace-match "")))
21380 ;; Make sure entries from the diary have the right text properties.
21381 (eval-after-load "diary-lib"
21382 '(if (boundp 'diary-modify-entry-list-string-function)
21383 ;; We can rely on the hook, nothing to do
21385 ;; Hook not avaiable, must use advice to make this work
21386 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21387 "Make the position visible."
21388 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21389 (stringp string)
21390 buffer-file-name)
21391 (setq string (org-modify-diary-entry-string string))))))
21393 (defun org-modify-diary-entry-string (string)
21394 "Add text properties to string, allowing org-mode to act on it."
21395 (org-add-props string nil
21396 'mouse-face 'highlight
21397 'keymap org-agenda-keymap
21398 'help-echo (if buffer-file-name
21399 (format "mouse-2 or RET jump to diary file %s"
21400 (abbreviate-file-name buffer-file-name))
21402 'org-agenda-diary-link t
21403 'org-marker (org-agenda-new-marker (point-at-bol))))
21405 (defun org-diary-default-entry ()
21406 "Add a dummy entry to the diary.
21407 Needed to avoid empty dates which mess up holiday display."
21408 ;; Catch the error if dealing with the new add-to-diary-alist
21409 (when org-disable-agenda-to-diary
21410 (condition-case nil
21411 (add-to-diary-list original-date "Org-mode dummy" "")
21412 (error
21413 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21415 ;;;###autoload
21416 (defun org-diary (&rest args)
21417 "Return diary information from org-files.
21418 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21419 It accesses org files and extracts information from those files to be
21420 listed in the diary. The function accepts arguments specifying what
21421 items should be listed. The following arguments are allowed:
21423 :timestamp List the headlines of items containing a date stamp or
21424 date range matching the selected date. Deadlines will
21425 also be listed, on the expiration day.
21427 :sexp List entries resulting from diary-like sexps.
21429 :deadline List any deadlines past due, or due within
21430 `org-deadline-warning-days'. The listing occurs only
21431 in the diary for *today*, not at any other date. If
21432 an entry is marked DONE, it is no longer listed.
21434 :scheduled List all items which are scheduled for the given date.
21435 The diary for *today* also contains items which were
21436 scheduled earlier and are not yet marked DONE.
21438 :todo List all TODO items from the org-file. This may be a
21439 long list - so this is not turned on by default.
21440 Like deadlines, these entries only show up in the
21441 diary for *today*, not at any other date.
21443 The call in the diary file should look like this:
21445 &%%(org-diary) ~/path/to/some/orgfile.org
21447 Use a separate line for each org file to check. Or, if you omit the file name,
21448 all files listed in `org-agenda-files' will be checked automatically:
21450 &%%(org-diary)
21452 If you don't give any arguments (as in the example above), the default
21453 arguments (:deadline :scheduled :timestamp :sexp) are used.
21454 So the example above may also be written as
21456 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21458 The function expects the lisp variables `entry' and `date' to be provided
21459 by the caller, because this is how the calendar works. Don't use this
21460 function from a program - use `org-agenda-get-day-entries' instead."
21461 (when (> (- (time-to-seconds (current-time))
21462 org-agenda-last-marker-time)
21464 (org-agenda-reset-markers))
21465 (org-compile-prefix-format 'agenda)
21466 (org-set-sorting-strategy 'agenda)
21467 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21468 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21469 (list entry)
21470 (org-agenda-files t)))
21471 file rtn results)
21472 (org-prepare-agenda-buffers files)
21473 ;; If this is called during org-agenda, don't return any entries to
21474 ;; the calendar. Org Agenda will list these entries itself.
21475 (if org-disable-agenda-to-diary (setq files nil))
21476 (while (setq file (pop files))
21477 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21478 (setq results (append results rtn)))
21479 (if results
21480 (concat (org-finalize-agenda-entries results) "\n"))))
21482 ;;; Agenda entry finders
21484 (defun org-agenda-get-day-entries (file date &rest args)
21485 "Does the work for `org-diary' and `org-agenda'.
21486 FILE is the path to a file to be checked for entries. DATE is date like
21487 the one returned by `calendar-current-date'. ARGS are symbols indicating
21488 which kind of entries should be extracted. For details about these, see
21489 the documentation of `org-diary'."
21490 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21491 (let* ((org-startup-folded nil)
21492 (org-startup-align-all-tables nil)
21493 (buffer (if (file-exists-p file)
21494 (org-get-agenda-file-buffer file)
21495 (error "No such file %s" file)))
21496 arg results rtn)
21497 (if (not buffer)
21498 ;; If file does not exist, make sure an error message ends up in diary
21499 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21500 (with-current-buffer buffer
21501 (unless (org-mode-p)
21502 (error "Agenda file %s is not in `org-mode'" file))
21503 (let ((case-fold-search nil))
21504 (save-excursion
21505 (save-restriction
21506 (if org-agenda-restrict
21507 (narrow-to-region org-agenda-restrict-begin
21508 org-agenda-restrict-end)
21509 (widen))
21510 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21511 (while (setq arg (pop args))
21512 (cond
21513 ((and (eq arg :todo)
21514 (equal date (calendar-current-date)))
21515 (setq rtn (org-agenda-get-todos))
21516 (setq results (append results rtn)))
21517 ((eq arg :timestamp)
21518 (setq rtn (org-agenda-get-blocks))
21519 (setq results (append results rtn))
21520 (setq rtn (org-agenda-get-timestamps))
21521 (setq results (append results rtn)))
21522 ((eq arg :sexp)
21523 (setq rtn (org-agenda-get-sexps))
21524 (setq results (append results rtn)))
21525 ((eq arg :scheduled)
21526 (setq rtn (org-agenda-get-scheduled))
21527 (setq results (append results rtn)))
21528 ((eq arg :closed)
21529 (setq rtn (org-agenda-get-closed))
21530 (setq results (append results rtn)))
21531 ((eq arg :deadline)
21532 (setq rtn (org-agenda-get-deadlines))
21533 (setq results (append results rtn))))))))
21534 results))))
21536 (defun org-entry-is-todo-p ()
21537 (member (org-get-todo-state) org-not-done-keywords))
21539 (defun org-entry-is-done-p ()
21540 (member (org-get-todo-state) org-done-keywords))
21542 (defun org-get-todo-state ()
21543 (save-excursion
21544 (org-back-to-heading t)
21545 (and (looking-at org-todo-line-regexp)
21546 (match-end 2)
21547 (match-string 2))))
21549 (defun org-at-date-range-p (&optional inactive-ok)
21550 "Is the cursor inside a date range?"
21551 (interactive)
21552 (save-excursion
21553 (catch 'exit
21554 (let ((pos (point)))
21555 (skip-chars-backward "^[<\r\n")
21556 (skip-chars-backward "<[")
21557 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21558 (>= (match-end 0) pos)
21559 (throw 'exit t))
21560 (skip-chars-backward "^<[\r\n")
21561 (skip-chars-backward "<[")
21562 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21563 (>= (match-end 0) pos)
21564 (throw 'exit t)))
21565 nil)))
21567 (defun org-agenda-get-todos ()
21568 "Return the TODO information for agenda display."
21569 (let* ((props (list 'face nil
21570 'done-face 'org-done
21571 'org-not-done-regexp org-not-done-regexp
21572 'org-todo-regexp org-todo-regexp
21573 'mouse-face 'highlight
21574 'keymap org-agenda-keymap
21575 'help-echo
21576 (format "mouse-2 or RET jump to org file %s"
21577 (abbreviate-file-name buffer-file-name))))
21578 ;; FIXME: get rid of the \n at some point but watch out
21579 (regexp (concat "^\\*+[ \t]+\\("
21580 (if org-select-this-todo-keyword
21581 (if (equal org-select-this-todo-keyword "*")
21582 org-todo-regexp
21583 (concat "\\<\\("
21584 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21585 "\\)\\>"))
21586 org-not-done-regexp)
21587 "[^\n\r]*\\)"))
21588 marker priority category tags
21589 ee txt beg end)
21590 (goto-char (point-min))
21591 (while (re-search-forward regexp nil t)
21592 (catch :skip
21593 (save-match-data
21594 (beginning-of-line)
21595 (setq beg (point) end (progn (outline-next-heading) (point)))
21596 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21597 (re-search-forward org-ts-regexp end t))
21598 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21599 (re-search-forward org-scheduled-time-regexp end t))
21600 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21601 (re-search-forward org-deadline-time-regexp end t)
21602 (org-deadline-close (match-string 1))))
21603 (goto-char (1+ beg))
21604 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21605 (throw :skip nil)))
21606 (goto-char beg)
21607 (org-agenda-skip)
21608 (goto-char (match-beginning 1))
21609 (setq marker (org-agenda-new-marker (match-beginning 0))
21610 category (org-get-category)
21611 tags (org-get-tags-at (point))
21612 txt (org-format-agenda-item "" (match-string 1) category tags)
21613 priority (1+ (org-get-priority txt)))
21614 (org-add-props txt props
21615 'org-marker marker 'org-hd-marker marker
21616 'priority priority 'org-category category
21617 'type "todo")
21618 (push txt ee)
21619 (if org-agenda-todo-list-sublevels
21620 (goto-char (match-end 1))
21621 (org-end-of-subtree 'invisible))))
21622 (nreverse ee)))
21624 (defconst org-agenda-no-heading-message
21625 "No heading for this item in buffer or region.")
21627 (defun org-agenda-get-timestamps ()
21628 "Return the date stamp information for agenda display."
21629 (let* ((props (list 'face nil
21630 'org-not-done-regexp org-not-done-regexp
21631 'org-todo-regexp org-todo-regexp
21632 'mouse-face 'highlight
21633 'keymap org-agenda-keymap
21634 'help-echo
21635 (format "mouse-2 or RET jump to org file %s"
21636 (abbreviate-file-name buffer-file-name))))
21637 (d1 (calendar-absolute-from-gregorian date))
21638 (remove-re
21639 (concat
21640 (regexp-quote
21641 (format-time-string
21642 "<%Y-%m-%d"
21643 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21644 ".*?>"))
21645 (regexp
21646 (concat
21647 (regexp-quote
21648 (substring
21649 (format-time-string
21650 (car org-time-stamp-formats)
21651 (apply 'encode-time ; DATE bound by calendar
21652 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21653 0 11))
21654 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21655 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21656 marker hdmarker deadlinep scheduledp donep tmp priority category
21657 ee txt timestr tags b0 b3 e3 head)
21658 (goto-char (point-min))
21659 (while (re-search-forward regexp nil t)
21660 (setq b0 (match-beginning 0)
21661 b3 (match-beginning 3) e3 (match-end 3))
21662 (catch :skip
21663 (and (org-at-date-range-p) (throw :skip nil))
21664 (org-agenda-skip)
21665 (if (and (match-end 1)
21666 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21667 (throw :skip nil))
21668 (if (and e3
21669 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21670 (throw :skip nil))
21671 (setq marker (org-agenda-new-marker b0)
21672 category (org-get-category b0)
21673 tmp (buffer-substring (max (point-min)
21674 (- b0 org-ds-keyword-length))
21676 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21677 deadlinep (string-match org-deadline-regexp tmp)
21678 scheduledp (string-match org-scheduled-regexp tmp)
21679 donep (org-entry-is-done-p))
21680 (if (or scheduledp deadlinep) (throw :skip t))
21681 (if (string-match ">" timestr)
21682 ;; substring should only run to end of time stamp
21683 (setq timestr (substring timestr 0 (match-end 0))))
21684 (save-excursion
21685 (if (re-search-backward "^\\*+ " nil t)
21686 (progn
21687 (goto-char (match-beginning 0))
21688 (setq hdmarker (org-agenda-new-marker)
21689 tags (org-get-tags-at))
21690 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21691 (setq head (match-string 1))
21692 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21693 (setq txt (org-format-agenda-item
21694 nil head category tags timestr nil
21695 remove-re)))
21696 (setq txt org-agenda-no-heading-message))
21697 (setq priority (org-get-priority txt))
21698 (org-add-props txt props
21699 'org-marker marker 'org-hd-marker hdmarker)
21700 (org-add-props txt nil 'priority priority
21701 'org-category category 'date date
21702 'type "timestamp")
21703 (push txt ee))
21704 (outline-next-heading)))
21705 (nreverse ee)))
21707 (defun org-agenda-get-sexps ()
21708 "Return the sexp information for agenda display."
21709 (require 'diary-lib)
21710 (let* ((props (list 'face nil
21711 'mouse-face 'highlight
21712 'keymap org-agenda-keymap
21713 'help-echo
21714 (format "mouse-2 or RET jump to org file %s"
21715 (abbreviate-file-name buffer-file-name))))
21716 (regexp "^&?%%(")
21717 marker category ee txt tags entry result beg b sexp sexp-entry)
21718 (goto-char (point-min))
21719 (while (re-search-forward regexp nil t)
21720 (catch :skip
21721 (org-agenda-skip)
21722 (setq beg (match-beginning 0))
21723 (goto-char (1- (match-end 0)))
21724 (setq b (point))
21725 (forward-sexp 1)
21726 (setq sexp (buffer-substring b (point)))
21727 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21728 (org-trim (match-string 1))
21729 ""))
21730 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21731 (when result
21732 (setq marker (org-agenda-new-marker beg)
21733 category (org-get-category beg))
21735 (if (string-match "\\S-" result)
21736 (setq txt result)
21737 (setq txt "SEXP entry returned empty string"))
21739 (setq txt (org-format-agenda-item
21740 "" txt category tags 'time))
21741 (org-add-props txt props 'org-marker marker)
21742 (org-add-props txt nil
21743 'org-category category 'date date
21744 'type "sexp")
21745 (push txt ee))))
21746 (nreverse ee)))
21748 (defun org-agenda-get-closed ()
21749 "Return the logged TODO entries for agenda display."
21750 (let* ((props (list 'mouse-face 'highlight
21751 'org-not-done-regexp org-not-done-regexp
21752 'org-todo-regexp org-todo-regexp
21753 'keymap org-agenda-keymap
21754 'help-echo
21755 (format "mouse-2 or RET jump to org file %s"
21756 (abbreviate-file-name buffer-file-name))))
21757 (regexp (concat
21758 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21759 (regexp-quote
21760 (substring
21761 (format-time-string
21762 (car org-time-stamp-formats)
21763 (apply 'encode-time ; DATE bound by calendar
21764 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21765 1 11))))
21766 marker hdmarker priority category tags closedp
21767 ee txt timestr)
21768 (goto-char (point-min))
21769 (while (re-search-forward regexp nil t)
21770 (catch :skip
21771 (org-agenda-skip)
21772 (setq marker (org-agenda-new-marker (match-beginning 0))
21773 closedp (equal (match-string 1) org-closed-string)
21774 category (org-get-category (match-beginning 0))
21775 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21776 ;; donep (org-entry-is-done-p)
21778 (if (string-match "\\]" timestr)
21779 ;; substring should only run to end of time stamp
21780 (setq timestr (substring timestr 0 (match-end 0))))
21781 (save-excursion
21782 (if (re-search-backward "^\\*+ " nil t)
21783 (progn
21784 (goto-char (match-beginning 0))
21785 (setq hdmarker (org-agenda-new-marker)
21786 tags (org-get-tags-at))
21787 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21788 (setq txt (org-format-agenda-item
21789 (if closedp "Closed: " "Clocked: ")
21790 (match-string 1) category tags timestr)))
21791 (setq txt org-agenda-no-heading-message))
21792 (setq priority 100000)
21793 (org-add-props txt props
21794 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21795 'priority priority 'org-category category
21796 'type "closed" 'date date
21797 'undone-face 'org-warning 'done-face 'org-done)
21798 (push txt ee))
21799 (goto-char (point-at-eol))))
21800 (nreverse ee)))
21802 (defun org-agenda-get-deadlines ()
21803 "Return the deadline information for agenda display."
21804 (let* ((props (list 'mouse-face 'highlight
21805 'org-not-done-regexp org-not-done-regexp
21806 'org-todo-regexp org-todo-regexp
21807 'keymap org-agenda-keymap
21808 'help-echo
21809 (format "mouse-2 or RET jump to org file %s"
21810 (abbreviate-file-name buffer-file-name))))
21811 (regexp org-deadline-time-regexp)
21812 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21813 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21814 d2 diff dfrac wdays pos pos1 category tags
21815 ee txt head face s upcomingp donep timestr)
21816 (goto-char (point-min))
21817 (while (re-search-forward regexp nil t)
21818 (catch :skip
21819 (org-agenda-skip)
21820 (setq s (match-string 1)
21821 pos (1- (match-beginning 1))
21822 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21823 diff (- d2 d1)
21824 wdays (org-get-wdays s)
21825 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
21826 upcomingp (and todayp (> diff 0)))
21827 ;; When to show a deadline in the calendar:
21828 ;; If the expiration is within wdays warning time.
21829 ;; Past-due deadlines are only shown on the current date
21830 (if (or (and (<= diff wdays)
21831 (and todayp (not org-agenda-only-exact-dates)))
21832 (= diff 0))
21833 (save-excursion
21834 (setq category (org-get-category))
21835 (if (re-search-backward "^\\*+[ \t]+" nil t)
21836 (progn
21837 (goto-char (match-end 0))
21838 (setq pos1 (match-beginning 0))
21839 (setq tags (org-get-tags-at pos1))
21840 (setq head (buffer-substring-no-properties
21841 (point)
21842 (progn (skip-chars-forward "^\r\n")
21843 (point))))
21844 (setq donep (string-match org-looking-at-done-regexp head))
21845 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21846 (setq timestr
21847 (concat (substring s (match-beginning 1)) " "))
21848 (setq timestr 'time))
21849 (if (and donep
21850 (or org-agenda-skip-deadline-if-done
21851 (not (= diff 0))))
21852 (setq txt nil)
21853 (setq txt (org-format-agenda-item
21854 (if (= diff 0)
21855 (car org-agenda-deadline-leaders)
21856 (format (nth 1 org-agenda-deadline-leaders)
21857 diff))
21858 head category tags timestr))))
21859 (setq txt org-agenda-no-heading-message))
21860 (when txt
21861 (setq face (org-agenda-deadline-face dfrac wdays))
21862 (org-add-props txt props
21863 'org-marker (org-agenda-new-marker pos)
21864 'org-hd-marker (org-agenda-new-marker pos1)
21865 'priority (+ (- diff)
21866 (org-get-priority txt))
21867 'org-category category
21868 'type (if upcomingp "upcoming-deadline" "deadline")
21869 'date (if upcomingp date d2)
21870 'face (if donep 'org-done face)
21871 'undone-face face 'done-face 'org-done)
21872 (push txt ee))))))
21873 (nreverse ee)))
21875 (defun org-agenda-deadline-face (fraction &optional wdays)
21876 "Return the face to displaying a deadline item.
21877 FRACTION is what fraction of the head-warning time has passed."
21878 (if (equal wdays 0) (setq fraction 1.))
21879 (let ((faces org-agenda-deadline-faces) f)
21880 (catch 'exit
21881 (while (setq f (pop faces))
21882 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21884 (defun org-agenda-get-scheduled ()
21885 "Return the scheduled information for agenda display."
21886 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21887 'org-todo-regexp org-todo-regexp
21888 'done-face 'org-done
21889 'mouse-face 'highlight
21890 'keymap org-agenda-keymap
21891 'help-echo
21892 (format "mouse-2 or RET jump to org file %s"
21893 (abbreviate-file-name buffer-file-name))))
21894 (regexp org-scheduled-time-regexp)
21895 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21896 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21897 d2 diff pos pos1 category tags
21898 ee txt head pastschedp donep face timestr s)
21899 (goto-char (point-min))
21900 (while (re-search-forward regexp nil t)
21901 (catch :skip
21902 (org-agenda-skip)
21903 (setq s (match-string 1)
21904 pos (1- (match-beginning 1))
21905 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21906 ;;; is this right?
21907 ;;; do we need to do this for deadleine too????
21908 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
21909 diff (- d2 d1))
21910 (setq pastschedp (and todayp (< diff 0)))
21911 ;; When to show a scheduled item in the calendar:
21912 ;; If it is on or past the date.
21913 (if (or (and (< diff 0)
21914 (< (abs diff) org-scheduled-past-days)
21915 (and todayp (not org-agenda-only-exact-dates)))
21916 (= diff 0))
21917 (save-excursion
21918 (setq category (org-get-category))
21919 (if (re-search-backward "^\\*+[ \t]+" nil t)
21920 (progn
21921 (goto-char (match-end 0))
21922 (setq pos1 (match-beginning 0))
21923 (setq tags (org-get-tags-at))
21924 (setq head (buffer-substring-no-properties
21925 (point)
21926 (progn (skip-chars-forward "^\r\n") (point))))
21927 (setq donep (string-match org-looking-at-done-regexp head))
21928 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21929 (setq timestr
21930 (concat (substring s (match-beginning 1)) " "))
21931 (setq timestr 'time))
21932 (if (and donep
21933 (or org-agenda-skip-scheduled-if-done
21934 (not (= diff 0))))
21935 (setq txt nil)
21936 (setq txt (org-format-agenda-item
21937 (if (= diff 0)
21938 (car org-agenda-scheduled-leaders)
21939 (format (nth 1 org-agenda-scheduled-leaders)
21940 (- 1 diff)))
21941 head category tags timestr))))
21942 (setq txt org-agenda-no-heading-message))
21943 (when txt
21944 (setq face (if pastschedp
21945 'org-scheduled-previously
21946 'org-scheduled-today))
21947 (org-add-props txt props
21948 'undone-face face
21949 'face (if donep 'org-done face)
21950 'org-marker (org-agenda-new-marker pos)
21951 'org-hd-marker (org-agenda-new-marker pos1)
21952 'type (if pastschedp "past-scheduled" "scheduled")
21953 'date (if pastschedp d2 date)
21954 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21955 'org-category category)
21956 (push txt ee))))))
21957 (nreverse ee)))
21959 (defun org-agenda-get-blocks ()
21960 "Return the date-range information for agenda display."
21961 (let* ((props (list 'face nil
21962 'org-not-done-regexp org-not-done-regexp
21963 'org-todo-regexp org-todo-regexp
21964 'mouse-face 'highlight
21965 'keymap org-agenda-keymap
21966 'help-echo
21967 (format "mouse-2 or RET jump to org file %s"
21968 (abbreviate-file-name buffer-file-name))))
21969 (regexp org-tr-regexp)
21970 (d0 (calendar-absolute-from-gregorian date))
21971 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21972 donep head)
21973 (goto-char (point-min))
21974 (while (re-search-forward regexp nil t)
21975 (catch :skip
21976 (org-agenda-skip)
21977 (setq pos (point))
21978 (setq timestr (match-string 0)
21979 s1 (match-string 1)
21980 s2 (match-string 2)
21981 d1 (time-to-days (org-time-string-to-time s1))
21982 d2 (time-to-days (org-time-string-to-time s2)))
21983 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21984 ;; Only allow days between the limits, because the normal
21985 ;; date stamps will catch the limits.
21986 (save-excursion
21987 (setq marker (org-agenda-new-marker (point)))
21988 (setq category (org-get-category))
21989 (if (re-search-backward "^\\*+ " nil t)
21990 (progn
21991 (goto-char (match-beginning 0))
21992 (setq hdmarker (org-agenda-new-marker (point)))
21993 (setq tags (org-get-tags-at))
21994 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21995 (setq head (match-string 1))
21996 (and org-agenda-skip-timestamp-if-done
21997 (org-entry-is-done-p)
21998 (throw :skip t))
21999 (setq txt (org-format-agenda-item
22000 (format (if (= d1 d2) "" "(%d/%d): ")
22001 (1+ (- d0 d1)) (1+ (- d2 d1)))
22002 head category tags
22003 (if (= d0 d1) timestr))))
22004 (setq txt org-agenda-no-heading-message))
22005 (org-add-props txt props
22006 'org-marker marker 'org-hd-marker hdmarker
22007 'type "block" 'date date
22008 'priority (org-get-priority txt) 'org-category category)
22009 (push txt ee)))
22010 (goto-char pos)))
22011 ;; Sort the entries by expiration date.
22012 (nreverse ee)))
22014 ;;; Agenda presentation and sorting
22016 (defconst org-plain-time-of-day-regexp
22017 (concat
22018 "\\(\\<[012]?[0-9]"
22019 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22020 "\\(--?"
22021 "\\(\\<[012]?[0-9]"
22022 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22023 "\\)?")
22024 "Regular expression to match a plain time or time range.
22025 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22026 groups carry important information:
22027 0 the full match
22028 1 the first time, range or not
22029 8 the second time, if it is a range.")
22031 (defconst org-plain-time-extension-regexp
22032 (concat
22033 "\\(\\<[012]?[0-9]"
22034 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22035 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
22036 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
22037 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22038 groups carry important information:
22039 0 the full match
22040 7 hours of duration
22041 9 minutes of duration")
22043 (defconst org-stamp-time-of-day-regexp
22044 (concat
22045 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
22046 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
22047 "\\(--?"
22048 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
22049 "Regular expression to match a timestamp time or time range.
22050 After a match, the following groups carry important information:
22051 0 the full match
22052 1 date plus weekday, for backreferencing to make sure both times on same day
22053 2 the first time, range or not
22054 4 the second time, if it is a range.")
22056 (defvar org-prefix-has-time nil
22057 "A flag, set by `org-compile-prefix-format'.
22058 The flag is set if the currently compiled format contains a `%t'.")
22059 (defvar org-prefix-has-tag nil
22060 "A flag, set by `org-compile-prefix-format'.
22061 The flag is set if the currently compiled format contains a `%T'.")
22063 (defun org-format-agenda-item (extra txt &optional category tags dotime
22064 noprefix remove-re)
22065 "Format TXT to be inserted into the agenda buffer.
22066 In particular, it adds the prefix and corresponding text properties. EXTRA
22067 must be a string and replaces the `%s' specifier in the prefix format.
22068 CATEGORY (string, symbol or nil) may be used to overrule the default
22069 category taken from local variable or file name. It will replace the `%c'
22070 specifier in the format. DOTIME, when non-nil, indicates that a
22071 time-of-day should be extracted from TXT for sorting of this entry, and for
22072 the `%t' specifier in the format. When DOTIME is a string, this string is
22073 searched for a time before TXT is. NOPREFIX is a flag and indicates that
22074 only the correctly processes TXT should be returned - this is used by
22075 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
22076 Any match of REMOVE-RE will be removed from TXT."
22077 (save-match-data
22078 ;; Diary entries sometimes have extra whitespace at the beginning
22079 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
22080 (let* ((category (or category
22081 org-category
22082 (if buffer-file-name
22083 (file-name-sans-extension
22084 (file-name-nondirectory buffer-file-name))
22085 "")))
22086 (tag (if tags (nth (1- (length tags)) tags) ""))
22087 time ; time and tag are needed for the eval of the prefix format
22088 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
22089 (time-of-day (and dotime (org-get-time-of-day ts)))
22090 stamp plain s0 s1 s2 rtn srp)
22091 (when (and dotime time-of-day org-prefix-has-time)
22092 ;; Extract starting and ending time and move them to prefix
22093 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
22094 (setq plain (string-match org-plain-time-of-day-regexp ts)))
22095 (setq s0 (match-string 0 ts)
22096 srp (and stamp (match-end 3))
22097 s1 (match-string (if plain 1 2) ts)
22098 s2 (match-string (if plain 8 (if srp 4 6)) ts))
22100 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
22101 ;; them, we might want to remove them there to avoid duplication.
22102 ;; The user can turn this off with a variable.
22103 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
22104 (string-match (concat (regexp-quote s0) " *") txt)
22105 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
22106 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
22107 (= (match-beginning 0) 0)
22109 (setq txt (replace-match "" nil nil txt))))
22110 ;; Normalize the time(s) to 24 hour
22111 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
22112 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
22114 (when (and s1 (not s2) org-agenda-default-appointment-duration
22115 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
22116 (let ((m (+ (string-to-number (match-string 2 s1))
22117 (* 60 (string-to-number (match-string 1 s1)))
22118 org-agenda-default-appointment-duration))
22120 (setq h (/ m 60) m (- m (* h 60)))
22121 (setq s2 (format "%02d:%02d" h m))))
22123 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22124 txt)
22125 ;; Tags are in the string
22126 (if (or (eq org-agenda-remove-tags t)
22127 (and org-agenda-remove-tags
22128 org-prefix-has-tag))
22129 (setq txt (replace-match "" t t txt))
22130 (setq txt (replace-match
22131 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
22132 (match-string 2 txt))
22133 t t txt))))
22135 (when remove-re
22136 (while (string-match remove-re txt)
22137 (setq txt (replace-match "" t t txt))))
22139 ;; Create the final string
22140 (if noprefix
22141 (setq rtn txt)
22142 ;; Prepare the variables needed in the eval of the compiled format
22143 (setq time (cond (s2 (concat s1 "-" s2))
22144 (s1 (concat s1 "......"))
22145 (t ""))
22146 extra (or extra "")
22147 category (if (symbolp category) (symbol-name category) category))
22148 ;; Evaluate the compiled format
22149 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
22151 ;; And finally add the text properties
22152 (org-add-props rtn nil
22153 'org-category (downcase category) 'tags tags
22154 'org-highest-priority org-highest-priority
22155 'org-lowest-priority org-lowest-priority
22156 'prefix-length (- (length rtn) (length txt))
22157 'time-of-day time-of-day
22158 'txt txt
22159 'time time
22160 'extra extra
22161 'dotime dotime))))
22163 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
22164 (defvar org-agenda-sorting-strategy-selected nil)
22166 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
22167 (catch 'exit
22168 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
22169 ((and todayp (member 'today (car org-agenda-time-grid))))
22170 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
22171 ((member 'weekly (car org-agenda-time-grid)))
22172 (t (throw 'exit list)))
22173 (let* ((have (delq nil (mapcar
22174 (lambda (x) (get-text-property 1 'time-of-day x))
22175 list)))
22176 (string (nth 1 org-agenda-time-grid))
22177 (gridtimes (nth 2 org-agenda-time-grid))
22178 (req (car org-agenda-time-grid))
22179 (remove (member 'remove-match req))
22180 new time)
22181 (if (and (member 'require-timed req) (not have))
22182 ;; don't show empty grid
22183 (throw 'exit list))
22184 (while (setq time (pop gridtimes))
22185 (unless (and remove (member time have))
22186 (setq time (int-to-string time))
22187 (push (org-format-agenda-item
22188 nil string "" nil
22189 (concat (substring time 0 -2) ":" (substring time -2)))
22190 new)
22191 (put-text-property
22192 1 (length (car new)) 'face 'org-time-grid (car new))))
22193 (if (member 'time-up org-agenda-sorting-strategy-selected)
22194 (append new list)
22195 (append list new)))))
22197 (defun org-compile-prefix-format (key)
22198 "Compile the prefix format into a Lisp form that can be evaluated.
22199 The resulting form is returned and stored in the variable
22200 `org-prefix-format-compiled'."
22201 (setq org-prefix-has-time nil org-prefix-has-tag nil)
22202 (let ((s (cond
22203 ((stringp org-agenda-prefix-format)
22204 org-agenda-prefix-format)
22205 ((assq key org-agenda-prefix-format)
22206 (cdr (assq key org-agenda-prefix-format)))
22207 (t " %-12:c%?-12t% s")))
22208 (start 0)
22209 varform vars var e c f opt)
22210 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
22211 s start)
22212 (setq var (cdr (assoc (match-string 4 s)
22213 '(("c" . category) ("t" . time) ("s" . extra)
22214 ("T" . tag))))
22215 c (or (match-string 3 s) "")
22216 opt (match-beginning 1)
22217 start (1+ (match-beginning 0)))
22218 (if (equal var 'time) (setq org-prefix-has-time t))
22219 (if (equal var 'tag) (setq org-prefix-has-tag t))
22220 (setq f (concat "%" (match-string 2 s) "s"))
22221 (if opt
22222 (setq varform
22223 `(if (equal "" ,var)
22225 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
22226 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
22227 (setq s (replace-match "%s" t nil s))
22228 (push varform vars))
22229 (setq vars (nreverse vars))
22230 (setq org-prefix-format-compiled `(format ,s ,@vars))))
22232 (defun org-set-sorting-strategy (key)
22233 (if (symbolp (car org-agenda-sorting-strategy))
22234 ;; the old format
22235 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
22236 (setq org-agenda-sorting-strategy-selected
22237 (or (cdr (assq key org-agenda-sorting-strategy))
22238 (cdr (assq 'agenda org-agenda-sorting-strategy))
22239 '(time-up category-keep priority-down)))))
22241 (defun org-get-time-of-day (s &optional string mod24)
22242 "Check string S for a time of day.
22243 If found, return it as a military time number between 0 and 2400.
22244 If not found, return nil.
22245 The optional STRING argument forces conversion into a 5 character wide string
22246 HH:MM."
22247 (save-match-data
22248 (when
22249 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
22250 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
22251 (let* ((h (string-to-number (match-string 1 s)))
22252 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
22253 (ampm (if (match-end 4) (downcase (match-string 4 s))))
22254 (am-p (equal ampm "am"))
22255 (h1 (cond ((not ampm) h)
22256 ((= h 12) (if am-p 0 12))
22257 (t (+ h (if am-p 0 12)))))
22258 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
22259 (mod h1 24) h1))
22260 (t0 (+ (* 100 h2) m))
22261 (t1 (concat (if (>= h1 24) "+" " ")
22262 (if (< t0 100) "0" "")
22263 (if (< t0 10) "0" "")
22264 (int-to-string t0))))
22265 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
22267 (defun org-finalize-agenda-entries (list &optional nosort)
22268 "Sort and concatenate the agenda items."
22269 (setq list (mapcar 'org-agenda-highlight-todo list))
22270 (if nosort
22271 list
22272 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
22274 (defun org-agenda-highlight-todo (x)
22275 (let (re pl)
22276 (if (eq x 'line)
22277 (save-excursion
22278 (beginning-of-line 1)
22279 (setq re (get-text-property (point) 'org-todo-regexp))
22280 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
22281 (when (looking-at (concat "[ \t]*\\.*" re " +"))
22282 (add-text-properties (match-beginning 0) (match-end 0)
22283 (list 'face (org-get-todo-face 0)))
22284 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
22285 (delete-region (match-beginning 1) (1- (match-end 0)))
22286 (goto-char (match-beginning 1))
22287 (insert (format org-agenda-todo-keyword-format s)))))
22288 (setq re (concat (get-text-property 0 'org-todo-regexp x))
22289 pl (get-text-property 0 'prefix-length x))
22290 (when (and re
22291 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
22292 x (or pl 0)) pl))
22293 (add-text-properties
22294 (or (match-end 1) (match-end 0)) (match-end 0)
22295 (list 'face (org-get-todo-face (match-string 2 x)))
22297 (setq x (concat (substring x 0 (match-end 1))
22298 (format org-agenda-todo-keyword-format
22299 (match-string 2 x))
22301 (substring x (match-end 3)))))
22302 x)))
22304 (defsubst org-cmp-priority (a b)
22305 "Compare the priorities of string A and B."
22306 (let ((pa (or (get-text-property 1 'priority a) 0))
22307 (pb (or (get-text-property 1 'priority b) 0)))
22308 (cond ((> pa pb) +1)
22309 ((< pa pb) -1)
22310 (t nil))))
22312 (defsubst org-cmp-category (a b)
22313 "Compare the string values of categories of strings A and B."
22314 (let ((ca (or (get-text-property 1 'org-category a) ""))
22315 (cb (or (get-text-property 1 'org-category b) "")))
22316 (cond ((string-lessp ca cb) -1)
22317 ((string-lessp cb ca) +1)
22318 (t nil))))
22320 (defsubst org-cmp-tag (a b)
22321 "Compare the string values of categories of strings A and B."
22322 (let ((ta (car (last (get-text-property 1 'tags a))))
22323 (tb (car (last (get-text-property 1 'tags b)))))
22324 (cond ((not ta) +1)
22325 ((not tb) -1)
22326 ((string-lessp ta tb) -1)
22327 ((string-lessp tb ta) +1)
22328 (t nil))))
22330 (defsubst org-cmp-time (a b)
22331 "Compare the time-of-day values of strings A and B."
22332 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
22333 (ta (or (get-text-property 1 'time-of-day a) def))
22334 (tb (or (get-text-property 1 'time-of-day b) def)))
22335 (cond ((< ta tb) -1)
22336 ((< tb ta) +1)
22337 (t nil))))
22339 (defun org-entries-lessp (a b)
22340 "Predicate for sorting agenda entries."
22341 ;; The following variables will be used when the form is evaluated.
22342 ;; So even though the compiler complains, keep them.
22343 (let* ((time-up (org-cmp-time a b))
22344 (time-down (if time-up (- time-up) nil))
22345 (priority-up (org-cmp-priority a b))
22346 (priority-down (if priority-up (- priority-up) nil))
22347 (category-up (org-cmp-category a b))
22348 (category-down (if category-up (- category-up) nil))
22349 (category-keep (if category-up +1 nil))
22350 (tag-up (org-cmp-tag a b))
22351 (tag-down (if tag-up (- tag-up) nil)))
22352 (cdr (assoc
22353 (eval (cons 'or org-agenda-sorting-strategy-selected))
22354 '((-1 . t) (1 . nil) (nil . nil))))))
22356 ;;; Agenda restriction lock
22358 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
22359 "Overlay to mark the headline to which arenda commands are restricted.")
22360 (org-overlay-put org-agenda-restriction-lock-overlay
22361 'face 'org-agenda-restriction-lock)
22362 (org-overlay-put org-agenda-restriction-lock-overlay
22363 'help-echo "Agendas are currently limited to this subtree.")
22364 (org-detach-overlay org-agenda-restriction-lock-overlay)
22365 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
22366 "Overlay marking the agenda restriction line in speedbar.")
22367 (org-overlay-put org-speedbar-restriction-lock-overlay
22368 'face 'org-agenda-restriction-lock)
22369 (org-overlay-put org-speedbar-restriction-lock-overlay
22370 'help-echo "Agendas are currently limited to this item.")
22371 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22373 (defun org-agenda-set-restriction-lock (&optional type)
22374 "Set restriction lock for agenda, to current subtree or file.
22375 Restriction will be the file if TYPE is `file', or if type is the
22376 universal prefix '(4), or if the cursor is before the first headline
22377 in the file. Otherwise, restriction will be to the current subtree."
22378 (interactive "P")
22379 (and (equal type '(4)) (setq type 'file))
22380 (setq type (cond
22381 (type type)
22382 ((org-at-heading-p) 'subtree)
22383 ((condition-case nil (org-back-to-heading t) (error nil))
22384 'subtree)
22385 (t 'file)))
22386 (if (eq type 'subtree)
22387 (progn
22388 (setq org-agenda-restrict t)
22389 (setq org-agenda-overriding-restriction 'subtree)
22390 (put 'org-agenda-files 'org-restrict
22391 (list (buffer-file-name (buffer-base-buffer))))
22392 (org-back-to-heading t)
22393 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22394 (move-marker org-agenda-restrict-begin (point))
22395 (move-marker org-agenda-restrict-end
22396 (save-excursion (org-end-of-subtree t)))
22397 (message "Locking agenda restriction to subtree"))
22398 (put 'org-agenda-files 'org-restrict
22399 (list (buffer-file-name (buffer-base-buffer))))
22400 (setq org-agenda-restrict nil)
22401 (setq org-agenda-overriding-restriction 'file)
22402 (move-marker org-agenda-restrict-begin nil)
22403 (move-marker org-agenda-restrict-end nil)
22404 (message "Locking agenda restriction to file"))
22405 (setq current-prefix-arg nil)
22406 (org-agenda-maybe-redo))
22408 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22409 "Remove the agenda restriction lock."
22410 (interactive "P")
22411 (org-detach-overlay org-agenda-restriction-lock-overlay)
22412 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22413 (setq org-agenda-overriding-restriction nil)
22414 (setq org-agenda-restrict nil)
22415 (put 'org-agenda-files 'org-restrict nil)
22416 (move-marker org-agenda-restrict-begin nil)
22417 (move-marker org-agenda-restrict-end nil)
22418 (setq current-prefix-arg nil)
22419 (message "Agenda restriction lock removed")
22420 (or noupdate (org-agenda-maybe-redo)))
22422 (defun org-agenda-maybe-redo ()
22423 "If there is any window showing the agenda view, update it."
22424 (let ((w (get-buffer-window org-agenda-buffer-name t))
22425 (w0 (selected-window)))
22426 (when w
22427 (select-window w)
22428 (org-agenda-redo)
22429 (select-window w0)
22430 (if org-agenda-overriding-restriction
22431 (message "Agenda view shifted to new %s restriction"
22432 org-agenda-overriding-restriction)
22433 (message "Agenda restriction lock removed")))))
22435 ;;; Agenda commands
22437 (defun org-agenda-check-type (error &rest types)
22438 "Check if agenda buffer is of allowed type.
22439 If ERROR is non-nil, throw an error, otherwise just return nil."
22440 (if (memq org-agenda-type types)
22442 (if error
22443 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22444 nil)))
22446 (defun org-agenda-quit ()
22447 "Exit agenda by removing the window or the buffer."
22448 (interactive)
22449 (let ((buf (current-buffer)))
22450 (if (not (one-window-p)) (delete-window))
22451 (kill-buffer buf)
22452 (org-agenda-reset-markers)
22453 (org-columns-remove-overlays))
22454 ;; Maybe restore the pre-agenda window configuration.
22455 (and org-agenda-restore-windows-after-quit
22456 (not (eq org-agenda-window-setup 'other-frame))
22457 org-pre-agenda-window-conf
22458 (set-window-configuration org-pre-agenda-window-conf)))
22460 (defun org-agenda-exit ()
22461 "Exit agenda by removing the window or the buffer.
22462 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22463 Org-mode buffers visited directly by the user will not be touched."
22464 (interactive)
22465 (org-release-buffers org-agenda-new-buffers)
22466 (setq org-agenda-new-buffers nil)
22467 (org-agenda-quit))
22469 (defun org-agenda-execute (arg)
22470 "Execute another agenda command, keeping same window.\\<global-map>
22471 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22472 (interactive "P")
22473 (let ((org-agenda-window-setup 'current-window))
22474 (org-agenda arg)))
22476 (defun org-save-all-org-buffers ()
22477 "Save all Org-mode buffers without user confirmation."
22478 (interactive)
22479 (message "Saving all Org-mode buffers...")
22480 (save-some-buffers t 'org-mode-p)
22481 (message "Saving all Org-mode buffers... done"))
22483 (defun org-agenda-redo ()
22484 "Rebuild Agenda.
22485 When this is the global TODO list, a prefix argument will be interpreted."
22486 (interactive)
22487 (let* ((org-agenda-keep-modes t)
22488 (line (org-current-line))
22489 (window-line (- line (org-current-line (window-start))))
22490 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22491 (message "Rebuilding agenda buffer...")
22492 (org-let lprops '(eval org-agenda-redo-command))
22493 (setq org-agenda-undo-list nil
22494 org-agenda-pending-undo-list nil)
22495 (message "Rebuilding agenda buffer...done")
22496 (goto-line line)
22497 (recenter window-line)))
22499 (defun org-agenda-manipulate-query-add ()
22500 "Manipulate the query by adding a search term with positive selection.
22501 Positive selection means, the term must be matched for selection of an entry."
22502 (interactive)
22503 (org-agenda-manipulate-query ?\[))
22504 (defun org-agenda-manipulate-query-subtract ()
22505 "Manipulate the query by adding a search term with negative selection.
22506 Negative selection means, term must not be matched for selection of an entry."
22507 (interactive)
22508 (org-agenda-manipulate-query ?\]))
22509 (defun org-agenda-manipulate-query-add-re ()
22510 "Manipulate the query by adding a search regexp with positive selection.
22511 Positive selection means, the regexp must match for selection of an entry."
22512 (interactive)
22513 (org-agenda-manipulate-query ?\{))
22514 (defun org-agenda-manipulate-query-subtract-re ()
22515 "Manipulate the query by adding a search regexp with negative selection.
22516 Negative selection means, regexp must not match for selection of an entry."
22517 (interactive)
22518 (org-agenda-manipulate-query ?\}))
22519 (defun org-agenda-manipulate-query (char)
22520 (cond
22521 ((eq org-agenda-type 'search)
22522 (org-add-to-string
22523 'org-agenda-query-string
22524 (cdr (assoc char '((?\[ . " +") (?\] . " -")
22525 (?\{ . " +{}") (?\} . " -{}")))))
22526 (setq org-agenda-redo-command
22527 (list 'org-search-view
22528 org-todo-only
22529 org-agenda-query-string
22530 (+ (length org-agenda-query-string)
22531 (if (member char '(?\{ ?\})) 0 1))))
22532 (set-register org-agenda-query-register org-agenda-query-string)
22533 (org-agenda-redo))
22534 (t (error "Canot manipulate query for %s-type agenda buffers"
22535 org-agenda-type))))
22537 (defun org-add-to-string (var string)
22538 (set var (concat (symbol-value var) string)))
22540 (defun org-agenda-goto-date (date)
22541 "Jump to DATE in agenda."
22542 (interactive (list (org-read-date)))
22543 (org-agenda-list nil date))
22545 (defun org-agenda-goto-today ()
22546 "Go to today."
22547 (interactive)
22548 (org-agenda-check-type t 'timeline 'agenda)
22549 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22550 (cond
22551 (tdpos (goto-char tdpos))
22552 ((eq org-agenda-type 'agenda)
22553 (let* ((sd (time-to-days
22554 (time-subtract (current-time)
22555 (list 0 (* 3600 org-extend-today-until) 0))))
22556 (comp (org-agenda-compute-time-span sd org-agenda-span))
22557 (org-agenda-overriding-arguments org-agenda-last-arguments))
22558 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22559 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22560 (org-agenda-redo)
22561 (org-agenda-find-same-or-today-or-agenda)))
22562 (t (error "Cannot find today")))))
22564 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22565 (goto-char
22566 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22567 (text-property-any (point-min) (point-max) 'org-today t)
22568 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22569 (point-min))))
22571 (defun org-agenda-later (arg)
22572 "Go forward in time by thee current span.
22573 With prefix ARG, go forward that many times the current span."
22574 (interactive "p")
22575 (org-agenda-check-type t 'agenda)
22576 (let* ((span org-agenda-span)
22577 (sd org-starting-day)
22578 (greg (calendar-gregorian-from-absolute sd))
22579 (cnt (get-text-property (point) 'org-day-cnt))
22580 greg2 nd)
22581 (cond
22582 ((eq span 'day)
22583 (setq sd (+ arg sd) nd 1))
22584 ((eq span 'week)
22585 (setq sd (+ (* 7 arg) sd) nd 7))
22586 ((eq span 'month)
22587 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22588 sd (calendar-absolute-from-gregorian greg2))
22589 (setcar greg2 (1+ (car greg2)))
22590 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22591 ((eq span 'year)
22592 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22593 sd (calendar-absolute-from-gregorian greg2))
22594 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22595 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22596 (let ((org-agenda-overriding-arguments
22597 (list (car org-agenda-last-arguments) sd nd t)))
22598 (org-agenda-redo)
22599 (org-agenda-find-same-or-today-or-agenda cnt))))
22601 (defun org-agenda-earlier (arg)
22602 "Go backward in time by the current span.
22603 With prefix ARG, go backward that many times the current span."
22604 (interactive "p")
22605 (org-agenda-later (- arg)))
22607 (defun org-agenda-day-view (&optional day-of-year)
22608 "Switch to daily view for agenda.
22609 With argument DAY-OF-YEAR, switch to that day of the year."
22610 (interactive "P")
22611 (setq org-agenda-ndays 1)
22612 (org-agenda-change-time-span 'day day-of-year))
22613 (defun org-agenda-week-view (&optional iso-week)
22614 "Switch to daily view for agenda.
22615 With argument ISO-WEEK, switch to the corresponding ISO week.
22616 If ISO-WEEK has more then 2 digits, only the last two encode the
22617 week. Any digits before this encode a year. So 200712 means
22618 week 12 of year 2007. Years in the range 1938-2037 can also be
22619 written as 2-digit years."
22620 (interactive "P")
22621 (setq org-agenda-ndays 7)
22622 (org-agenda-change-time-span 'week iso-week))
22623 (defun org-agenda-month-view (&optional month)
22624 "Switch to daily view for agenda.
22625 With argument MONTH, switch to that month."
22626 (interactive "P")
22627 ;; FIXME: allow month like 812 to mean 2008 december
22628 (org-agenda-change-time-span 'month month))
22629 (defun org-agenda-year-view (&optional year)
22630 "Switch to daily view for agenda.
22631 With argument YEAR, switch to that year.
22632 If MONTH has more then 2 digits, only the last two encode the
22633 month. Any digits before this encode a year. So 200712 means
22634 December year 2007. Years in the range 1938-2037 can also be
22635 written as 2-digit years."
22636 (interactive "P")
22637 (when year
22638 (setq year (org-small-year-to-year year)))
22639 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22640 (org-agenda-change-time-span 'year year)
22641 (error "Abort")))
22643 (defun org-agenda-change-time-span (span &optional n)
22644 "Change the agenda view to SPAN.
22645 SPAN may be `day', `week', `month', `year'."
22646 (org-agenda-check-type t 'agenda)
22647 (if (and (not n) (equal org-agenda-span span))
22648 (error "Viewing span is already \"%s\"" span))
22649 (let* ((sd (or (get-text-property (point) 'day)
22650 org-starting-day))
22651 (computed (org-agenda-compute-time-span sd span n))
22652 (org-agenda-overriding-arguments
22653 (list (car org-agenda-last-arguments)
22654 (car computed) (cdr computed) t)))
22655 (org-agenda-redo)
22656 (org-agenda-find-same-or-today-or-agenda))
22657 (org-agenda-set-mode-name)
22658 (message "Switched to %s view" span))
22660 (defun org-agenda-compute-time-span (sd span &optional n)
22661 "Compute starting date and number of days for agenda.
22662 SPAN may be `day', `week', `month', `year'. The return value
22663 is a cons cell with the starting date and the number of days,
22664 so that the date SD will be in that range."
22665 (let* ((greg (calendar-gregorian-from-absolute sd))
22666 (dg (nth 1 greg))
22667 (mg (car greg))
22668 (yg (nth 2 greg))
22669 nd w1 y1 m1 thisweek)
22670 (cond
22671 ((eq span 'day)
22672 (when n
22673 (setq sd (+ (calendar-absolute-from-gregorian
22674 (list mg 1 yg))
22675 n -1)))
22676 (setq nd 1))
22677 ((eq span 'week)
22678 (let* ((nt (calendar-day-of-week
22679 (calendar-gregorian-from-absolute sd)))
22680 (d (if org-agenda-start-on-weekday
22681 (- nt org-agenda-start-on-weekday)
22682 0)))
22683 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22684 (when n
22685 (require 'cal-iso)
22686 (setq thisweek (car (calendar-iso-from-absolute sd)))
22687 (when (> n 99)
22688 (setq y1 (org-small-year-to-year (/ n 100))
22689 n (mod n 100)))
22690 (setq sd
22691 (calendar-absolute-from-iso
22692 (list n 1
22693 (or y1 (nth 2 (calendar-iso-from-absolute sd)))))))
22694 (setq nd 7)))
22695 ((eq span 'month)
22696 (when (and n (> n 99))
22697 (setq y1 (org-small-year-to-year (/ n 100))
22698 n (mod n 100)))
22699 (setq sd (calendar-absolute-from-gregorian
22700 (list (or n mg) 1 (or y1 yg)))
22701 nd (- (calendar-absolute-from-gregorian
22702 (list (1+ (or n mg)) 1 (or y1 yg)))
22703 sd)))
22704 ((eq span 'year)
22705 (setq sd (calendar-absolute-from-gregorian
22706 (list 1 1 (or n yg)))
22707 nd (- (calendar-absolute-from-gregorian
22708 (list 1 1 (1+ (or n yg))))
22709 sd))))
22710 (cons sd nd)))
22712 (defun org-days-to-iso-week (days)
22713 "Return the iso week number."
22714 (require 'cal-iso)
22715 (car (calendar-iso-from-absolute days)))
22717 (defun org-small-year-to-year (year)
22718 "Convert 2-digit years into 4-digit years.
22719 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
22720 The year 2000 cannot be abbreviated. Any year lager than 99
22721 is retrned unchanged."
22722 (if (< year 38)
22723 (setq year (+ 2000 year))
22724 (if (< year 100)
22725 (setq year (+ 1900 year))))
22726 year)
22728 ;; FIXME: does not work if user makes date format that starts with a blank
22729 (defun org-agenda-next-date-line (&optional arg)
22730 "Jump to the next line indicating a date in agenda buffer."
22731 (interactive "p")
22732 (org-agenda-check-type t 'agenda 'timeline)
22733 (beginning-of-line 1)
22734 (if (looking-at "^\\S-") (forward-char 1))
22735 (if (not (re-search-forward "^\\S-" nil t arg))
22736 (progn
22737 (backward-char 1)
22738 (error "No next date after this line in this buffer")))
22739 (goto-char (match-beginning 0)))
22741 (defun org-agenda-previous-date-line (&optional arg)
22742 "Jump to the previous line indicating a date in agenda buffer."
22743 (interactive "p")
22744 (org-agenda-check-type t 'agenda 'timeline)
22745 (beginning-of-line 1)
22746 (if (not (re-search-backward "^\\S-" nil t arg))
22747 (error "No previous date before this line in this buffer")))
22749 ;; Initialize the highlight
22750 (defvar org-hl (org-make-overlay 1 1))
22751 (org-overlay-put org-hl 'face 'highlight)
22753 (defun org-highlight (begin end &optional buffer)
22754 "Highlight a region with overlay."
22755 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22756 org-hl begin end (or buffer (current-buffer))))
22758 (defun org-unhighlight ()
22759 "Detach overlay INDEX."
22760 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22762 ;; FIXME this is currently not used.
22763 (defun org-highlight-until-next-command (beg end &optional buffer)
22764 (org-highlight beg end buffer)
22765 (add-hook 'pre-command-hook 'org-unhighlight-once))
22766 (defun org-unhighlight-once ()
22767 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22768 (org-unhighlight))
22770 (defun org-agenda-follow-mode ()
22771 "Toggle follow mode in an agenda buffer."
22772 (interactive)
22773 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22774 (org-agenda-set-mode-name)
22775 (message "Follow mode is %s"
22776 (if org-agenda-follow-mode "on" "off")))
22778 (defun org-agenda-log-mode ()
22779 "Toggle log mode in an agenda buffer."
22780 (interactive)
22781 (org-agenda-check-type t 'agenda 'timeline)
22782 (setq org-agenda-show-log (not org-agenda-show-log))
22783 (org-agenda-set-mode-name)
22784 (org-agenda-redo)
22785 (message "Log mode is %s"
22786 (if org-agenda-show-log "on" "off")))
22788 (defun org-agenda-toggle-diary ()
22789 "Toggle diary inclusion in an agenda buffer."
22790 (interactive)
22791 (org-agenda-check-type t 'agenda)
22792 (setq org-agenda-include-diary (not org-agenda-include-diary))
22793 (org-agenda-redo)
22794 (org-agenda-set-mode-name)
22795 (message "Diary inclusion turned %s"
22796 (if org-agenda-include-diary "on" "off")))
22798 (defun org-agenda-toggle-time-grid ()
22799 "Toggle time grid in an agenda buffer."
22800 (interactive)
22801 (org-agenda-check-type t 'agenda)
22802 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22803 (org-agenda-redo)
22804 (org-agenda-set-mode-name)
22805 (message "Time-grid turned %s"
22806 (if org-agenda-use-time-grid "on" "off")))
22808 (defun org-agenda-set-mode-name ()
22809 "Set the mode name to indicate all the small mode settings."
22810 (setq mode-name
22811 (concat "Org-Agenda"
22812 (if (equal org-agenda-ndays 1) " Day" "")
22813 (if (equal org-agenda-ndays 7) " Week" "")
22814 (if org-agenda-follow-mode " Follow" "")
22815 (if org-agenda-include-diary " Diary" "")
22816 (if org-agenda-use-time-grid " Grid" "")
22817 (if org-agenda-show-log " Log" "")))
22818 (force-mode-line-update))
22820 (defun org-agenda-post-command-hook ()
22821 (and (eolp) (not (bolp)) (backward-char 1))
22822 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22823 (if (and org-agenda-follow-mode
22824 (get-text-property (point) 'org-marker))
22825 (org-agenda-show)))
22827 (defun org-agenda-show-priority ()
22828 "Show the priority of the current item.
22829 This priority is composed of the main priority given with the [#A] cookies,
22830 and by additional input from the age of a schedules or deadline entry."
22831 (interactive)
22832 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22833 (message "Priority is %d" (if pri pri -1000))))
22835 (defun org-agenda-show-tags ()
22836 "Show the tags applicable to the current item."
22837 (interactive)
22838 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22839 (if tags
22840 (message "Tags are :%s:"
22841 (org-no-properties (mapconcat 'identity tags ":")))
22842 (message "No tags associated with this line"))))
22844 (defun org-agenda-goto (&optional highlight)
22845 "Go to the Org-mode file which contains the item at point."
22846 (interactive)
22847 (let* ((marker (or (get-text-property (point) 'org-marker)
22848 (org-agenda-error)))
22849 (buffer (marker-buffer marker))
22850 (pos (marker-position marker)))
22851 (switch-to-buffer-other-window buffer)
22852 (widen)
22853 (goto-char pos)
22854 (when (org-mode-p)
22855 (org-show-context 'agenda)
22856 (save-excursion
22857 (and (outline-next-heading)
22858 (org-flag-heading nil)))) ; show the next heading
22859 (recenter (/ (window-height) 2))
22860 (run-hooks 'org-agenda-after-show-hook)
22861 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22863 (defvar org-agenda-after-show-hook nil
22864 "Normal hook run after an item has been shown from the agenda.
22865 Point is in the buffer where the item originated.")
22867 (defun org-agenda-kill ()
22868 "Kill the entry or subtree belonging to the current agenda entry."
22869 (interactive)
22870 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22871 (let* ((marker (or (get-text-property (point) 'org-marker)
22872 (org-agenda-error)))
22873 (buffer (marker-buffer marker))
22874 (pos (marker-position marker))
22875 (type (get-text-property (point) 'type))
22876 dbeg dend (n 0) conf)
22877 (org-with-remote-undo buffer
22878 (with-current-buffer buffer
22879 (save-excursion
22880 (goto-char pos)
22881 (if (and (org-mode-p) (not (member type '("sexp"))))
22882 (setq dbeg (progn (org-back-to-heading t) (point))
22883 dend (org-end-of-subtree t t))
22884 (setq dbeg (point-at-bol)
22885 dend (min (point-max) (1+ (point-at-eol)))))
22886 (goto-char dbeg)
22887 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22888 (setq conf (or (eq t org-agenda-confirm-kill)
22889 (and (numberp org-agenda-confirm-kill)
22890 (> n org-agenda-confirm-kill))))
22891 (and conf
22892 (not (y-or-n-p
22893 (format "Delete entry with %d lines in buffer \"%s\"? "
22894 n (buffer-name buffer))))
22895 (error "Abort"))
22896 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22897 (with-current-buffer buffer (delete-region dbeg dend))
22898 (message "Agenda item and source killed"))))
22900 (defun org-agenda-archive ()
22901 "Kill the entry or subtree belonging to the current agenda entry."
22902 (interactive)
22903 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22904 (let* ((marker (or (get-text-property (point) 'org-marker)
22905 (org-agenda-error)))
22906 (buffer (marker-buffer marker))
22907 (pos (marker-position marker)))
22908 (org-with-remote-undo buffer
22909 (with-current-buffer buffer
22910 (if (org-mode-p)
22911 (save-excursion
22912 (goto-char pos)
22913 (org-remove-subtree-entries-from-agenda)
22914 (org-back-to-heading t)
22915 (org-archive-subtree))
22916 (error "Archiving works only in Org-mode files"))))))
22918 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22919 "Remove all lines in the agenda that correspond to a given subtree.
22920 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22921 If this information is not given, the function uses the tree at point."
22922 (let ((buf (or buf (current-buffer))) m p)
22923 (save-excursion
22924 (unless (and beg end)
22925 (org-back-to-heading t)
22926 (setq beg (point))
22927 (org-end-of-subtree t)
22928 (setq end (point)))
22929 (set-buffer (get-buffer org-agenda-buffer-name))
22930 (save-excursion
22931 (goto-char (point-max))
22932 (beginning-of-line 1)
22933 (while (not (bobp))
22934 (when (and (setq m (get-text-property (point) 'org-marker))
22935 (equal buf (marker-buffer m))
22936 (setq p (marker-position m))
22937 (>= p beg)
22938 (<= p end))
22939 (let ((inhibit-read-only t))
22940 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22941 (beginning-of-line 0))))))
22943 (defun org-agenda-open-link ()
22944 "Follow the link in the current line, if any."
22945 (interactive)
22946 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22947 (save-excursion
22948 (save-restriction
22949 (narrow-to-region (point-at-bol) (point-at-eol))
22950 (org-open-at-point))))
22952 (defun org-agenda-copy-local-variable (var)
22953 "Get a variable from a referenced buffer and install it here."
22954 (let ((m (get-text-property (point) 'org-marker)))
22955 (when (and m (buffer-live-p (marker-buffer m)))
22956 (org-set-local var (with-current-buffer (marker-buffer m)
22957 (symbol-value var))))))
22959 (defun org-agenda-switch-to (&optional delete-other-windows)
22960 "Go to the Org-mode file which contains the item at point."
22961 (interactive)
22962 (let* ((marker (or (get-text-property (point) 'org-marker)
22963 (org-agenda-error)))
22964 (buffer (marker-buffer marker))
22965 (pos (marker-position marker)))
22966 (switch-to-buffer buffer)
22967 (and delete-other-windows (delete-other-windows))
22968 (widen)
22969 (goto-char pos)
22970 (when (org-mode-p)
22971 (org-show-context 'agenda)
22972 (save-excursion
22973 (and (outline-next-heading)
22974 (org-flag-heading nil)))))) ; show the next heading
22976 (defun org-agenda-goto-mouse (ev)
22977 "Go to the Org-mode file which contains the item at the mouse click."
22978 (interactive "e")
22979 (mouse-set-point ev)
22980 (org-agenda-goto))
22982 (defun org-agenda-show ()
22983 "Display the Org-mode file which contains the item at point."
22984 (interactive)
22985 (let ((win (selected-window)))
22986 (org-agenda-goto t)
22987 (select-window win)))
22989 (defun org-agenda-recenter (arg)
22990 "Display the Org-mode file which contains the item at point and recenter."
22991 (interactive "P")
22992 (let ((win (selected-window)))
22993 (org-agenda-goto t)
22994 (recenter arg)
22995 (select-window win)))
22997 (defun org-agenda-show-mouse (ev)
22998 "Display the Org-mode file which contains the item at the mouse click."
22999 (interactive "e")
23000 (mouse-set-point ev)
23001 (org-agenda-show))
23003 (defun org-agenda-check-no-diary ()
23004 "Check if the entry is a diary link and abort if yes."
23005 (if (get-text-property (point) 'org-agenda-diary-link)
23006 (org-agenda-error)))
23008 (defun org-agenda-error ()
23009 (error "Command not allowed in this line"))
23011 (defun org-agenda-tree-to-indirect-buffer ()
23012 "Show the subtree corresponding to the current entry in an indirect buffer.
23013 This calls the command `org-tree-to-indirect-buffer' from the original
23014 Org-mode buffer.
23015 With numerical prefix arg ARG, go up to this level and then take that tree.
23016 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
23017 dedicated frame)."
23018 (interactive)
23019 (org-agenda-check-no-diary)
23020 (let* ((marker (or (get-text-property (point) 'org-marker)
23021 (org-agenda-error)))
23022 (buffer (marker-buffer marker))
23023 (pos (marker-position marker)))
23024 (with-current-buffer buffer
23025 (save-excursion
23026 (goto-char pos)
23027 (call-interactively 'org-tree-to-indirect-buffer)))))
23029 (defvar org-last-heading-marker (make-marker)
23030 "Marker pointing to the headline that last changed its TODO state
23031 by a remote command from the agenda.")
23033 (defun org-agenda-todo-nextset ()
23034 "Switch TODO entry to next sequence."
23035 (interactive)
23036 (org-agenda-todo 'nextset))
23038 (defun org-agenda-todo-previousset ()
23039 "Switch TODO entry to previous sequence."
23040 (interactive)
23041 (org-agenda-todo 'previousset))
23043 (defun org-agenda-todo (&optional arg)
23044 "Cycle TODO state of line at point, also in Org-mode file.
23045 This changes the line at point, all other lines in the agenda referring to
23046 the same tree node, and the headline of the tree node in the Org-mode file."
23047 (interactive "P")
23048 (org-agenda-check-no-diary)
23049 (let* ((col (current-column))
23050 (marker (or (get-text-property (point) 'org-marker)
23051 (org-agenda-error)))
23052 (buffer (marker-buffer marker))
23053 (pos (marker-position marker))
23054 (hdmarker (get-text-property (point) 'org-hd-marker))
23055 (inhibit-read-only t)
23056 newhead)
23057 (org-with-remote-undo buffer
23058 (with-current-buffer buffer
23059 (widen)
23060 (goto-char pos)
23061 (org-show-context 'agenda)
23062 (save-excursion
23063 (and (outline-next-heading)
23064 (org-flag-heading nil))) ; show the next heading
23065 (org-todo arg)
23066 (and (bolp) (forward-char 1))
23067 (setq newhead (org-get-heading))
23068 (save-excursion
23069 (org-back-to-heading)
23070 (move-marker org-last-heading-marker (point))))
23071 (beginning-of-line 1)
23072 (save-excursion
23073 (org-agenda-change-all-lines newhead hdmarker 'fixface))
23074 (move-to-column col))))
23076 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
23077 "Change all lines in the agenda buffer which match HDMARKER.
23078 The new content of the line will be NEWHEAD (as modified by
23079 `org-format-agenda-item'). HDMARKER is checked with
23080 `equal' against all `org-hd-marker' text properties in the file.
23081 If FIXFACE is non-nil, the face of each item is modified acording to
23082 the new TODO state."
23083 (let* ((inhibit-read-only t)
23084 props m pl undone-face done-face finish new dotime cat tags)
23085 (save-excursion
23086 (goto-char (point-max))
23087 (beginning-of-line 1)
23088 (while (not finish)
23089 (setq finish (bobp))
23090 (when (and (setq m (get-text-property (point) 'org-hd-marker))
23091 (equal m hdmarker))
23092 (setq props (text-properties-at (point))
23093 dotime (get-text-property (point) 'dotime)
23094 cat (get-text-property (point) 'org-category)
23095 tags (get-text-property (point) 'tags)
23096 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
23097 pl (get-text-property (point) 'prefix-length)
23098 undone-face (get-text-property (point) 'undone-face)
23099 done-face (get-text-property (point) 'done-face))
23100 (move-to-column pl)
23101 (cond
23102 ((equal new "")
23103 (beginning-of-line 1)
23104 (and (looking-at ".*\n?") (replace-match "")))
23105 ((looking-at ".*")
23106 (replace-match new t t)
23107 (beginning-of-line 1)
23108 (add-text-properties (point-at-bol) (point-at-eol) props)
23109 (when fixface
23110 (add-text-properties
23111 (point-at-bol) (point-at-eol)
23112 (list 'face
23113 (if org-last-todo-state-is-todo
23114 undone-face done-face))))
23115 (org-agenda-highlight-todo 'line)
23116 (beginning-of-line 1))
23117 (t (error "Line update did not work"))))
23118 (beginning-of-line 0)))
23119 (org-finalize-agenda)))
23121 (defun org-agenda-align-tags (&optional line)
23122 "Align all tags in agenda items to `org-agenda-tags-column'."
23123 (let ((inhibit-read-only t) l c)
23124 (save-excursion
23125 (goto-char (if line (point-at-bol) (point-min)))
23126 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
23127 (if line (point-at-eol) nil) t)
23128 (add-text-properties
23129 (match-beginning 2) (match-end 2)
23130 (list 'face (delq nil (list 'org-tag (get-text-property
23131 (match-beginning 2) 'face)))))
23132 (setq l (- (match-end 2) (match-beginning 2))
23133 c (if (< org-agenda-tags-column 0)
23134 (- (abs org-agenda-tags-column) l)
23135 org-agenda-tags-column))
23136 (delete-region (match-beginning 1) (match-end 1))
23137 (goto-char (match-beginning 1))
23138 (insert (org-add-props
23139 (make-string (max 1 (- c (current-column))) ?\ )
23140 (text-properties-at (point))))))))
23142 (defun org-agenda-priority-up ()
23143 "Increase the priority of line at point, also in Org-mode file."
23144 (interactive)
23145 (org-agenda-priority 'up))
23147 (defun org-agenda-priority-down ()
23148 "Decrease the priority of line at point, also in Org-mode file."
23149 (interactive)
23150 (org-agenda-priority 'down))
23152 (defun org-agenda-priority (&optional force-direction)
23153 "Set the priority of line at point, also in Org-mode file.
23154 This changes the line at point, all other lines in the agenda referring to
23155 the same tree node, and the headline of the tree node in the Org-mode file."
23156 (interactive)
23157 (org-agenda-check-no-diary)
23158 (let* ((marker (or (get-text-property (point) 'org-marker)
23159 (org-agenda-error)))
23160 (hdmarker (get-text-property (point) 'org-hd-marker))
23161 (buffer (marker-buffer hdmarker))
23162 (pos (marker-position hdmarker))
23163 (inhibit-read-only t)
23164 newhead)
23165 (org-with-remote-undo buffer
23166 (with-current-buffer buffer
23167 (widen)
23168 (goto-char pos)
23169 (org-show-context 'agenda)
23170 (save-excursion
23171 (and (outline-next-heading)
23172 (org-flag-heading nil))) ; show the next heading
23173 (funcall 'org-priority force-direction)
23174 (end-of-line 1)
23175 (setq newhead (org-get-heading)))
23176 (org-agenda-change-all-lines newhead hdmarker)
23177 (beginning-of-line 1))))
23179 (defun org-get-tags-at (&optional pos)
23180 "Get a list of all headline tags applicable at POS.
23181 POS defaults to point. If tags are inherited, the list contains
23182 the targets in the same sequence as the headlines appear, i.e.
23183 the tags of the current headline come last."
23184 (interactive)
23185 (let (tags lastpos)
23186 (save-excursion
23187 (save-restriction
23188 (widen)
23189 (goto-char (or pos (point)))
23190 (save-match-data
23191 (condition-case nil
23192 (progn
23193 (org-back-to-heading t)
23194 (while (not (equal lastpos (point)))
23195 (setq lastpos (point))
23196 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
23197 (setq tags (append (org-split-string
23198 (org-match-string-no-properties 1) ":")
23199 tags)))
23200 (or org-use-tag-inheritance (error ""))
23201 (org-up-heading-all 1)))
23202 (error nil))))
23203 tags)))
23205 ;; FIXME: should fix the tags property of the agenda line.
23206 (defun org-agenda-set-tags ()
23207 "Set tags for the current headline."
23208 (interactive)
23209 (org-agenda-check-no-diary)
23210 (if (and (org-region-active-p) (interactive-p))
23211 (call-interactively 'org-change-tag-in-region)
23212 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23213 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23214 (org-agenda-error)))
23215 (buffer (marker-buffer hdmarker))
23216 (pos (marker-position hdmarker))
23217 (inhibit-read-only t)
23218 newhead)
23219 (org-with-remote-undo buffer
23220 (with-current-buffer buffer
23221 (widen)
23222 (goto-char pos)
23223 (save-excursion
23224 (org-show-context 'agenda))
23225 (save-excursion
23226 (and (outline-next-heading)
23227 (org-flag-heading nil))) ; show the next heading
23228 (goto-char pos)
23229 (call-interactively 'org-set-tags)
23230 (end-of-line 1)
23231 (setq newhead (org-get-heading)))
23232 (org-agenda-change-all-lines newhead hdmarker)
23233 (beginning-of-line 1)))))
23235 (defun org-agenda-toggle-archive-tag ()
23236 "Toggle the archive tag for the current entry."
23237 (interactive)
23238 (org-agenda-check-no-diary)
23239 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23240 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23241 (org-agenda-error)))
23242 (buffer (marker-buffer hdmarker))
23243 (pos (marker-position hdmarker))
23244 (inhibit-read-only t)
23245 newhead)
23246 (org-with-remote-undo buffer
23247 (with-current-buffer buffer
23248 (widen)
23249 (goto-char pos)
23250 (org-show-context 'agenda)
23251 (save-excursion
23252 (and (outline-next-heading)
23253 (org-flag-heading nil))) ; show the next heading
23254 (call-interactively 'org-toggle-archive-tag)
23255 (end-of-line 1)
23256 (setq newhead (org-get-heading)))
23257 (org-agenda-change-all-lines newhead hdmarker)
23258 (beginning-of-line 1))))
23260 (defun org-agenda-date-later (arg &optional what)
23261 "Change the date of this item to one day later."
23262 (interactive "p")
23263 (org-agenda-check-type t 'agenda 'timeline)
23264 (org-agenda-check-no-diary)
23265 (let* ((marker (or (get-text-property (point) 'org-marker)
23266 (org-agenda-error)))
23267 (buffer (marker-buffer marker))
23268 (pos (marker-position marker)))
23269 (org-with-remote-undo buffer
23270 (with-current-buffer buffer
23271 (widen)
23272 (goto-char pos)
23273 (if (not (org-at-timestamp-p))
23274 (error "Cannot find time stamp"))
23275 (org-timestamp-change arg (or what 'day)))
23276 (org-agenda-show-new-time marker org-last-changed-timestamp))
23277 (message "Time stamp changed to %s" org-last-changed-timestamp)))
23279 (defun org-agenda-date-earlier (arg &optional what)
23280 "Change the date of this item to one day earlier."
23281 (interactive "p")
23282 (org-agenda-date-later (- arg) what))
23284 (defun org-agenda-show-new-time (marker stamp &optional prefix)
23285 "Show new date stamp via text properties."
23286 ;; We use text properties to make this undoable
23287 (let ((inhibit-read-only t))
23288 (setq stamp (concat " " prefix " => " stamp))
23289 (save-excursion
23290 (goto-char (point-max))
23291 (while (not (bobp))
23292 (when (equal marker (get-text-property (point) 'org-marker))
23293 (move-to-column (- (window-width) (length stamp)) t)
23294 (if (featurep 'xemacs)
23295 ;; Use `duplicable' property to trigger undo recording
23296 (let ((ex (make-extent nil nil))
23297 (gl (make-glyph stamp)))
23298 (set-glyph-face gl 'secondary-selection)
23299 (set-extent-properties
23300 ex (list 'invisible t 'end-glyph gl 'duplicable t))
23301 (insert-extent ex (1- (point)) (point-at-eol)))
23302 (add-text-properties
23303 (1- (point)) (point-at-eol)
23304 (list 'display (org-add-props stamp nil
23305 'face 'secondary-selection))))
23306 (beginning-of-line 1))
23307 (beginning-of-line 0)))))
23309 (defun org-agenda-date-prompt (arg)
23310 "Change the date of this item. Date is prompted for, with default today.
23311 The prefix ARG is passed to the `org-time-stamp' command and can therefore
23312 be used to request time specification in the time stamp."
23313 (interactive "P")
23314 (org-agenda-check-type t 'agenda 'timeline)
23315 (org-agenda-check-no-diary)
23316 (let* ((marker (or (get-text-property (point) 'org-marker)
23317 (org-agenda-error)))
23318 (buffer (marker-buffer marker))
23319 (pos (marker-position marker)))
23320 (org-with-remote-undo buffer
23321 (with-current-buffer buffer
23322 (widen)
23323 (goto-char pos)
23324 (if (not (org-at-timestamp-p))
23325 (error "Cannot find time stamp"))
23326 (org-time-stamp arg)
23327 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
23329 (defun org-agenda-schedule (arg)
23330 "Schedule the item at point."
23331 (interactive "P")
23332 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags 'search)
23333 (org-agenda-check-no-diary)
23334 (let* ((marker (or (get-text-property (point) 'org-marker)
23335 (org-agenda-error)))
23336 (type (marker-insertion-type marker))
23337 (buffer (marker-buffer marker))
23338 (pos (marker-position marker))
23339 (org-insert-labeled-timestamps-at-point nil)
23341 (when type (message "%s" type) (sit-for 3))
23342 (set-marker-insertion-type marker t)
23343 (org-with-remote-undo buffer
23344 (with-current-buffer buffer
23345 (widen)
23346 (goto-char pos)
23347 (setq ts (org-schedule arg)))
23348 (org-agenda-show-new-time marker ts "S"))
23349 (message "Item scheduled for %s" ts)))
23351 (defun org-agenda-deadline (arg)
23352 "Schedule the item at point."
23353 (interactive "P")
23354 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags 'search)
23355 (org-agenda-check-no-diary)
23356 (let* ((marker (or (get-text-property (point) 'org-marker)
23357 (org-agenda-error)))
23358 (buffer (marker-buffer marker))
23359 (pos (marker-position marker))
23360 (org-insert-labeled-timestamps-at-point nil)
23362 (org-with-remote-undo buffer
23363 (with-current-buffer buffer
23364 (widen)
23365 (goto-char pos)
23366 (setq ts (org-deadline arg)))
23367 (org-agenda-show-new-time marker ts "S"))
23368 (message "Deadline for this item set to %s" ts)))
23370 (defun org-get-heading (&optional no-tags)
23371 "Return the heading of the current entry, without the stars."
23372 (save-excursion
23373 (org-back-to-heading t)
23374 (if (looking-at
23375 (if no-tags
23376 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
23377 "\\*+[ \t]+\\([^\r\n]*\\)"))
23378 (match-string 1) "")))
23380 (defun org-agenda-clock-in (&optional arg)
23381 "Start the clock on the currently selected item."
23382 (interactive "P")
23383 (org-agenda-check-no-diary)
23384 (let* ((marker (or (get-text-property (point) 'org-marker)
23385 (org-agenda-error)))
23386 (pos (marker-position marker)))
23387 (org-with-remote-undo (marker-buffer marker)
23388 (with-current-buffer (marker-buffer marker)
23389 (widen)
23390 (goto-char pos)
23391 (org-clock-in)))))
23393 (defun org-agenda-clock-out (&optional arg)
23394 "Stop the currently running clock."
23395 (interactive "P")
23396 (unless (marker-buffer org-clock-marker)
23397 (error "No running clock"))
23398 (org-with-remote-undo (marker-buffer org-clock-marker)
23399 (org-clock-out)))
23401 (defun org-agenda-clock-cancel (&optional arg)
23402 "Cancel the currently running clock."
23403 (interactive "P")
23404 (unless (marker-buffer org-clock-marker)
23405 (error "No running clock"))
23406 (org-with-remote-undo (marker-buffer org-clock-marker)
23407 (org-clock-cancel)))
23409 (defun org-agenda-diary-entry ()
23410 "Make a diary entry, like the `i' command from the calendar.
23411 All the standard commands work: block, weekly etc."
23412 (interactive)
23413 (org-agenda-check-type t 'agenda 'timeline)
23414 (require 'diary-lib)
23415 (let* ((char (progn
23416 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
23417 (read-char-exclusive)))
23418 (cmd (cdr (assoc char
23419 '((?d . insert-diary-entry)
23420 (?w . insert-weekly-diary-entry)
23421 (?m . insert-monthly-diary-entry)
23422 (?y . insert-yearly-diary-entry)
23423 (?a . insert-anniversary-diary-entry)
23424 (?b . insert-block-diary-entry)
23425 (?c . insert-cyclic-diary-entry)))))
23426 (oldf (symbol-function 'calendar-cursor-to-date))
23427 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
23428 (point (point))
23429 (mark (or (mark t) (point))))
23430 (unless cmd
23431 (error "No command associated with <%c>" char))
23432 (unless (and (get-text-property point 'day)
23433 (or (not (equal ?b char))
23434 (get-text-property mark 'day)))
23435 (error "Don't know which date to use for diary entry"))
23436 ;; We implement this by hacking the `calendar-cursor-to-date' function
23437 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
23438 (let ((calendar-mark-ring
23439 (list (calendar-gregorian-from-absolute
23440 (or (get-text-property mark 'day)
23441 (get-text-property point 'day))))))
23442 (unwind-protect
23443 (progn
23444 (fset 'calendar-cursor-to-date
23445 (lambda (&optional error)
23446 (calendar-gregorian-from-absolute
23447 (get-text-property point 'day))))
23448 (call-interactively cmd))
23449 (fset 'calendar-cursor-to-date oldf)))))
23452 (defun org-agenda-execute-calendar-command (cmd)
23453 "Execute a calendar command from the agenda, with the date associated to
23454 the cursor position."
23455 (org-agenda-check-type t 'agenda 'timeline)
23456 (require 'diary-lib)
23457 (unless (get-text-property (point) 'day)
23458 (error "Don't know which date to use for calendar command"))
23459 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
23460 (point (point))
23461 (date (calendar-gregorian-from-absolute
23462 (get-text-property point 'day)))
23463 ;; the following 3 vars are needed in the calendar
23464 (displayed-day (extract-calendar-day date))
23465 (displayed-month (extract-calendar-month date))
23466 (displayed-year (extract-calendar-year date)))
23467 (unwind-protect
23468 (progn
23469 (fset 'calendar-cursor-to-date
23470 (lambda (&optional error)
23471 (calendar-gregorian-from-absolute
23472 (get-text-property point 'day))))
23473 (call-interactively cmd))
23474 (fset 'calendar-cursor-to-date oldf))))
23476 (defun org-agenda-phases-of-moon ()
23477 "Display the phases of the moon for the 3 months around the cursor date."
23478 (interactive)
23479 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23481 (defun org-agenda-holidays ()
23482 "Display the holidays for the 3 months around the cursor date."
23483 (interactive)
23484 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23486 (defvar calendar-longitude)
23487 (defvar calendar-latitude)
23488 (defvar calendar-location-name)
23490 (defun org-agenda-sunrise-sunset (arg)
23491 "Display sunrise and sunset for the cursor date.
23492 Latitude and longitude can be specified with the variables
23493 `calendar-latitude' and `calendar-longitude'. When called with prefix
23494 argument, latitude and longitude will be prompted for."
23495 (interactive "P")
23496 (require 'solar)
23497 (let ((calendar-longitude (if arg nil calendar-longitude))
23498 (calendar-latitude (if arg nil calendar-latitude))
23499 (calendar-location-name
23500 (if arg "the given coordinates" calendar-location-name)))
23501 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23503 (defun org-agenda-goto-calendar ()
23504 "Open the Emacs calendar with the date at the cursor."
23505 (interactive)
23506 (org-agenda-check-type t 'agenda 'timeline)
23507 (let* ((day (or (get-text-property (point) 'day)
23508 (error "Don't know which date to open in calendar")))
23509 (date (calendar-gregorian-from-absolute day))
23510 (calendar-move-hook nil)
23511 (view-calendar-holidays-initially nil)
23512 (view-diary-entries-initially nil))
23513 (calendar)
23514 (calendar-goto-date date)))
23516 (defun org-calendar-goto-agenda ()
23517 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23518 This is a command that has to be installed in `calendar-mode-map'."
23519 (interactive)
23520 (org-agenda-list nil (calendar-absolute-from-gregorian
23521 (calendar-cursor-to-date))
23522 nil))
23524 (defun org-agenda-convert-date ()
23525 (interactive)
23526 (org-agenda-check-type t 'agenda 'timeline)
23527 (let ((day (get-text-property (point) 'day))
23528 date s)
23529 (unless day
23530 (error "Don't know which date to convert"))
23531 (setq date (calendar-gregorian-from-absolute day))
23532 (setq s (concat
23533 "Gregorian: " (calendar-date-string date) "\n"
23534 "ISO: " (calendar-iso-date-string date) "\n"
23535 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23536 "Julian: " (calendar-julian-date-string date) "\n"
23537 "Astron. JD: " (calendar-astro-date-string date)
23538 " (Julian date number at noon UTC)\n"
23539 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23540 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23541 "French: " (calendar-french-date-string date) "\n"
23542 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23543 "Mayan: " (calendar-mayan-date-string date) "\n"
23544 "Coptic: " (calendar-coptic-date-string date) "\n"
23545 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23546 "Persian: " (calendar-persian-date-string date) "\n"
23547 "Chinese: " (calendar-chinese-date-string date) "\n"))
23548 (with-output-to-temp-buffer "*Dates*"
23549 (princ s))
23550 (if (fboundp 'fit-window-to-buffer)
23551 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23554 ;;;; Embedded LaTeX
23556 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23557 "Keymap for the minor `org-cdlatex-mode'.")
23559 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23560 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23561 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23562 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23563 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23565 (defvar org-cdlatex-texmathp-advice-is-done nil
23566 "Flag remembering if we have applied the advice to texmathp already.")
23568 (define-minor-mode org-cdlatex-mode
23569 "Toggle the minor `org-cdlatex-mode'.
23570 This mode supports entering LaTeX environment and math in LaTeX fragments
23571 in Org-mode.
23572 \\{org-cdlatex-mode-map}"
23573 nil " OCDL" nil
23574 (when org-cdlatex-mode (require 'cdlatex))
23575 (unless org-cdlatex-texmathp-advice-is-done
23576 (setq org-cdlatex-texmathp-advice-is-done t)
23577 (defadvice texmathp (around org-math-always-on activate)
23578 "Always return t in org-mode buffers.
23579 This is because we want to insert math symbols without dollars even outside
23580 the LaTeX math segments. If Orgmode thinks that point is actually inside
23581 en embedded LaTeX fragement, let texmathp do its job.
23582 \\[org-cdlatex-mode-map]"
23583 (interactive)
23584 (let (p)
23585 (cond
23586 ((not (org-mode-p)) ad-do-it)
23587 ((eq this-command 'cdlatex-math-symbol)
23588 (setq ad-return-value t
23589 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23591 (let ((p (org-inside-LaTeX-fragment-p)))
23592 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23593 (setq ad-return-value t
23594 texmathp-why '("Org-mode embedded math" . 0))
23595 (if p ad-do-it)))))))))
23597 (defun turn-on-org-cdlatex ()
23598 "Unconditionally turn on `org-cdlatex-mode'."
23599 (org-cdlatex-mode 1))
23601 (defun org-inside-LaTeX-fragment-p ()
23602 "Test if point is inside a LaTeX fragment.
23603 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23604 sequence appearing also before point.
23605 Even though the matchers for math are configurable, this function assumes
23606 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23607 delimiters are skipped when they have been removed by customization.
23608 The return value is nil, or a cons cell with the delimiter and
23609 and the position of this delimiter.
23611 This function does a reasonably good job, but can locally be fooled by
23612 for example currency specifications. For example it will assume being in
23613 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23614 fragments that are properly closed, but during editing, we have to live
23615 with the uncertainty caused by missing closing delimiters. This function
23616 looks only before point, not after."
23617 (catch 'exit
23618 (let ((pos (point))
23619 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23620 (lim (progn
23621 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23622 (point)))
23623 dd-on str (start 0) m re)
23624 (goto-char pos)
23625 (when dodollar
23626 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23627 re (nth 1 (assoc "$" org-latex-regexps)))
23628 (while (string-match re str start)
23629 (cond
23630 ((= (match-end 0) (length str))
23631 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23632 ((= (match-end 0) (- (length str) 5))
23633 (throw 'exit nil))
23634 (t (setq start (match-end 0))))))
23635 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23636 (goto-char pos)
23637 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23638 (and (match-beginning 2) (throw 'exit nil))
23639 ;; count $$
23640 (while (re-search-backward "\\$\\$" lim t)
23641 (setq dd-on (not dd-on)))
23642 (goto-char pos)
23643 (if dd-on (cons "$$" m))))))
23646 (defun org-try-cdlatex-tab ()
23647 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23648 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23649 - inside a LaTeX fragment, or
23650 - after the first word in a line, where an abbreviation expansion could
23651 insert a LaTeX environment."
23652 (when org-cdlatex-mode
23653 (cond
23654 ((save-excursion
23655 (skip-chars-backward "a-zA-Z0-9*")
23656 (skip-chars-backward " \t")
23657 (bolp))
23658 (cdlatex-tab) t)
23659 ((org-inside-LaTeX-fragment-p)
23660 (cdlatex-tab) t)
23661 (t nil))))
23663 (defun org-cdlatex-underscore-caret (&optional arg)
23664 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23665 Revert to the normal definition outside of these fragments."
23666 (interactive "P")
23667 (if (org-inside-LaTeX-fragment-p)
23668 (call-interactively 'cdlatex-sub-superscript)
23669 (let (org-cdlatex-mode)
23670 (call-interactively (key-binding (vector last-input-event))))))
23672 (defun org-cdlatex-math-modify (&optional arg)
23673 "Execute `cdlatex-math-modify' in LaTeX fragments.
23674 Revert to the normal definition outside of these fragments."
23675 (interactive "P")
23676 (if (org-inside-LaTeX-fragment-p)
23677 (call-interactively 'cdlatex-math-modify)
23678 (let (org-cdlatex-mode)
23679 (call-interactively (key-binding (vector last-input-event))))))
23681 (defvar org-latex-fragment-image-overlays nil
23682 "List of overlays carrying the images of latex fragments.")
23683 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23685 (defun org-remove-latex-fragment-image-overlays ()
23686 "Remove all overlays with LaTeX fragment images in current buffer."
23687 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23688 (setq org-latex-fragment-image-overlays nil))
23690 (defun org-preview-latex-fragment (&optional subtree)
23691 "Preview the LaTeX fragment at point, or all locally or globally.
23692 If the cursor is in a LaTeX fragment, create the image and overlay
23693 it over the source code. If there is no fragment at point, display
23694 all fragments in the current text, from one headline to the next. With
23695 prefix SUBTREE, display all fragments in the current subtree. With a
23696 double prefix `C-u C-u', or when the cursor is before the first headline,
23697 display all fragments in the buffer.
23698 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23699 (interactive "P")
23700 (org-remove-latex-fragment-image-overlays)
23701 (save-excursion
23702 (save-restriction
23703 (let (beg end at msg)
23704 (cond
23705 ((or (equal subtree '(16))
23706 (not (save-excursion
23707 (re-search-backward (concat "^" outline-regexp) nil t))))
23708 (setq beg (point-min) end (point-max)
23709 msg "Creating images for buffer...%s"))
23710 ((equal subtree '(4))
23711 (org-back-to-heading)
23712 (setq beg (point) end (org-end-of-subtree t)
23713 msg "Creating images for subtree...%s"))
23715 (if (setq at (org-inside-LaTeX-fragment-p))
23716 (goto-char (max (point-min) (- (cdr at) 2)))
23717 (org-back-to-heading))
23718 (setq beg (point) end (progn (outline-next-heading) (point))
23719 msg (if at "Creating image...%s"
23720 "Creating images for entry...%s"))))
23721 (message msg "")
23722 (narrow-to-region beg end)
23723 (goto-char beg)
23724 (org-format-latex
23725 (concat "ltxpng/" (file-name-sans-extension
23726 (file-name-nondirectory
23727 buffer-file-name)))
23728 default-directory 'overlays msg at 'forbuffer)
23729 (message msg "done. Use `C-c C-c' to remove images.")))))
23731 (defvar org-latex-regexps
23732 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23733 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23734 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23735 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23736 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23737 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23738 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23739 "Regular expressions for matching embedded LaTeX.")
23741 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23742 "Replace LaTeX fragments with links to an image, and produce images."
23743 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23744 (let* ((prefixnodir (file-name-nondirectory prefix))
23745 (absprefix (expand-file-name prefix dir))
23746 (todir (file-name-directory absprefix))
23747 (opt org-format-latex-options)
23748 (matchers (plist-get opt :matchers))
23749 (re-list org-latex-regexps)
23750 (cnt 0) txt link beg end re e checkdir
23751 m n block linkfile movefile ov)
23752 ;; Check if there are old images files with this prefix, and remove them
23753 (when (file-directory-p todir)
23754 (mapc 'delete-file
23755 (directory-files
23756 todir 'full
23757 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23758 ;; Check the different regular expressions
23759 (while (setq e (pop re-list))
23760 (setq m (car e) re (nth 1 e) n (nth 2 e)
23761 block (if (nth 3 e) "\n\n" ""))
23762 (when (member m matchers)
23763 (goto-char (point-min))
23764 (while (re-search-forward re nil t)
23765 (when (or (not at) (equal (cdr at) (match-beginning n)))
23766 (setq txt (match-string n)
23767 beg (match-beginning n) end (match-end n)
23768 cnt (1+ cnt)
23769 linkfile (format "%s_%04d.png" prefix cnt)
23770 movefile (format "%s_%04d.png" absprefix cnt)
23771 link (concat block "[[file:" linkfile "]]" block))
23772 (if msg (message msg cnt))
23773 (goto-char beg)
23774 (unless checkdir ; make sure the directory exists
23775 (setq checkdir t)
23776 (or (file-directory-p todir) (make-directory todir)))
23777 (org-create-formula-image
23778 txt movefile opt forbuffer)
23779 (if overlays
23780 (progn
23781 (setq ov (org-make-overlay beg end))
23782 (if (featurep 'xemacs)
23783 (progn
23784 (org-overlay-put ov 'invisible t)
23785 (org-overlay-put
23786 ov 'end-glyph
23787 (make-glyph (vector 'png :file movefile))))
23788 (org-overlay-put
23789 ov 'display
23790 (list 'image :type 'png :file movefile :ascent 'center)))
23791 (push ov org-latex-fragment-image-overlays)
23792 (goto-char end))
23793 (delete-region beg end)
23794 (insert link))))))))
23796 ;; This function borrows from Ganesh Swami's latex2png.el
23797 (defun org-create-formula-image (string tofile options buffer)
23798 (let* ((tmpdir (if (featurep 'xemacs)
23799 (temp-directory)
23800 temporary-file-directory))
23801 (texfilebase (make-temp-name
23802 (expand-file-name "orgtex" tmpdir)))
23803 (texfile (concat texfilebase ".tex"))
23804 (dvifile (concat texfilebase ".dvi"))
23805 (pngfile (concat texfilebase ".png"))
23806 (fnh (face-attribute 'default :height nil))
23807 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23808 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23809 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23810 "Black"))
23811 (bg (or (plist-get options (if buffer :background :html-background))
23812 "Transparent")))
23813 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23814 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23815 (with-temp-file texfile
23816 (insert org-format-latex-header
23817 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23818 (let ((dir default-directory))
23819 (condition-case nil
23820 (progn
23821 (cd tmpdir)
23822 (call-process "latex" nil nil nil texfile))
23823 (error nil))
23824 (cd dir))
23825 (if (not (file-exists-p dvifile))
23826 (progn (message "Failed to create dvi file from %s" texfile) nil)
23827 (call-process "dvipng" nil nil nil
23828 "-E" "-fg" fg "-bg" bg
23829 "-D" dpi
23830 ;;"-x" scale "-y" scale
23831 "-T" "tight"
23832 "-o" pngfile
23833 dvifile)
23834 (if (not (file-exists-p pngfile))
23835 (progn (message "Failed to create png file from %s" texfile) nil)
23836 ;; Use the requested file name and clean up
23837 (copy-file pngfile tofile 'replace)
23838 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23839 (delete-file (concat texfilebase e)))
23840 pngfile))))
23842 (defun org-dvipng-color (attr)
23843 "Return an rgb color specification for dvipng."
23844 (apply 'format "rgb %s %s %s"
23845 (mapcar 'org-normalize-color
23846 (color-values (face-attribute 'default attr nil)))))
23848 (defun org-normalize-color (value)
23849 "Return string to be used as color value for an RGB component."
23850 (format "%g" (/ value 65535.0)))
23852 ;;;; Exporting
23854 ;;; Variables, constants, and parameter plists
23856 (defconst org-level-max 20)
23858 (defvar org-export-html-preamble nil
23859 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23860 (defvar org-export-html-postamble nil
23861 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23862 (defvar org-export-html-auto-preamble t
23863 "Should default preamble be inserted? Set by publishing functions.")
23864 (defvar org-export-html-auto-postamble t
23865 "Should default postamble be inserted? Set by publishing functions.")
23866 (defvar org-current-export-file nil) ; dynamically scoped parameter
23867 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23870 (defconst org-export-plist-vars
23871 '((:language . org-export-default-language)
23872 (:customtime . org-display-custom-times)
23873 (:headline-levels . org-export-headline-levels)
23874 (:section-numbers . org-export-with-section-numbers)
23875 (:table-of-contents . org-export-with-toc)
23876 (:preserve-breaks . org-export-preserve-breaks)
23877 (:archived-trees . org-export-with-archived-trees)
23878 (:emphasize . org-export-with-emphasize)
23879 (:sub-superscript . org-export-with-sub-superscripts)
23880 (:special-strings . org-export-with-special-strings)
23881 (:footnotes . org-export-with-footnotes)
23882 (:drawers . org-export-with-drawers)
23883 (:tags . org-export-with-tags)
23884 (:TeX-macros . org-export-with-TeX-macros)
23885 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23886 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23887 (:fixed-width . org-export-with-fixed-width)
23888 (:timestamps . org-export-with-timestamps)
23889 (:author-info . org-export-author-info)
23890 (:time-stamp-file . org-export-time-stamp-file)
23891 (:tables . org-export-with-tables)
23892 (:table-auto-headline . org-export-highlight-first-table-line)
23893 (:style . org-export-html-style)
23894 (:agenda-style . org-agenda-export-html-style)
23895 (:convert-org-links . org-export-html-link-org-files-as-html)
23896 (:inline-images . org-export-html-inline-images)
23897 (:html-extension . org-export-html-extension)
23898 (:html-table-tag . org-export-html-table-tag)
23899 (:expand-quoted-html . org-export-html-expand)
23900 (:timestamp . org-export-html-with-timestamp)
23901 (:publishing-directory . org-export-publishing-directory)
23902 (:preamble . org-export-html-preamble)
23903 (:postamble . org-export-html-postamble)
23904 (:auto-preamble . org-export-html-auto-preamble)
23905 (:auto-postamble . org-export-html-auto-postamble)
23906 (:author . user-full-name)
23907 (:email . user-mail-address)))
23909 (defun org-default-export-plist ()
23910 "Return the property list with default settings for the export variables."
23911 (let ((l org-export-plist-vars) rtn e)
23912 (while (setq e (pop l))
23913 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23914 rtn))
23916 (defun org-infile-export-plist ()
23917 "Return the property list with file-local settings for export."
23918 (save-excursion
23919 (save-restriction
23920 (widen)
23921 (goto-char 0)
23922 (let ((re (org-make-options-regexp
23923 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23924 p key val text options)
23925 (while (re-search-forward re nil t)
23926 (setq key (org-match-string-no-properties 1)
23927 val (org-match-string-no-properties 2))
23928 (cond
23929 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23930 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23931 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23932 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23933 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23934 ((string-equal key "TEXT")
23935 (setq text (if text (concat text "\n" val) val)))
23936 ((string-equal key "OPTIONS") (setq options val))))
23937 (setq p (plist-put p :text text))
23938 (when options
23939 (let ((op '(("H" . :headline-levels)
23940 ("num" . :section-numbers)
23941 ("toc" . :table-of-contents)
23942 ("\\n" . :preserve-breaks)
23943 ("@" . :expand-quoted-html)
23944 (":" . :fixed-width)
23945 ("|" . :tables)
23946 ("^" . :sub-superscript)
23947 ("-" . :special-strings)
23948 ("f" . :footnotes)
23949 ("d" . :drawers)
23950 ("tags" . :tags)
23951 ("*" . :emphasize)
23952 ("TeX" . :TeX-macros)
23953 ("LaTeX" . :LaTeX-fragments)
23954 ("skip" . :skip-before-1st-heading)
23955 ("author" . :author-info)
23956 ("timestamp" . :time-stamp-file)))
23958 (while (setq o (pop op))
23959 (if (string-match (concat (regexp-quote (car o))
23960 ":\\([^ \t\n\r;,.]*\\)")
23961 options)
23962 (setq p (plist-put p (cdr o)
23963 (car (read-from-string
23964 (match-string 1 options)))))))))
23965 p))))
23967 (defun org-export-directory (type plist)
23968 (let* ((val (plist-get plist :publishing-directory))
23969 (dir (if (listp val)
23970 (or (cdr (assoc type val)) ".")
23971 val)))
23972 dir))
23974 (defun org-skip-comments (lines)
23975 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23976 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23977 (re2 "^\\(\\*+\\)[ \t\n\r]")
23978 (case-fold-search nil)
23979 rtn line level)
23980 (while (setq line (pop lines))
23981 (cond
23982 ((and (string-match re1 line)
23983 (setq level (- (match-end 1) (match-beginning 1))))
23984 ;; Beginning of a COMMENT subtree. Skip it.
23985 (while (and (setq line (pop lines))
23986 (or (not (string-match re2 line))
23987 (> (- (match-end 1) (match-beginning 1)) level))))
23988 (setq lines (cons line lines)))
23989 ((string-match "^#" line)
23990 ;; an ordinary comment line
23992 ((and org-export-table-remove-special-lines
23993 (string-match "^[ \t]*|" line)
23994 (or (string-match "^[ \t]*| *[!_^] *|" line)
23995 (and (string-match "| *<[0-9]+> *|" line)
23996 (not (string-match "| *[^ <|]" line)))))
23997 ;; a special table line that should be removed
23999 (t (setq rtn (cons line rtn)))))
24000 (nreverse rtn)))
24002 (defun org-export (&optional arg)
24003 (interactive)
24004 (let ((help "[t] insert the export option template
24005 \[v] limit export to visible part of outline tree
24007 \[a] export as ASCII
24009 \[h] export as HTML
24010 \[H] export as HTML to temporary buffer
24011 \[R] export region as HTML
24012 \[b] export as HTML and browse immediately
24013 \[x] export as XOXO
24015 \[l] export as LaTeX
24016 \[L] export as LaTeX to temporary buffer
24018 \[i] export current file as iCalendar file
24019 \[I] export all agenda files as iCalendar files
24020 \[c] export agenda files into combined iCalendar file
24022 \[F] publish current file
24023 \[P] publish current project
24024 \[X] publish... (project will be prompted for)
24025 \[A] publish all projects")
24026 (cmds
24027 '((?t . org-insert-export-options-template)
24028 (?v . org-export-visible)
24029 (?a . org-export-as-ascii)
24030 (?h . org-export-as-html)
24031 (?b . org-export-as-html-and-open)
24032 (?H . org-export-as-html-to-buffer)
24033 (?R . org-export-region-as-html)
24034 (?x . org-export-as-xoxo)
24035 (?l . org-export-as-latex)
24036 (?L . org-export-as-latex-to-buffer)
24037 (?i . org-export-icalendar-this-file)
24038 (?I . org-export-icalendar-all-agenda-files)
24039 (?c . org-export-icalendar-combine-agenda-files)
24040 (?F . org-publish-current-file)
24041 (?P . org-publish-current-project)
24042 (?X . org-publish)
24043 (?A . org-publish-all)))
24044 r1 r2 ass)
24045 (save-window-excursion
24046 (delete-other-windows)
24047 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
24048 (princ help))
24049 (message "Select command: ")
24050 (setq r1 (read-char-exclusive)))
24051 (setq r2 (if (< r1 27) (+ r1 96) r1))
24052 (if (setq ass (assq r2 cmds))
24053 (call-interactively (cdr ass))
24054 (error "No command associated with key %c" r1))))
24056 (defconst org-html-entities
24057 '(("nbsp")
24058 ("iexcl")
24059 ("cent")
24060 ("pound")
24061 ("curren")
24062 ("yen")
24063 ("brvbar")
24064 ("vert" . "&#124;")
24065 ("sect")
24066 ("uml")
24067 ("copy")
24068 ("ordf")
24069 ("laquo")
24070 ("not")
24071 ("shy")
24072 ("reg")
24073 ("macr")
24074 ("deg")
24075 ("plusmn")
24076 ("sup2")
24077 ("sup3")
24078 ("acute")
24079 ("micro")
24080 ("para")
24081 ("middot")
24082 ("odot"."o")
24083 ("star"."*")
24084 ("cedil")
24085 ("sup1")
24086 ("ordm")
24087 ("raquo")
24088 ("frac14")
24089 ("frac12")
24090 ("frac34")
24091 ("iquest")
24092 ("Agrave")
24093 ("Aacute")
24094 ("Acirc")
24095 ("Atilde")
24096 ("Auml")
24097 ("Aring") ("AA"."&Aring;")
24098 ("AElig")
24099 ("Ccedil")
24100 ("Egrave")
24101 ("Eacute")
24102 ("Ecirc")
24103 ("Euml")
24104 ("Igrave")
24105 ("Iacute")
24106 ("Icirc")
24107 ("Iuml")
24108 ("ETH")
24109 ("Ntilde")
24110 ("Ograve")
24111 ("Oacute")
24112 ("Ocirc")
24113 ("Otilde")
24114 ("Ouml")
24115 ("times")
24116 ("Oslash")
24117 ("Ugrave")
24118 ("Uacute")
24119 ("Ucirc")
24120 ("Uuml")
24121 ("Yacute")
24122 ("THORN")
24123 ("szlig")
24124 ("agrave")
24125 ("aacute")
24126 ("acirc")
24127 ("atilde")
24128 ("auml")
24129 ("aring")
24130 ("aelig")
24131 ("ccedil")
24132 ("egrave")
24133 ("eacute")
24134 ("ecirc")
24135 ("euml")
24136 ("igrave")
24137 ("iacute")
24138 ("icirc")
24139 ("iuml")
24140 ("eth")
24141 ("ntilde")
24142 ("ograve")
24143 ("oacute")
24144 ("ocirc")
24145 ("otilde")
24146 ("ouml")
24147 ("divide")
24148 ("oslash")
24149 ("ugrave")
24150 ("uacute")
24151 ("ucirc")
24152 ("uuml")
24153 ("yacute")
24154 ("thorn")
24155 ("yuml")
24156 ("fnof")
24157 ("Alpha")
24158 ("Beta")
24159 ("Gamma")
24160 ("Delta")
24161 ("Epsilon")
24162 ("Zeta")
24163 ("Eta")
24164 ("Theta")
24165 ("Iota")
24166 ("Kappa")
24167 ("Lambda")
24168 ("Mu")
24169 ("Nu")
24170 ("Xi")
24171 ("Omicron")
24172 ("Pi")
24173 ("Rho")
24174 ("Sigma")
24175 ("Tau")
24176 ("Upsilon")
24177 ("Phi")
24178 ("Chi")
24179 ("Psi")
24180 ("Omega")
24181 ("alpha")
24182 ("beta")
24183 ("gamma")
24184 ("delta")
24185 ("epsilon")
24186 ("varepsilon"."&epsilon;")
24187 ("zeta")
24188 ("eta")
24189 ("theta")
24190 ("iota")
24191 ("kappa")
24192 ("lambda")
24193 ("mu")
24194 ("nu")
24195 ("xi")
24196 ("omicron")
24197 ("pi")
24198 ("rho")
24199 ("sigmaf") ("varsigma"."&sigmaf;")
24200 ("sigma")
24201 ("tau")
24202 ("upsilon")
24203 ("phi")
24204 ("chi")
24205 ("psi")
24206 ("omega")
24207 ("thetasym") ("vartheta"."&thetasym;")
24208 ("upsih")
24209 ("piv")
24210 ("bull") ("bullet"."&bull;")
24211 ("hellip") ("dots"."&hellip;")
24212 ("prime")
24213 ("Prime")
24214 ("oline")
24215 ("frasl")
24216 ("weierp")
24217 ("image")
24218 ("real")
24219 ("trade")
24220 ("alefsym")
24221 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
24222 ("uarr") ("uparrow"."&uarr;")
24223 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
24224 ("darr")("downarrow"."&darr;")
24225 ("harr") ("leftrightarrow"."&harr;")
24226 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
24227 ("lArr") ("Leftarrow"."&lArr;")
24228 ("uArr") ("Uparrow"."&uArr;")
24229 ("rArr") ("Rightarrow"."&rArr;")
24230 ("dArr") ("Downarrow"."&dArr;")
24231 ("hArr") ("Leftrightarrow"."&hArr;")
24232 ("forall")
24233 ("part") ("partial"."&part;")
24234 ("exist") ("exists"."&exist;")
24235 ("empty") ("emptyset"."&empty;")
24236 ("nabla")
24237 ("isin") ("in"."&isin;")
24238 ("notin")
24239 ("ni")
24240 ("prod")
24241 ("sum")
24242 ("minus")
24243 ("lowast") ("ast"."&lowast;")
24244 ("radic")
24245 ("prop") ("proptp"."&prop;")
24246 ("infin") ("infty"."&infin;")
24247 ("ang") ("angle"."&ang;")
24248 ("and") ("wedge"."&and;")
24249 ("or") ("vee"."&or;")
24250 ("cap")
24251 ("cup")
24252 ("int")
24253 ("there4")
24254 ("sim")
24255 ("cong") ("simeq"."&cong;")
24256 ("asymp")("approx"."&asymp;")
24257 ("ne") ("neq"."&ne;")
24258 ("equiv")
24259 ("le")
24260 ("ge")
24261 ("sub") ("subset"."&sub;")
24262 ("sup") ("supset"."&sup;")
24263 ("nsub")
24264 ("sube")
24265 ("supe")
24266 ("oplus")
24267 ("otimes")
24268 ("perp")
24269 ("sdot") ("cdot"."&sdot;")
24270 ("lceil")
24271 ("rceil")
24272 ("lfloor")
24273 ("rfloor")
24274 ("lang")
24275 ("rang")
24276 ("loz") ("Diamond"."&loz;")
24277 ("spades") ("spadesuit"."&spades;")
24278 ("clubs") ("clubsuit"."&clubs;")
24279 ("hearts") ("diamondsuit"."&hearts;")
24280 ("diams") ("diamondsuit"."&diams;")
24281 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
24282 ("quot")
24283 ("amp")
24284 ("lt")
24285 ("gt")
24286 ("OElig")
24287 ("oelig")
24288 ("Scaron")
24289 ("scaron")
24290 ("Yuml")
24291 ("circ")
24292 ("tilde")
24293 ("ensp")
24294 ("emsp")
24295 ("thinsp")
24296 ("zwnj")
24297 ("zwj")
24298 ("lrm")
24299 ("rlm")
24300 ("ndash")
24301 ("mdash")
24302 ("lsquo")
24303 ("rsquo")
24304 ("sbquo")
24305 ("ldquo")
24306 ("rdquo")
24307 ("bdquo")
24308 ("dagger")
24309 ("Dagger")
24310 ("permil")
24311 ("lsaquo")
24312 ("rsaquo")
24313 ("euro")
24315 ("arccos"."arccos")
24316 ("arcsin"."arcsin")
24317 ("arctan"."arctan")
24318 ("arg"."arg")
24319 ("cos"."cos")
24320 ("cosh"."cosh")
24321 ("cot"."cot")
24322 ("coth"."coth")
24323 ("csc"."csc")
24324 ("deg"."deg")
24325 ("det"."det")
24326 ("dim"."dim")
24327 ("exp"."exp")
24328 ("gcd"."gcd")
24329 ("hom"."hom")
24330 ("inf"."inf")
24331 ("ker"."ker")
24332 ("lg"."lg")
24333 ("lim"."lim")
24334 ("liminf"."liminf")
24335 ("limsup"."limsup")
24336 ("ln"."ln")
24337 ("log"."log")
24338 ("max"."max")
24339 ("min"."min")
24340 ("Pr"."Pr")
24341 ("sec"."sec")
24342 ("sin"."sin")
24343 ("sinh"."sinh")
24344 ("sup"."sup")
24345 ("tan"."tan")
24346 ("tanh"."tanh")
24348 "Entities for TeX->HTML translation.
24349 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
24350 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
24351 In that case, \"\\ent\" will be translated to \"&other;\".
24352 The list contains HTML entities for Latin-1, Greek and other symbols.
24353 It is supplemented by a number of commonly used TeX macros with appropriate
24354 translations. There is currently no way for users to extend this.")
24356 ;;; General functions for all backends
24358 (defun org-cleaned-string-for-export (string &rest parameters)
24359 "Cleanup a buffer STRING so that links can be created safely."
24360 (interactive)
24361 (let* ((re-radio (and org-target-link-regexp
24362 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
24363 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
24364 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
24365 (re-archive (concat ":" org-archive-tag ":"))
24366 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
24367 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
24368 (htmlp (plist-get parameters :for-html))
24369 (asciip (plist-get parameters :for-ascii))
24370 (latexp (plist-get parameters :for-LaTeX))
24371 (commentsp (plist-get parameters :comments))
24372 (archived-trees (plist-get parameters :archived-trees))
24373 (inhibit-read-only t)
24374 (drawers org-drawers)
24375 (exp-drawers (plist-get parameters :drawers))
24376 (outline-regexp "\\*+ ")
24377 a b xx
24378 rtn p)
24379 (with-current-buffer (get-buffer-create " org-mode-tmp")
24380 (erase-buffer)
24381 (insert string)
24382 ;; Remove license-to-kill stuff
24383 (while (setq p (text-property-any (point-min) (point-max)
24384 :org-license-to-kill t))
24385 (delete-region p (next-single-property-change p :org-license-to-kill)))
24387 (let ((org-inhibit-startup t)) (org-mode))
24388 (untabify (point-min) (point-max))
24390 ;; Get rid of drawers
24391 (unless (eq t exp-drawers)
24392 (goto-char (point-min))
24393 (let ((re (concat "^[ \t]*:\\("
24394 (mapconcat
24395 'identity
24396 (org-delete-all exp-drawers
24397 (copy-sequence drawers))
24398 "\\|")
24399 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
24400 (while (re-search-forward re nil t)
24401 (replace-match ""))))
24403 ;; Get the correct stuff before the first headline
24404 (when (plist-get parameters :skip-before-1st-heading)
24405 (goto-char (point-min))
24406 (when (re-search-forward "^\\*+[ \t]" nil t)
24407 (delete-region (point-min) (match-beginning 0))
24408 (goto-char (point-min))
24409 (insert "\n")))
24410 (when (plist-get parameters :add-text)
24411 (goto-char (point-min))
24412 (insert (plist-get parameters :add-text) "\n"))
24414 ;; Get rid of archived trees
24415 (when (not (eq archived-trees t))
24416 (goto-char (point-min))
24417 (while (re-search-forward re-archive nil t)
24418 (if (not (org-on-heading-p t))
24419 (org-end-of-subtree t)
24420 (beginning-of-line 1)
24421 (setq a (if archived-trees
24422 (1+ (point-at-eol)) (point))
24423 b (org-end-of-subtree t))
24424 (if (> b a) (delete-region a b)))))
24426 ;; Find targets in comments and move them out of comments,
24427 ;; but mark them as targets that should be invisible
24428 (goto-char (point-min))
24429 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
24430 (replace-match "\\1(INVISIBLE)"))
24432 ;; Protect backend specific stuff, throw away the others.
24433 (let ((formatters
24434 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
24435 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
24436 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
24437 fmt)
24438 (goto-char (point-min))
24439 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
24440 (goto-char (match-end 0))
24441 (while (not (looking-at "#\\+END_EXAMPLE"))
24442 (insert ": ")
24443 (beginning-of-line 2)))
24444 (goto-char (point-min))
24445 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
24446 (add-text-properties (match-beginning 0) (match-end 0)
24447 '(org-protected t)))
24448 (while formatters
24449 (setq fmt (pop formatters))
24450 (when (car fmt)
24451 (goto-char (point-min))
24452 (while (re-search-forward (concat "^#\\+" (cadr fmt)
24453 ":[ \t]*\\(.*\\)") nil t)
24454 (replace-match "\\1" t)
24455 (add-text-properties
24456 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
24457 '(org-protected t))))
24458 (goto-char (point-min))
24459 (while (re-search-forward
24460 (concat "^#\\+"
24461 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
24462 (cadddr fmt) "\\>.*\n?") nil t)
24463 (if (car fmt)
24464 (add-text-properties (match-beginning 1) (1+ (match-end 1))
24465 '(org-protected t))
24466 (delete-region (match-beginning 0) (match-end 0))))))
24468 ;; Protect quoted subtrees
24469 (goto-char (point-min))
24470 (while (re-search-forward re-quote nil t)
24471 (goto-char (match-beginning 0))
24472 (end-of-line 1)
24473 (add-text-properties (point) (org-end-of-subtree t)
24474 '(org-protected t)))
24476 ;; Protect verbatim elements
24477 (goto-char (point-min))
24478 (while (re-search-forward org-verbatim-re nil t)
24479 (add-text-properties (match-beginning 4) (match-end 4)
24480 '(org-protected t))
24481 (goto-char (1+ (match-end 4))))
24483 ;; Remove subtrees that are commented
24484 (goto-char (point-min))
24485 (while (re-search-forward re-commented nil t)
24486 (goto-char (match-beginning 0))
24487 (delete-region (point) (org-end-of-subtree t)))
24489 ;; Remove special table lines
24490 (when org-export-table-remove-special-lines
24491 (goto-char (point-min))
24492 (while (re-search-forward "^[ \t]*|" nil t)
24493 (beginning-of-line 1)
24494 (if (or (looking-at "[ \t]*| *[!_^] *|")
24495 (and (looking-at ".*?| *<[0-9]+> *|")
24496 (not (looking-at ".*?| *[^ <|]"))))
24497 (delete-region (max (point-min) (1- (point-at-bol)))
24498 (point-at-eol))
24499 (end-of-line 1))))
24501 ;; Specific LaTeX stuff
24502 (when latexp
24503 (require 'org-export-latex nil)
24504 (org-export-latex-cleaned-string))
24506 (when asciip
24507 (org-export-ascii-clean-string))
24509 ;; Specific HTML stuff
24510 (when htmlp
24511 ;; Convert LaTeX fragments to images
24512 (when (plist-get parameters :LaTeX-fragments)
24513 (org-format-latex
24514 (concat "ltxpng/" (file-name-sans-extension
24515 (file-name-nondirectory
24516 org-current-export-file)))
24517 org-current-export-dir nil "Creating LaTeX image %s"))
24518 (message "Exporting..."))
24520 ;; Remove or replace comments
24521 (goto-char (point-min))
24522 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24523 (if commentsp
24524 (progn (add-text-properties
24525 (match-beginning 0) (match-end 0) '(org-protected t))
24526 (replace-match (format commentsp (match-string 1)) t t))
24527 (replace-match "")))
24529 ;; Find matches for radio targets and turn them into internal links
24530 (goto-char (point-min))
24531 (when re-radio
24532 (while (re-search-forward re-radio nil t)
24533 (org-if-unprotected
24534 (replace-match "\\1[[\\2]]"))))
24536 ;; Find all links that contain a newline and put them into a single line
24537 (goto-char (point-min))
24538 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24539 (org-if-unprotected
24540 (replace-match "\\1 \\3")
24541 (goto-char (match-beginning 0))))
24544 ;; Normalize links: Convert angle and plain links into bracket links
24545 ;; Expand link abbreviations
24546 (goto-char (point-min))
24547 (while (re-search-forward re-plain-link nil t)
24548 (goto-char (1- (match-end 0)))
24549 (org-if-unprotected
24550 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24551 ":" (match-string 3) "]]")))
24552 ;; added 'org-link face to links
24553 (put-text-property 0 (length s) 'face 'org-link s)
24554 (replace-match s t t))))
24555 (goto-char (point-min))
24556 (while (re-search-forward re-angle-link nil t)
24557 (goto-char (1- (match-end 0)))
24558 (org-if-unprotected
24559 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24560 ":" (match-string 3) "]]")))
24561 (put-text-property 0 (length s) 'face 'org-link s)
24562 (replace-match s t t))))
24563 (goto-char (point-min))
24564 (while (re-search-forward org-bracket-link-regexp nil t)
24565 (org-if-unprotected
24566 (let* ((s (concat "[[" (setq xx (save-match-data
24567 (org-link-expand-abbrev (match-string 1))))
24569 (if (match-end 3)
24570 (match-string 2)
24571 (concat "[" xx "]"))
24572 "]")))
24573 (put-text-property 0 (length s) 'face 'org-link s)
24574 (replace-match s t t))))
24576 ;; Find multiline emphasis and put them into single line
24577 (when (plist-get parameters :emph-multiline)
24578 (goto-char (point-min))
24579 (while (re-search-forward org-emph-re nil t)
24580 (if (not (= (char-after (match-beginning 3))
24581 (char-after (match-beginning 4))))
24582 (org-if-unprotected
24583 (subst-char-in-region (match-beginning 0) (match-end 0)
24584 ?\n ?\ t)
24585 (goto-char (1- (match-end 0))))
24586 (goto-char (1+ (match-beginning 0))))))
24588 (setq rtn (buffer-string)))
24589 (kill-buffer " org-mode-tmp")
24590 rtn))
24592 (defun org-export-grab-title-from-buffer ()
24593 "Get a title for the current document, from looking at the buffer."
24594 (let ((inhibit-read-only t))
24595 (save-excursion
24596 (goto-char (point-min))
24597 (let ((end (save-excursion (outline-next-heading) (point))))
24598 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24599 ;; Mark the line so that it will not be exported as normal text.
24600 (org-unmodified
24601 (add-text-properties (match-beginning 0) (match-end 0)
24602 (list :org-license-to-kill t)))
24603 ;; Return the title string
24604 (org-trim (match-string 0)))))))
24606 (defun org-export-get-title-from-subtree ()
24607 "Return subtree title and exclude it from export."
24608 (let (title (m (mark)))
24609 (save-excursion
24610 (goto-char (region-beginning))
24611 (when (and (org-at-heading-p)
24612 (>= (org-end-of-subtree t t) (region-end)))
24613 ;; This is a subtree, we take the title from the first heading
24614 (goto-char (region-beginning))
24615 (looking-at org-todo-line-regexp)
24616 (setq title (match-string 3))
24617 (org-unmodified
24618 (add-text-properties (point) (1+ (point-at-eol))
24619 (list :org-license-to-kill t)))))
24620 title))
24622 (defun org-solidify-link-text (s &optional alist)
24623 "Take link text and make a safe target out of it."
24624 (save-match-data
24625 (let* ((rtn
24626 (mapconcat
24627 'identity
24628 (org-split-string s "[ \t\r\n]+") "--"))
24629 (a (assoc rtn alist)))
24630 (or (cdr a) rtn))))
24632 (defun org-get-min-level (lines)
24633 "Get the minimum level in LINES."
24634 (let ((re "^\\(\\*+\\) ") l min)
24635 (catch 'exit
24636 (while (setq l (pop lines))
24637 (if (string-match re l)
24638 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24639 1)))
24641 ;; Variable holding the vector with section numbers
24642 (defvar org-section-numbers (make-vector org-level-max 0))
24644 (defun org-init-section-numbers ()
24645 "Initialize the vector for the section numbers."
24646 (let* ((level -1)
24647 (numbers (nreverse (org-split-string "" "\\.")))
24648 (depth (1- (length org-section-numbers)))
24649 (i depth) number-string)
24650 (while (>= i 0)
24651 (if (> i level)
24652 (aset org-section-numbers i 0)
24653 (setq number-string (or (car numbers) "0"))
24654 (if (string-match "\\`[A-Z]\\'" number-string)
24655 (aset org-section-numbers i
24656 (- (string-to-char number-string) ?A -1))
24657 (aset org-section-numbers i (string-to-number number-string)))
24658 (pop numbers))
24659 (setq i (1- i)))))
24661 (defun org-section-number (&optional level)
24662 "Return a string with the current section number.
24663 When LEVEL is non-nil, increase section numbers on that level."
24664 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24665 (when level
24666 (when (> level -1)
24667 (aset org-section-numbers
24668 level (1+ (aref org-section-numbers level))))
24669 (setq idx (1+ level))
24670 (while (<= idx depth)
24671 (if (not (= idx 1))
24672 (aset org-section-numbers idx 0))
24673 (setq idx (1+ idx))))
24674 (setq idx 0)
24675 (while (<= idx depth)
24676 (setq n (aref org-section-numbers idx))
24677 (setq string (concat string (if (not (string= string "")) "." "")
24678 (int-to-string n)))
24679 (setq idx (1+ idx)))
24680 (save-match-data
24681 (if (string-match "\\`\\([@0]\\.\\)+" string)
24682 (setq string (replace-match "" t nil string)))
24683 (if (string-match "\\(\\.0\\)+\\'" string)
24684 (setq string (replace-match "" t nil string))))
24685 string))
24687 ;;; ASCII export
24689 (defvar org-last-level nil) ; dynamically scoped variable
24690 (defvar org-min-level nil) ; dynamically scoped variable
24691 (defvar org-levels-open nil) ; dynamically scoped parameter
24692 (defvar org-ascii-current-indentation nil) ; For communication
24694 (defun org-export-as-ascii (arg)
24695 "Export the outline as a pretty ASCII file.
24696 If there is an active region, export only the region.
24697 The prefix ARG specifies how many levels of the outline should become
24698 underlined headlines. The default is 3."
24699 (interactive "P")
24700 (setq-default org-todo-line-regexp org-todo-line-regexp)
24701 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24702 (org-infile-export-plist)))
24703 (region-p (org-region-active-p))
24704 (subtree-p
24705 (when region-p
24706 (save-excursion
24707 (goto-char (region-beginning))
24708 (and (org-at-heading-p)
24709 (>= (org-end-of-subtree t t) (region-end))))))
24710 (custom-times org-display-custom-times)
24711 (org-ascii-current-indentation '(0 . 0))
24712 (level 0) line txt
24713 (umax nil)
24714 (umax-toc nil)
24715 (case-fold-search nil)
24716 (filename (concat (file-name-as-directory
24717 (org-export-directory :ascii opt-plist))
24718 (file-name-sans-extension
24719 (or (and subtree-p
24720 (org-entry-get (region-beginning)
24721 "EXPORT_FILE_NAME" t))
24722 (file-name-nondirectory buffer-file-name)))
24723 ".txt"))
24724 (filename (if (equal (file-truename filename)
24725 (file-truename buffer-file-name))
24726 (concat filename ".txt")
24727 filename))
24728 (buffer (find-file-noselect filename))
24729 (org-levels-open (make-vector org-level-max nil))
24730 (odd org-odd-levels-only)
24731 (date (plist-get opt-plist :date))
24732 (author (plist-get opt-plist :author))
24733 (title (or (and subtree-p (org-export-get-title-from-subtree))
24734 (plist-get opt-plist :title)
24735 (and (not
24736 (plist-get opt-plist :skip-before-1st-heading))
24737 (org-export-grab-title-from-buffer))
24738 (file-name-sans-extension
24739 (file-name-nondirectory buffer-file-name))))
24740 (email (plist-get opt-plist :email))
24741 (language (plist-get opt-plist :language))
24742 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24743 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24744 (todo nil)
24745 (lang-words nil)
24746 (region
24747 (buffer-substring
24748 (if (org-region-active-p) (region-beginning) (point-min))
24749 (if (org-region-active-p) (region-end) (point-max))))
24750 (lines (org-split-string
24751 (org-cleaned-string-for-export
24752 region
24753 :for-ascii t
24754 :skip-before-1st-heading
24755 (plist-get opt-plist :skip-before-1st-heading)
24756 :drawers (plist-get opt-plist :drawers)
24757 :verbatim-multiline t
24758 :archived-trees
24759 (plist-get opt-plist :archived-trees)
24760 :add-text (plist-get opt-plist :text))
24761 "\n"))
24762 thetoc have-headings first-heading-pos
24763 table-open table-buffer)
24765 (let ((inhibit-read-only t))
24766 (org-unmodified
24767 (remove-text-properties (point-min) (point-max)
24768 '(:org-license-to-kill t))))
24770 (setq org-min-level (org-get-min-level lines))
24771 (setq org-last-level org-min-level)
24772 (org-init-section-numbers)
24774 (find-file-noselect filename)
24776 (setq lang-words (or (assoc language org-export-language-setup)
24777 (assoc "en" org-export-language-setup)))
24778 (switch-to-buffer-other-window buffer)
24779 (erase-buffer)
24780 (fundamental-mode)
24781 ;; create local variables for all options, to make sure all called
24782 ;; functions get the correct information
24783 (mapc (lambda (x)
24784 (set (make-local-variable (cdr x))
24785 (plist-get opt-plist (car x))))
24786 org-export-plist-vars)
24787 (org-set-local 'org-odd-levels-only odd)
24788 (setq umax (if arg (prefix-numeric-value arg)
24789 org-export-headline-levels))
24790 (setq umax-toc (if (integerp org-export-with-toc)
24791 (min org-export-with-toc umax)
24792 umax))
24794 ;; File header
24795 (if title (org-insert-centered title ?=))
24796 (insert "\n")
24797 (if (and (or author email)
24798 org-export-author-info)
24799 (insert (concat (nth 1 lang-words) ": " (or author "")
24800 (if email (concat " <" email ">") "")
24801 "\n")))
24803 (cond
24804 ((and date (string-match "%" date))
24805 (setq date (format-time-string date)))
24806 (date)
24807 (t (setq date (format-time-string "%Y/%m/%d %X"))))
24809 (if (and date org-export-time-stamp-file)
24810 (insert (concat (nth 2 lang-words) ": " date"\n")))
24812 (insert "\n\n")
24814 (if org-export-with-toc
24815 (progn
24816 (push (concat (nth 3 lang-words) "\n") thetoc)
24817 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24818 (mapc '(lambda (line)
24819 (if (string-match org-todo-line-regexp
24820 line)
24821 ;; This is a headline
24822 (progn
24823 (setq have-headings t)
24824 (setq level (- (match-end 1) (match-beginning 1))
24825 level (org-tr-level level)
24826 txt (match-string 3 line)
24827 todo
24828 (or (and org-export-mark-todo-in-toc
24829 (match-beginning 2)
24830 (not (member (match-string 2 line)
24831 org-done-keywords)))
24832 ; TODO, not DONE
24833 (and org-export-mark-todo-in-toc
24834 (= level umax-toc)
24835 (org-search-todo-below
24836 line lines level))))
24837 (setq txt (org-html-expand-for-ascii txt))
24839 (while (string-match org-bracket-link-regexp txt)
24840 (setq txt
24841 (replace-match
24842 (match-string (if (match-end 2) 3 1) txt)
24843 t t txt)))
24845 (if (and (memq org-export-with-tags '(not-in-toc nil))
24846 (string-match
24847 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24848 txt))
24849 (setq txt (replace-match "" t t txt)))
24850 (if (string-match quote-re0 txt)
24851 (setq txt (replace-match "" t t txt)))
24853 (if org-export-with-section-numbers
24854 (setq txt (concat (org-section-number level)
24855 " " txt)))
24856 (if (<= level umax-toc)
24857 (progn
24858 (push
24859 (concat
24860 (make-string
24861 (* (max 0 (- level org-min-level)) 4) ?\ )
24862 (format (if todo "%s (*)\n" "%s\n") txt))
24863 thetoc)
24864 (setq org-last-level level))
24865 ))))
24866 lines)
24867 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24869 (org-init-section-numbers)
24870 (while (setq line (pop lines))
24871 ;; Remove the quoted HTML tags.
24872 (setq line (org-html-expand-for-ascii line))
24873 ;; Remove targets
24874 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24875 (setq line (replace-match "" t t line)))
24876 ;; Replace internal links
24877 (while (string-match org-bracket-link-regexp line)
24878 (setq line (replace-match
24879 (if (match-end 3) "[\\3]" "[\\1]")
24880 t nil line)))
24881 (when custom-times
24882 (setq line (org-translate-time line)))
24883 (cond
24884 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24885 ;; a Headline
24886 (setq first-heading-pos (or first-heading-pos (point)))
24887 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24888 txt (match-string 2 line))
24889 (org-ascii-level-start level txt umax lines))
24891 ((and org-export-with-tables
24892 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24893 (if (not table-open)
24894 ;; New table starts
24895 (setq table-open t table-buffer nil))
24896 ;; Accumulate lines
24897 (setq table-buffer (cons line table-buffer))
24898 (when (or (not lines)
24899 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24900 (car lines))))
24901 (setq table-open nil
24902 table-buffer (nreverse table-buffer))
24903 (insert (mapconcat
24904 (lambda (x)
24905 (org-fix-indentation x org-ascii-current-indentation))
24906 (org-format-table-ascii table-buffer)
24907 "\n") "\n")))
24909 (setq line (org-fix-indentation line org-ascii-current-indentation))
24910 (if (and org-export-with-fixed-width
24911 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24912 (setq line (replace-match "\\1" nil nil line)))
24913 (insert line "\n"))))
24915 (normal-mode)
24917 ;; insert the table of contents
24918 (when thetoc
24919 (goto-char (point-min))
24920 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24921 (progn
24922 (goto-char (match-beginning 0))
24923 (replace-match ""))
24924 (goto-char first-heading-pos))
24925 (mapc 'insert thetoc)
24926 (or (looking-at "[ \t]*\n[ \t]*\n")
24927 (insert "\n\n")))
24929 ;; Convert whitespace place holders
24930 (goto-char (point-min))
24931 (let (beg end)
24932 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24933 (setq end (next-single-property-change beg 'org-whitespace))
24934 (goto-char beg)
24935 (delete-region beg end)
24936 (insert (make-string (- end beg) ?\ ))))
24938 (save-buffer)
24939 ;; remove display and invisible chars
24940 (let (beg end)
24941 (goto-char (point-min))
24942 (while (setq beg (next-single-property-change (point) 'display))
24943 (setq end (next-single-property-change beg 'display))
24944 (delete-region beg end)
24945 (goto-char beg)
24946 (insert "=>"))
24947 (goto-char (point-min))
24948 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24949 (setq end (next-single-property-change beg 'org-cwidth))
24950 (delete-region beg end)
24951 (goto-char beg)))
24952 (goto-char (point-min))))
24954 (defun org-export-ascii-clean-string ()
24955 "Do extra work for ASCII export"
24956 (goto-char (point-min))
24957 (while (re-search-forward org-verbatim-re nil t)
24958 (goto-char (match-end 2))
24959 (backward-delete-char 1) (insert "'")
24960 (goto-char (match-beginning 2))
24961 (delete-char 1) (insert "`")
24962 (goto-char (match-end 2))))
24964 (defun org-search-todo-below (line lines level)
24965 "Search the subtree below LINE for any TODO entries."
24966 (let ((rest (cdr (memq line lines)))
24967 (re org-todo-line-regexp)
24968 line lv todo)
24969 (catch 'exit
24970 (while (setq line (pop rest))
24971 (if (string-match re line)
24972 (progn
24973 (setq lv (- (match-end 1) (match-beginning 1))
24974 todo (and (match-beginning 2)
24975 (not (member (match-string 2 line)
24976 org-done-keywords))))
24977 ; TODO, not DONE
24978 (if (<= lv level) (throw 'exit nil))
24979 (if todo (throw 'exit t))))))))
24981 (defun org-html-expand-for-ascii (line)
24982 "Handle quoted HTML for ASCII export."
24983 (if org-export-html-expand
24984 (while (string-match "@<[^<>\n]*>" line)
24985 ;; We just remove the tags for now.
24986 (setq line (replace-match "" nil nil line))))
24987 line)
24989 (defun org-insert-centered (s &optional underline)
24990 "Insert the string S centered and underline it with character UNDERLINE."
24991 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24992 (insert (make-string ind ?\ ) s "\n")
24993 (if underline
24994 (insert (make-string ind ?\ )
24995 (make-string (string-width s) underline)
24996 "\n"))))
24998 (defun org-ascii-level-start (level title umax &optional lines)
24999 "Insert a new level in ASCII export."
25000 (let (char (n (- level umax 1)) (ind 0))
25001 (if (> level umax)
25002 (progn
25003 (insert (make-string (* 2 n) ?\ )
25004 (char-to-string (nth (% n (length org-export-ascii-bullets))
25005 org-export-ascii-bullets))
25006 " " title "\n")
25007 ;; find the indentation of the next non-empty line
25008 (catch 'stop
25009 (while lines
25010 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
25011 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
25012 (throw 'stop (setq ind (org-get-indentation (car lines)))))
25013 (pop lines)))
25014 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
25015 (if (or (not (equal (char-before) ?\n))
25016 (not (equal (char-before (1- (point))) ?\n)))
25017 (insert "\n"))
25018 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
25019 (unless org-export-with-tags
25020 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25021 (setq title (replace-match "" t t title))))
25022 (if org-export-with-section-numbers
25023 (setq title (concat (org-section-number level) " " title)))
25024 (insert title "\n" (make-string (string-width title) char) "\n")
25025 (setq org-ascii-current-indentation '(0 . 0)))))
25027 (defun org-export-visible (type arg)
25028 "Create a copy of the visible part of the current buffer, and export it.
25029 The copy is created in a temporary buffer and removed after use.
25030 TYPE is the final key (as a string) that also select the export command in
25031 the `C-c C-e' export dispatcher.
25032 As a special case, if the you type SPC at the prompt, the temporary
25033 org-mode file will not be removed but presented to you so that you can
25034 continue to use it. The prefix arg ARG is passed through to the exporting
25035 command."
25036 (interactive
25037 (list (progn
25038 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
25039 (read-char-exclusive))
25040 current-prefix-arg))
25041 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
25042 (error "Invalid export key"))
25043 (let* ((binding (cdr (assoc type
25044 '((?a . org-export-as-ascii)
25045 (?\C-a . org-export-as-ascii)
25046 (?b . org-export-as-html-and-open)
25047 (?\C-b . org-export-as-html-and-open)
25048 (?h . org-export-as-html)
25049 (?H . org-export-as-html-to-buffer)
25050 (?R . org-export-region-as-html)
25051 (?x . org-export-as-xoxo)))))
25052 (keepp (equal type ?\ ))
25053 (file buffer-file-name)
25054 (buffer (get-buffer-create "*Org Export Visible*"))
25055 s e)
25056 ;; Need to hack the drawers here.
25057 (save-excursion
25058 (goto-char (point-min))
25059 (while (re-search-forward org-drawer-regexp nil t)
25060 (goto-char (match-beginning 1))
25061 (or (org-invisible-p) (org-flag-drawer nil))))
25062 (with-current-buffer buffer (erase-buffer))
25063 (save-excursion
25064 (setq s (goto-char (point-min)))
25065 (while (not (= (point) (point-max)))
25066 (goto-char (org-find-invisible))
25067 (append-to-buffer buffer s (point))
25068 (setq s (goto-char (org-find-visible))))
25069 (org-cycle-hide-drawers 'all)
25070 (goto-char (point-min))
25071 (unless keepp
25072 ;; Copy all comment lines to the end, to make sure #+ settings are
25073 ;; still available for the second export step. Kind of a hack, but
25074 ;; does do the trick.
25075 (if (looking-at "#[^\r\n]*")
25076 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
25077 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
25078 (append-to-buffer buffer (1+ (match-beginning 0))
25079 (min (point-max) (1+ (match-end 0))))))
25080 (set-buffer buffer)
25081 (let ((buffer-file-name file)
25082 (org-inhibit-startup t))
25083 (org-mode)
25084 (show-all)
25085 (unless keepp (funcall binding arg))))
25086 (if (not keepp)
25087 (kill-buffer buffer)
25088 (switch-to-buffer-other-window buffer)
25089 (goto-char (point-min)))))
25091 (defun org-find-visible ()
25092 (let ((s (point)))
25093 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25094 (get-char-property s 'invisible)))
25096 (defun org-find-invisible ()
25097 (let ((s (point)))
25098 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25099 (not (get-char-property s 'invisible))))
25102 ;;; HTML export
25104 (defun org-get-current-options ()
25105 "Return a string with current options as keyword options.
25106 Does include HTML export options as well as TODO and CATEGORY stuff."
25107 (format
25108 "#+TITLE: %s
25109 #+AUTHOR: %s
25110 #+EMAIL: %s
25111 #+DATE: %s
25112 #+LANGUAGE: %s
25113 #+TEXT: Some descriptive text to be emitted. Several lines OK.
25114 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s -:%s f:%s *:%s TeX:%s LaTeX:%s skip:%s d:%s tags:%s
25115 #+CATEGORY: %s
25116 #+SEQ_TODO: %s
25117 #+TYP_TODO: %s
25118 #+PRIORITIES: %c %c %c
25119 #+DRAWERS: %s
25120 #+STARTUP: %s %s %s %s %s
25121 #+TAGS: %s
25122 #+ARCHIVE: %s
25123 #+LINK: %s
25125 (buffer-name) (user-full-name) user-mail-address
25126 (format-time-string (car org-time-stamp-formats))
25127 org-export-default-language
25128 org-export-headline-levels
25129 org-export-with-section-numbers
25130 org-export-with-toc
25131 org-export-preserve-breaks
25132 org-export-html-expand
25133 org-export-with-fixed-width
25134 org-export-with-tables
25135 org-export-with-sub-superscripts
25136 org-export-with-special-strings
25137 org-export-with-footnotes
25138 org-export-with-emphasize
25139 org-export-with-TeX-macros
25140 org-export-with-LaTeX-fragments
25141 org-export-skip-text-before-1st-heading
25142 org-export-with-drawers
25143 org-export-with-tags
25144 (file-name-nondirectory buffer-file-name)
25145 "TODO FEEDBACK VERIFY DONE"
25146 "Me Jason Marie DONE"
25147 org-highest-priority org-lowest-priority org-default-priority
25148 (mapconcat 'identity org-drawers " ")
25149 (cdr (assoc org-startup-folded
25150 '((nil . "showall") (t . "overview") (content . "content"))))
25151 (if org-odd-levels-only "odd" "oddeven")
25152 (if org-hide-leading-stars "hidestars" "showstars")
25153 (if org-startup-align-all-tables "align" "noalign")
25154 (cond ((eq org-log-done t) "logdone")
25155 ((equal org-log-done 'note) "lognotedone")
25156 ((not org-log-done) "nologdone"))
25157 (or (mapconcat (lambda (x)
25158 (cond
25159 ((equal '(:startgroup) x) "{")
25160 ((equal '(:endgroup) x) "}")
25161 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
25162 (t (car x))))
25163 (or org-tag-alist (org-get-buffer-tags)) " ") "")
25164 org-archive-location
25165 "org file:~/org/%s.org"
25168 (defun org-insert-export-options-template ()
25169 "Insert into the buffer a template with information for exporting."
25170 (interactive)
25171 (if (not (bolp)) (newline))
25172 (let ((s (org-get-current-options)))
25173 (and (string-match "#\\+CATEGORY" s)
25174 (setq s (substring s 0 (match-beginning 0))))
25175 (insert s)))
25177 (defun org-toggle-fixed-width-section (arg)
25178 "Toggle the fixed-width export.
25179 If there is no active region, the QUOTE keyword at the current headline is
25180 inserted or removed. When present, it causes the text between this headline
25181 and the next to be exported as fixed-width text, and unmodified.
25182 If there is an active region, this command adds or removes a colon as the
25183 first character of this line. If the first character of a line is a colon,
25184 this line is also exported in fixed-width font."
25185 (interactive "P")
25186 (let* ((cc 0)
25187 (regionp (org-region-active-p))
25188 (beg (if regionp (region-beginning) (point)))
25189 (end (if regionp (region-end)))
25190 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
25191 (case-fold-search nil)
25192 (re "[ \t]*\\(:\\)")
25193 off)
25194 (if regionp
25195 (save-excursion
25196 (goto-char beg)
25197 (setq cc (current-column))
25198 (beginning-of-line 1)
25199 (setq off (looking-at re))
25200 (while (> nlines 0)
25201 (setq nlines (1- nlines))
25202 (beginning-of-line 1)
25203 (cond
25204 (arg
25205 (move-to-column cc t)
25206 (insert ":\n")
25207 (forward-line -1))
25208 ((and off (looking-at re))
25209 (replace-match "" t t nil 1))
25210 ((not off) (move-to-column cc t) (insert ":")))
25211 (forward-line 1)))
25212 (save-excursion
25213 (org-back-to-heading)
25214 (if (looking-at (concat outline-regexp
25215 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
25216 (replace-match "" t t nil 1)
25217 (if (looking-at outline-regexp)
25218 (progn
25219 (goto-char (match-end 0))
25220 (insert org-quote-string " "))))))))
25222 (defun org-export-as-html-and-open (arg)
25223 "Export the outline as HTML and immediately open it with a browser.
25224 If there is an active region, export only the region.
25225 The prefix ARG specifies how many levels of the outline should become
25226 headlines. The default is 3. Lower levels will become bulleted lists."
25227 (interactive "P")
25228 (org-export-as-html arg 'hidden)
25229 (org-open-file buffer-file-name))
25231 (defun org-export-as-html-batch ()
25232 "Call `org-export-as-html', may be used in batch processing as
25233 emacs --batch
25234 --load=$HOME/lib/emacs/org.el
25235 --eval \"(setq org-export-headline-levels 2)\"
25236 --visit=MyFile --funcall org-export-as-html-batch"
25237 (org-export-as-html org-export-headline-levels 'hidden))
25239 (defun org-export-as-html-to-buffer (arg)
25240 "Call `org-exort-as-html` with output to a temporary buffer.
25241 No file is created. The prefix ARG is passed through to `org-export-as-html'."
25242 (interactive "P")
25243 (org-export-as-html arg nil nil "*Org HTML Export*")
25244 (switch-to-buffer-other-window "*Org HTML Export*"))
25246 (defun org-replace-region-by-html (beg end)
25247 "Assume the current region has org-mode syntax, and convert it to HTML.
25248 This can be used in any buffer. For example, you could write an
25249 itemized list in org-mode syntax in an HTML buffer and then use this
25250 command to convert it."
25251 (interactive "r")
25252 (let (reg html buf pop-up-frames)
25253 (save-window-excursion
25254 (if (org-mode-p)
25255 (setq html (org-export-region-as-html
25256 beg end t 'string))
25257 (setq reg (buffer-substring beg end)
25258 buf (get-buffer-create "*Org tmp*"))
25259 (with-current-buffer buf
25260 (erase-buffer)
25261 (insert reg)
25262 (org-mode)
25263 (setq html (org-export-region-as-html
25264 (point-min) (point-max) t 'string)))
25265 (kill-buffer buf)))
25266 (delete-region beg end)
25267 (insert html)))
25269 (defun org-export-region-as-html (beg end &optional body-only buffer)
25270 "Convert region from BEG to END in org-mode buffer to HTML.
25271 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
25272 contents, and only produce the region of converted text, useful for
25273 cut-and-paste operations.
25274 If BUFFER is a buffer or a string, use/create that buffer as a target
25275 of the converted HTML. If BUFFER is the symbol `string', return the
25276 produced HTML as a string and leave not buffer behind. For example,
25277 a Lisp program could call this function in the following way:
25279 (setq html (org-export-region-as-html beg end t 'string))
25281 When called interactively, the output buffer is selected, and shown
25282 in a window. A non-interactive call will only retunr the buffer."
25283 (interactive "r\nP")
25284 (when (interactive-p)
25285 (setq buffer "*Org HTML Export*"))
25286 (let ((transient-mark-mode t) (zmacs-regions t)
25287 rtn)
25288 (goto-char end)
25289 (set-mark (point)) ;; to activate the region
25290 (goto-char beg)
25291 (setq rtn (org-export-as-html
25292 nil nil nil
25293 buffer body-only))
25294 (if (fboundp 'deactivate-mark) (deactivate-mark))
25295 (if (and (interactive-p) (bufferp rtn))
25296 (switch-to-buffer-other-window rtn)
25297 rtn)))
25299 (defvar html-table-tag nil) ; dynamically scoped into this.
25300 (defun org-export-as-html (arg &optional hidden ext-plist
25301 to-buffer body-only pub-dir)
25302 "Export the outline as a pretty HTML file.
25303 If there is an active region, export only the region. The prefix
25304 ARG specifies how many levels of the outline should become
25305 headlines. The default is 3. Lower levels will become bulleted
25306 lists. When HIDDEN is non-nil, don't display the HTML buffer.
25307 EXT-PLIST is a property list with external parameters overriding
25308 org-mode's default settings, but still inferior to file-local
25309 settings. When TO-BUFFER is non-nil, create a buffer with that
25310 name and export to that buffer. If TO-BUFFER is the symbol
25311 `string', don't leave any buffer behind but just return the
25312 resulting HTML as a string. When BODY-ONLY is set, don't produce
25313 the file header and footer, simply return the content of
25314 <body>...</body>, without even the body tags themselves. When
25315 PUB-DIR is set, use this as the publishing directory."
25316 (interactive "P")
25318 ;; Make sure we have a file name when we need it.
25319 (when (and (not (or to-buffer body-only))
25320 (not buffer-file-name))
25321 (if (buffer-base-buffer)
25322 (org-set-local 'buffer-file-name
25323 (with-current-buffer (buffer-base-buffer)
25324 buffer-file-name))
25325 (error "Need a file name to be able to export.")))
25327 (message "Exporting...")
25328 (setq-default org-todo-line-regexp org-todo-line-regexp)
25329 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
25330 (setq-default org-done-keywords org-done-keywords)
25331 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
25332 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25333 ext-plist
25334 (org-infile-export-plist)))
25336 (style (plist-get opt-plist :style))
25337 (html-extension (plist-get opt-plist :html-extension))
25338 (link-validate (plist-get opt-plist :link-validation-function))
25339 valid thetoc have-headings first-heading-pos
25340 (odd org-odd-levels-only)
25341 (region-p (org-region-active-p))
25342 (subtree-p
25343 (when region-p
25344 (save-excursion
25345 (goto-char (region-beginning))
25346 (and (org-at-heading-p)
25347 (>= (org-end-of-subtree t t) (region-end))))))
25348 ;; The following two are dynamically scoped into other
25349 ;; routines below.
25350 (org-current-export-dir
25351 (or pub-dir (org-export-directory :html opt-plist)))
25352 (org-current-export-file buffer-file-name)
25353 (level 0) (line "") (origline "") txt todo
25354 (umax nil)
25355 (umax-toc nil)
25356 (filename (if to-buffer nil
25357 (expand-file-name
25358 (concat
25359 (file-name-sans-extension
25360 (or (and subtree-p
25361 (org-entry-get (region-beginning)
25362 "EXPORT_FILE_NAME" t))
25363 (file-name-nondirectory buffer-file-name)))
25364 "." html-extension)
25365 (file-name-as-directory
25366 (or pub-dir (org-export-directory :html opt-plist))))))
25367 (current-dir (if buffer-file-name
25368 (file-name-directory buffer-file-name)
25369 default-directory))
25370 (buffer (if to-buffer
25371 (cond
25372 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
25373 (t (get-buffer-create to-buffer)))
25374 (find-file-noselect filename)))
25375 (org-levels-open (make-vector org-level-max nil))
25376 (date (plist-get opt-plist :date))
25377 (author (plist-get opt-plist :author))
25378 (title (or (and subtree-p (org-export-get-title-from-subtree))
25379 (plist-get opt-plist :title)
25380 (and (not
25381 (plist-get opt-plist :skip-before-1st-heading))
25382 (org-export-grab-title-from-buffer))
25383 (and buffer-file-name
25384 (file-name-sans-extension
25385 (file-name-nondirectory buffer-file-name)))
25386 "UNTITLED"))
25387 (html-table-tag (plist-get opt-plist :html-table-tag))
25388 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
25389 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
25390 (inquote nil)
25391 (infixed nil)
25392 (in-local-list nil)
25393 (local-list-num nil)
25394 (local-list-indent nil)
25395 (llt org-plain-list-ordered-item-terminator)
25396 (email (plist-get opt-plist :email))
25397 (language (plist-get opt-plist :language))
25398 (lang-words nil)
25399 (target-alist nil) tg
25400 (head-count 0) cnt
25401 (start 0)
25402 (coding-system (and (boundp 'buffer-file-coding-system)
25403 buffer-file-coding-system))
25404 (coding-system-for-write (or org-export-html-coding-system
25405 coding-system))
25406 (save-buffer-coding-system (or org-export-html-coding-system
25407 coding-system))
25408 (charset (and coding-system-for-write
25409 (fboundp 'coding-system-get)
25410 (coding-system-get coding-system-for-write
25411 'mime-charset)))
25412 (region
25413 (buffer-substring
25414 (if region-p (region-beginning) (point-min))
25415 (if region-p (region-end) (point-max))))
25416 (lines
25417 (org-split-string
25418 (org-cleaned-string-for-export
25419 region
25420 :emph-multiline t
25421 :for-html t
25422 :skip-before-1st-heading
25423 (plist-get opt-plist :skip-before-1st-heading)
25424 :drawers (plist-get opt-plist :drawers)
25425 :archived-trees
25426 (plist-get opt-plist :archived-trees)
25427 :add-text
25428 (plist-get opt-plist :text)
25429 :LaTeX-fragments
25430 (plist-get opt-plist :LaTeX-fragments))
25431 "[\r\n]"))
25432 table-open type
25433 table-buffer table-orig-buffer
25434 ind start-is-num starter didclose
25435 rpl path desc descp desc1 desc2 link
25436 snumber fnc
25439 (let ((inhibit-read-only t))
25440 (org-unmodified
25441 (remove-text-properties (point-min) (point-max)
25442 '(:org-license-to-kill t))))
25444 (message "Exporting...")
25446 (setq org-min-level (org-get-min-level lines))
25447 (setq org-last-level org-min-level)
25448 (org-init-section-numbers)
25450 (cond
25451 ((and date (string-match "%" date))
25452 (setq date (format-time-string date)))
25453 (date)
25454 (t (setq date (format-time-string "%Y/%m/%d %X"))))
25456 ;; Get the language-dependent settings
25457 (setq lang-words (or (assoc language org-export-language-setup)
25458 (assoc "en" org-export-language-setup)))
25460 ;; Switch to the output buffer
25461 (set-buffer buffer)
25462 (let ((inhibit-read-only t)) (erase-buffer))
25463 (fundamental-mode)
25465 (and (fboundp 'set-buffer-file-coding-system)
25466 (set-buffer-file-coding-system coding-system-for-write))
25468 (let ((case-fold-search nil)
25469 (org-odd-levels-only odd))
25470 ;; create local variables for all options, to make sure all called
25471 ;; functions get the correct information
25472 (mapc (lambda (x)
25473 (set (make-local-variable (cdr x))
25474 (plist-get opt-plist (car x))))
25475 org-export-plist-vars)
25476 (setq umax (if arg (prefix-numeric-value arg)
25477 org-export-headline-levels))
25478 (setq umax-toc (if (integerp org-export-with-toc)
25479 (min org-export-with-toc umax)
25480 umax))
25481 (unless body-only
25482 ;; File header
25483 (insert (format
25484 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25485 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25486 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25487 lang=\"%s\" xml:lang=\"%s\">
25488 <head>
25489 <title>%s</title>
25490 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25491 <meta name=\"generator\" content=\"Org-mode\"/>
25492 <meta name=\"generated\" content=\"%s\"/>
25493 <meta name=\"author\" content=\"%s\"/>
25495 </head><body>
25497 language language (org-html-expand title)
25498 (or charset "iso-8859-1") date author style))
25500 (insert (or (plist-get opt-plist :preamble) ""))
25502 (when (plist-get opt-plist :auto-preamble)
25503 (if title (insert (format org-export-html-title-format
25504 (org-html-expand title))))))
25506 (if (and org-export-with-toc (not body-only))
25507 (progn
25508 (push (format "<h%d>%s</h%d>\n"
25509 org-export-html-toplevel-hlevel
25510 (nth 3 lang-words)
25511 org-export-html-toplevel-hlevel)
25512 thetoc)
25513 (push "<div id=\"text-table-of-contents\">\n" thetoc)
25514 (push "<ul>\n<li>" thetoc)
25515 (setq lines
25516 (mapcar '(lambda (line)
25517 (if (string-match org-todo-line-regexp line)
25518 ;; This is a headline
25519 (progn
25520 (setq have-headings t)
25521 (setq level (- (match-end 1) (match-beginning 1))
25522 level (org-tr-level level)
25523 txt (save-match-data
25524 (org-html-expand
25525 (org-export-cleanup-toc-line
25526 (match-string 3 line))))
25527 todo
25528 (or (and org-export-mark-todo-in-toc
25529 (match-beginning 2)
25530 (not (member (match-string 2 line)
25531 org-done-keywords)))
25532 ; TODO, not DONE
25533 (and org-export-mark-todo-in-toc
25534 (= level umax-toc)
25535 (org-search-todo-below
25536 line lines level))))
25537 (if (string-match
25538 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25539 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25540 (if (string-match quote-re0 txt)
25541 (setq txt (replace-match "" t t txt)))
25542 (setq snumber (org-section-number level))
25543 (if org-export-with-section-numbers
25544 (setq txt (concat snumber " " txt)))
25545 (if (<= level (max umax umax-toc))
25546 (setq head-count (+ head-count 1)))
25547 (if (<= level umax-toc)
25548 (progn
25549 (if (> level org-last-level)
25550 (progn
25551 (setq cnt (- level org-last-level))
25552 (while (>= (setq cnt (1- cnt)) 0)
25553 (push "\n<ul>\n<li>" thetoc))
25554 (push "\n" thetoc)))
25555 (if (< level org-last-level)
25556 (progn
25557 (setq cnt (- org-last-level level))
25558 (while (>= (setq cnt (1- cnt)) 0)
25559 (push "</li>\n</ul>" thetoc))
25560 (push "\n" thetoc)))
25561 ;; Check for targets
25562 (while (string-match org-target-regexp line)
25563 (setq tg (match-string 1 line)
25564 line (replace-match
25565 (concat "@<span class=\"target\">" tg "@</span> ")
25566 t t line))
25567 (push (cons (org-solidify-link-text tg)
25568 (format "sec-%s" snumber))
25569 target-alist))
25570 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25571 (setq txt (replace-match "" t t txt)))
25572 (push
25573 (format
25574 (if todo
25575 "</li>\n<li><a href=\"#sec-%s\"><span class=\"todo\">%s</span></a>"
25576 "</li>\n<li><a href=\"#sec-%s\">%s</a>")
25577 snumber txt) thetoc)
25579 (setq org-last-level level))
25581 line)
25582 lines))
25583 (while (> org-last-level (1- org-min-level))
25584 (setq org-last-level (1- org-last-level))
25585 (push "</li>\n</ul>\n" thetoc))
25586 (push "</div>\n" thetoc)
25587 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25589 (setq head-count 0)
25590 (org-init-section-numbers)
25592 (while (setq line (pop lines) origline line)
25593 (catch 'nextline
25595 ;; end of quote section?
25596 (when (and inquote (string-match "^\\*+ " line))
25597 (insert "</pre>\n")
25598 (setq inquote nil))
25599 ;; inside a quote section?
25600 (when inquote
25601 (insert (org-html-protect line) "\n")
25602 (throw 'nextline nil))
25604 ;; verbatim lines
25605 (when (and org-export-with-fixed-width
25606 (string-match "^[ \t]*:\\(.*\\)" line))
25607 (when (not infixed)
25608 (setq infixed t)
25609 (insert "<pre>\n"))
25610 (insert (org-html-protect (match-string 1 line)) "\n")
25611 (when (and lines
25612 (not (string-match "^[ \t]*\\(:.*\\)"
25613 (car lines))))
25614 (setq infixed nil)
25615 (insert "</pre>\n"))
25616 (throw 'nextline nil))
25618 ;; Protected HTML
25619 (when (get-text-property 0 'org-protected line)
25620 (let (par)
25621 (when (re-search-backward
25622 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25623 (setq par (match-string 1))
25624 (replace-match "\\2\n"))
25625 (insert line "\n")
25626 (while (and lines
25627 (or (= (length (car lines)) 0)
25628 (get-text-property 0 'org-protected (car lines))))
25629 (insert (pop lines) "\n"))
25630 (and par (insert "<p>\n")))
25631 (throw 'nextline nil))
25633 ;; Horizontal line
25634 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25635 (insert "\n<hr/>\n")
25636 (throw 'nextline nil))
25638 ;; make targets to anchors
25639 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25640 (cond
25641 ((match-end 2)
25642 (setq line (replace-match
25643 (concat "@<a name=\""
25644 (org-solidify-link-text (match-string 1 line))
25645 "\">\\nbsp@</a>")
25646 t t line)))
25647 ((and org-export-with-toc (equal (string-to-char line) ?*))
25648 (setq line (replace-match
25649 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25650 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25651 t t line)))
25653 (setq line (replace-match
25654 (concat "@<a name=\""
25655 (org-solidify-link-text (match-string 1 line))
25656 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25657 t t line)))))
25659 (setq line (org-html-handle-time-stamps line))
25661 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25662 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25663 ;; Also handle sub_superscripts and checkboxes
25664 (or (string-match org-table-hline-regexp line)
25665 (setq line (org-html-expand line)))
25667 ;; Format the links
25668 (setq start 0)
25669 (while (string-match org-bracket-link-analytic-regexp line start)
25670 (setq start (match-beginning 0))
25671 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25672 (setq path (match-string 3 line))
25673 (setq desc1 (if (match-end 5) (match-string 5 line))
25674 desc2 (if (match-end 2) (concat type ":" path) path)
25675 descp (and desc1 (not (equal desc1 desc2)))
25676 desc (or desc1 desc2))
25677 ;; Make an image out of the description if that is so wanted
25678 (when (and descp (org-file-image-p desc))
25679 (save-match-data
25680 (if (string-match "^file:" desc)
25681 (setq desc (substring desc (match-end 0)))))
25682 (setq desc (concat "<img src=\"" desc "\"/>")))
25683 ;; FIXME: do we need to unescape here somewhere?
25684 (cond
25685 ((equal type "internal")
25686 (setq rpl
25687 (concat
25688 "<a href=\"#"
25689 (org-solidify-link-text
25690 (save-match-data (org-link-unescape path)) target-alist)
25691 "\">" desc "</a>")))
25692 ((member type '("http" "https"))
25693 ;; standard URL, just check if we need to inline an image
25694 (if (and (or (eq t org-export-html-inline-images)
25695 (and org-export-html-inline-images (not descp)))
25696 (org-file-image-p path))
25697 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25698 (setq link (concat type ":" path))
25699 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25700 ((member type '("ftp" "mailto" "news"))
25701 ;; standard URL
25702 (setq link (concat type ":" path))
25703 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25704 ((string= type "file")
25705 ;; FILE link
25706 (let* ((filename path)
25707 (abs-p (file-name-absolute-p filename))
25708 thefile file-is-image-p search)
25709 (save-match-data
25710 (if (string-match "::\\(.*\\)" filename)
25711 (setq search (match-string 1 filename)
25712 filename (replace-match "" t nil filename)))
25713 (setq valid
25714 (if (functionp link-validate)
25715 (funcall link-validate filename current-dir)
25717 (setq file-is-image-p (org-file-image-p filename))
25718 (setq thefile (if abs-p (expand-file-name filename) filename))
25719 (when (and org-export-html-link-org-files-as-html
25720 (string-match "\\.org$" thefile))
25721 (setq thefile (concat (substring thefile 0
25722 (match-beginning 0))
25723 "." html-extension))
25724 (if (and search
25725 ;; make sure this is can be used as target search
25726 (not (string-match "^[0-9]*$" search))
25727 (not (string-match "^\\*" search))
25728 (not (string-match "^/.*/$" search)))
25729 (setq thefile (concat thefile "#"
25730 (org-solidify-link-text
25731 (org-link-unescape search)))))
25732 (when (string-match "^file:" desc)
25733 (setq desc (replace-match "" t t desc))
25734 (if (string-match "\\.org$" desc)
25735 (setq desc (replace-match "" t t desc))))))
25736 (setq rpl (if (and file-is-image-p
25737 (or (eq t org-export-html-inline-images)
25738 (and org-export-html-inline-images
25739 (not descp))))
25740 (concat "<img src=\"" thefile "\"/>")
25741 (concat "<a href=\"" thefile "\">" desc "</a>")))
25742 (if (not valid) (setq rpl desc))))
25744 ((functionp (setq fnc (nth 2 (assoc type org-link-protocols))))
25745 (setq rpl
25746 (save-match-data
25747 (funcall fnc (org-link-unescape path) desc1 'html))))
25750 ;; just publish the path, as default
25751 (setq rpl (concat "<i>&lt;" type ":"
25752 (save-match-data (org-link-unescape path))
25753 "&gt;</i>"))))
25754 (setq line (replace-match rpl t t line)
25755 start (+ start (length rpl))))
25757 ;; TODO items
25758 (if (and (string-match org-todo-line-regexp line)
25759 (match-beginning 2))
25761 (setq line
25762 (concat (substring line 0 (match-beginning 2))
25763 "<span class=\""
25764 (if (member (match-string 2 line)
25765 org-done-keywords)
25766 "done" "todo")
25767 "\">" (match-string 2 line)
25768 "</span>" (substring line (match-end 2)))))
25770 ;; Does this contain a reference to a footnote?
25771 (when org-export-with-footnotes
25772 (setq start 0)
25773 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25774 (if (get-text-property (match-beginning 2) 'org-protected line)
25775 (setq start (match-end 2))
25776 (let ((n (match-string 2 line)))
25777 (setq line
25778 (replace-match
25779 (format
25780 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25781 (match-string 1 line) n n n)
25782 t t line))))))
25784 (cond
25785 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25786 ;; This is a headline
25787 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25788 txt (match-string 2 line))
25789 (if (string-match quote-re0 txt)
25790 (setq txt (replace-match "" t t txt)))
25791 (if (<= level (max umax umax-toc))
25792 (setq head-count (+ head-count 1)))
25793 (when in-local-list
25794 ;; Close any local lists before inserting a new header line
25795 (while local-list-num
25796 (org-close-li)
25797 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25798 (pop local-list-num))
25799 (setq local-list-indent nil
25800 in-local-list nil))
25801 (setq first-heading-pos (or first-heading-pos (point)))
25802 (org-html-level-start level txt umax
25803 (and org-export-with-toc (<= level umax))
25804 head-count)
25805 ;; QUOTES
25806 (when (string-match quote-re line)
25807 (insert "<pre>")
25808 (setq inquote t)))
25810 ((and org-export-with-tables
25811 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25812 (if (not table-open)
25813 ;; New table starts
25814 (setq table-open t table-buffer nil table-orig-buffer nil))
25815 ;; Accumulate lines
25816 (setq table-buffer (cons line table-buffer)
25817 table-orig-buffer (cons origline table-orig-buffer))
25818 (when (or (not lines)
25819 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25820 (car lines))))
25821 (setq table-open nil
25822 table-buffer (nreverse table-buffer)
25823 table-orig-buffer (nreverse table-orig-buffer))
25824 (org-close-par-maybe)
25825 (insert (org-format-table-html table-buffer table-orig-buffer))))
25827 ;; Normal lines
25828 (when (string-match
25829 (cond
25830 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25831 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25832 ((= llt ?\)) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25833 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25834 line)
25835 (setq ind (org-get-string-indentation line)
25836 start-is-num (match-beginning 4)
25837 starter (if (match-beginning 2)
25838 (substring (match-string 2 line) 0 -1))
25839 line (substring line (match-beginning 5)))
25840 (unless (string-match "[^ \t]" line)
25841 ;; empty line. Pretend indentation is large.
25842 (setq ind (if org-empty-line-terminates-plain-lists
25844 (1+ (or (car local-list-indent) 1)))))
25845 (setq didclose nil)
25846 (while (and in-local-list
25847 (or (and (= ind (car local-list-indent))
25848 (not starter))
25849 (< ind (car local-list-indent))))
25850 (setq didclose t)
25851 (org-close-li)
25852 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25853 (pop local-list-num) (pop local-list-indent)
25854 (setq in-local-list local-list-indent))
25855 (cond
25856 ((and starter
25857 (or (not in-local-list)
25858 (> ind (car local-list-indent))))
25859 ;; Start new (level of) list
25860 (org-close-par-maybe)
25861 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25862 (push start-is-num local-list-num)
25863 (push ind local-list-indent)
25864 (setq in-local-list t))
25865 (starter
25866 ;; continue current list
25867 (org-close-li)
25868 (insert "<li>\n"))
25869 (didclose
25870 ;; we did close a list, normal text follows: need <p>
25871 (org-open-par)))
25872 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25873 (setq line
25874 (replace-match
25875 (if (equal (match-string 1 line) "X")
25876 "<b>[X]</b>"
25877 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25878 t t line))))
25880 ;; Empty lines start a new paragraph. If hand-formatted lists
25881 ;; are not fully interpreted, lines starting with "-", "+", "*"
25882 ;; also start a new paragraph.
25883 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25885 ;; Is this the start of a footnote?
25886 (when org-export-with-footnotes
25887 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25888 (org-close-par-maybe)
25889 (let ((n (match-string 1 line)))
25890 (setq line (replace-match
25891 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25893 ;; Check if the line break needs to be conserved
25894 (cond
25895 ((string-match "\\\\\\\\[ \t]*$" line)
25896 (setq line (replace-match "<br/>" t t line)))
25897 (org-export-preserve-breaks
25898 (setq line (concat line "<br/>"))))
25900 (insert line "\n")))))
25902 ;; Properly close all local lists and other lists
25903 (when inquote (insert "</pre>\n"))
25904 (when in-local-list
25905 ;; Close any local lists before inserting a new header line
25906 (while local-list-num
25907 (org-close-li)
25908 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25909 (pop local-list-num))
25910 (setq local-list-indent nil
25911 in-local-list nil))
25912 (org-html-level-start 1 nil umax
25913 (and org-export-with-toc (<= level umax))
25914 head-count)
25915 ;; the </div> to lose the last text-... div.
25916 (insert "</div>\n")
25918 (unless body-only
25919 (when (plist-get opt-plist :auto-postamble)
25920 (insert "<div id=\"postamble\">")
25921 (when (and org-export-author-info author)
25922 (insert "<p class=\"author\"> "
25923 (nth 1 lang-words) ": " author "\n")
25924 (when email
25925 (if (listp (split-string email ",+ *"))
25926 (mapc (lambda(e)
25927 (insert "<a href=\"mailto:" e "\">&lt;"
25928 e "&gt;</a>\n"))
25929 (split-string email ",+ *"))
25930 (insert "<a href=\"mailto:" email "\">&lt;"
25931 email "&gt;</a>\n")))
25932 (insert "</p>\n"))
25933 (when (and date org-export-time-stamp-file)
25934 (insert "<p class=\"date\"> "
25935 (nth 2 lang-words) ": "
25936 date "</p>\n"))
25937 (insert "</div>"))
25939 (if org-export-html-with-timestamp
25940 (insert org-export-html-html-helper-timestamp))
25941 (insert (or (plist-get opt-plist :postamble) ""))
25942 (insert "</body>\n</html>\n"))
25944 (normal-mode)
25945 (if (eq major-mode default-major-mode) (html-mode))
25947 ;; insert the table of contents
25948 (goto-char (point-min))
25949 (when thetoc
25950 (if (or (re-search-forward
25951 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25952 (re-search-forward
25953 "\\[TABLE-OF-CONTENTS\\]" nil t))
25954 (progn
25955 (goto-char (match-beginning 0))
25956 (replace-match ""))
25957 (goto-char first-heading-pos)
25958 (when (looking-at "\\s-*</p>")
25959 (goto-char (match-end 0))
25960 (insert "\n")))
25961 (insert "<div id=\"table-of-contents\">\n")
25962 (mapc 'insert thetoc)
25963 (insert "</div>\n"))
25964 ;; remove empty paragraphs and lists
25965 (goto-char (point-min))
25966 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25967 (replace-match ""))
25968 (goto-char (point-min))
25969 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25970 (replace-match ""))
25971 (goto-char (point-min))
25972 (while (re-search-forward "</ul>\\s-*<ul>\n?" nil t)
25973 (replace-match ""))
25974 ;; Convert whitespace place holders
25975 (goto-char (point-min))
25976 (let (beg end n)
25977 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25978 (setq n (get-text-property beg 'org-whitespace)
25979 end (next-single-property-change beg 'org-whitespace))
25980 (goto-char beg)
25981 (delete-region beg end)
25982 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25983 (make-string n ?x)))))
25984 (or to-buffer (save-buffer))
25985 (goto-char (point-min))
25986 (message "Exporting... done")
25987 (if (eq to-buffer 'string)
25988 (prog1 (buffer-substring (point-min) (point-max))
25989 (kill-buffer (current-buffer)))
25990 (current-buffer)))))
25992 (defvar org-table-colgroup-info nil)
25993 (defun org-format-table-ascii (lines)
25994 "Format a table for ascii export."
25995 (if (stringp lines)
25996 (setq lines (org-split-string lines "\n")))
25997 (if (not (string-match "^[ \t]*|" (car lines)))
25998 ;; Table made by table.el - test for spanning
25999 lines
26001 ;; A normal org table
26002 ;; Get rid of hlines at beginning and end
26003 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26004 (setq lines (nreverse lines))
26005 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26006 (setq lines (nreverse lines))
26007 (when org-export-table-remove-special-lines
26008 ;; Check if the table has a marking column. If yes remove the
26009 ;; column and the special lines
26010 (setq lines (org-table-clean-before-export lines)))
26011 ;; Get rid of the vertical lines except for grouping
26012 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
26013 rtn line vl1 start)
26014 (while (setq line (pop lines))
26015 (if (string-match org-table-hline-regexp line)
26016 (and (string-match "|\\(.*\\)|" line)
26017 (setq line (replace-match " \\1" t nil line)))
26018 (setq start 0 vl1 vl)
26019 (while (string-match "|" line start)
26020 (setq start (match-end 0))
26021 (or (pop vl1) (setq line (replace-match " " t t line)))))
26022 (push line rtn))
26023 (nreverse rtn))))
26025 (defun org-colgroup-info-to-vline-list (info)
26026 (let (vl new last)
26027 (while info
26028 (setq last new new (pop info))
26029 (if (or (memq last '(:end :startend))
26030 (memq new '(:start :startend)))
26031 (push t vl)
26032 (push nil vl)))
26033 (setq vl (nreverse vl))
26034 (and vl (setcar vl nil))
26035 vl))
26037 (defun org-format-table-html (lines olines)
26038 "Find out which HTML converter to use and return the HTML code."
26039 (if (stringp lines)
26040 (setq lines (org-split-string lines "\n")))
26041 (if (string-match "^[ \t]*|" (car lines))
26042 ;; A normal org table
26043 (org-format-org-table-html lines)
26044 ;; Table made by table.el - test for spanning
26045 (let* ((hlines (delq nil (mapcar
26046 (lambda (x)
26047 (if (string-match "^[ \t]*\\+-" x) x
26048 nil))
26049 lines)))
26050 (first (car hlines))
26051 (ll (and (string-match "\\S-+" first)
26052 (match-string 0 first)))
26053 (re (concat "^[ \t]*" (regexp-quote ll)))
26054 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
26055 hlines))))
26056 (if (and (not spanning)
26057 (not org-export-prefer-native-exporter-for-tables))
26058 ;; We can use my own converter with HTML conversions
26059 (org-format-table-table-html lines)
26060 ;; Need to use the code generator in table.el, with the original text.
26061 (org-format-table-table-html-using-table-generate-source olines)))))
26063 (defun org-format-org-table-html (lines &optional splice)
26064 "Format a table into HTML."
26065 ;; Get rid of hlines at beginning and end
26066 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26067 (setq lines (nreverse lines))
26068 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26069 (setq lines (nreverse lines))
26070 (when org-export-table-remove-special-lines
26071 ;; Check if the table has a marking column. If yes remove the
26072 ;; column and the special lines
26073 (setq lines (org-table-clean-before-export lines)))
26075 (let ((head (and org-export-highlight-first-table-line
26076 (delq nil (mapcar
26077 (lambda (x) (string-match "^[ \t]*|-" x))
26078 (cdr lines)))))
26079 (nlines 0) fnum i
26080 tbopen line fields html gr colgropen)
26081 (if splice (setq head nil))
26082 (unless splice (push (if head "<thead>" "<tbody>") html))
26083 (setq tbopen t)
26084 (while (setq line (pop lines))
26085 (catch 'next-line
26086 (if (string-match "^[ \t]*|-" line)
26087 (progn
26088 (unless splice
26089 (push (if head "</thead>" "</tbody>") html)
26090 (if lines (push "<tbody>" html) (setq tbopen nil)))
26091 (setq head nil) ;; head ends here, first time around
26092 ;; ignore this line
26093 (throw 'next-line t)))
26094 ;; Break the line into fields
26095 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26096 (unless fnum (setq fnum (make-vector (length fields) 0)))
26097 (setq nlines (1+ nlines) i -1)
26098 (push (concat "<tr>"
26099 (mapconcat
26100 (lambda (x)
26101 (setq i (1+ i))
26102 (if (and (< i nlines)
26103 (string-match org-table-number-regexp x))
26104 (incf (aref fnum i)))
26105 (if head
26106 (concat (car org-export-table-header-tags) x
26107 (cdr org-export-table-header-tags))
26108 (concat (car org-export-table-data-tags) x
26109 (cdr org-export-table-data-tags))))
26110 fields "")
26111 "</tr>")
26112 html)))
26113 (unless splice (if tbopen (push "</tbody>" html)))
26114 (unless splice (push "</table>\n" html))
26115 (setq html (nreverse html))
26116 (unless splice
26117 ;; Put in col tags with the alignment (unfortuntely often ignored...)
26118 (push (mapconcat
26119 (lambda (x)
26120 (setq gr (pop org-table-colgroup-info))
26121 (format "%s<col align=\"%s\"></col>%s"
26122 (if (memq gr '(:start :startend))
26123 (prog1
26124 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
26125 (setq colgropen t))
26127 (if (> (/ (float x) nlines) org-table-number-fraction)
26128 "right" "left")
26129 (if (memq gr '(:end :startend))
26130 (progn (setq colgropen nil) "</colgroup>")
26131 "")))
26132 fnum "")
26133 html)
26134 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
26135 (push html-table-tag html))
26136 (concat (mapconcat 'identity html "\n") "\n")))
26138 (defun org-table-clean-before-export (lines)
26139 "Check if the table has a marking column.
26140 If yes remove the column and the special lines."
26141 (setq org-table-colgroup-info nil)
26142 (if (memq nil
26143 (mapcar
26144 (lambda (x) (or (string-match "^[ \t]*|-" x)
26145 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
26146 lines))
26147 (progn
26148 (setq org-table-clean-did-remove-column nil)
26149 (delq nil
26150 (mapcar
26151 (lambda (x)
26152 (cond
26153 ((string-match "^[ \t]*| */ *|" x)
26154 (setq org-table-colgroup-info
26155 (mapcar (lambda (x)
26156 (cond ((member x '("<" "&lt;")) :start)
26157 ((member x '(">" "&gt;")) :end)
26158 ((member x '("<>" "&lt;&gt;")) :startend)
26159 (t nil)))
26160 (org-split-string x "[ \t]*|[ \t]*")))
26161 nil)
26162 (t x)))
26163 lines)))
26164 (setq org-table-clean-did-remove-column t)
26165 (delq nil
26166 (mapcar
26167 (lambda (x)
26168 (cond
26169 ((string-match "^[ \t]*| */ *|" x)
26170 (setq org-table-colgroup-info
26171 (mapcar (lambda (x)
26172 (cond ((member x '("<" "&lt;")) :start)
26173 ((member x '(">" "&gt;")) :end)
26174 ((member x '("<>" "&lt;&gt;")) :startend)
26175 (t nil)))
26176 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
26177 nil)
26178 ((string-match "^[ \t]*| *[!_^/] *|" x)
26179 nil) ; ignore this line
26180 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
26181 (string-match "^\\([ \t]*\\)|[^|]*|" x))
26182 ;; remove the first column
26183 (replace-match "\\1|" t nil x))))
26184 lines))))
26186 (defun org-format-table-table-html (lines)
26187 "Format a table generated by table.el into HTML.
26188 This conversion does *not* use `table-generate-source' from table.el.
26189 This has the advantage that Org-mode's HTML conversions can be used.
26190 But it has the disadvantage, that no cell- or row-spanning is allowed."
26191 (let (line field-buffer
26192 (head org-export-highlight-first-table-line)
26193 fields html empty)
26194 (setq html (concat html-table-tag "\n"))
26195 (while (setq line (pop lines))
26196 (setq empty "&nbsp;")
26197 (catch 'next-line
26198 (if (string-match "^[ \t]*\\+-" line)
26199 (progn
26200 (if field-buffer
26201 (progn
26202 (setq
26203 html
26204 (concat
26205 html
26206 "<tr>"
26207 (mapconcat
26208 (lambda (x)
26209 (if (equal x "") (setq x empty))
26210 (if head
26211 (concat (car org-export-table-header-tags) x
26212 (cdr org-export-table-header-tags))
26213 (concat (car org-export-table-data-tags) x
26214 (cdr org-export-table-data-tags))))
26215 field-buffer "\n")
26216 "</tr>\n"))
26217 (setq head nil)
26218 (setq field-buffer nil)))
26219 ;; Ignore this line
26220 (throw 'next-line t)))
26221 ;; Break the line into fields and store the fields
26222 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26223 (if field-buffer
26224 (setq field-buffer (mapcar
26225 (lambda (x)
26226 (concat x "<br/>" (pop fields)))
26227 field-buffer))
26228 (setq field-buffer fields))))
26229 (setq html (concat html "</table>\n"))
26230 html))
26232 (defun org-format-table-table-html-using-table-generate-source (lines)
26233 "Format a table into html, using `table-generate-source' from table.el.
26234 This has the advantage that cell- or row-spanning is allowed.
26235 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
26236 (require 'table)
26237 (with-current-buffer (get-buffer-create " org-tmp1 ")
26238 (erase-buffer)
26239 (insert (mapconcat 'identity lines "\n"))
26240 (goto-char (point-min))
26241 (if (not (re-search-forward "|[^+]" nil t))
26242 (error "Error processing table"))
26243 (table-recognize-table)
26244 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
26245 (table-generate-source 'html " org-tmp2 ")
26246 (set-buffer " org-tmp2 ")
26247 (buffer-substring (point-min) (point-max))))
26249 (defun org-html-handle-time-stamps (s)
26250 "Format time stamps in string S, or remove them."
26251 (catch 'exit
26252 (let (r b)
26253 (while (string-match org-maybe-keyword-time-regexp s)
26254 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
26255 ;; never export CLOCK
26256 (throw 'exit ""))
26257 (or b (setq b (substring s 0 (match-beginning 0))))
26258 (if (not org-export-with-timestamps)
26259 (setq r (concat r (substring s 0 (match-beginning 0)))
26260 s (substring s (match-end 0)))
26261 (setq r (concat
26262 r (substring s 0 (match-beginning 0))
26263 (if (match-end 1)
26264 (format "@<span class=\"timestamp-kwd\">%s @</span>"
26265 (match-string 1 s)))
26266 (format " @<span class=\"timestamp\">%s@</span>"
26267 (substring
26268 (org-translate-time (match-string 3 s)) 1 -1)))
26269 s (substring s (match-end 0)))))
26270 ;; Line break if line started and ended with time stamp stuff
26271 (if (not r)
26273 (setq r (concat r s))
26274 (unless (string-match "\\S-" (concat b s))
26275 (setq r (concat r "@<br/>")))
26276 r))))
26278 (defun org-html-protect (s)
26279 ;; convert & to &amp;, < to &lt; and > to &gt;
26280 (let ((start 0))
26281 (while (string-match "&" s start)
26282 (setq s (replace-match "&amp;" t t s)
26283 start (1+ (match-beginning 0))))
26284 (while (string-match "<" s)
26285 (setq s (replace-match "&lt;" t t s)))
26286 (while (string-match ">" s)
26287 (setq s (replace-match "&gt;" t t s))))
26290 (defun org-export-cleanup-toc-line (s)
26291 "Remove tags and time staps from lines going into the toc."
26292 (when (memq org-export-with-tags '(not-in-toc nil))
26293 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
26294 (setq s (replace-match "" t t s))))
26295 (when org-export-remove-timestamps-from-toc
26296 (while (string-match org-maybe-keyword-time-regexp s)
26297 (setq s (replace-match "" t t s))))
26298 (while (string-match org-bracket-link-regexp s)
26299 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
26300 t t s)))
26303 (defun org-html-expand (string)
26304 "Prepare STRING for HTML export. Applies all active conversions.
26305 If there are links in the string, don't modify these."
26306 (let* ((re (concat org-bracket-link-regexp "\\|"
26307 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
26308 m s l res)
26309 (while (setq m (string-match re string))
26310 (setq s (substring string 0 m)
26311 l (match-string 0 string)
26312 string (substring string (match-end 0)))
26313 (push (org-html-do-expand s) res)
26314 (push l res))
26315 (push (org-html-do-expand string) res)
26316 (apply 'concat (nreverse res))))
26318 (defun org-html-do-expand (s)
26319 "Apply all active conversions to translate special ASCII to HTML."
26320 (setq s (org-html-protect s))
26321 (if org-export-html-expand
26322 (let ((start 0))
26323 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
26324 (setq s (replace-match "<\\1>" t nil s)))))
26325 (if org-export-with-emphasize
26326 (setq s (org-export-html-convert-emphasize s)))
26327 (if org-export-with-special-strings
26328 (setq s (org-export-html-convert-special-strings s)))
26329 (if org-export-with-sub-superscripts
26330 (setq s (org-export-html-convert-sub-super s)))
26331 (if org-export-with-TeX-macros
26332 (let ((start 0) wd ass)
26333 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
26334 (if (get-text-property (match-beginning 0) 'org-protected s)
26335 (setq start (match-end 0))
26336 (setq wd (match-string 1 s))
26337 (if (setq ass (assoc wd org-html-entities))
26338 (setq s (replace-match (or (cdr ass)
26339 (concat "&" (car ass) ";"))
26340 t t s))
26341 (setq start (+ start (length wd))))))))
26344 (defun org-create-multibrace-regexp (left right n)
26345 "Create a regular expression which will match a balanced sexp.
26346 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
26347 as single character strings.
26348 The regexp returned will match the entire expression including the
26349 delimiters. It will also define a single group which contains the
26350 match except for the outermost delimiters. The maximum depth of
26351 stacked delimiters is N. Escaping delimiters is not possible."
26352 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
26353 (or "\\|")
26354 (re nothing)
26355 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
26356 (while (> n 1)
26357 (setq n (1- n)
26358 re (concat re or next)
26359 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
26360 (concat left "\\(" re "\\)" right)))
26362 (defvar org-match-substring-regexp
26363 (concat
26364 "\\([^\\]\\)\\([_^]\\)\\("
26365 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26366 "\\|"
26367 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
26368 "\\|"
26369 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
26370 "The regular expression matching a sub- or superscript.")
26372 (defvar org-match-substring-with-braces-regexp
26373 (concat
26374 "\\([^\\]\\)\\([_^]\\)\\("
26375 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26376 "\\)")
26377 "The regular expression matching a sub- or superscript, forcing braces.")
26379 (defconst org-export-html-special-string-regexps
26380 '(("\\\\-" . "&shy;")
26381 ("---\\([^-]\\)" . "&mdash;\\1")
26382 ("--\\([^-]\\)" . "&ndash;\\1")
26383 ("\\.\\.\\." . "&hellip;"))
26384 "Regular expressions for special string conversion.")
26386 (defun org-export-html-convert-special-strings (string)
26387 "Convert special characters in STRING to HTML."
26388 (let ((all org-export-html-special-string-regexps)
26389 e a re rpl start)
26390 (while (setq a (pop all))
26391 (setq re (car a) rpl (cdr a) start 0)
26392 (while (string-match re string start)
26393 (if (get-text-property (match-beginning 0) 'org-protected string)
26394 (setq start (match-end 0))
26395 (setq string (replace-match rpl t nil string)))))
26396 string))
26398 (defun org-export-html-convert-sub-super (string)
26399 "Convert sub- and superscripts in STRING to HTML."
26400 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
26401 (while (string-match org-match-substring-regexp string s)
26402 (cond
26403 ((and requireb (match-end 8)) (setq s (match-end 2)))
26404 ((get-text-property (match-beginning 2) 'org-protected string)
26405 (setq s (match-end 2)))
26407 (setq s (match-end 1)
26408 key (if (string= (match-string 2 string) "_") "sub" "sup")
26409 c (or (match-string 8 string)
26410 (match-string 6 string)
26411 (match-string 5 string))
26412 string (replace-match
26413 (concat (match-string 1 string)
26414 "<" key ">" c "</" key ">")
26415 t t string)))))
26416 (while (string-match "\\\\\\([_^]\\)" string)
26417 (setq string (replace-match (match-string 1 string) t t string)))
26418 string))
26420 (defun org-export-html-convert-emphasize (string)
26421 "Apply emphasis."
26422 (let ((s 0) rpl)
26423 (while (string-match org-emph-re string s)
26424 (if (not (equal
26425 (substring string (match-beginning 3) (1+ (match-beginning 3)))
26426 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
26427 (setq s (match-beginning 0)
26429 (concat
26430 (match-string 1 string)
26431 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
26432 (match-string 4 string)
26433 (nth 3 (assoc (match-string 3 string)
26434 org-emphasis-alist))
26435 (match-string 5 string))
26436 string (replace-match rpl t t string)
26437 s (+ s (- (length rpl) 2)))
26438 (setq s (1+ s))))
26439 string))
26441 (defvar org-par-open nil)
26442 (defun org-open-par ()
26443 "Insert <p>, but first close previous paragraph if any."
26444 (org-close-par-maybe)
26445 (insert "\n<p>")
26446 (setq org-par-open t))
26447 (defun org-close-par-maybe ()
26448 "Close paragraph if there is one open."
26449 (when org-par-open
26450 (insert "</p>")
26451 (setq org-par-open nil)))
26452 (defun org-close-li ()
26453 "Close <li> if necessary."
26454 (org-close-par-maybe)
26455 (insert "</li>\n"))
26457 (defvar body-only) ; dynamically scoped into this.
26458 (defun org-html-level-start (level title umax with-toc head-count)
26459 "Insert a new level in HTML export.
26460 When TITLE is nil, just close all open levels."
26461 (org-close-par-maybe)
26462 (let ((l org-level-max) snumber)
26463 (while (>= l level)
26464 (if (aref org-levels-open (1- l))
26465 (progn
26466 (org-html-level-close l umax)
26467 (aset org-levels-open (1- l) nil)))
26468 (setq l (1- l)))
26469 (when title
26470 ;; If title is nil, this means this function is called to close
26471 ;; all levels, so the rest is done only if title is given
26472 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
26473 (setq title (replace-match
26474 (if org-export-with-tags
26475 (save-match-data
26476 (concat
26477 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
26478 (mapconcat 'identity (org-split-string
26479 (match-string 1 title) ":")
26480 "&nbsp;")
26481 "</span>"))
26483 t t title)))
26484 (if (> level umax)
26485 (progn
26486 (if (aref org-levels-open (1- level))
26487 (progn
26488 (org-close-li)
26489 (insert "<li>" title "<br/>\n"))
26490 (aset org-levels-open (1- level) t)
26491 (org-close-par-maybe)
26492 (insert "<ul>\n<li>" title "<br/>\n")))
26493 (aset org-levels-open (1- level) t)
26494 (setq snumber (org-section-number level))
26495 (if (and org-export-with-section-numbers (not body-only))
26496 (setq title (concat snumber " " title)))
26497 (setq level (+ level org-export-html-toplevel-hlevel -1))
26498 (unless (= head-count 1) (insert "\n</div>\n"))
26499 (insert (format "\n<div id=\"outline-container-%s\" class=\"outline-%d\">\n<h%d id=\"sec-%s\">%s</h%d>\n<div id=\"text-%s\">\n"
26500 snumber level level snumber title level snumber))
26501 (org-open-par)))))
26503 (defun org-html-level-close (level max-outline-level)
26504 "Terminate one level in HTML export."
26505 (if (<= level max-outline-level)
26506 (insert "</div>\n")
26507 (org-close-li)
26508 (insert "</ul>\n")))
26510 ;;; iCalendar export
26512 ;;;###autoload
26513 (defun org-export-icalendar-this-file ()
26514 "Export current file as an iCalendar file.
26515 The iCalendar file will be located in the same directory as the Org-mode
26516 file, but with extension `.ics'."
26517 (interactive)
26518 (org-export-icalendar nil buffer-file-name))
26520 ;;;###autoload
26521 (defun org-export-icalendar-all-agenda-files ()
26522 "Export all files in `org-agenda-files' to iCalendar .ics files.
26523 Each iCalendar file will be located in the same directory as the Org-mode
26524 file, but with extension `.ics'."
26525 (interactive)
26526 (apply 'org-export-icalendar nil (org-agenda-files t)))
26528 ;;;###autoload
26529 (defun org-export-icalendar-combine-agenda-files ()
26530 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26531 The file is stored under the name `org-combined-agenda-icalendar-file'."
26532 (interactive)
26533 (apply 'org-export-icalendar t (org-agenda-files t)))
26535 (defun org-export-icalendar (combine &rest files)
26536 "Create iCalendar files for all elements of FILES.
26537 If COMBINE is non-nil, combine all calendar entries into a single large
26538 file and store it under the name `org-combined-agenda-icalendar-file'."
26539 (save-excursion
26540 (org-prepare-agenda-buffers files)
26541 (let* ((dir (org-export-directory
26542 :ical (list :publishing-directory
26543 org-export-publishing-directory)))
26544 file ical-file ical-buffer category started org-agenda-new-buffers)
26545 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26546 (when combine
26547 (setq ical-file
26548 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26549 org-combined-agenda-icalendar-file
26550 (expand-file-name org-combined-agenda-icalendar-file dir))
26551 ical-buffer (org-get-agenda-file-buffer ical-file))
26552 (set-buffer ical-buffer) (erase-buffer))
26553 (while (setq file (pop files))
26554 (catch 'nextfile
26555 (org-check-agenda-file file)
26556 (set-buffer (org-get-agenda-file-buffer file))
26557 (unless combine
26558 (setq ical-file (concat (file-name-as-directory dir)
26559 (file-name-sans-extension
26560 (file-name-nondirectory buffer-file-name))
26561 ".ics"))
26562 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26563 (with-current-buffer ical-buffer (erase-buffer)))
26564 (setq category (or org-category
26565 (file-name-sans-extension
26566 (file-name-nondirectory buffer-file-name))))
26567 (if (symbolp category) (setq category (symbol-name category)))
26568 (let ((standard-output ical-buffer))
26569 (if combine
26570 (and (not started) (setq started t)
26571 (org-start-icalendar-file org-icalendar-combined-name))
26572 (org-start-icalendar-file category))
26573 (org-print-icalendar-entries combine)
26574 (when (or (and combine (not files)) (not combine))
26575 (org-finish-icalendar-file)
26576 (set-buffer ical-buffer)
26577 (save-buffer)
26578 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26579 (org-release-buffers org-agenda-new-buffers))))
26581 (defvar org-after-save-iCalendar-file-hook nil
26582 "Hook run after an iCalendar file has been saved.
26583 The iCalendar buffer is still current when this hook is run.
26584 A good way to use this is to tell a desktop calenndar application to re-read
26585 the iCalendar file.")
26587 (defun org-print-icalendar-entries (&optional combine)
26588 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26589 When COMBINE is non nil, add the category to each line."
26590 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26591 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26592 (dts (org-ical-ts-to-string
26593 (format-time-string (cdr org-time-stamp-formats) (current-time))
26594 "DTSTART"))
26595 hd ts ts2 state status (inc t) pos b sexp rrule
26596 scheduledp deadlinep tmp pri category entry location summary desc
26597 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26598 (org-refresh-category-properties)
26599 (save-excursion
26600 (goto-char (point-min))
26601 (while (re-search-forward re1 nil t)
26602 (catch :skip
26603 (org-agenda-skip)
26604 (when (boundp 'org-icalendar-verify-function)
26605 (unless (funcall org-icalendar-verify-function)
26606 (outline-next-heading)
26607 (backward-char 1)
26608 (throw :skip nil)))
26609 (setq pos (match-beginning 0)
26610 ts (match-string 0)
26611 inc t
26612 hd (org-get-heading)
26613 summary (org-icalendar-cleanup-string
26614 (org-entry-get nil "SUMMARY"))
26615 desc (org-icalendar-cleanup-string
26616 (or (org-entry-get nil "DESCRIPTION")
26617 (and org-icalendar-include-body (org-get-entry)))
26618 t org-icalendar-include-body)
26619 location (org-icalendar-cleanup-string
26620 (org-entry-get nil "LOCATION"))
26621 category (org-get-category))
26622 (if (looking-at re2)
26623 (progn
26624 (goto-char (match-end 0))
26625 (setq ts2 (match-string 1) inc nil))
26626 (setq tmp (buffer-substring (max (point-min)
26627 (- pos org-ds-keyword-length))
26628 pos)
26629 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26630 (progn
26631 (setq inc nil)
26632 (replace-match "\\1" t nil ts))
26634 deadlinep (string-match org-deadline-regexp tmp)
26635 scheduledp (string-match org-scheduled-regexp tmp)
26636 ;; donep (org-entry-is-done-p)
26638 (if (or (string-match org-tr-regexp hd)
26639 (string-match org-ts-regexp hd))
26640 (setq hd (replace-match "" t t hd)))
26641 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26642 (setq rrule
26643 (concat "\nRRULE:FREQ="
26644 (cdr (assoc
26645 (match-string 2 ts)
26646 '(("d" . "DAILY")("w" . "WEEKLY")
26647 ("m" . "MONTHLY")("y" . "YEARLY"))))
26648 ";INTERVAL=" (match-string 1 ts)))
26649 (setq rrule ""))
26650 (setq summary (or summary hd))
26651 (if (string-match org-bracket-link-regexp summary)
26652 (setq summary
26653 (replace-match (if (match-end 3)
26654 (match-string 3 summary)
26655 (match-string 1 summary))
26656 t t summary)))
26657 (if deadlinep (setq summary (concat "DL: " summary)))
26658 (if scheduledp (setq summary (concat "S: " summary)))
26659 (if (string-match "\\`<%%" ts)
26660 (with-current-buffer sexp-buffer
26661 (insert (substring ts 1 -1) " " summary "\n"))
26662 (princ (format "BEGIN:VEVENT
26664 %s%s
26665 SUMMARY:%s%s%s
26666 CATEGORIES:%s
26667 END:VEVENT\n"
26668 (org-ical-ts-to-string ts "DTSTART")
26669 (org-ical-ts-to-string ts2 "DTEND" inc)
26670 rrule summary
26671 (if (and desc (string-match "\\S-" desc))
26672 (concat "\nDESCRIPTION: " desc) "")
26673 (if (and location (string-match "\\S-" location))
26674 (concat "\nLOCATION: " location) "")
26675 category)))))
26677 (when (and org-icalendar-include-sexps
26678 (condition-case nil (require 'icalendar) (error nil))
26679 (fboundp 'icalendar-export-region))
26680 ;; Get all the literal sexps
26681 (goto-char (point-min))
26682 (while (re-search-forward "^&?%%(" nil t)
26683 (catch :skip
26684 (org-agenda-skip)
26685 (setq b (match-beginning 0))
26686 (goto-char (1- (match-end 0)))
26687 (forward-sexp 1)
26688 (end-of-line 1)
26689 (setq sexp (buffer-substring b (point)))
26690 (with-current-buffer sexp-buffer
26691 (insert sexp "\n"))
26692 (princ (org-diary-to-ical-string sexp-buffer)))))
26694 (when org-icalendar-include-todo
26695 (goto-char (point-min))
26696 (while (re-search-forward org-todo-line-regexp nil t)
26697 (catch :skip
26698 (org-agenda-skip)
26699 (when (boundp 'org-icalendar-verify-function)
26700 (unless (funcall org-icalendar-verify-function)
26701 (outline-next-heading)
26702 (backward-char 1)
26703 (throw :skip nil)))
26704 (setq state (match-string 2))
26705 (setq status (if (member state org-done-keywords)
26706 "COMPLETED" "NEEDS-ACTION"))
26707 (when (and state
26708 (or (not (member state org-done-keywords))
26709 (eq org-icalendar-include-todo 'all))
26710 (not (member org-archive-tag (org-get-tags-at)))
26712 (setq hd (match-string 3)
26713 summary (org-icalendar-cleanup-string
26714 (org-entry-get nil "SUMMARY"))
26715 desc (org-icalendar-cleanup-string
26716 (or (org-entry-get nil "DESCRIPTION")
26717 (and org-icalendar-include-body (org-get-entry)))
26718 t org-icalendar-include-body)
26719 location (org-icalendar-cleanup-string
26720 (org-entry-get nil "LOCATION")))
26721 (if (string-match org-bracket-link-regexp hd)
26722 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26723 (match-string 1 hd))
26724 t t hd)))
26725 (if (string-match org-priority-regexp hd)
26726 (setq pri (string-to-char (match-string 2 hd))
26727 hd (concat (substring hd 0 (match-beginning 1))
26728 (substring hd (match-end 1))))
26729 (setq pri org-default-priority))
26730 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26731 (- org-lowest-priority org-highest-priority))))))
26733 (princ (format "BEGIN:VTODO
26735 SUMMARY:%s%s%s
26736 CATEGORIES:%s
26737 SEQUENCE:1
26738 PRIORITY:%d
26739 STATUS:%s
26740 END:VTODO\n"
26742 (or summary hd)
26743 (if (and location (string-match "\\S-" location))
26744 (concat "\nLOCATION: " location) "")
26745 (if (and desc (string-match "\\S-" desc))
26746 (concat "\nDESCRIPTION: " desc) "")
26747 category pri status)))))))))
26749 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26750 "Take out stuff and quote what needs to be quoted.
26751 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26752 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26753 characters."
26754 (if (not s)
26756 (when is-body
26757 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26758 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26759 (while (string-match re s) (setq s (replace-match "" t t s)))
26760 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26761 (let ((start 0))
26762 (while (string-match "\\([,;\\]\\)" s start)
26763 (setq start (+ (match-beginning 0) 2)
26764 s (replace-match "\\\\\\1" nil nil s))))
26765 (when is-body
26766 (while (string-match "[ \t]*\n[ \t]*" s)
26767 (setq s (replace-match "\\n" t t s))))
26768 (setq s (org-trim s))
26769 (if is-body
26770 (if maxlength
26771 (if (and (numberp maxlength)
26772 (> (length s) maxlength))
26773 (setq s (substring s 0 maxlength)))))
26776 (defun org-get-entry ()
26777 "Clean-up description string."
26778 (save-excursion
26779 (org-back-to-heading t)
26780 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26782 (defun org-start-icalendar-file (name)
26783 "Start an iCalendar file by inserting the header."
26784 (let ((user user-full-name)
26785 (name (or name "unknown"))
26786 (timezone (cadr (current-time-zone))))
26787 (princ
26788 (format "BEGIN:VCALENDAR
26789 VERSION:2.0
26790 X-WR-CALNAME:%s
26791 PRODID:-//%s//Emacs with Org-mode//EN
26792 X-WR-TIMEZONE:%s
26793 CALSCALE:GREGORIAN\n" name user timezone))))
26795 (defun org-finish-icalendar-file ()
26796 "Finish an iCalendar file by inserting the END statement."
26797 (princ "END:VCALENDAR\n"))
26799 (defun org-ical-ts-to-string (s keyword &optional inc)
26800 "Take a time string S and convert it to iCalendar format.
26801 KEYWORD is added in front, to make a complete line like DTSTART....
26802 When INC is non-nil, increase the hour by two (if time string contains
26803 a time), or the day by one (if it does not contain a time)."
26804 (let ((t1 (org-parse-time-string s 'nodefault))
26805 t2 fmt have-time time)
26806 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26807 (setq t2 t1 have-time t)
26808 (setq t2 (org-parse-time-string s)))
26809 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26810 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26811 (when inc
26812 (if have-time
26813 (if org-agenda-default-appointment-duration
26814 (setq mi (+ org-agenda-default-appointment-duration mi))
26815 (setq h (+ 2 h)))
26816 (setq d (1+ d))))
26817 (setq time (encode-time s mi h d m y)))
26818 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26819 (concat keyword (format-time-string fmt time))))
26821 ;;; XOXO export
26823 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26824 (with-current-buffer buffer
26825 (apply 'insert output)))
26826 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26828 (defun org-export-as-xoxo (&optional buffer)
26829 "Export the org buffer as XOXO.
26830 The XOXO buffer is named *xoxo-<source buffer name>*"
26831 (interactive (list (current-buffer)))
26832 ;; A quickie abstraction
26834 ;; Output everything as XOXO
26835 (with-current-buffer (get-buffer buffer)
26836 (let* ((pos (point))
26837 (opt-plist (org-combine-plists (org-default-export-plist)
26838 (org-infile-export-plist)))
26839 (filename (concat (file-name-as-directory
26840 (org-export-directory :xoxo opt-plist))
26841 (file-name-sans-extension
26842 (file-name-nondirectory buffer-file-name))
26843 ".html"))
26844 (out (find-file-noselect filename))
26845 (last-level 1)
26846 (hanging-li nil))
26847 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26848 ;; Check the output buffer is empty.
26849 (with-current-buffer out (erase-buffer))
26850 ;; Kick off the output
26851 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26852 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26853 (let* ((hd (match-string-no-properties 1))
26854 (level (length hd))
26855 (text (concat
26856 (match-string-no-properties 2)
26857 (save-excursion
26858 (goto-char (match-end 0))
26859 (let ((str ""))
26860 (catch 'loop
26861 (while 't
26862 (forward-line)
26863 (if (looking-at "^[ \t]\\(.*\\)")
26864 (setq str (concat str (match-string-no-properties 1)))
26865 (throw 'loop str)))))))))
26867 ;; Handle level rendering
26868 (cond
26869 ((> level last-level)
26870 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26872 ((< level last-level)
26873 (dotimes (- (- last-level level) 1)
26874 (if hanging-li
26875 (org-export-as-xoxo-insert-into out "</li>\n"))
26876 (org-export-as-xoxo-insert-into out "</ol>\n"))
26877 (when hanging-li
26878 (org-export-as-xoxo-insert-into out "</li>\n")
26879 (setq hanging-li nil)))
26881 ((equal level last-level)
26882 (if hanging-li
26883 (org-export-as-xoxo-insert-into out "</li>\n")))
26886 (setq last-level level)
26888 ;; And output the new li
26889 (setq hanging-li 't)
26890 (if (equal ?+ (elt text 0))
26891 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26892 (org-export-as-xoxo-insert-into out "<li>" text))))
26894 ;; Finally finish off the ol
26895 (dotimes (- last-level 1)
26896 (if hanging-li
26897 (org-export-as-xoxo-insert-into out "</li>\n"))
26898 (org-export-as-xoxo-insert-into out "</ol>\n"))
26900 (goto-char pos)
26901 ;; Finish the buffer off and clean it up.
26902 (switch-to-buffer-other-window out)
26903 (indent-region (point-min) (point-max) nil)
26904 (save-buffer)
26905 (goto-char (point-min))
26909 ;;;; Key bindings
26911 ;; Make `C-c C-x' a prefix key
26912 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26914 ;; TAB key with modifiers
26915 (org-defkey org-mode-map "\C-i" 'org-cycle)
26916 (org-defkey org-mode-map [(tab)] 'org-cycle)
26917 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26918 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26919 (org-defkey org-mode-map "\M-\t" 'org-complete)
26920 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26921 ;; The following line is necessary under Suse GNU/Linux
26922 (unless (featurep 'xemacs)
26923 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26924 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26925 (define-key org-mode-map [backtab] 'org-shifttab)
26927 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26928 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26929 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26931 ;; Cursor keys with modifiers
26932 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26933 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26934 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26935 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26937 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26938 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26939 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26940 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26942 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26943 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26944 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26945 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26947 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26948 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26950 ;;; Extra keys for tty access.
26951 ;; We only set them when really needed because otherwise the
26952 ;; menus don't show the simple keys
26954 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26955 (not window-system))
26956 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26957 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26958 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26959 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26960 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26961 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26962 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26963 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26964 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26965 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26966 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26967 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26968 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26969 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26970 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26971 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26972 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26973 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26974 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26975 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26976 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26977 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26979 ;; All the other keys
26981 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26982 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26983 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26984 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26985 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26986 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26987 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26988 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26989 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26990 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26991 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26992 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26993 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26994 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26995 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26996 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26997 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26998 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26999 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
27000 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
27001 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
27002 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
27003 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
27004 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
27005 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
27006 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
27007 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
27008 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
27009 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
27010 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
27011 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
27012 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
27013 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
27014 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
27015 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
27016 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
27017 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
27018 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
27019 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
27020 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
27021 (org-defkey org-mode-map "\C-c^" 'org-sort)
27022 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
27023 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
27024 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
27025 (org-defkey org-mode-map "\C-m" 'org-return)
27026 (org-defkey org-mode-map "\C-j" 'org-return-indent)
27027 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
27028 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
27029 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
27030 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
27031 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
27032 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
27033 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
27034 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
27035 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
27036 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
27037 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
27038 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
27039 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
27040 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
27041 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
27043 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
27044 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
27045 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
27046 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
27048 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
27049 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
27050 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
27051 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
27052 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
27053 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
27054 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
27055 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
27056 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
27057 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
27058 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
27059 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
27061 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
27063 (when (featurep 'xemacs)
27064 (org-defkey org-mode-map 'button3 'popup-mode-menu))
27066 (defsubst org-table-p () (org-at-table-p))
27068 (defun org-self-insert-command (N)
27069 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
27070 If the cursor is in a table looking at whitespace, the whitespace is
27071 overwritten, and the table is not marked as requiring realignment."
27072 (interactive "p")
27073 (if (and (org-table-p)
27074 (progn
27075 ;; check if we blank the field, and if that triggers align
27076 (and org-table-auto-blank-field
27077 (member last-command
27078 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
27079 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
27080 ;; got extra space, this field does not determine column width
27081 (let (org-table-may-need-update) (org-table-blank-field))
27082 ;; no extra space, this field may determine column width
27083 (org-table-blank-field)))
27085 (eq N 1)
27086 (looking-at "[^|\n]* |"))
27087 (let (org-table-may-need-update)
27088 (goto-char (1- (match-end 0)))
27089 (delete-backward-char 1)
27090 (goto-char (match-beginning 0))
27091 (self-insert-command N))
27092 (setq org-table-may-need-update t)
27093 (self-insert-command N)
27094 (org-fix-tags-on-the-fly)))
27096 (defun org-fix-tags-on-the-fly ()
27097 (when (and (equal (char-after (point-at-bol)) ?*)
27098 (org-on-heading-p))
27099 (org-align-tags-here org-tags-column)))
27101 (defun org-delete-backward-char (N)
27102 "Like `delete-backward-char', insert whitespace at field end in tables.
27103 When deleting backwards, in tables this function will insert whitespace in
27104 front of the next \"|\" separator, to keep the table aligned. The table will
27105 still be marked for re-alignment if the field did fill the entire column,
27106 because, in this case the deletion might narrow the column."
27107 (interactive "p")
27108 (if (and (org-table-p)
27109 (eq N 1)
27110 (string-match "|" (buffer-substring (point-at-bol) (point)))
27111 (looking-at ".*?|"))
27112 (let ((pos (point))
27113 (noalign (looking-at "[^|\n\r]* |"))
27114 (c org-table-may-need-update))
27115 (backward-delete-char N)
27116 (skip-chars-forward "^|")
27117 (insert " ")
27118 (goto-char (1- pos))
27119 ;; noalign: if there were two spaces at the end, this field
27120 ;; does not determine the width of the column.
27121 (if noalign (setq org-table-may-need-update c)))
27122 (backward-delete-char N)
27123 (org-fix-tags-on-the-fly)))
27125 (defun org-delete-char (N)
27126 "Like `delete-char', but insert whitespace at field end in tables.
27127 When deleting characters, in tables this function will insert whitespace in
27128 front of the next \"|\" separator, to keep the table aligned. The table will
27129 still be marked for re-alignment if the field did fill the entire column,
27130 because, in this case the deletion might narrow the column."
27131 (interactive "p")
27132 (if (and (org-table-p)
27133 (not (bolp))
27134 (not (= (char-after) ?|))
27135 (eq N 1))
27136 (if (looking-at ".*?|")
27137 (let ((pos (point))
27138 (noalign (looking-at "[^|\n\r]* |"))
27139 (c org-table-may-need-update))
27140 (replace-match (concat
27141 (substring (match-string 0) 1 -1)
27142 " |"))
27143 (goto-char pos)
27144 ;; noalign: if there were two spaces at the end, this field
27145 ;; does not determine the width of the column.
27146 (if noalign (setq org-table-may-need-update c)))
27147 (delete-char N))
27148 (delete-char N)
27149 (org-fix-tags-on-the-fly)))
27151 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
27152 (put 'org-self-insert-command 'delete-selection t)
27153 (put 'orgtbl-self-insert-command 'delete-selection t)
27154 (put 'org-delete-char 'delete-selection 'supersede)
27155 (put 'org-delete-backward-char 'delete-selection 'supersede)
27157 ;; Make `flyspell-mode' delay after some commands
27158 (put 'org-self-insert-command 'flyspell-delayed t)
27159 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
27160 (put 'org-delete-char 'flyspell-delayed t)
27161 (put 'org-delete-backward-char 'flyspell-delayed t)
27163 ;; Make pabbrev-mode expand after org-mode commands
27164 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
27165 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
27167 ;; How to do this: Measure non-white length of current string
27168 ;; If equal to column width, we should realign.
27170 (defun org-remap (map &rest commands)
27171 "In MAP, remap the functions given in COMMANDS.
27172 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
27173 (let (new old)
27174 (while commands
27175 (setq old (pop commands) new (pop commands))
27176 (if (fboundp 'command-remapping)
27177 (org-defkey map (vector 'remap old) new)
27178 (substitute-key-definition old new map global-map)))))
27180 (when (eq org-enable-table-editor 'optimized)
27181 ;; If the user wants maximum table support, we need to hijack
27182 ;; some standard editing functions
27183 (org-remap org-mode-map
27184 'self-insert-command 'org-self-insert-command
27185 'delete-char 'org-delete-char
27186 'delete-backward-char 'org-delete-backward-char)
27187 (org-defkey org-mode-map "|" 'org-force-self-insert))
27189 (defun org-shiftcursor-error ()
27190 "Throw an error because Shift-Cursor command was applied in wrong context."
27191 (error "This command is active in special context like tables, headlines or timestamps"))
27193 (defun org-shifttab (&optional arg)
27194 "Global visibility cycling or move to previous table field.
27195 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
27196 on context.
27197 See the individual commands for more information."
27198 (interactive "P")
27199 (cond
27200 ((org-at-table-p) (call-interactively 'org-table-previous-field))
27201 (arg (message "Content view to level: ")
27202 (org-content (prefix-numeric-value arg))
27203 (setq org-cycle-global-status 'overview))
27204 (t (call-interactively 'org-global-cycle))))
27206 (defun org-shiftmetaleft ()
27207 "Promote subtree or delete table column.
27208 Calls `org-promote-subtree', `org-outdent-item',
27209 or `org-table-delete-column', depending on context.
27210 See the individual commands for more information."
27211 (interactive)
27212 (cond
27213 ((org-at-table-p) (call-interactively 'org-table-delete-column))
27214 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
27215 ((org-at-item-p) (call-interactively 'org-outdent-item))
27216 (t (org-shiftcursor-error))))
27218 (defun org-shiftmetaright ()
27219 "Demote subtree or insert table column.
27220 Calls `org-demote-subtree', `org-indent-item',
27221 or `org-table-insert-column', depending on context.
27222 See the individual commands for more information."
27223 (interactive)
27224 (cond
27225 ((org-at-table-p) (call-interactively 'org-table-insert-column))
27226 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
27227 ((org-at-item-p) (call-interactively 'org-indent-item))
27228 (t (org-shiftcursor-error))))
27230 (defun org-shiftmetaup (&optional arg)
27231 "Move subtree up or kill table row.
27232 Calls `org-move-subtree-up' or `org-table-kill-row' or
27233 `org-move-item-up' depending on context. See the individual commands
27234 for more information."
27235 (interactive "P")
27236 (cond
27237 ((org-at-table-p) (call-interactively 'org-table-kill-row))
27238 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27239 ((org-at-item-p) (call-interactively 'org-move-item-up))
27240 (t (org-shiftcursor-error))))
27241 (defun org-shiftmetadown (&optional arg)
27242 "Move subtree down or insert table row.
27243 Calls `org-move-subtree-down' or `org-table-insert-row' or
27244 `org-move-item-down', depending on context. See the individual
27245 commands for more information."
27246 (interactive "P")
27247 (cond
27248 ((org-at-table-p) (call-interactively 'org-table-insert-row))
27249 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27250 ((org-at-item-p) (call-interactively 'org-move-item-down))
27251 (t (org-shiftcursor-error))))
27253 (defun org-metaleft (&optional arg)
27254 "Promote heading or move table column to left.
27255 Calls `org-do-promote' or `org-table-move-column', depending on context.
27256 With no specific context, calls the Emacs default `backward-word'.
27257 See the individual commands for more information."
27258 (interactive "P")
27259 (cond
27260 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
27261 ((or (org-on-heading-p) (org-region-active-p))
27262 (call-interactively 'org-do-promote))
27263 ((org-at-item-p) (call-interactively 'org-outdent-item))
27264 (t (call-interactively 'backward-word))))
27266 (defun org-metaright (&optional arg)
27267 "Demote subtree or move table column to right.
27268 Calls `org-do-demote' or `org-table-move-column', depending on context.
27269 With no specific context, calls the Emacs default `forward-word'.
27270 See the individual commands for more information."
27271 (interactive "P")
27272 (cond
27273 ((org-at-table-p) (call-interactively 'org-table-move-column))
27274 ((or (org-on-heading-p) (org-region-active-p))
27275 (call-interactively 'org-do-demote))
27276 ((org-at-item-p) (call-interactively 'org-indent-item))
27277 (t (call-interactively 'forward-word))))
27279 (defun org-metaup (&optional arg)
27280 "Move subtree up or move table row up.
27281 Calls `org-move-subtree-up' or `org-table-move-row' or
27282 `org-move-item-up', depending on context. See the individual commands
27283 for more information."
27284 (interactive "P")
27285 (cond
27286 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
27287 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27288 ((org-at-item-p) (call-interactively 'org-move-item-up))
27289 (t (transpose-lines 1) (beginning-of-line -1))))
27291 (defun org-metadown (&optional arg)
27292 "Move subtree down or move table row down.
27293 Calls `org-move-subtree-down' or `org-table-move-row' or
27294 `org-move-item-down', depending on context. See the individual
27295 commands for more information."
27296 (interactive "P")
27297 (cond
27298 ((org-at-table-p) (call-interactively 'org-table-move-row))
27299 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27300 ((org-at-item-p) (call-interactively 'org-move-item-down))
27301 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
27303 (defun org-shiftup (&optional arg)
27304 "Increase item in timestamp or increase priority of current headline.
27305 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
27306 depending on context. See the individual commands for more information."
27307 (interactive "P")
27308 (cond
27309 ((org-at-timestamp-p t)
27310 (call-interactively (if org-edit-timestamp-down-means-later
27311 'org-timestamp-down 'org-timestamp-up)))
27312 ((org-on-heading-p) (call-interactively 'org-priority-up))
27313 ((org-at-item-p) (call-interactively 'org-previous-item))
27314 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
27316 (defun org-shiftdown (&optional arg)
27317 "Decrease item in timestamp or decrease priority of current headline.
27318 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
27319 depending on context. See the individual commands for more information."
27320 (interactive "P")
27321 (cond
27322 ((org-at-timestamp-p t)
27323 (call-interactively (if org-edit-timestamp-down-means-later
27324 'org-timestamp-up 'org-timestamp-down)))
27325 ((org-on-heading-p) (call-interactively 'org-priority-down))
27326 (t (call-interactively 'org-next-item))))
27328 (defun org-shiftright ()
27329 "Next TODO keyword or timestamp one day later, depending on context."
27330 (interactive)
27331 (cond
27332 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
27333 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
27334 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
27335 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
27336 (t (org-shiftcursor-error))))
27338 (defun org-shiftleft ()
27339 "Previous TODO keyword or timestamp one day earlier, depending on context."
27340 (interactive)
27341 (cond
27342 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
27343 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
27344 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
27345 ((org-at-property-p)
27346 (call-interactively 'org-property-previous-allowed-value))
27347 (t (org-shiftcursor-error))))
27349 (defun org-shiftcontrolright ()
27350 "Switch to next TODO set."
27351 (interactive)
27352 (cond
27353 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
27354 (t (org-shiftcursor-error))))
27356 (defun org-shiftcontrolleft ()
27357 "Switch to previous TODO set."
27358 (interactive)
27359 (cond
27360 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
27361 (t (org-shiftcursor-error))))
27363 (defun org-ctrl-c-ret ()
27364 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
27365 (interactive)
27366 (cond
27367 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
27368 (t (call-interactively 'org-insert-heading))))
27370 (defun org-copy-special ()
27371 "Copy region in table or copy current subtree.
27372 Calls `org-table-copy' or `org-copy-subtree', depending on context.
27373 See the individual commands for more information."
27374 (interactive)
27375 (call-interactively
27376 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
27378 (defun org-cut-special ()
27379 "Cut region in table or cut current subtree.
27380 Calls `org-table-copy' or `org-cut-subtree', depending on context.
27381 See the individual commands for more information."
27382 (interactive)
27383 (call-interactively
27384 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
27386 (defun org-paste-special (arg)
27387 "Paste rectangular region into table, or past subtree relative to level.
27388 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
27389 See the individual commands for more information."
27390 (interactive "P")
27391 (if (org-at-table-p)
27392 (org-table-paste-rectangle)
27393 (org-paste-subtree arg)))
27395 (defun org-ctrl-c-ctrl-c (&optional arg)
27396 "Set tags in headline, or update according to changed information at point.
27398 This command does many different things, depending on context:
27400 - If the cursor is in a headline, prompt for tags and insert them
27401 into the current line, aligned to `org-tags-column'. When called
27402 with prefix arg, realign all tags in the current buffer.
27404 - If the cursor is in one of the special #+KEYWORD lines, this
27405 triggers scanning the buffer for these lines and updating the
27406 information.
27408 - If the cursor is inside a table, realign the table. This command
27409 works even if the automatic table editor has been turned off.
27411 - If the cursor is on a #+TBLFM line, re-apply the formulas to
27412 the entire table.
27414 - If the cursor is a the beginning of a dynamic block, update it.
27416 - If the cursor is inside a table created by the table.el package,
27417 activate that table.
27419 - If the current buffer is a remember buffer, close note and file it.
27420 with a prefix argument, file it without further interaction to the default
27421 location.
27423 - If the cursor is on a <<<target>>>, update radio targets and corresponding
27424 links in this buffer.
27426 - If the cursor is on a numbered item in a plain list, renumber the
27427 ordered list.
27429 - If the cursor is on a checkbox, toggle it."
27430 (interactive "P")
27431 (let ((org-enable-table-editor t))
27432 (cond
27433 ((or org-clock-overlays
27434 org-occur-highlights
27435 org-latex-fragment-image-overlays)
27436 (org-remove-clock-overlays)
27437 (org-remove-occur-highlights)
27438 (org-remove-latex-fragment-image-overlays)
27439 (message "Temporary highlights/overlays removed from current buffer"))
27440 ((and (local-variable-p 'org-finish-function (current-buffer))
27441 (fboundp org-finish-function))
27442 (funcall org-finish-function))
27443 ((org-at-property-p)
27444 (call-interactively 'org-property-action))
27445 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
27446 ((org-on-heading-p) (call-interactively 'org-set-tags))
27447 ((org-at-table.el-p)
27448 (require 'table)
27449 (beginning-of-line 1)
27450 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
27451 (call-interactively 'table-recognize-table))
27452 ((org-at-table-p)
27453 (org-table-maybe-eval-formula)
27454 (if arg
27455 (call-interactively 'org-table-recalculate)
27456 (org-table-maybe-recalculate-line))
27457 (call-interactively 'org-table-align))
27458 ((org-at-item-checkbox-p)
27459 (call-interactively 'org-toggle-checkbox))
27460 ((org-at-item-p)
27461 (call-interactively 'org-maybe-renumber-ordered-list))
27462 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
27463 ;; Dynamic block
27464 (beginning-of-line 1)
27465 (org-update-dblock))
27466 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
27467 (cond
27468 ((equal (match-string 1) "TBLFM")
27469 ;; Recalculate the table before this line
27470 (save-excursion
27471 (beginning-of-line 1)
27472 (skip-chars-backward " \r\n\t")
27473 (if (org-at-table-p)
27474 (org-call-with-arg 'org-table-recalculate t))))
27476 (call-interactively 'org-mode-restart))))
27477 (t (error "C-c C-c can do nothing useful at this location.")))))
27479 (defun org-mode-restart ()
27480 "Restart Org-mode, to scan again for special lines.
27481 Also updates the keyword regular expressions."
27482 (interactive)
27483 (let ((org-inhibit-startup t)) (org-mode))
27484 (message "Org-mode restarted to refresh keyword and special line setup"))
27486 (defun org-kill-note-or-show-branches ()
27487 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
27488 (interactive)
27489 (if (not org-finish-function)
27490 (call-interactively 'show-branches)
27491 (let ((org-note-abort t))
27492 (funcall org-finish-function))))
27494 (defun org-return (&optional indent)
27495 "Goto next table row or insert a newline.
27496 Calls `org-table-next-row' or `newline', depending on context.
27497 See the individual commands for more information."
27498 (interactive)
27499 (cond
27500 ((bobp) (if indent (newline-and-indent) (newline)))
27501 ((and (org-at-heading-p)
27502 (looking-at
27503 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27504 (org-show-entry)
27505 (end-of-line 1)
27506 (newline))
27507 ((org-at-table-p)
27508 (org-table-justify-field-maybe)
27509 (call-interactively 'org-table-next-row))
27510 (t (if indent (newline-and-indent) (newline)))))
27512 (defun org-return-indent ()
27513 "Goto next table row or insert a newline and indent.
27514 Calls `org-table-next-row' or `newline-and-indent', depending on
27515 context. See the individual commands for more information."
27516 (interactive)
27517 (org-return t))
27519 (defun org-ctrl-c-star ()
27520 "Compute table, or change heading status of lines.
27521 Calls `org-table-recalculate' or `org-toggle-region-headlines',
27522 depending on context. This will also turn a plain list item or a normal
27523 line into a subheading."
27524 (interactive)
27525 (cond
27526 ((org-at-table-p)
27527 (call-interactively 'org-table-recalculate))
27528 ((org-region-active-p)
27529 ;; Convert all lines in region to list items
27530 (call-interactively 'org-toggle-region-headings))
27531 ((org-on-heading-p)
27532 (org-toggle-region-headings (point-at-bol)
27533 (min (1+ (point-at-eol)) (point-max))))
27534 ((org-at-item-p)
27535 ;; Convert to heading
27536 (let ((level (save-match-data
27537 (save-excursion
27538 (condition-case nil
27539 (progn
27540 (org-back-to-heading t)
27541 (funcall outline-level))
27542 (error 0))))))
27543 (replace-match
27544 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
27545 (t (org-toggle-region-headings (point-at-bol)
27546 (min (1+ (point-at-eol)) (point-max))))))
27548 (defun org-ctrl-c-minus ()
27549 "Insert separator line in table or modify bullet status of line.
27550 Also turns a plain line or a region of lines into list items.
27551 Calls `org-table-insert-hline', `org-toggle-region-items', or
27552 `org-cycle-list-bullet', depending on context."
27553 (interactive)
27554 (cond
27555 ((org-at-table-p)
27556 (call-interactively 'org-table-insert-hline))
27557 ((org-on-heading-p)
27558 ;; Convert to item
27559 (save-excursion
27560 (beginning-of-line 1)
27561 (if (looking-at "\\*+ ")
27562 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
27563 ((org-region-active-p)
27564 ;; Convert all lines in region to list items
27565 (call-interactively 'org-toggle-region-items))
27566 ((org-in-item-p)
27567 (call-interactively 'org-cycle-list-bullet))
27568 (t (org-toggle-region-items (point-at-bol)
27569 (min (1+ (point-at-eol)) (point-max))))))
27571 (defun org-toggle-region-items (beg end)
27572 "Convert all lines in region to list items.
27573 If the first line is already an item, convert all list items in the region
27574 to normal lines."
27575 (interactive "r")
27576 (let (l2 l)
27577 (save-excursion
27578 (goto-char end)
27579 (setq l2 (org-current-line))
27580 (goto-char beg)
27581 (beginning-of-line 1)
27582 (setq l (1- (org-current-line)))
27583 (if (org-at-item-p)
27584 ;; We already have items, de-itemize
27585 (while (< (setq l (1+ l)) l2)
27586 (when (org-at-item-p)
27587 (goto-char (match-beginning 2))
27588 (delete-region (match-beginning 2) (match-end 2))
27589 (and (looking-at "[ \t]+") (replace-match "")))
27590 (beginning-of-line 2))
27591 (while (< (setq l (1+ l)) l2)
27592 (unless (org-at-item-p)
27593 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27594 (replace-match "\\1- \\2")))
27595 (beginning-of-line 2))))))
27597 (defun org-toggle-region-headings (beg end)
27598 "Convert all lines in region to list items.
27599 If the first line is already an item, convert all list items in the region
27600 to normal lines."
27601 (interactive "r")
27602 (let (l2 l)
27603 (save-excursion
27604 (goto-char end)
27605 (setq l2 (org-current-line))
27606 (goto-char beg)
27607 (beginning-of-line 1)
27608 (setq l (1- (org-current-line)))
27609 (if (org-on-heading-p)
27610 ;; We already have headlines, de-star them
27611 (while (< (setq l (1+ l)) l2)
27612 (when (org-on-heading-p t)
27613 (and (looking-at outline-regexp) (replace-match "")))
27614 (beginning-of-line 2))
27615 (let* ((stars (save-excursion
27616 (re-search-backward org-complex-heading-regexp nil t)
27617 (or (match-string 1) "*")))
27618 (add-stars (if org-odd-levels-only "**" "*"))
27619 (rpl (concat stars add-stars " \\2")))
27620 (while (< (setq l (1+ l)) l2)
27621 (unless (org-on-heading-p)
27622 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27623 (replace-match rpl)))
27624 (beginning-of-line 2)))))))
27626 (defun org-meta-return (&optional arg)
27627 "Insert a new heading or wrap a region in a table.
27628 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27629 See the individual commands for more information."
27630 (interactive "P")
27631 (cond
27632 ((org-at-table-p)
27633 (call-interactively 'org-table-wrap-region))
27634 (t (call-interactively 'org-insert-heading))))
27636 ;;; Menu entries
27638 ;; Define the Org-mode menus
27639 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27640 '("Tbl"
27641 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27642 ["Next Field" org-cycle (org-at-table-p)]
27643 ["Previous Field" org-shifttab (org-at-table-p)]
27644 ["Next Row" org-return (org-at-table-p)]
27645 "--"
27646 ["Blank Field" org-table-blank-field (org-at-table-p)]
27647 ["Edit Field" org-table-edit-field (org-at-table-p)]
27648 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27649 "--"
27650 ("Column"
27651 ["Move Column Left" org-metaleft (org-at-table-p)]
27652 ["Move Column Right" org-metaright (org-at-table-p)]
27653 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27654 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27655 ("Row"
27656 ["Move Row Up" org-metaup (org-at-table-p)]
27657 ["Move Row Down" org-metadown (org-at-table-p)]
27658 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27659 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27660 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27661 "--"
27662 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27663 ("Rectangle"
27664 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27665 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27666 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27667 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27668 "--"
27669 ("Calculate"
27670 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27671 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27672 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27673 "--"
27674 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27675 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27676 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27677 "--"
27678 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27679 "--"
27680 ["Sum Column/Rectangle" org-table-sum
27681 (or (org-at-table-p) (org-region-active-p))]
27682 ["Which Column?" org-table-current-column (org-at-table-p)])
27683 ["Debug Formulas"
27684 org-table-toggle-formula-debugger
27685 :style toggle :selected org-table-formula-debug]
27686 ["Show Col/Row Numbers"
27687 org-table-toggle-coordinate-overlays
27688 :style toggle :selected org-table-overlay-coordinates]
27689 "--"
27690 ["Create" org-table-create (and (not (org-at-table-p))
27691 org-enable-table-editor)]
27692 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27693 ["Import from File" org-table-import (not (org-at-table-p))]
27694 ["Export to File" org-table-export (org-at-table-p)]
27695 "--"
27696 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27698 (easy-menu-define org-org-menu org-mode-map "Org menu"
27699 '("Org"
27700 ("Show/Hide"
27701 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27702 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27703 ["Sparse Tree" org-occur t]
27704 ["Reveal Context" org-reveal t]
27705 ["Show All" show-all t]
27706 "--"
27707 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27708 "--"
27709 ["New Heading" org-insert-heading t]
27710 ("Navigate Headings"
27711 ["Up" outline-up-heading t]
27712 ["Next" outline-next-visible-heading t]
27713 ["Previous" outline-previous-visible-heading t]
27714 ["Next Same Level" outline-forward-same-level t]
27715 ["Previous Same Level" outline-backward-same-level t]
27716 "--"
27717 ["Jump" org-goto t])
27718 ("Edit Structure"
27719 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27720 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27721 "--"
27722 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27723 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27724 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27725 "--"
27726 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27727 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27728 ["Demote Heading" org-metaright (not (org-at-table-p))]
27729 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27730 "--"
27731 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27732 "--"
27733 ["Convert to odd levels" org-convert-to-odd-levels t]
27734 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27735 ("Editing"
27736 ["Emphasis..." org-emphasize t])
27737 ("Archive"
27738 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27739 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27740 ; :active t :keys "C-u C-c C-x C-a"]
27741 ["Sparse trees open ARCHIVE trees"
27742 (setq org-sparse-tree-open-archived-trees
27743 (not org-sparse-tree-open-archived-trees))
27744 :style toggle :selected org-sparse-tree-open-archived-trees]
27745 ["Cycling opens ARCHIVE trees"
27746 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27747 :style toggle :selected org-cycle-open-archived-trees]
27748 ["Agenda includes ARCHIVE trees"
27749 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27750 :style toggle :selected (not org-agenda-skip-archived-trees)]
27751 "--"
27752 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27753 ; ["Check and Move Children" (org-archive-subtree '(4))
27754 ; :active t :keys "C-u C-c C-x C-s"]
27756 "--"
27757 ("TODO Lists"
27758 ["TODO/DONE/-" org-todo t]
27759 ("Select keyword"
27760 ["Next keyword" org-shiftright (org-on-heading-p)]
27761 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27762 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27763 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27764 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27765 ["Show TODO Tree" org-show-todo-tree t]
27766 ["Global TODO list" org-todo-list t]
27767 "--"
27768 ["Set Priority" org-priority t]
27769 ["Priority Up" org-shiftup t]
27770 ["Priority Down" org-shiftdown t])
27771 ("TAGS and Properties"
27772 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27773 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27774 "--"
27775 ["Set property" 'org-set-property t]
27776 ["Column view of properties" org-columns t]
27777 ["Insert Column View DBlock" org-insert-columns-dblock t])
27778 ("Dates and Scheduling"
27779 ["Timestamp" org-time-stamp t]
27780 ["Timestamp (inactive)" org-time-stamp-inactive t]
27781 ("Change Date"
27782 ["1 Day Later" org-shiftright t]
27783 ["1 Day Earlier" org-shiftleft t]
27784 ["1 ... Later" org-shiftup t]
27785 ["1 ... Earlier" org-shiftdown t])
27786 ["Compute Time Range" org-evaluate-time-range t]
27787 ["Schedule Item" org-schedule t]
27788 ["Deadline" org-deadline t]
27789 "--"
27790 ["Custom time format" org-toggle-time-stamp-overlays
27791 :style radio :selected org-display-custom-times]
27792 "--"
27793 ["Goto Calendar" org-goto-calendar t]
27794 ["Date from Calendar" org-date-from-calendar t])
27795 ("Logging work"
27796 ["Clock in" org-clock-in t]
27797 ["Clock out" org-clock-out t]
27798 ["Clock cancel" org-clock-cancel t]
27799 ["Goto running clock" org-clock-goto t]
27800 ["Display times" org-clock-display t]
27801 ["Create clock table" org-clock-report t]
27802 "--"
27803 ["Record DONE time"
27804 (progn (setq org-log-done (not org-log-done))
27805 (message "Switching to %s will %s record a timestamp"
27806 (car org-done-keywords)
27807 (if org-log-done "automatically" "not")))
27808 :style toggle :selected org-log-done])
27809 "--"
27810 ["Agenda Command..." org-agenda t]
27811 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27812 ("File List for Agenda")
27813 ("Special views current file"
27814 ["TODO Tree" org-show-todo-tree t]
27815 ["Check Deadlines" org-check-deadlines t]
27816 ["Timeline" org-timeline t]
27817 ["Tags Tree" org-tags-sparse-tree t])
27818 "--"
27819 ("Hyperlinks"
27820 ["Store Link (Global)" org-store-link t]
27821 ["Insert Link" org-insert-link t]
27822 ["Follow Link" org-open-at-point t]
27823 "--"
27824 ["Next link" org-next-link t]
27825 ["Previous link" org-previous-link t]
27826 "--"
27827 ["Descriptive Links"
27828 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27829 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27830 ["Literal Links"
27831 (progn
27832 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27833 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27834 "--"
27835 ["Export/Publish..." org-export t]
27836 ("LaTeX"
27837 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27838 :selected org-cdlatex-mode]
27839 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27840 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27841 ["Modify math symbol" org-cdlatex-math-modify
27842 (org-inside-LaTeX-fragment-p)]
27843 ["Export LaTeX fragments as images"
27844 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27845 :style toggle :selected org-export-with-LaTeX-fragments])
27846 "--"
27847 ("Documentation"
27848 ["Show Version" org-version t]
27849 ["Info Documentation" org-info t])
27850 ("Customize"
27851 ["Browse Org Group" org-customize t]
27852 "--"
27853 ["Expand This Menu" org-create-customize-menu
27854 (fboundp 'customize-menu-create)])
27855 "--"
27856 ["Refresh setup" org-mode-restart t]
27859 (defun org-info (&optional node)
27860 "Read documentation for Org-mode in the info system.
27861 With optional NODE, go directly to that node."
27862 (interactive)
27863 (info (format "(org)%s" (or node ""))))
27865 (defun org-install-agenda-files-menu ()
27866 (let ((bl (buffer-list)))
27867 (save-excursion
27868 (while bl
27869 (set-buffer (pop bl))
27870 (if (org-mode-p) (setq bl nil)))
27871 (when (org-mode-p)
27872 (easy-menu-change
27873 '("Org") "File List for Agenda"
27874 (append
27875 (list
27876 ["Edit File List" (org-edit-agenda-file-list) t]
27877 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27878 ["Remove Current File from List" org-remove-file t]
27879 ["Cycle through agenda files" org-cycle-agenda-files t]
27880 ["Occur in all agenda files" org-occur-in-agenda-files t]
27881 "--")
27882 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27884 ;;;; Documentation
27886 (defun org-customize ()
27887 "Call the customize function with org as argument."
27888 (interactive)
27889 (customize-browse 'org))
27891 (defun org-create-customize-menu ()
27892 "Create a full customization menu for Org-mode, insert it into the menu."
27893 (interactive)
27894 (if (fboundp 'customize-menu-create)
27895 (progn
27896 (easy-menu-change
27897 '("Org") "Customize"
27898 `(["Browse Org group" org-customize t]
27899 "--"
27900 ,(customize-menu-create 'org)
27901 ["Set" Custom-set t]
27902 ["Save" Custom-save t]
27903 ["Reset to Current" Custom-reset-current t]
27904 ["Reset to Saved" Custom-reset-saved t]
27905 ["Reset to Standard Settings" Custom-reset-standard t]))
27906 (message "\"Org\"-menu now contains full customization menu"))
27907 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27909 ;;;; Miscellaneous stuff
27912 ;;; Generally useful functions
27914 (defun org-context ()
27915 "Return a list of contexts of the current cursor position.
27916 If several contexts apply, all are returned.
27917 Each context entry is a list with a symbol naming the context, and
27918 two positions indicating start and end of the context. Possible
27919 contexts are:
27921 :headline anywhere in a headline
27922 :headline-stars on the leading stars in a headline
27923 :todo-keyword on a TODO keyword (including DONE) in a headline
27924 :tags on the TAGS in a headline
27925 :priority on the priority cookie in a headline
27926 :item on the first line of a plain list item
27927 :item-bullet on the bullet/number of a plain list item
27928 :checkbox on the checkbox in a plain list item
27929 :table in an org-mode table
27930 :table-special on a special filed in a table
27931 :table-table in a table.el table
27932 :link on a hyperlink
27933 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27934 :target on a <<target>>
27935 :radio-target on a <<<radio-target>>>
27936 :latex-fragment on a LaTeX fragment
27937 :latex-preview on a LaTeX fragment with overlayed preview image
27939 This function expects the position to be visible because it uses font-lock
27940 faces as a help to recognize the following contexts: :table-special, :link,
27941 and :keyword."
27942 (let* ((f (get-text-property (point) 'face))
27943 (faces (if (listp f) f (list f)))
27944 (p (point)) clist o)
27945 ;; First the large context
27946 (cond
27947 ((org-on-heading-p t)
27948 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27949 (when (progn
27950 (beginning-of-line 1)
27951 (looking-at org-todo-line-tags-regexp))
27952 (push (org-point-in-group p 1 :headline-stars) clist)
27953 (push (org-point-in-group p 2 :todo-keyword) clist)
27954 (push (org-point-in-group p 4 :tags) clist))
27955 (goto-char p)
27956 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27957 (if (looking-at "\\[#[A-Z0-9]\\]")
27958 (push (org-point-in-group p 0 :priority) clist)))
27960 ((org-at-item-p)
27961 (push (org-point-in-group p 2 :item-bullet) clist)
27962 (push (list :item (point-at-bol)
27963 (save-excursion (org-end-of-item) (point)))
27964 clist)
27965 (and (org-at-item-checkbox-p)
27966 (push (org-point-in-group p 0 :checkbox) clist)))
27968 ((org-at-table-p)
27969 (push (list :table (org-table-begin) (org-table-end)) clist)
27970 (if (memq 'org-formula faces)
27971 (push (list :table-special
27972 (previous-single-property-change p 'face)
27973 (next-single-property-change p 'face)) clist)))
27974 ((org-at-table-p 'any)
27975 (push (list :table-table) clist)))
27976 (goto-char p)
27978 ;; Now the small context
27979 (cond
27980 ((org-at-timestamp-p)
27981 (push (org-point-in-group p 0 :timestamp) clist))
27982 ((memq 'org-link faces)
27983 (push (list :link
27984 (previous-single-property-change p 'face)
27985 (next-single-property-change p 'face)) clist))
27986 ((memq 'org-special-keyword faces)
27987 (push (list :keyword
27988 (previous-single-property-change p 'face)
27989 (next-single-property-change p 'face)) clist))
27990 ((org-on-target-p)
27991 (push (org-point-in-group p 0 :target) clist)
27992 (goto-char (1- (match-beginning 0)))
27993 (if (looking-at org-radio-target-regexp)
27994 (push (org-point-in-group p 0 :radio-target) clist))
27995 (goto-char p))
27996 ((setq o (car (delq nil
27997 (mapcar
27998 (lambda (x)
27999 (if (memq x org-latex-fragment-image-overlays) x))
28000 (org-overlays-at (point))))))
28001 (push (list :latex-fragment
28002 (org-overlay-start o) (org-overlay-end o)) clist)
28003 (push (list :latex-preview
28004 (org-overlay-start o) (org-overlay-end o)) clist))
28005 ((org-inside-LaTeX-fragment-p)
28006 ;; FIXME: positions wrong.
28007 (push (list :latex-fragment (point) (point)) clist)))
28009 (setq clist (nreverse (delq nil clist)))
28010 clist))
28012 ;; FIXME: Compare with at-regexp-p Do we need both?
28013 (defun org-in-regexp (re &optional nlines visually)
28014 "Check if point is inside a match of regexp.
28015 Normally only the current line is checked, but you can include NLINES extra
28016 lines both before and after point into the search.
28017 If VISUALLY is set, require that the cursor is not after the match but
28018 really on, so that the block visually is on the match."
28019 (catch 'exit
28020 (let ((pos (point))
28021 (eol (point-at-eol (+ 1 (or nlines 0))))
28022 (inc (if visually 1 0)))
28023 (save-excursion
28024 (beginning-of-line (- 1 (or nlines 0)))
28025 (while (re-search-forward re eol t)
28026 (if (and (<= (match-beginning 0) pos)
28027 (>= (+ inc (match-end 0)) pos))
28028 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
28030 (defun org-at-regexp-p (regexp)
28031 "Is point inside a match of REGEXP in the current line?"
28032 (catch 'exit
28033 (save-excursion
28034 (let ((pos (point)) (end (point-at-eol)))
28035 (beginning-of-line 1)
28036 (while (re-search-forward regexp end t)
28037 (if (and (<= (match-beginning 0) pos)
28038 (>= (match-end 0) pos))
28039 (throw 'exit t)))
28040 nil))))
28042 (defun org-occur-in-agenda-files (regexp &optional nlines)
28043 "Call `multi-occur' with buffers for all agenda files."
28044 (interactive "sOrg-files matching: \np")
28045 (let* ((files (org-agenda-files))
28046 (tnames (mapcar 'file-truename files))
28047 (extra org-agenda-text-search-extra-files)
28049 (while (setq f (pop extra))
28050 (unless (member (file-truename f) tnames)
28051 (add-to-list 'files f 'append)
28052 (add-to-list 'tnames (file-truename f) 'append)))
28053 (multi-occur
28054 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
28055 regexp)))
28057 (if (boundp 'occur-mode-find-occurrence-hook)
28058 ;; Emacs 23
28059 (add-hook 'occur-mode-find-occurrence-hook
28060 (lambda ()
28061 (when (org-mode-p)
28062 (org-reveal))))
28063 ;; Emacs 22
28064 (defadvice occur-mode-goto-occurrence
28065 (after org-occur-reveal activate)
28066 (and (org-mode-p) (org-reveal)))
28067 (defadvice occur-mode-goto-occurrence-other-window
28068 (after org-occur-reveal activate)
28069 (and (org-mode-p) (org-reveal)))
28070 (defadvice occur-mode-display-occurrence
28071 (after org-occur-reveal activate)
28072 (when (org-mode-p)
28073 (let ((pos (occur-mode-find-occurrence)))
28074 (with-current-buffer (marker-buffer pos)
28075 (save-excursion
28076 (goto-char pos)
28077 (org-reveal)))))))
28079 (defun org-uniquify (list)
28080 "Remove duplicate elements from LIST."
28081 (let (res)
28082 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
28083 res))
28085 (defun org-delete-all (elts list)
28086 "Remove all elements in ELTS from LIST."
28087 (while elts
28088 (setq list (delete (pop elts) list)))
28089 list)
28091 (defun org-back-over-empty-lines ()
28092 "Move backwards over witespace, to the beginning of the first empty line.
28093 Returns the number of empty lines passed."
28094 (let ((pos (point)))
28095 (skip-chars-backward " \t\n\r")
28096 (beginning-of-line 2)
28097 (goto-char (min (point) pos))
28098 (count-lines (point) pos)))
28100 (defun org-skip-whitespace ()
28101 (skip-chars-forward " \t\n\r"))
28103 (defun org-point-in-group (point group &optional context)
28104 "Check if POINT is in match-group GROUP.
28105 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
28106 match. If the match group does ot exist or point is not inside it,
28107 return nil."
28108 (and (match-beginning group)
28109 (>= point (match-beginning group))
28110 (<= point (match-end group))
28111 (if context
28112 (list context (match-beginning group) (match-end group))
28113 t)))
28115 (defun org-switch-to-buffer-other-window (&rest args)
28116 "Switch to buffer in a second window on the current frame.
28117 In particular, do not allow pop-up frames."
28118 (let (pop-up-frames special-display-buffer-names special-display-regexps
28119 special-display-function)
28120 (apply 'switch-to-buffer-other-window args)))
28122 (defun org-combine-plists (&rest plists)
28123 "Create a single property list from all plists in PLISTS.
28124 The process starts by copying the first list, and then setting properties
28125 from the other lists. Settings in the last list are the most significant
28126 ones and overrule settings in the other lists."
28127 (let ((rtn (copy-sequence (pop plists)))
28128 p v ls)
28129 (while plists
28130 (setq ls (pop plists))
28131 (while ls
28132 (setq p (pop ls) v (pop ls))
28133 (setq rtn (plist-put rtn p v))))
28134 rtn))
28136 (defun org-move-line-down (arg)
28137 "Move the current line down. With prefix argument, move it past ARG lines."
28138 (interactive "p")
28139 (let ((col (current-column))
28140 beg end pos)
28141 (beginning-of-line 1) (setq beg (point))
28142 (beginning-of-line 2) (setq end (point))
28143 (beginning-of-line (+ 1 arg))
28144 (setq pos (move-marker (make-marker) (point)))
28145 (insert (delete-and-extract-region beg end))
28146 (goto-char pos)
28147 (move-to-column col)))
28149 (defun org-move-line-up (arg)
28150 "Move the current line up. With prefix argument, move it past ARG lines."
28151 (interactive "p")
28152 (let ((col (current-column))
28153 beg end pos)
28154 (beginning-of-line 1) (setq beg (point))
28155 (beginning-of-line 2) (setq end (point))
28156 (beginning-of-line (- arg))
28157 (setq pos (move-marker (make-marker) (point)))
28158 (insert (delete-and-extract-region beg end))
28159 (goto-char pos)
28160 (move-to-column col)))
28162 (defun org-replace-escapes (string table)
28163 "Replace %-escapes in STRING with values in TABLE.
28164 TABLE is an association list with keys like \"%a\" and string values.
28165 The sequences in STRING may contain normal field width and padding information,
28166 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
28167 so values can contain further %-escapes if they are define later in TABLE."
28168 (let ((case-fold-search nil)
28169 e re rpl)
28170 (while (setq e (pop table))
28171 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
28172 (while (string-match re string)
28173 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
28174 (cdr e)))
28175 (setq string (replace-match rpl t t string))))
28176 string))
28179 (defun org-sublist (list start end)
28180 "Return a section of LIST, from START to END.
28181 Counting starts at 1."
28182 (let (rtn (c start))
28183 (setq list (nthcdr (1- start) list))
28184 (while (and list (<= c end))
28185 (push (pop list) rtn)
28186 (setq c (1+ c)))
28187 (nreverse rtn)))
28189 (defun org-find-base-buffer-visiting (file)
28190 "Like `find-buffer-visiting' but alway return the base buffer and
28191 not an indirect buffer."
28192 (let ((buf (find-buffer-visiting file)))
28193 (if buf
28194 (or (buffer-base-buffer buf) buf)
28195 nil)))
28197 (defun org-image-file-name-regexp ()
28198 "Return regexp matching the file names of images."
28199 (if (fboundp 'image-file-name-regexp)
28200 (image-file-name-regexp)
28201 (let ((image-file-name-extensions
28202 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
28203 "xbm" "xpm" "pbm" "pgm" "ppm")))
28204 (concat "\\."
28205 (regexp-opt (nconc (mapcar 'upcase
28206 image-file-name-extensions)
28207 image-file-name-extensions)
28209 "\\'"))))
28211 (defun org-file-image-p (file)
28212 "Return non-nil if FILE is an image."
28213 (save-match-data
28214 (string-match (org-image-file-name-regexp) file)))
28216 ;;; Paragraph filling stuff.
28217 ;; We want this to be just right, so use the full arsenal.
28219 (defun org-indent-line-function ()
28220 "Indent line like previous, but further if previous was headline or item."
28221 (interactive)
28222 (let* ((pos (point))
28223 (itemp (org-at-item-p))
28224 column bpos bcol tpos tcol bullet btype bullet-type)
28225 ;; Find the previous relevant line
28226 (beginning-of-line 1)
28227 (cond
28228 ((looking-at "#") (setq column 0))
28229 ((looking-at "\\*+ ") (setq column 0))
28231 (beginning-of-line 0)
28232 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
28233 (beginning-of-line 0))
28234 (cond
28235 ((looking-at "\\*+[ \t]+")
28236 (goto-char (match-end 0))
28237 (setq column (current-column)))
28238 ((org-in-item-p)
28239 (org-beginning-of-item)
28240 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28241 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
28242 (setq bpos (match-beginning 1) tpos (match-end 0)
28243 bcol (progn (goto-char bpos) (current-column))
28244 tcol (progn (goto-char tpos) (current-column))
28245 bullet (match-string 1)
28246 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
28247 (if (not itemp)
28248 (setq column tcol)
28249 (goto-char pos)
28250 (beginning-of-line 1)
28251 (if (looking-at "\\S-")
28252 (progn
28253 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28254 (setq bullet (match-string 1)
28255 btype (if (string-match "[0-9]" bullet) "n" bullet))
28256 (setq column (if (equal btype bullet-type) bcol tcol)))
28257 (setq column (org-get-indentation)))))
28258 (t (setq column (org-get-indentation))))))
28259 (goto-char pos)
28260 (if (<= (current-column) (current-indentation))
28261 (indent-line-to column)
28262 (save-excursion (indent-line-to column)))
28263 (setq column (current-column))
28264 (beginning-of-line 1)
28265 (if (looking-at
28266 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
28267 (replace-match (concat "\\1" (format org-property-format
28268 (match-string 2) (match-string 3)))
28269 t nil))
28270 (move-to-column column)))
28272 (defun org-set-autofill-regexps ()
28273 (interactive)
28274 ;; In the paragraph separator we include headlines, because filling
28275 ;; text in a line directly attached to a headline would otherwise
28276 ;; fill the headline as well.
28277 (org-set-local 'comment-start-skip "^#+[ \t]*")
28278 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
28279 ;; The paragraph starter includes hand-formatted lists.
28280 (org-set-local 'paragraph-start
28281 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
28282 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
28283 ;; But only if the user has not turned off tables or fixed-width regions
28284 (org-set-local
28285 'auto-fill-inhibit-regexp
28286 (concat "\\*+ \\|#\\+"
28287 "\\|[ \t]*" org-keyword-time-regexp
28288 (if (or org-enable-table-editor org-enable-fixed-width-editor)
28289 (concat
28290 "\\|[ \t]*["
28291 (if org-enable-table-editor "|" "")
28292 (if org-enable-fixed-width-editor ":" "")
28293 "]"))))
28294 ;; We use our own fill-paragraph function, to make sure that tables
28295 ;; and fixed-width regions are not wrapped. That function will pass
28296 ;; through to `fill-paragraph' when appropriate.
28297 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
28298 ; Adaptive filling: To get full control, first make sure that
28299 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
28300 (org-set-local 'adaptive-fill-regexp "\000")
28301 (org-set-local 'adaptive-fill-function
28302 'org-adaptive-fill-function)
28303 (org-set-local
28304 'align-mode-rules-list
28305 '((org-in-buffer-settings
28306 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
28307 (modes . '(org-mode))))))
28309 (defun org-fill-paragraph (&optional justify)
28310 "Re-align a table, pass through to fill-paragraph if no table."
28311 (let ((table-p (org-at-table-p))
28312 (table.el-p (org-at-table.el-p)))
28313 (cond ((and (equal (char-after (point-at-bol)) ?*)
28314 (save-excursion (goto-char (point-at-bol))
28315 (looking-at outline-regexp)))
28316 t) ; skip headlines
28317 (table.el-p t) ; skip table.el tables
28318 (table-p (org-table-align) t) ; align org-mode tables
28319 (t nil)))) ; call paragraph-fill
28321 ;; For reference, this is the default value of adaptive-fill-regexp
28322 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
28324 (defun org-adaptive-fill-function ()
28325 "Return a fill prefix for org-mode files.
28326 In particular, this makes sure hanging paragraphs for hand-formatted lists
28327 work correctly."
28328 (cond ((looking-at "#[ \t]+")
28329 (match-string 0))
28330 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
28331 (save-excursion
28332 (goto-char (match-end 0))
28333 (make-string (current-column) ?\ )))
28334 (t nil)))
28336 ;;;; Functions extending outline functionality
28339 (defun org-beginning-of-line (&optional arg)
28340 "Go to the beginning of the current line. If that is invisible, continue
28341 to a visible line beginning. This makes the function of C-a more intuitive.
28342 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28343 first attempt, and only move to after the tags when the cursor is already
28344 beyond the end of the headline."
28345 (interactive "P")
28346 (let ((pos (point)))
28347 (beginning-of-line 1)
28348 (if (bobp)
28350 (backward-char 1)
28351 (if (org-invisible-p)
28352 (while (and (not (bobp)) (org-invisible-p))
28353 (backward-char 1)
28354 (beginning-of-line 1))
28355 (forward-char 1)))
28356 (when org-special-ctrl-a/e
28357 (cond
28358 ((and (looking-at org-todo-line-regexp)
28359 (= (char-after (match-end 1)) ?\ ))
28360 (goto-char
28361 (if (eq org-special-ctrl-a/e t)
28362 (cond ((> pos (match-beginning 3)) (match-beginning 3))
28363 ((= pos (point)) (match-beginning 3))
28364 (t (point)))
28365 (cond ((> pos (point)) (point))
28366 ((not (eq last-command this-command)) (point))
28367 (t (match-beginning 3))))))
28368 ((org-at-item-p)
28369 (goto-char
28370 (if (eq org-special-ctrl-a/e t)
28371 (cond ((> pos (match-end 4)) (match-end 4))
28372 ((= pos (point)) (match-end 4))
28373 (t (point)))
28374 (cond ((> pos (point)) (point))
28375 ((not (eq last-command this-command)) (point))
28376 (t (match-end 4))))))))))
28378 (defun org-end-of-line (&optional arg)
28379 "Go to the end of the line.
28380 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28381 first attempt, and only move to after the tags when the cursor is already
28382 beyond the end of the headline."
28383 (interactive "P")
28384 (if (or (not org-special-ctrl-a/e)
28385 (not (org-on-heading-p)))
28386 (end-of-line arg)
28387 (let ((pos (point)))
28388 (beginning-of-line 1)
28389 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
28390 (if (eq org-special-ctrl-a/e t)
28391 (if (or (< pos (match-beginning 1))
28392 (= pos (match-end 0)))
28393 (goto-char (match-beginning 1))
28394 (goto-char (match-end 0)))
28395 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
28396 (goto-char (match-end 0))
28397 (goto-char (match-beginning 1))))
28398 (end-of-line arg)))))
28400 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
28401 (define-key org-mode-map "\C-e" 'org-end-of-line)
28403 (defun org-kill-line (&optional arg)
28404 "Kill line, to tags or end of line."
28405 (interactive "P")
28406 (cond
28407 ((or (not org-special-ctrl-k)
28408 (bolp)
28409 (not (org-on-heading-p)))
28410 (call-interactively 'kill-line))
28411 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
28412 (kill-region (point) (match-beginning 1))
28413 (org-set-tags nil t))
28414 (t (kill-region (point) (point-at-eol)))))
28416 (define-key org-mode-map "\C-k" 'org-kill-line)
28418 (defun org-invisible-p ()
28419 "Check if point is at a character currently not visible."
28420 ;; Early versions of noutline don't have `outline-invisible-p'.
28421 (if (fboundp 'outline-invisible-p)
28422 (outline-invisible-p)
28423 (get-char-property (point) 'invisible)))
28425 (defun org-invisible-p2 ()
28426 "Check if point is at a character currently not visible."
28427 (save-excursion
28428 (if (and (eolp) (not (bobp))) (backward-char 1))
28429 ;; Early versions of noutline don't have `outline-invisible-p'.
28430 (if (fboundp 'outline-invisible-p)
28431 (outline-invisible-p)
28432 (get-char-property (point) 'invisible))))
28434 (defalias 'org-back-to-heading 'outline-back-to-heading)
28435 (defalias 'org-on-heading-p 'outline-on-heading-p)
28436 (defalias 'org-at-heading-p 'outline-on-heading-p)
28437 (defun org-at-heading-or-item-p ()
28438 (or (org-on-heading-p) (org-at-item-p)))
28440 (defun org-on-target-p ()
28441 (or (org-in-regexp org-radio-target-regexp)
28442 (org-in-regexp org-target-regexp)))
28444 (defun org-up-heading-all (arg)
28445 "Move to the heading line of which the present line is a subheading.
28446 This function considers both visible and invisible heading lines.
28447 With argument, move up ARG levels."
28448 (if (fboundp 'outline-up-heading-all)
28449 (outline-up-heading-all arg) ; emacs 21 version of outline.el
28450 (outline-up-heading arg t))) ; emacs 22 version of outline.el
28452 (defun org-up-heading-safe ()
28453 "Move to the heading line of which the present line is a subheading.
28454 This version will not throw an error. It will return the level of the
28455 headline found, or nil if no higher level is found."
28456 (let ((pos (point)) start-level level
28457 (re (concat "^" outline-regexp)))
28458 (catch 'exit
28459 (outline-back-to-heading t)
28460 (setq start-level (funcall outline-level))
28461 (if (equal start-level 1) (throw 'exit nil))
28462 (while (re-search-backward re nil t)
28463 (setq level (funcall outline-level))
28464 (if (< level start-level) (throw 'exit level)))
28465 nil)))
28467 (defun org-first-sibling-p ()
28468 "Is this heading the first child of its parents?"
28469 (interactive)
28470 (let ((re (concat "^" outline-regexp))
28471 level l)
28472 (unless (org-at-heading-p t)
28473 (error "Not at a heading"))
28474 (setq level (funcall outline-level))
28475 (save-excursion
28476 (if (not (re-search-backward re nil t))
28478 (setq l (funcall outline-level))
28479 (< l level)))))
28481 (defun org-goto-sibling (&optional previous)
28482 "Goto the next sibling, even if it is invisible.
28483 When PREVIOUS is set, go to the previous sibling instead. Returns t
28484 when a sibling was found. When none is found, return nil and don't
28485 move point."
28486 (let ((fun (if previous 're-search-backward 're-search-forward))
28487 (pos (point))
28488 (re (concat "^" outline-regexp))
28489 level l)
28490 (when (condition-case nil (org-back-to-heading t) (error nil))
28491 (setq level (funcall outline-level))
28492 (catch 'exit
28493 (or previous (forward-char 1))
28494 (while (funcall fun re nil t)
28495 (setq l (funcall outline-level))
28496 (when (< l level) (goto-char pos) (throw 'exit nil))
28497 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
28498 (goto-char pos)
28499 nil))))
28501 (defun org-show-siblings ()
28502 "Show all siblings of the current headline."
28503 (save-excursion
28504 (while (org-goto-sibling) (org-flag-heading nil)))
28505 (save-excursion
28506 (while (org-goto-sibling 'previous)
28507 (org-flag-heading nil))))
28509 (defun org-show-hidden-entry ()
28510 "Show an entry where even the heading is hidden."
28511 (save-excursion
28512 (org-show-entry)))
28514 (defun org-flag-heading (flag &optional entry)
28515 "Flag the current heading. FLAG non-nil means make invisible.
28516 When ENTRY is non-nil, show the entire entry."
28517 (save-excursion
28518 (org-back-to-heading t)
28519 ;; Check if we should show the entire entry
28520 (if entry
28521 (progn
28522 (org-show-entry)
28523 (save-excursion
28524 (and (outline-next-heading)
28525 (org-flag-heading nil))))
28526 (outline-flag-region (max (point-min) (1- (point)))
28527 (save-excursion (outline-end-of-heading) (point))
28528 flag))))
28530 (defun org-end-of-subtree (&optional invisible-OK to-heading)
28531 ;; This is an exact copy of the original function, but it uses
28532 ;; `org-back-to-heading', to make it work also in invisible
28533 ;; trees. And is uses an invisible-OK argument.
28534 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
28535 (org-back-to-heading invisible-OK)
28536 (let ((first t)
28537 (level (funcall outline-level)))
28538 (while (and (not (eobp))
28539 (or first (> (funcall outline-level) level)))
28540 (setq first nil)
28541 (outline-next-heading))
28542 (unless to-heading
28543 (if (memq (preceding-char) '(?\n ?\^M))
28544 (progn
28545 ;; Go to end of line before heading
28546 (forward-char -1)
28547 (if (memq (preceding-char) '(?\n ?\^M))
28548 ;; leave blank line before heading
28549 (forward-char -1))))))
28550 (point))
28552 (defun org-show-subtree ()
28553 "Show everything after this heading at deeper levels."
28554 (outline-flag-region
28555 (point)
28556 (save-excursion
28557 (outline-end-of-subtree) (outline-next-heading) (point))
28558 nil))
28560 (defun org-show-entry ()
28561 "Show the body directly following this heading.
28562 Show the heading too, if it is currently invisible."
28563 (interactive)
28564 (save-excursion
28565 (condition-case nil
28566 (progn
28567 (org-back-to-heading t)
28568 (outline-flag-region
28569 (max (point-min) (1- (point)))
28570 (save-excursion
28571 (re-search-forward
28572 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
28573 (or (match-beginning 1) (point-max)))
28574 nil))
28575 (error nil))))
28577 (defun org-make-options-regexp (kwds)
28578 "Make a regular expression for keyword lines."
28579 (concat
28581 "#?[ \t]*\\+\\("
28582 (mapconcat 'regexp-quote kwds "\\|")
28583 "\\):[ \t]*"
28584 "\\(.+\\)"))
28586 ;; Make isearch reveal the necessary context
28587 (defun org-isearch-end ()
28588 "Reveal context after isearch exits."
28589 (when isearch-success ; only if search was successful
28590 (if (featurep 'xemacs)
28591 ;; Under XEmacs, the hook is run in the correct place,
28592 ;; we directly show the context.
28593 (org-show-context 'isearch)
28594 ;; In Emacs the hook runs *before* restoring the overlays.
28595 ;; So we have to use a one-time post-command-hook to do this.
28596 ;; (Emacs 22 has a special variable, see function `org-mode')
28597 (unless (and (boundp 'isearch-mode-end-hook-quit)
28598 isearch-mode-end-hook-quit)
28599 ;; Only when the isearch was not quitted.
28600 (org-add-hook 'post-command-hook 'org-isearch-post-command
28601 'append 'local)))))
28603 (defun org-isearch-post-command ()
28604 "Remove self from hook, and show context."
28605 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28606 (org-show-context 'isearch))
28609 ;;;; Integration with and fixes for other packages
28611 ;;; Imenu support
28613 (defvar org-imenu-markers nil
28614 "All markers currently used by Imenu.")
28615 (make-variable-buffer-local 'org-imenu-markers)
28617 (defun org-imenu-new-marker (&optional pos)
28618 "Return a new marker for use by Imenu, and remember the marker."
28619 (let ((m (make-marker)))
28620 (move-marker m (or pos (point)))
28621 (push m org-imenu-markers)
28624 (defun org-imenu-get-tree ()
28625 "Produce the index for Imenu."
28626 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28627 (setq org-imenu-markers nil)
28628 (let* ((n org-imenu-depth)
28629 (re (concat "^" outline-regexp))
28630 (subs (make-vector (1+ n) nil))
28631 (last-level 0)
28632 m tree level head)
28633 (save-excursion
28634 (save-restriction
28635 (widen)
28636 (goto-char (point-max))
28637 (while (re-search-backward re nil t)
28638 (setq level (org-reduced-level (funcall outline-level)))
28639 (when (<= level n)
28640 (looking-at org-complex-heading-regexp)
28641 (setq head (org-match-string-no-properties 4)
28642 m (org-imenu-new-marker))
28643 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28644 (if (>= level last-level)
28645 (push (cons head m) (aref subs level))
28646 (push (cons head (aref subs (1+ level))) (aref subs level))
28647 (loop for i from (1+ level) to n do (aset subs i nil)))
28648 (setq last-level level)))))
28649 (aref subs 1)))
28651 (eval-after-load "imenu"
28652 '(progn
28653 (add-hook 'imenu-after-jump-hook
28654 (lambda () (org-show-context 'org-goto)))))
28656 ;; Speedbar support
28658 (defun org-speedbar-set-agenda-restriction ()
28659 "Restrict future agenda commands to the location at point in speedbar.
28660 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28661 (interactive)
28662 (let (p m tp np dir txt w)
28663 (cond
28664 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28665 'org-imenu t))
28666 (setq m (get-text-property p 'org-imenu-marker))
28667 (save-excursion
28668 (save-restriction
28669 (set-buffer (marker-buffer m))
28670 (goto-char m)
28671 (org-agenda-set-restriction-lock 'subtree))))
28672 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28673 'speedbar-function 'speedbar-find-file))
28674 (setq tp (previous-single-property-change
28675 (1+ p) 'speedbar-function)
28676 np (next-single-property-change
28677 tp 'speedbar-function)
28678 dir (speedbar-line-directory)
28679 txt (buffer-substring-no-properties (or tp (point-min))
28680 (or np (point-max))))
28681 (save-excursion
28682 (save-restriction
28683 (set-buffer (find-file-noselect
28684 (let ((default-directory dir))
28685 (expand-file-name txt))))
28686 (unless (org-mode-p)
28687 (error "Cannot restrict to non-Org-mode file"))
28688 (org-agenda-set-restriction-lock 'file))))
28689 (t (error "Don't know how to restrict Org-mode's agenda")))
28690 (org-move-overlay org-speedbar-restriction-lock-overlay
28691 (point-at-bol) (point-at-eol))
28692 (setq current-prefix-arg nil)
28693 (org-agenda-maybe-redo)))
28695 (eval-after-load "speedbar"
28696 '(progn
28697 (speedbar-add-supported-extension ".org")
28698 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28699 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28700 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28701 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28702 (add-hook 'speedbar-visiting-tag-hook
28703 (lambda () (org-show-context 'org-goto)))))
28706 ;;; Fixes and Hacks
28708 ;; Make flyspell not check words in links, to not mess up our keymap
28709 (defun org-mode-flyspell-verify ()
28710 "Don't let flyspell put overlays at active buttons."
28711 (not (get-text-property (point) 'keymap)))
28713 ;; Make `bookmark-jump' show the jump location if it was hidden.
28714 (eval-after-load "bookmark"
28715 '(if (boundp 'bookmark-after-jump-hook)
28716 ;; We can use the hook
28717 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28718 ;; Hook not available, use advice
28719 (defadvice bookmark-jump (after org-make-visible activate)
28720 "Make the position visible."
28721 (org-bookmark-jump-unhide))))
28723 (defun org-bookmark-jump-unhide ()
28724 "Unhide the current position, to show the bookmark location."
28725 (and (org-mode-p)
28726 (or (org-invisible-p)
28727 (save-excursion (goto-char (max (point-min) (1- (point))))
28728 (org-invisible-p)))
28729 (org-show-context 'bookmark-jump)))
28731 ;; Make session.el ignore our circular variable
28732 (eval-after-load "session"
28733 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28735 ;;;; Experimental code
28737 (defun org-closed-in-range ()
28738 "Sparse tree of items closed in a certain time range.
28739 Still experimental, may disappear in the future."
28740 (interactive)
28741 ;; Get the time interval from the user.
28742 (let* ((time1 (time-to-seconds
28743 (org-read-date nil 'to-time nil "Starting date: ")))
28744 (time2 (time-to-seconds
28745 (org-read-date nil 'to-time nil "End date:")))
28746 ;; callback function
28747 (callback (lambda ()
28748 (let ((time
28749 (time-to-seconds
28750 (apply 'encode-time
28751 (org-parse-time-string
28752 (match-string 1))))))
28753 ;; check if time in interval
28754 (and (>= time time1) (<= time time2))))))
28755 ;; make tree, check each match with the callback
28756 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28759 ;;;; Finish up
28761 (provide 'org)
28763 (run-hooks 'org-load-hook)
28765 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28766 ;;; org.el ends here