Reduce the cluttering in the agenda display due to ISO weeks.
[org-mode.git] / org.el
blob84991c30f018af2c8d15fc4ea6d9a9015271d976
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. The fourth element is optional and can
1566 specify a destination file for remember items created with this template.
1567 The default file is given by `org-default-notes-file'. An optional fifth
1568 element can specify the headline in that file that should be offered
1569 first when the user is asked to file the entry. The default headline is
1570 given in the variable `org-remember-default-headline'.
1572 An optional sixth element specifies the contexts in which the user can
1573 select the template. This element can be either a list of major modes
1574 or a function. `org-remember' will first check whether the function
1575 returns `t' or if we are in any of the listed major modes, and select
1576 the template accordingly.
1578 The template specifies the structure of the remember buffer. It should have
1579 a first line starting with a star, to act as the org-mode headline.
1580 Furthermore, the following %-escapes will be replaced with content:
1582 %^{prompt} Prompt the user for a string and replace this sequence with it.
1583 A default value and a completion table ca be specified like this:
1584 %^{prompt|default|completion2|completion3|...}
1585 %t time stamp, date only
1586 %T time stamp with date and time
1587 %u, %U like the above, but inactive time stamps
1588 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1589 You may define a prompt like %^{Please specify birthday}t
1590 %n user name (taken from `user-full-name')
1591 %a annotation, normally the link created with org-store-link
1592 %i initial content, the region active. If %i is indented,
1593 the entire inserted text will be indented as well.
1594 %c content of the clipboard, or current kill ring head
1595 %^g prompt for tags, with completion on tags in target file
1596 %^G prompt for tags, with completion all tags in all agenda files
1597 %:keyword specific information for certain link types, see below
1598 %[pathname] insert the contents of the file given by `pathname'
1599 %(sexp) evaluate elisp `(sexp)' and replace with the result
1600 %! Store this note immediately after filling the template
1602 %? After completing the template, position cursor here.
1604 Apart from these general escapes, you can access information specific to the
1605 link type that is created. For example, calling `remember' in emails or gnus
1606 will record the author and the subject of the message, which you can access
1607 with %:author and %:subject, respectively. Here is a complete list of what
1608 is recorded for each link type.
1610 Link type | Available information
1611 -------------------+------------------------------------------------------
1612 bbdb | %:type %:name %:company
1613 vm, wl, mh, rmail | %:type %:subject %:message-id
1614 | %:from %:fromname %:fromaddress
1615 | %:to %:toname %:toaddress
1616 | %:fromto (either \"to NAME\" or \"from NAME\")
1617 gnus | %:group, for messages also all email fields
1618 w3, w3m | %:type %:url
1619 info | %:type %:file %:node
1620 calendar | %:type %:date"
1621 :group 'org-remember
1622 :get (lambda (var) ; Make sure all entries have at least 5 elements
1623 (mapcar (lambda (x)
1624 (if (not (stringp (car x))) (setq x (cons "" x)))
1625 (cond ((= (length x) 4) (append x '("")))
1626 ((= (length x) 3) (append x '("" "")))
1627 (t x)))
1628 (default-value var)))
1629 :type '(repeat
1630 :tag "enabled"
1631 (list :value ("" ?a "\n" nil nil nil)
1632 (string :tag "Name")
1633 (character :tag "Selection Key")
1634 (string :tag "Template")
1635 (choice
1636 (file :tag "Destination file")
1637 (const :tag "Prompt for file" nil))
1638 (choice
1639 (string :tag "Destination headline")
1640 (const :tag "Selection interface for heading"))
1641 (choice
1642 (const :tag "Use by default" nil)
1643 (const :tag "Use in all contexts" t)
1644 (repeat :tag "Use only if in major mode"
1645 (symbol :tag "Major mode"))
1646 (function :tag "Perform a check against function")))))
1648 (defcustom org-reverse-note-order nil
1649 "Non-nil means, store new notes at the beginning of a file or entry.
1650 When nil, new notes will be filed to the end of a file or entry.
1651 This can also be a list with cons cells of regular expressions that
1652 are matched against file names, and values."
1653 :group 'org-remember
1654 :type '(choice
1655 (const :tag "Reverse always" t)
1656 (const :tag "Reverse never" nil)
1657 (repeat :tag "By file name regexp"
1658 (cons regexp boolean))))
1660 (defcustom org-refile-targets nil
1661 "Targets for refiling entries with \\[org-refile].
1662 This is list of cons cells. Each cell contains:
1663 - a specification of the files to be considered, either a list of files,
1664 or a symbol whose function or value fields will be used to retrieve
1665 a file name or a list of file names. Nil means, refile to a different
1666 heading in the current buffer.
1667 - A specification of how to find candidate refile targets. This may be
1668 any of
1669 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1670 This tag has to be present in all target headlines, inheritance will
1671 not be considered.
1672 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1673 todo keyword.
1674 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1675 headlines that are refiling targets.
1676 - a cons cell (:level . N). Any headline of level N is considered a target.
1677 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1678 ;; FIXME: what if there are a var and func with same name???
1679 :group 'org-remember
1680 :type '(repeat
1681 (cons
1682 (choice :value org-agenda-files
1683 (const :tag "All agenda files" org-agenda-files)
1684 (const :tag "Current buffer" nil)
1685 (function) (variable) (file))
1686 (choice :tag "Identify target headline by"
1687 (cons :tag "Specific tag" (const :tag) (string))
1688 (cons :tag "TODO keyword" (const :todo) (string))
1689 (cons :tag "Regular expression" (const :regexp) (regexp))
1690 (cons :tag "Level number" (const :level) (integer))
1691 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1693 (defcustom org-refile-use-outline-path nil
1694 "Non-nil means, provide refile targets as paths.
1695 So a level 3 headline will be available as level1/level2/level3.
1696 When the value is `file', also include the file name (without directory)
1697 into the path. When `full-file-path', include the full file path."
1698 :group 'org-remember
1699 :type '(choice
1700 (const :tag "Not" nil)
1701 (const :tag "Yes" t)
1702 (const :tag "Start with file name" file)
1703 (const :tag "Start with full file path" full-file-path)))
1705 (defgroup org-todo nil
1706 "Options concerning TODO items in Org-mode."
1707 :tag "Org TODO"
1708 :group 'org)
1710 (defgroup org-progress nil
1711 "Options concerning Progress logging in Org-mode."
1712 :tag "Org Progress"
1713 :group 'org-time)
1715 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1716 "List of TODO entry keyword sequences and their interpretation.
1717 \\<org-mode-map>This is a list of sequences.
1719 Each sequence starts with a symbol, either `sequence' or `type',
1720 indicating if the keywords should be interpreted as a sequence of
1721 action steps, or as different types of TODO items. The first
1722 keywords are states requiring action - these states will select a headline
1723 for inclusion into the global TODO list Org-mode produces. If one of
1724 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1725 signify that no further action is necessary. If \"|\" is not found,
1726 the last keyword is treated as the only DONE state of the sequence.
1728 The command \\[org-todo] cycles an entry through these states, and one
1729 additional state where no keyword is present. For details about this
1730 cycling, see the manual.
1732 TODO keywords and interpretation can also be set on a per-file basis with
1733 the special #+SEQ_TODO and #+TYP_TODO lines.
1735 Each keyword can optionally specify a character for fast state selection
1736 \(in combination with the variable `org-use-fast-todo-selection')
1737 and specifiers for state change logging, using the same syntax
1738 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1739 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1740 indicates to record a time stamp each time this state is selected.
1742 Each keyword may also specify if a timestamp or a note should be
1743 recorded when entering or leaving the state, by adding additional
1744 characters in the parenthesis after the keyword. This looks like this:
1745 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1746 record only the time of the state change. With X and Y being either
1747 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1748 Y when leaving the state if and only if the *target* state does not
1749 define X. You may omit any of the fast-selection key or X or /Y,
1750 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1752 For backward compatibility, this variable may also be just a list
1753 of keywords - in this case the interptetation (sequence or type) will be
1754 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1755 :group 'org-todo
1756 :group 'org-keywords
1757 :type '(choice
1758 (repeat :tag "Old syntax, just keywords"
1759 (string :tag "Keyword"))
1760 (repeat :tag "New syntax"
1761 (cons
1762 (choice
1763 :tag "Interpretation"
1764 (const :tag "Sequence (cycling hits every state)" sequence)
1765 (const :tag "Type (cycling directly to DONE)" type))
1766 (repeat
1767 (string :tag "Keyword"))))))
1769 (defvar org-todo-keywords-1 nil
1770 "All TODO and DONE keywords active in a buffer.")
1771 (make-variable-buffer-local 'org-todo-keywords-1)
1772 (defvar org-todo-keywords-for-agenda nil)
1773 (defvar org-done-keywords-for-agenda nil)
1774 (defvar org-not-done-keywords nil)
1775 (make-variable-buffer-local 'org-not-done-keywords)
1776 (defvar org-done-keywords nil)
1777 (make-variable-buffer-local 'org-done-keywords)
1778 (defvar org-todo-heads nil)
1779 (make-variable-buffer-local 'org-todo-heads)
1780 (defvar org-todo-sets nil)
1781 (make-variable-buffer-local 'org-todo-sets)
1782 (defvar org-todo-log-states nil)
1783 (make-variable-buffer-local 'org-todo-log-states)
1784 (defvar org-todo-kwd-alist nil)
1785 (make-variable-buffer-local 'org-todo-kwd-alist)
1786 (defvar org-todo-key-alist nil)
1787 (make-variable-buffer-local 'org-todo-key-alist)
1788 (defvar org-todo-key-trigger nil)
1789 (make-variable-buffer-local 'org-todo-key-trigger)
1791 (defcustom org-todo-interpretation 'sequence
1792 "Controls how TODO keywords are interpreted.
1793 This variable is in principle obsolete and is only used for
1794 backward compatibility, if the interpretation of todo keywords is
1795 not given already in `org-todo-keywords'. See that variable for
1796 more information."
1797 :group 'org-todo
1798 :group 'org-keywords
1799 :type '(choice (const sequence)
1800 (const type)))
1802 (defcustom org-use-fast-todo-selection 'prefix
1803 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1804 This variable describes if and under what circumstances the cycling
1805 mechanism for TODO keywords will be replaced by a single-key, direct
1806 selection scheme.
1808 When nil, fast selection is never used.
1810 When the symbol `prefix', it will be used when `org-todo' is called with
1811 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1812 in an agenda buffer.
1814 When t, fast selection is used by default. In this case, the prefix
1815 argument forces cycling instead.
1817 In all cases, the special interface is only used if access keys have actually
1818 been assigned by the user, i.e. if keywords in the configuration are followed
1819 by a letter in parenthesis, like TODO(t)."
1820 :group 'org-todo
1821 :type '(choice
1822 (const :tag "Never" nil)
1823 (const :tag "By default" t)
1824 (const :tag "Only with C-u C-c C-t" prefix)))
1826 (defcustom org-after-todo-state-change-hook nil
1827 "Hook which is run after the state of a TODO item was changed.
1828 The new state (a string with a TODO keyword, or nil) is available in the
1829 Lisp variable `state'."
1830 :group 'org-todo
1831 :type 'hook)
1833 (defcustom org-log-done nil
1834 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1835 When equal to the list (done), also prompt for a closing note.
1836 This can also be configured on a per-file basis by adding one of
1837 the following lines anywhere in the buffer:
1839 #+STARTUP: logdone
1840 #+STARTUP: lognotedone
1841 #+STARTUP: nologdone"
1842 :group 'org-todo
1843 :group 'org-progress
1844 :type '(choice
1845 (const :tag "No logging" nil)
1846 (const :tag "Record CLOSED timestamp" time)
1847 (const :tag "Record CLOSED timestamp with closing note." note)))
1849 ;; Normalize old uses of org-log-done.
1850 (cond
1851 ((eq org-log-done t) (setq org-log-done 'time))
1852 ((and (listp org-log-done) (memq 'done org-log-done))
1853 (setq org-log-done 'note)))
1855 ;; FIXME: document
1856 (defcustom org-log-note-clock-out nil
1857 "Non-nil means, recored a note when clocking out of an item.
1858 This can also be configured on a per-file basis by adding one of
1859 the following lines anywhere in the buffer:
1861 #+STARTUP: lognoteclock-out
1862 #+STARTUP: nolognoteclock-out"
1863 :group 'org-todo
1864 :group 'org-progress
1865 :type 'boolean)
1867 (defcustom org-log-done-with-time t
1868 "Non-nil means, the CLOSED time stamp will contain date and time.
1869 When nil, only the date will be recorded."
1870 :group 'org-progress
1871 :type 'boolean)
1873 (defcustom org-log-note-headings
1874 '((done . "CLOSING NOTE %t")
1875 (state . "State %-12s %t")
1876 (clock-out . ""))
1877 "Headings for notes added when clocking out or closing TODO items.
1878 The value is an alist, with the car being a symbol indicating the note
1879 context, and the cdr is the heading to be used. The heading may also be the
1880 empty string.
1881 %t in the heading will be replaced by a time stamp.
1882 %s will be replaced by the new TODO state, in double quotes.
1883 %u will be replaced by the user name.
1884 %U will be replaced by the full user name."
1885 :group 'org-todo
1886 :group 'org-progress
1887 :type '(list :greedy t
1888 (cons (const :tag "Heading when closing an item" done) string)
1889 (cons (const :tag
1890 "Heading when changing todo state (todo sequence only)"
1891 state) string)
1892 (cons (const :tag "Heading when clocking out" clock-out) string)))
1894 (defcustom org-log-states-order-reversed t
1895 "Non-nil means, the latest state change note will be directly after heading.
1896 When nil, the notes will be orderer according to time."
1897 :group 'org-todo
1898 :group 'org-progress
1899 :type 'boolean)
1901 (defcustom org-log-repeat 'time
1902 "Non-nil means, record moving through the DONE state when triggering repeat.
1903 An auto-repeating tasks is immediately switched back to TODO when marked
1904 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1905 the TODO keyword definition, or recording a cloing note by setting
1906 `org-log-done', there will be no record of the task moving trhough DONE.
1907 This variable forces taking a note anyway. Possible values are:
1909 nil Don't force a record
1910 time Record a time stamp
1911 note Record a note
1913 This option can also be set with on a per-file-basis with
1915 #+STARTUP: logrepeat
1916 #+STARTUP: lognoterepeat
1917 #+STARTUP: nologrepeat
1919 You can have local logging settings for a subtree by setting the LOGGING
1920 property to one or more of these keywords."
1921 :group 'org-todo
1922 :group 'org-progress
1923 :type '(choice
1924 (const :tag "Don't force a record" nil)
1925 (const :tag "Force recording the DONE state" time)
1926 (const :tag "Force recording a note with the DONE state" note)))
1928 (defcustom org-clock-into-drawer 2
1929 "Should clocking info be wrapped into a drawer?
1930 When t, clocking info will always be inserted into a :CLOCK: drawer.
1931 If necessary, the drawer will be created.
1932 When nil, the drawer will not be created, but used when present.
1933 When an integer and the number of clocking entries in an item
1934 reaches or exceeds this number, a drawer will be created."
1935 :group 'org-todo
1936 :group 'org-progress
1937 :type '(choice
1938 (const :tag "Always" t)
1939 (const :tag "Only when drawer exists" nil)
1940 (integer :tag "When at least N clock entries")))
1942 (defcustom org-clock-out-when-done t
1943 "When t, the clock will be stopped when the relevant entry is marked DONE.
1944 Nil means, clock will keep running until stopped explicitly with
1945 `C-c C-x C-o', or until the clock is started in a different item."
1946 :group 'org-progress
1947 :type 'boolean)
1949 (defcustom org-clock-in-switch-to-state nil
1950 "Set task to a special todo state while clocking it.
1951 The value should be the state to which the entry should be switched."
1952 :group 'org-progress
1953 :group 'org-todo
1954 :type '(choice
1955 (const :tag "Don't force a state" nil)
1956 (string :tag "State")))
1958 (defgroup org-priorities nil
1959 "Priorities in Org-mode."
1960 :tag "Org Priorities"
1961 :group 'org-todo)
1963 (defcustom org-highest-priority ?A
1964 "The highest priority of TODO items. A character like ?A, ?B etc.
1965 Must have a smaller ASCII number than `org-lowest-priority'."
1966 :group 'org-priorities
1967 :type 'character)
1969 (defcustom org-lowest-priority ?C
1970 "The lowest priority of TODO items. A character like ?A, ?B etc.
1971 Must have a larger ASCII number than `org-highest-priority'."
1972 :group 'org-priorities
1973 :type 'character)
1975 (defcustom org-default-priority ?B
1976 "The default priority of TODO items.
1977 This is the priority an item get if no explicit priority is given."
1978 :group 'org-priorities
1979 :type 'character)
1981 (defcustom org-priority-start-cycle-with-default t
1982 "Non-nil means, start with default priority when starting to cycle.
1983 When this is nil, the first step in the cycle will be (depending on the
1984 command used) one higher or lower that the default priority."
1985 :group 'org-priorities
1986 :type 'boolean)
1988 (defgroup org-time nil
1989 "Options concerning time stamps and deadlines in Org-mode."
1990 :tag "Org Time"
1991 :group 'org)
1993 (defcustom org-insert-labeled-timestamps-at-point nil
1994 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1995 When nil, these labeled time stamps are forces into the second line of an
1996 entry, just after the headline. When scheduling from the global TODO list,
1997 the time stamp will always be forced into the second line."
1998 :group 'org-time
1999 :type 'boolean)
2001 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2002 "Formats for `format-time-string' which are used for time stamps.
2003 It is not recommended to change this constant.")
2005 (defcustom org-time-stamp-rounding-minutes '(0 5)
2006 "Number of minutes to round time stamps to.
2007 These are two values, the first applies when first creating a time stamp.
2008 The second applies when changing it with the commands `S-up' and `S-down'.
2009 When changing the time stamp, this means that it will change in steps
2010 of N minutes, as given by the second value.
2012 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2013 numbers should be factors of 60, so for example 5, 10, 15.
2015 When this is larger than 1, you can still force an exact time-stamp by using
2016 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2017 and by using a prefix arg to `S-up/down' to specify the exact number
2018 of minutes to shift."
2019 :group 'org-time
2020 :get '(lambda (var) ; Make sure all entries have 5 elements
2021 (if (integerp (default-value var))
2022 (list (default-value var) 5)
2023 (default-value var)))
2024 :type '(list
2025 (integer :tag "when inserting times")
2026 (integer :tag "when modifying times")))
2028 ;; Make sure old customizations of this variable don't lead to problems.
2029 (when (integerp org-time-stamp-rounding-minutes)
2030 (setq org-time-stamp-rounding-minutes
2031 (list org-time-stamp-rounding-minutes
2032 org-time-stamp-rounding-minutes)))
2034 (defcustom org-display-custom-times nil
2035 "Non-nil means, overlay custom formats over all time stamps.
2036 The formats are defined through the variable `org-time-stamp-custom-formats'.
2037 To turn this on on a per-file basis, insert anywhere in the file:
2038 #+STARTUP: customtime"
2039 :group 'org-time
2040 :set 'set-default
2041 :type 'sexp)
2042 (make-variable-buffer-local 'org-display-custom-times)
2044 (defcustom org-time-stamp-custom-formats
2045 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2046 "Custom formats for time stamps. See `format-time-string' for the syntax.
2047 These are overlayed over the default ISO format if the variable
2048 `org-display-custom-times' is set. Time like %H:%M should be at the
2049 end of the second format."
2050 :group 'org-time
2051 :type 'sexp)
2053 (defun org-time-stamp-format (&optional long inactive)
2054 "Get the right format for a time string."
2055 (let ((f (if long (cdr org-time-stamp-formats)
2056 (car org-time-stamp-formats))))
2057 (if inactive
2058 (concat "[" (substring f 1 -1) "]")
2059 f)))
2061 (defcustom org-read-date-prefer-future t
2062 "Non-nil means, assume future for incomplete date input from user.
2063 This affects the following situations:
2064 1. The user gives a day, but no month.
2065 For example, if today is the 15th, and you enter \"3\", Org-mode will
2066 read this as the third of *next* month. However, if you enter \"17\",
2067 it will be considered as *this* month.
2068 2. The user gives a month but not a year.
2069 For example, if it is april and you enter \"feb 2\", this will be read
2070 as feb 2, *next* year. \"May 5\", however, will be this year.
2072 Currently this does not work for ISO week specifications.
2074 When this option is nil, the current month and year will always be used
2075 as defaults."
2076 :group 'org-time
2077 :type 'boolean)
2079 (defcustom org-read-date-display-live t
2080 "Non-nil means, display current interpretation of date prompt live.
2081 This display will be in an overlay, in the minibuffer."
2082 :group 'org-time
2083 :type 'boolean)
2085 (defcustom org-read-date-popup-calendar t
2086 "Non-nil means, pop up a calendar when prompting for a date.
2087 In the calendar, the date can be selected with mouse-1. However, the
2088 minibuffer will also be active, and you can simply enter the date as well.
2089 When nil, only the minibuffer will be available."
2090 :group 'org-time
2091 :type 'boolean)
2092 (if (fboundp 'defvaralias)
2093 (defvaralias 'org-popup-calendar-for-date-prompt
2094 'org-read-date-popup-calendar))
2096 (defcustom org-extend-today-until 0
2097 "The hour when your day really ends.
2098 This has influence for the following applications:
2099 - When switching the agenda to \"today\". It it is still earlier than
2100 the time given here, the day recognized as TODAY is actually yesterday.
2101 - When a date is read from the user and it is still before the time given
2102 here, the current date and time will be assumed to be yesterday, 23:59.
2104 FIXME:
2105 IMPORTANT: This is still a very experimental feature, it may disappear
2106 again or it may be extended to mean more things."
2107 :group 'org-time
2108 :type 'number)
2110 (defcustom org-edit-timestamp-down-means-later nil
2111 "Non-nil means, S-down will increase the time in a time stamp.
2112 When nil, S-up will increase."
2113 :group 'org-time
2114 :type 'boolean)
2116 (defcustom org-calendar-follow-timestamp-change t
2117 "Non-nil means, make the calendar window follow timestamp changes.
2118 When a timestamp is modified and the calendar window is visible, it will be
2119 moved to the new date."
2120 :group 'org-time
2121 :type 'boolean)
2123 (defcustom org-clock-heading-function nil
2124 "When non-nil, should be a function to create `org-clock-heading'.
2125 This is the string shown in the mode line when a clock is running.
2126 The function is called with point at the beginning of the headline."
2127 :group 'org-time ; FIXME: Should we have a separate group????
2128 :type 'function)
2130 (defgroup org-tags nil
2131 "Options concerning tags in Org-mode."
2132 :tag "Org Tags"
2133 :group 'org)
2135 (defcustom org-tag-alist nil
2136 "List of tags allowed in Org-mode files.
2137 When this list is nil, Org-mode will base TAG input on what is already in the
2138 buffer.
2139 The value of this variable is an alist, the car of each entry must be a
2140 keyword as a string, the cdr may be a character that is used to select
2141 that tag through the fast-tag-selection interface.
2142 See the manual for details."
2143 :group 'org-tags
2144 :type '(repeat
2145 (choice
2146 (cons (string :tag "Tag name")
2147 (character :tag "Access char"))
2148 (const :tag "Start radio group" (:startgroup))
2149 (const :tag "End radio group" (:endgroup)))))
2151 (defcustom org-use-fast-tag-selection 'auto
2152 "Non-nil means, use fast tag selection scheme.
2153 This is a special interface to select and deselect tags with single keys.
2154 When nil, fast selection is never used.
2155 When the symbol `auto', fast selection is used if and only if selection
2156 characters for tags have been configured, either through the variable
2157 `org-tag-alist' or through a #+TAGS line in the buffer.
2158 When t, fast selection is always used and selection keys are assigned
2159 automatically if necessary."
2160 :group 'org-tags
2161 :type '(choice
2162 (const :tag "Always" t)
2163 (const :tag "Never" nil)
2164 (const :tag "When selection characters are configured" 'auto)))
2166 (defcustom org-fast-tag-selection-single-key nil
2167 "Non-nil means, fast tag selection exits after first change.
2168 When nil, you have to press RET to exit it.
2169 During fast tag selection, you can toggle this flag with `C-c'.
2170 This variable can also have the value `expert'. In this case, the window
2171 displaying the tags menu is not even shown, until you press C-c again."
2172 :group 'org-tags
2173 :type '(choice
2174 (const :tag "No" nil)
2175 (const :tag "Yes" t)
2176 (const :tag "Expert" expert)))
2178 (defvar org-fast-tag-selection-include-todo nil
2179 "Non-nil means, fast tags selection interface will also offer TODO states.
2180 This is an undocumented feature, you should not rely on it.")
2182 (defcustom org-tags-column -80
2183 "The column to which tags should be indented in a headline.
2184 If this number is positive, it specifies the column. If it is negative,
2185 it means that the tags should be flushright to that column. For example,
2186 -80 works well for a normal 80 character screen."
2187 :group 'org-tags
2188 :type 'integer)
2190 (defcustom org-auto-align-tags t
2191 "Non-nil means, realign tags after pro/demotion of TODO state change.
2192 These operations change the length of a headline and therefore shift
2193 the tags around. With this options turned on, after each such operation
2194 the tags are again aligned to `org-tags-column'."
2195 :group 'org-tags
2196 :type 'boolean)
2198 (defcustom org-use-tag-inheritance t
2199 "Non-nil means, tags in levels apply also for sublevels.
2200 When nil, only the tags directly given in a specific line apply there.
2201 If you turn off this option, you very likely want to turn on the
2202 companion option `org-tags-match-list-sublevels'."
2203 :group 'org-tags
2204 :type 'boolean)
2206 (defcustom org-tags-match-list-sublevels nil
2207 "Non-nil means list also sublevels of headlines matching tag search.
2208 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2209 the sublevels of a headline matching a tag search often also match
2210 the same search. Listing all of them can create very long lists.
2211 Setting this variable to nil causes subtrees of a match to be skipped.
2212 This option is off by default, because inheritance in on. If you turn
2213 inheritance off, you very likely want to turn this option on.
2215 As a special case, if the tag search is restricted to TODO items, the
2216 value of this variable is ignored and sublevels are always checked, to
2217 make sure all corresponding TODO items find their way into the list."
2218 :group 'org-tags
2219 :type 'boolean)
2221 (defvar org-tags-history nil
2222 "History of minibuffer reads for tags.")
2223 (defvar org-last-tags-completion-table nil
2224 "The last used completion table for tags.")
2225 (defvar org-after-tags-change-hook nil
2226 "Hook that is run after the tags in a line have changed.")
2228 (defgroup org-properties nil
2229 "Options concerning properties in Org-mode."
2230 :tag "Org Properties"
2231 :group 'org)
2233 (defcustom org-property-format "%-10s %s"
2234 "How property key/value pairs should be formatted by `indent-line'.
2235 When `indent-line' hits a property definition, it will format the line
2236 according to this format, mainly to make sure that the values are
2237 lined-up with respect to each other."
2238 :group 'org-properties
2239 :type 'string)
2241 (defcustom org-use-property-inheritance nil
2242 "Non-nil means, properties apply also for sublevels.
2243 This setting is only relevant during property searches, not when querying
2244 an entry with `org-entry-get'. To retrieve a property with inheritance,
2245 you need to call `org-entry-get' with the inheritance flag.
2246 Turning this on can cause significant overhead when doing a search, so
2247 this is turned off by default.
2248 When nil, only the properties directly given in the current entry count.
2249 The value may also be a list of properties that shouldhave inheritance.
2251 However, note that some special properties use inheritance under special
2252 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2253 and the properties ending in \"_ALL\" when they are used as descriptor
2254 for valid values of a property."
2255 :group 'org-properties
2256 :type '(choice
2257 (const :tag "Not" nil)
2258 (const :tag "Always" nil)
2259 (repeat :tag "Specific properties" (string :tag "Property"))))
2261 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2262 "The default column format, if no other format has been defined.
2263 This variable can be set on the per-file basis by inserting a line
2265 #+COLUMNS: %25ITEM ....."
2266 :group 'org-properties
2267 :type 'string)
2269 (defcustom org-global-properties nil
2270 "List of property/value pairs that can be inherited by any entry.
2271 You can set buffer-local values for this by adding lines like
2273 #+PROPERTY: NAME VALUE"
2274 :group 'org-properties
2275 :type '(repeat
2276 (cons (string :tag "Property")
2277 (string :tag "Value"))))
2279 (defvar org-local-properties nil
2280 "List of property/value pairs that can be inherited by any entry.
2281 Valid for the current buffer.
2282 This variable is populated from #+PROPERTY lines.")
2284 (defgroup org-agenda nil
2285 "Options concerning agenda views in Org-mode."
2286 :tag "Org Agenda"
2287 :group 'org)
2289 (defvar org-category nil
2290 "Variable used by org files to set a category for agenda display.
2291 Such files should use a file variable to set it, for example
2293 # -*- mode: org; org-category: \"ELisp\"
2295 or contain a special line
2297 #+CATEGORY: ELisp
2299 If the file does not specify a category, then file's base name
2300 is used instead.")
2301 (make-variable-buffer-local 'org-category)
2303 (defcustom org-agenda-files nil
2304 "The files to be used for agenda display.
2305 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2306 \\[org-remove-file]. You can also use customize to edit the list.
2308 If an entry is a directory, all files in that directory that are matched by
2309 `org-agenda-file-regexp' will be part of the file list.
2311 If the value of the variable is not a list but a single file name, then
2312 the list of agenda files is actually stored and maintained in that file, one
2313 agenda file per line."
2314 :group 'org-agenda
2315 :type '(choice
2316 (repeat :tag "List of files and directories" file)
2317 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2319 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2320 "Regular expression to match files for `org-agenda-files'.
2321 If any element in the list in that variable contains a directory instead
2322 of a normal file, all files in that directory that are matched by this
2323 regular expression will be included."
2324 :group 'org-agenda
2325 :type 'regexp)
2327 (defcustom org-agenda-skip-unavailable-files nil
2328 "t means to just skip non-reachable files in `org-agenda-files'.
2329 Nil means to remove them, after a query, from the list."
2330 :group 'org-agenda
2331 :type 'boolean)
2333 (defcustom org-agenda-text-search-extra-files nil
2334 "List of extra files to be searched by text search commands.
2335 These files will be search in addition to the agenda files bu the
2336 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2337 Note that these files will only be searched for text search commands,
2338 not for the other agenda views like todo lists, tag earches or the weekly
2339 agenda. This variable is intended to list notes and possibly archive files
2340 that should also be searched by these two commands."
2341 :group 'org-agenda
2342 :type '(repeat file))
2344 (if (fboundp 'defvaralias)
2345 (defvaralias 'org-agenda-multi-occur-extra-files
2346 'org-agenda-text-search-extra-files))
2348 (defcustom org-agenda-confirm-kill 1
2349 "When set, remote killing from the agenda buffer needs confirmation.
2350 When t, a confirmation is always needed. When a number N, confirmation is
2351 only needed when the text to be killed contains more than N non-white lines."
2352 :group 'org-agenda
2353 :type '(choice
2354 (const :tag "Never" nil)
2355 (const :tag "Always" t)
2356 (number :tag "When more than N lines")))
2358 (defcustom org-calendar-to-agenda-key [?c]
2359 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2360 The command `org-calendar-goto-agenda' will be bound to this key. The
2361 default is the character `c' because then `c' can be used to switch back and
2362 forth between agenda and calendar."
2363 :group 'org-agenda
2364 :type 'sexp)
2366 (defcustom org-agenda-compact-blocks nil
2367 "Non-nil means, make the block agenda more compact.
2368 This is done by leaving out unnecessary lines."
2369 :group 'org-agenda
2370 :type nil)
2372 (defgroup org-agenda-export nil
2373 "Options concerning exporting agenda views in Org-mode."
2374 :tag "Org Agenda Export"
2375 :group 'org-agenda)
2377 (defcustom org-agenda-with-colors t
2378 "Non-nil means, use colors in agenda views."
2379 :group 'org-agenda-export
2380 :type 'boolean)
2382 (defcustom org-agenda-exporter-settings nil
2383 "Alist of variable/value pairs that should be active during agenda export.
2384 This is a good place to set uptions for ps-print and for htmlize."
2385 :group 'org-agenda-export
2386 :type '(repeat
2387 (list
2388 (variable)
2389 (sexp :tag "Value"))))
2391 (defcustom org-agenda-export-html-style ""
2392 "The style specification for exported HTML Agenda files.
2393 If this variable contains a string, it will replace the default <style>
2394 section as produced by `htmlize'.
2395 Since there are different ways of setting style information, this variable
2396 needs to contain the full HTML structure to provide a style, including the
2397 surrounding HTML tags. The style specifications should include definitions
2398 the fonts used by the agenda, here is an example:
2400 <style type=\"text/css\">
2401 p { font-weight: normal; color: gray; }
2402 .org-agenda-structure {
2403 font-size: 110%;
2404 color: #003399;
2405 font-weight: 600;
2407 .org-todo {
2408 color: #cc6666;
2409 font-weight: bold;
2411 .org-done {
2412 color: #339933;
2414 .title { text-align: center; }
2415 .todo, .deadline { color: red; }
2416 .done { color: green; }
2417 </style>
2419 or, if you want to keep the style in a file,
2421 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2423 As the value of this option simply gets inserted into the HTML <head> header,
2424 you can \"misuse\" it to also add other text to the header. However,
2425 <style>...</style> is required, if not present the variable will be ignored."
2426 :group 'org-agenda-export
2427 :group 'org-export-html
2428 :type 'string)
2430 (defgroup org-agenda-custom-commands nil
2431 "Options concerning agenda views in Org-mode."
2432 :tag "Org Agenda Custom Commands"
2433 :group 'org-agenda)
2435 (defconst org-sorting-choice
2436 '(choice
2437 (const time-up) (const time-down)
2438 (const category-keep) (const category-up) (const category-down)
2439 (const tag-down) (const tag-up)
2440 (const priority-up) (const priority-down))
2441 "Sorting choices.")
2443 (defconst org-agenda-custom-commands-local-options
2444 `(repeat :tag "Local settings for this command. Remember to quote values"
2445 (choice :tag "Setting"
2446 (list :tag "Any variable"
2447 (variable :tag "Variable")
2448 (sexp :tag "Value"))
2449 (list :tag "Files to be searched"
2450 (const org-agenda-files)
2451 (list
2452 (const :format "" quote)
2453 (repeat
2454 (file))))
2455 (list :tag "Sorting strategy"
2456 (const org-agenda-sorting-strategy)
2457 (list
2458 (const :format "" quote)
2459 (repeat
2460 ,org-sorting-choice)))
2461 (list :tag "Prefix format"
2462 (const org-agenda-prefix-format :value " %-12:c%?-12t% s")
2463 (string))
2464 (list :tag "Number of days in agenda"
2465 (const org-agenda-ndays)
2466 (integer :value 1))
2467 (list :tag "Fixed starting date"
2468 (const org-agenda-start-day)
2469 (string :value "2007-11-01"))
2470 (list :tag "Start on day of week"
2471 (const org-agenda-start-on-weekday)
2472 (choice :value 1
2473 (const :tag "Today" nil)
2474 (number :tag "Weekday No.")))
2475 (list :tag "Include data from diary"
2476 (const org-agenda-include-diary)
2477 (boolean))
2478 (list :tag "Deadline Warning days"
2479 (const org-deadline-warning-days)
2480 (integer :value 1))
2481 (list :tag "Standard skipping condition"
2482 :value (org-agenda-skip-function '(org-agenda-skip-entry-if))
2483 (const org-agenda-skip-function)
2484 (list
2485 (const :format "" quote)
2486 (list
2487 (choice
2488 :tag "Skiping range"
2489 (const :tag "Skip entry" org-agenda-skip-entry-if)
2490 (const :tag "Skip subtree" org-agenda-skip-subtree-if))
2491 (repeat :inline t :tag "Conditions for skipping"
2492 (choice
2493 :tag "Condition type"
2494 (list :tag "Regexp matches" :inline t (const :format "" 'regexp) (regexp))
2495 (list :tag "Regexp does not match" :inline t (const :format "" 'notregexp) (regexp))
2496 (const :tag "scheduled" 'scheduled)
2497 (const :tag "not scheduled" 'notscheduled)
2498 (const :tag "deadline" 'deadline)
2499 (const :tag "no deadline" 'notdeadline))))))
2500 (list :tag "Non-standard skipping condition"
2501 :value (org-agenda-skip-function)
2502 (list
2503 (const org-agenda-skip-function)
2504 (sexp :tag "Function or form (quoted!)")))))
2505 "Selection of examples for agenda command settings.
2506 This will be spliced into the custom type of
2507 `org-agenda-custom-commands'.")
2510 (defcustom org-agenda-custom-commands nil
2511 "Custom commands for the agenda.
2512 These commands will be offered on the splash screen displayed by the
2513 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2515 (key desc type match settings files)
2517 key The key (one or more characters as a string) to be associated
2518 with the command.
2519 desc A description of the command, when omitted or nil, a default
2520 description is built using MATCH.
2521 type The command type, any of the following symbols:
2522 agenda The daily/weekly agenda.
2523 todo Entries with a specific TODO keyword, in all agenda files.
2524 search Entries containing search words entry or headline.
2525 tags Tags/Property/TODO match in all agenda files.
2526 tags-todo Tags/P/T match in all agenda files, TODO entries only.
2527 todo-tree Sparse tree of specific TODO keyword in *current* file.
2528 tags-tree Sparse tree with all tags matches in *current* file.
2529 occur-tree Occur sparse tree for *current* file.
2530 ... A user-defined function.
2531 match What to search for:
2532 - a single keyword for TODO keyword searches
2533 - a tags match expression for tags searches
2534 - a word search expression for text searches.
2535 - a regular expression for occur searches
2536 For all other commands, this should be the empty string.
2537 settings A list of option settings, similar to that in a let form, so like
2538 this: ((opt1 val1) (opt2 val2) ...). The values will be
2539 evaluated at the moment of execution, so quote them when needed.
2540 files A list of files file to write the produced agenda buffer to
2541 with the command `org-store-agenda-views'.
2542 If a file name ends in \".html\", an HTML version of the buffer
2543 is written out. If it ends in \".ps\", a postscript version is
2544 produced. Otherwide, only the plain text is written to the file.
2546 You can also define a set of commands, to create a composite agenda buffer.
2547 In this case, an entry looks like this:
2549 (key desc (cmd1 cmd2 ...) general-settings-for-whole-set files)
2551 where
2553 desc A description string to be displayed in the dispatcher menu.
2554 cmd An agenda command, similar to the above. However, tree commands
2555 are no allowed, but instead you can get agenda and global todo list.
2556 So valid commands for a set are:
2557 (agenda \"\" settings)
2558 (alltodo \"\" settings)
2559 (stuck \"\" settings)
2560 (todo \"match\" settings files)
2561 (search \"match\" settings files)
2562 (tags \"match\" settings files)
2563 (tags-todo \"match\" settings files)
2565 Each command can carry a list of options, and another set of options can be
2566 given for the whole set of commands. Individual command options take
2567 precedence over the general options.
2569 When using several characters as key to a command, the first characters
2570 are prefix commands. For the dispatcher to display useful information, you
2571 should provide a description for the prefix, like
2573 (setq org-agenda-custom-commands
2574 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2575 (\"hl\" tags \"+HOME+Lisa\")
2576 (\"hp\" tags \"+HOME+Peter\")
2577 (\"hk\" tags \"+HOME+Kim\")))"
2578 :group 'org-agenda-custom-commands
2579 :type `(repeat
2580 (choice :value ("x" "Describe command here" tags "" nil)
2581 (list :tag "Single command"
2582 (string :tag "Access Key(s) ")
2583 (option (string :tag "Description"))
2584 (choice
2585 (const :tag "Agenda" agenda)
2586 (const :tag "TODO list" alltodo)
2587 (const :tag "Search words" search)
2588 (const :tag "Stuck projects" stuck)
2589 (const :tag "Tags search (all agenda files)" tags)
2590 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2591 (const :tag "TODO keyword search (all agenda files)" todo)
2592 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2593 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2594 (const :tag "Occur tree (current buffer)" occur-tree)
2595 (sexp :tag "Other, user-defined function"))
2596 (string :tag "Match (only for some commands)")
2597 ,org-agenda-custom-commands-local-options
2598 (option (repeat :tag "Export" (file :tag "Export to"))))
2599 (list :tag "Command series, all agenda files"
2600 (string :tag "Access Key(s)")
2601 (string :tag "Description ")
2602 (repeat :tag "Component"
2603 (choice
2604 (list :tag "Agenda"
2605 (const :format "" agenda)
2606 (const :tag "" :format "" "")
2607 ,org-agenda-custom-commands-local-options)
2608 (list :tag "TODO list (all keywords)"
2609 (const :format "" alltodo)
2610 (const :tag "" :format "" "")
2611 ,org-agenda-custom-commands-local-options)
2612 (list :tag "Search words"
2613 (const :format "" search)
2614 (string :tag "Match")
2615 ,org-agenda-custom-commands-local-options)
2616 (list :tag "Stuck projects"
2617 (const :format "" stuck)
2618 (const :tag "" :format "" "")
2619 ,org-agenda-custom-commands-local-options)
2620 (list :tag "Tags search"
2621 (const :format "" tags)
2622 (string :tag "Match")
2623 ,org-agenda-custom-commands-local-options)
2624 (list :tag "Tags search, TODO entries only"
2625 (const :format "" tags-todo)
2626 (string :tag "Match")
2627 ,org-agenda-custom-commands-local-options)
2628 (list :tag "TODO keyword search"
2629 (const :format "" todo)
2630 (string :tag "Match")
2631 ,org-agenda-custom-commands-local-options)
2632 (list :tag "Other, user-defined function"
2633 (symbol :tag "function")
2634 (string :tag "Match")
2635 ,org-agenda-custom-commands-local-options)))
2637 (repeat :tag "Settings for entire command set"
2638 (list (variable :tag "Any variable")
2639 (sexp :tag "Value")))
2640 (option (repeat :tag "Export" (file :tag "Export to"))))
2641 (cons :tag "Prefix key documentation"
2642 (string :tag "Access Key(s)")
2643 (string :tag "Description ")))))
2645 (defcustom org-agenda-query-register ?o
2646 "The register holding the current query string.
2647 The prupose of this is that if you construct a query string interactively,
2648 you can then use it to define a custom command."
2649 :group 'org-agenda-custom-commands
2650 :type 'character)
2652 (defcustom org-stuck-projects
2653 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2654 "How to identify stuck projects.
2655 This is a list of four items:
2656 1. A tags/todo matcher string that is used to identify a project.
2657 The entire tree below a headline matched by this is considered one project.
2658 2. A list of TODO keywords identifying non-stuck projects.
2659 If the project subtree contains any headline with one of these todo
2660 keywords, the project is considered to be not stuck. If you specify
2661 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2662 3. A list of tags identifying non-stuck projects.
2663 If the project subtree contains any headline with one of these tags,
2664 the project is considered to be not stuck. If you specify \"*\" as
2665 a tag, any tag will mark the project unstuck.
2666 4. An arbitrary regular expression matching non-stuck projects.
2668 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2669 or `C-c a #' to produce the list."
2670 :group 'org-agenda-custom-commands
2671 :type '(list
2672 (string :tag "Tags/TODO match to identify a project")
2673 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2674 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2675 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2678 (defgroup org-agenda-skip nil
2679 "Options concerning skipping parts of agenda files."
2680 :tag "Org Agenda Skip"
2681 :group 'org-agenda)
2683 (defcustom org-agenda-todo-list-sublevels t
2684 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2685 When nil, the sublevels of a TODO entry are not checked, resulting in
2686 potentially much shorter TODO lists."
2687 :group 'org-agenda-skip
2688 :group 'org-todo
2689 :type 'boolean)
2691 (defcustom org-agenda-todo-ignore-with-date nil
2692 "Non-nil means, don't show entries with a date in the global todo list.
2693 You can use this if you prefer to mark mere appointments with a TODO keyword,
2694 but don't want them to show up in the TODO list.
2695 When this is set, it also covers deadlines and scheduled items, the settings
2696 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2697 will be ignored."
2698 :group 'org-agenda-skip
2699 :group 'org-todo
2700 :type 'boolean)
2702 (defcustom org-agenda-todo-ignore-scheduled nil
2703 "Non-nil means, don't show scheduled entries in the global todo list.
2704 The idea behind this is that by scheduling it, you have already taken care
2705 of this item.
2706 See also `org-agenda-todo-ignore-with-date'."
2707 :group 'org-agenda-skip
2708 :group 'org-todo
2709 :type 'boolean)
2711 (defcustom org-agenda-todo-ignore-deadlines nil
2712 "Non-nil means, don't show near deadline entries in the global todo list.
2713 Near means closer than `org-deadline-warning-days' days.
2714 The idea behind this is that such items will appear in the agenda anyway.
2715 See also `org-agenda-todo-ignore-with-date'."
2716 :group 'org-agenda-skip
2717 :group 'org-todo
2718 :type 'boolean)
2720 (defcustom org-agenda-skip-scheduled-if-done nil
2721 "Non-nil means don't show scheduled items in agenda when they are done.
2722 This is relevant for the daily/weekly agenda, not for the TODO list. And
2723 it applies only to the actual date of the scheduling. Warnings about
2724 an item with a past scheduling dates are always turned off when the item
2725 is DONE."
2726 :group 'org-agenda-skip
2727 :type 'boolean)
2729 (defcustom org-agenda-skip-deadline-if-done nil
2730 "Non-nil means don't show deadines when the corresponding item is done.
2731 When nil, the deadline is still shown and should give you a happy feeling.
2732 This is relevant for the daily/weekly agenda. And it applied only to the
2733 actualy date of the deadline. Warnings about approching and past-due
2734 deadlines are always turned off when the item is DONE."
2735 :group 'org-agenda-skip
2736 :type 'boolean)
2738 (defcustom org-agenda-skip-timestamp-if-done nil
2739 "Non-nil means don't select item by timestamp or -range if it is DONE."
2740 :group 'org-agenda-skip
2741 :type 'boolean)
2743 (defcustom org-timeline-show-empty-dates 3
2744 "Non-nil means, `org-timeline' also shows dates without an entry.
2745 When nil, only the days which actually have entries are shown.
2746 When t, all days between the first and the last date are shown.
2747 When an integer, show also empty dates, but if there is a gap of more than
2748 N days, just insert a special line indicating the size of the gap."
2749 :group 'org-agenda-skip
2750 :type '(choice
2751 (const :tag "None" nil)
2752 (const :tag "All" t)
2753 (number :tag "at most")))
2756 (defgroup org-agenda-startup nil
2757 "Options concerning initial settings in the Agenda in Org Mode."
2758 :tag "Org Agenda Startup"
2759 :group 'org-agenda)
2761 (defcustom org-finalize-agenda-hook nil
2762 "Hook run just before displaying an agenda buffer."
2763 :group 'org-agenda-startup
2764 :type 'hook)
2766 (defcustom org-agenda-mouse-1-follows-link nil
2767 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2768 A longer mouse click will still set point. Does not work on XEmacs.
2769 Needs to be set before org.el is loaded."
2770 :group 'org-agenda-startup
2771 :type 'boolean)
2773 (defcustom org-agenda-start-with-follow-mode nil
2774 "The initial value of follow-mode in a newly created agenda window."
2775 :group 'org-agenda-startup
2776 :type 'boolean)
2778 (defgroup org-agenda-windows nil
2779 "Options concerning the windows used by the Agenda in Org Mode."
2780 :tag "Org Agenda Windows"
2781 :group 'org-agenda)
2783 (defcustom org-agenda-window-setup 'reorganize-frame
2784 "How the agenda buffer should be displayed.
2785 Possible values for this option are:
2787 current-window Show agenda in the current window, keeping all other windows.
2788 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2789 other-window Use `switch-to-buffer-other-window' to display agenda.
2790 reorganize-frame Show only two windows on the current frame, the current
2791 window and the agenda.
2792 See also the variable `org-agenda-restore-windows-after-quit'."
2793 :group 'org-agenda-windows
2794 :type '(choice
2795 (const current-window)
2796 (const other-frame)
2797 (const other-window)
2798 (const reorganize-frame)))
2800 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2801 "The min and max height of the agenda window as a fraction of frame height.
2802 The value of the variable is a cons cell with two numbers between 0 and 1.
2803 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2804 :group 'org-agenda-windows
2805 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2807 (defcustom org-agenda-restore-windows-after-quit nil
2808 "Non-nil means, restore window configuration open exiting agenda.
2809 Before the window configuration is changed for displaying the agenda,
2810 the current status is recorded. When the agenda is exited with
2811 `q' or `x' and this option is set, the old state is restored. If
2812 `org-agenda-window-setup' is `other-frame', the value of this
2813 option will be ignored.."
2814 :group 'org-agenda-windows
2815 :type 'boolean)
2817 (defcustom org-indirect-buffer-display 'other-window
2818 "How should indirect tree buffers be displayed?
2819 This applies to indirect buffers created with the commands
2820 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2821 Valid values are:
2822 current-window Display in the current window
2823 other-window Just display in another window.
2824 dedicated-frame Create one new frame, and re-use it each time.
2825 new-frame Make a new frame each time. Note that in this case
2826 previously-made indirect buffers are kept, and you need to
2827 kill these buffers yourself."
2828 :group 'org-structure
2829 :group 'org-agenda-windows
2830 :type '(choice
2831 (const :tag "In current window" current-window)
2832 (const :tag "In current frame, other window" other-window)
2833 (const :tag "Each time a new frame" new-frame)
2834 (const :tag "One dedicated frame" dedicated-frame)))
2836 (defgroup org-agenda-daily/weekly nil
2837 "Options concerning the daily/weekly agenda."
2838 :tag "Org Agenda Daily/Weekly"
2839 :group 'org-agenda)
2841 (defcustom org-agenda-ndays 7
2842 "Number of days to include in overview display.
2843 Should be 1 or 7."
2844 :group 'org-agenda-daily/weekly
2845 :type 'number)
2847 (defcustom org-agenda-start-on-weekday 1
2848 "Non-nil means, start the overview always on the specified weekday.
2849 0 denotes Sunday, 1 denotes Monday etc.
2850 When nil, always start on the current day."
2851 :group 'org-agenda-daily/weekly
2852 :type '(choice (const :tag "Today" nil)
2853 (number :tag "Weekday No.")))
2855 (defcustom org-agenda-show-all-dates t
2856 "Non-nil means, `org-agenda' shows every day in the selected range.
2857 When nil, only the days which actually have entries are shown."
2858 :group 'org-agenda-daily/weekly
2859 :type 'boolean)
2861 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2862 "Format string for displaying dates in the agenda.
2863 Used by the daily/weekly agenda and by the timeline. This should be
2864 a format string understood by `format-time-string', or a function returning
2865 the formatted date as a string. The function must take a single argument,
2866 a calendar-style date list like (month day year)."
2867 :group 'org-agenda-daily/weekly
2868 :type '(choice
2869 (string :tag "Format string")
2870 (function :tag "Function")))
2872 (defun org-agenda-format-date-aligned (date)
2873 "Format a date string for display in the daily/weekly agenda, or timeline.
2874 This function makes sure that dates are aligned for easy reading."
2875 (require 'cal-iso)
2876 (let* ((dayname (calendar-day-name date))
2877 (day (extract-calendar-day date))
2878 (day-of-week (calendar-day-of-week date))
2879 (month (extract-calendar-month date))
2880 (monthname (calendar-month-name month))
2881 (year (extract-calendar-year date))
2882 (iso-week (string-to-number
2883 (format-time-string
2884 "%V" (calendar-time-from-absolute
2885 (calendar-absolute-from-gregorian date) 1))))
2886 (weekyear (cond ((and (= month 1) (>= iso-week 52))
2887 (1- year))
2888 ((and (= month 12) (<= iso-week 1))
2889 (1+ year))
2890 (t year)))
2891 (weekstring (if (= day-of-week 1)
2892 (format " W%02d" iso-week)
2893 "")))
2894 (format "%-9s %2d %s %4d%s"
2895 dayname day monthname year weekstring)))
2897 (defcustom org-agenda-include-diary nil
2898 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2899 :group 'org-agenda-daily/weekly
2900 :type 'boolean)
2902 (defcustom org-agenda-include-all-todo nil
2903 "Set means weekly/daily agenda will always contain all TODO entries.
2904 The TODO entries will be listed at the top of the agenda, before
2905 the entries for specific days."
2906 :group 'org-agenda-daily/weekly
2907 :type 'boolean)
2909 (defcustom org-agenda-repeating-timestamp-show-all t
2910 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2911 When nil, only one occurence is shown, either today or the
2912 nearest into the future."
2913 :group 'org-agenda-daily/weekly
2914 :type 'boolean)
2916 (defcustom org-deadline-warning-days 14
2917 "No. of days before expiration during which a deadline becomes active.
2918 This variable governs the display in sparse trees and in the agenda.
2919 When 0 or negative, it means use this number (the absolute value of it)
2920 even if a deadline has a different individual lead time specified."
2921 :group 'org-time
2922 :group 'org-agenda-daily/weekly
2923 :type 'number)
2925 (defcustom org-scheduled-past-days 10000
2926 "No. of days to continue listing scheduled items that are not marked DONE.
2927 When an item is scheduled on a date, it shows up in the agenda on this
2928 day and will be listed until it is marked done for the number of days
2929 given here."
2930 :group 'org-agenda-daily/weekly
2931 :type 'number)
2933 (defgroup org-agenda-time-grid nil
2934 "Options concerning the time grid in the Org-mode Agenda."
2935 :tag "Org Agenda Time Grid"
2936 :group 'org-agenda)
2938 (defcustom org-agenda-use-time-grid t
2939 "Non-nil means, show a time grid in the agenda schedule.
2940 A time grid is a set of lines for specific times (like every two hours between
2941 8:00 and 20:00). The items scheduled for a day at specific times are
2942 sorted in between these lines.
2943 For details about when the grid will be shown, and what it will look like, see
2944 the variable `org-agenda-time-grid'."
2945 :group 'org-agenda-time-grid
2946 :type 'boolean)
2948 (defcustom org-agenda-time-grid
2949 '((daily today require-timed)
2950 "----------------"
2951 (800 1000 1200 1400 1600 1800 2000))
2953 "The settings for time grid for agenda display.
2954 This is a list of three items. The first item is again a list. It contains
2955 symbols specifying conditions when the grid should be displayed:
2957 daily if the agenda shows a single day
2958 weekly if the agenda shows an entire week
2959 today show grid on current date, independent of daily/weekly display
2960 require-timed show grid only if at least one item has a time specification
2962 The second item is a string which will be places behing the grid time.
2964 The third item is a list of integers, indicating the times that should have
2965 a grid line."
2966 :group 'org-agenda-time-grid
2967 :type
2968 '(list
2969 (set :greedy t :tag "Grid Display Options"
2970 (const :tag "Show grid in single day agenda display" daily)
2971 (const :tag "Show grid in weekly agenda display" weekly)
2972 (const :tag "Always show grid for today" today)
2973 (const :tag "Show grid only if any timed entries are present"
2974 require-timed)
2975 (const :tag "Skip grid times already present in an entry"
2976 remove-match))
2977 (string :tag "Grid String")
2978 (repeat :tag "Grid Times" (integer :tag "Time"))))
2980 (defgroup org-agenda-sorting nil
2981 "Options concerning sorting in the Org-mode Agenda."
2982 :tag "Org Agenda Sorting"
2983 :group 'org-agenda)
2985 (defcustom org-agenda-sorting-strategy
2986 '((agenda time-up category-keep priority-down)
2987 (todo category-keep priority-down)
2988 (tags category-keep priority-down)
2989 (search category-keep))
2990 "Sorting structure for the agenda items of a single day.
2991 This is a list of symbols which will be used in sequence to determine
2992 if an entry should be listed before another entry. The following
2993 symbols are recognized:
2995 time-up Put entries with time-of-day indications first, early first
2996 time-down Put entries with time-of-day indications first, late first
2997 category-keep Keep the default order of categories, corresponding to the
2998 sequence in `org-agenda-files'.
2999 category-up Sort alphabetically by category, A-Z.
3000 category-down Sort alphabetically by category, Z-A.
3001 tag-up Sort alphabetically by last tag, A-Z.
3002 tag-down Sort alphabetically by last tag, Z-A.
3003 priority-up Sort numerically by priority, high priority last.
3004 priority-down Sort numerically by priority, high priority first.
3006 The different possibilities will be tried in sequence, and testing stops
3007 if one comparison returns a \"not-equal\". For example, the default
3008 '(time-up category-keep priority-down)
3009 means: Pull out all entries having a specified time of day and sort them,
3010 in order to make a time schedule for the current day the first thing in the
3011 agenda listing for the day. Of the entries without a time indication, keep
3012 the grouped in categories, don't sort the categories, but keep them in
3013 the sequence given in `org-agenda-files'. Within each category sort by
3014 priority.
3016 Leaving out `category-keep' would mean that items will be sorted across
3017 categories by priority.
3019 Instead of a single list, this can also be a set of list for specific
3020 contents, with a context symbol in the car of the list, any of
3021 `agenda', `todo', `tags' for the corresponding agenda views."
3022 :group 'org-agenda-sorting
3023 :type `(choice
3024 (repeat :tag "General" ,org-sorting-choice)
3025 (list :tag "Individually"
3026 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
3027 (repeat ,org-sorting-choice))
3028 (cons (const :tag "Strategy for TODO lists" todo)
3029 (repeat ,org-sorting-choice))
3030 (cons (const :tag "Strategy for Tags matches" tags)
3031 (repeat ,org-sorting-choice)))))
3033 (defcustom org-sort-agenda-notime-is-late t
3034 "Non-nil means, items without time are considered late.
3035 This is only relevant for sorting. When t, items which have no explicit
3036 time like 15:30 will be considered as 99:01, i.e. later than any items which
3037 do have a time. When nil, the default time is before 0:00. You can use this
3038 option to decide if the schedule for today should come before or after timeless
3039 agenda entries."
3040 :group 'org-agenda-sorting
3041 :type 'boolean)
3043 (defgroup org-agenda-line-format nil
3044 "Options concerning the entry prefix in the Org-mode agenda display."
3045 :tag "Org Agenda Line Format"
3046 :group 'org-agenda)
3048 (defcustom org-agenda-prefix-format
3049 '((agenda . " %-12:c%?-12t% s")
3050 (timeline . " % s")
3051 (todo . " %-12:c")
3052 (tags . " %-12:c")
3053 (search . " %-12:c"))
3054 "Format specifications for the prefix of items in the agenda views.
3055 An alist with four entries, for the different agenda types. The keys to the
3056 sublists are `agenda', `timeline', `todo', and `tags'. The values
3057 are format strings.
3058 This format works similar to a printf format, with the following meaning:
3060 %c the category of the item, \"Diary\" for entries from the diary, or
3061 as given by the CATEGORY keyword or derived from the file name.
3062 %T the *last* tag of the item. Last because inherited tags come
3063 first in the list.
3064 %t the time-of-day specification if one applies to the entry, in the
3065 format HH:MM
3066 %s Scheduling/Deadline information, a short string
3068 All specifiers work basically like the standard `%s' of printf, but may
3069 contain two additional characters: A question mark just after the `%' and
3070 a whitespace/punctuation character just before the final letter.
3072 If the first character after `%' is a question mark, the entire field
3073 will only be included if the corresponding value applies to the
3074 current entry. This is useful for fields which should have fixed
3075 width when present, but zero width when absent. For example,
3076 \"%?-12t\" will result in a 12 character time field if a time of the
3077 day is specified, but will completely disappear in entries which do
3078 not contain a time.
3080 If there is punctuation or whitespace character just before the final
3081 format letter, this character will be appended to the field value if
3082 the value is not empty. For example, the format \"%-12:c\" leads to
3083 \"Diary: \" if the category is \"Diary\". If the category were be
3084 empty, no additional colon would be interted.
3086 The default value of this option is \" %-12:c%?-12t% s\", meaning:
3087 - Indent the line with two space characters
3088 - Give the category in a 12 chars wide field, padded with whitespace on
3089 the right (because of `-'). Append a colon if there is a category
3090 (because of `:').
3091 - If there is a time-of-day, put it into a 12 chars wide field. If no
3092 time, don't put in an empty field, just skip it (because of '?').
3093 - Finally, put the scheduling information and append a whitespace.
3095 As another example, if you don't want the time-of-day of entries in
3096 the prefix, you could use:
3098 (setq org-agenda-prefix-format \" %-11:c% s\")
3100 See also the variables `org-agenda-remove-times-when-in-prefix' and
3101 `org-agenda-remove-tags'."
3102 :type '(choice
3103 (string :tag "General format")
3104 (list :greedy t :tag "View dependent"
3105 (cons (const agenda) (string :tag "Format"))
3106 (cons (const timeline) (string :tag "Format"))
3107 (cons (const todo) (string :tag "Format"))
3108 (cons (const tags) (string :tag "Format"))
3109 (cons (const search) (string :tag "Format"))))
3110 :group 'org-agenda-line-format)
3112 (defvar org-prefix-format-compiled nil
3113 "The compiled version of the most recently used prefix format.
3114 See the variable `org-agenda-prefix-format'.")
3116 (defcustom org-agenda-todo-keyword-format "%-1s"
3117 "Format for the TODO keyword in agenda lines.
3118 Set this to something like \"%-12s\" if you want all TODO keywords
3119 to occupy a fixed space in the agenda display."
3120 :group 'org-agenda-line-format
3121 :type 'string)
3123 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
3124 "Text preceeding scheduled items in the agenda view.
3125 This is a list with two strings. The first applies when the item is
3126 scheduled on the current day. The second applies when it has been scheduled
3127 previously, it may contain a %d to capture how many days ago the item was
3128 scheduled."
3129 :group 'org-agenda-line-format
3130 :type '(list
3131 (string :tag "Scheduled today ")
3132 (string :tag "Scheduled previously")))
3134 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
3135 "Text preceeding deadline items in the agenda view.
3136 This is a list with two strings. The first applies when the item has its
3137 deadline on the current day. The second applies when it is in the past or
3138 in the future, it may contain %d to capture how many days away the deadline
3139 is (was)."
3140 :group 'org-agenda-line-format
3141 :type '(list
3142 (string :tag "Deadline today ")
3143 (string :tag "Deadline relative")))
3145 (defcustom org-agenda-remove-times-when-in-prefix t
3146 "Non-nil means, remove duplicate time specifications in agenda items.
3147 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
3148 time-of-day specification in a headline or diary entry is extracted and
3149 placed into the prefix. If this option is non-nil, the original specification
3150 \(a timestamp or -range, or just a plain time(range) specification like
3151 11:30-4pm) will be removed for agenda display. This makes the agenda less
3152 cluttered.
3153 The option can be t or nil. It may also be the symbol `beg', indicating
3154 that the time should only be removed what it is located at the beginning of
3155 the headline/diary entry."
3156 :group 'org-agenda-line-format
3157 :type '(choice
3158 (const :tag "Always" t)
3159 (const :tag "Never" nil)
3160 (const :tag "When at beginning of entry" beg)))
3163 (defcustom org-agenda-default-appointment-duration nil
3164 "Default duration for appointments that only have a starting time.
3165 When nil, no duration is specified in such cases.
3166 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
3167 :group 'org-agenda-line-format
3168 :type '(choice
3169 (integer :tag "Minutes")
3170 (const :tag "No default duration")))
3173 (defcustom org-agenda-remove-tags nil
3174 "Non-nil means, remove the tags from the headline copy in the agenda.
3175 When this is the symbol `prefix', only remove tags when
3176 `org-agenda-prefix-format' contains a `%T' specifier."
3177 :group 'org-agenda-line-format
3178 :type '(choice
3179 (const :tag "Always" t)
3180 (const :tag "Never" nil)
3181 (const :tag "When prefix format contains %T" prefix)))
3183 (if (fboundp 'defvaralias)
3184 (defvaralias 'org-agenda-remove-tags-when-in-prefix
3185 'org-agenda-remove-tags))
3187 (defcustom org-agenda-tags-column -80
3188 "Shift tags in agenda items to this column.
3189 If this number is positive, it specifies the column. If it is negative,
3190 it means that the tags should be flushright to that column. For example,
3191 -80 works well for a normal 80 character screen."
3192 :group 'org-agenda-line-format
3193 :type 'integer)
3195 (if (fboundp 'defvaralias)
3196 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
3198 (defcustom org-agenda-fontify-priorities t
3199 "Non-nil means, highlight low and high priorities in agenda.
3200 When t, the highest priority entries are bold, lowest priority italic.
3201 This may also be an association list of priority faces. The face may be
3202 a names face, or a list like `(:background \"Red\")'."
3203 :group 'org-agenda-line-format
3204 :type '(choice
3205 (const :tag "Never" nil)
3206 (const :tag "Defaults" t)
3207 (repeat :tag "Specify"
3208 (list (character :tag "Priority" :value ?A)
3209 (sexp :tag "face")))))
3211 (defgroup org-latex nil
3212 "Options for embedding LaTeX code into Org-mode."
3213 :tag "Org LaTeX"
3214 :group 'org)
3216 (defcustom org-format-latex-options
3217 '(:foreground default :background default :scale 1.0
3218 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
3219 :matchers ("begin" "$" "$$" "\\(" "\\["))
3220 "Options for creating images from LaTeX fragments.
3221 This is a property list with the following properties:
3222 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
3223 `default' means use the forground of the default face.
3224 :background the background color, or \"Transparent\".
3225 `default' means use the background of the default face.
3226 :scale a scaling factor for the size of the images
3227 :html-foreground, :html-background, :html-scale
3228 The same numbers for HTML export.
3229 :matchers a list indicating which matchers should be used to
3230 find LaTeX fragments. Valid members of this list are:
3231 \"begin\" find environments
3232 \"$\" find math expressions surrounded by $...$
3233 \"$$\" find math expressions surrounded by $$....$$
3234 \"\\(\" find math expressions surrounded by \\(...\\)
3235 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3236 :group 'org-latex
3237 :type 'plist)
3239 (defcustom org-format-latex-header "\\documentclass{article}
3240 \\usepackage{fullpage} % do not remove
3241 \\usepackage{amssymb}
3242 \\usepackage[usenames]{color}
3243 \\usepackage{amsmath}
3244 \\usepackage{latexsym}
3245 \\usepackage[mathscr]{eucal}
3246 \\pagestyle{empty} % do not remove"
3247 "The document header used for processing LaTeX fragments."
3248 :group 'org-latex
3249 :type 'string)
3251 (defgroup org-export nil
3252 "Options for exporting org-listings."
3253 :tag "Org Export"
3254 :group 'org)
3256 (defgroup org-export-general nil
3257 "General options for exporting Org-mode files."
3258 :tag "Org Export General"
3259 :group 'org-export)
3261 ;; FIXME
3262 (defvar org-export-publishing-directory nil)
3264 (defcustom org-export-with-special-strings t
3265 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3266 When this option is turned on, these strings will be exported as:
3268 Org HTML LaTeX
3269 -----+----------+--------
3270 \\- &shy; \\-
3271 -- &ndash; --
3272 --- &mdash; ---
3273 ... &hellip; \ldots
3275 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3276 :group 'org-export-translation
3277 :type 'boolean)
3279 (defcustom org-export-language-setup
3280 '(("en" "Author" "Date" "Table of Contents")
3281 ("cs" "Autor" "Datum" "Obsah")
3282 ("da" "Ophavsmand" "Dato" "Indhold")
3283 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3284 ("es" "Autor" "Fecha" "\xcdndice")
3285 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3286 ("it" "Autore" "Data" "Indice")
3287 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3288 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3289 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3290 "Terms used in export text, translated to different languages.
3291 Use the variable `org-export-default-language' to set the language,
3292 or use the +OPTION lines for a per-file setting."
3293 :group 'org-export-general
3294 :type '(repeat
3295 (list
3296 (string :tag "HTML language tag")
3297 (string :tag "Author")
3298 (string :tag "Date")
3299 (string :tag "Table of Contents"))))
3301 (defcustom org-export-default-language "en"
3302 "The default language of HTML export, as a string.
3303 This should have an association in `org-export-language-setup'."
3304 :group 'org-export-general
3305 :type 'string)
3307 (defcustom org-export-skip-text-before-1st-heading t
3308 "Non-nil means, skip all text before the first headline when exporting.
3309 When nil, that text is exported as well."
3310 :group 'org-export-general
3311 :type 'boolean)
3313 (defcustom org-export-headline-levels 3
3314 "The last level which is still exported as a headline.
3315 Inferior levels will produce itemize lists when exported.
3316 Note that a numeric prefix argument to an exporter function overrides
3317 this setting.
3319 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3320 :group 'org-export-general
3321 :type 'number)
3323 (defcustom org-export-with-section-numbers t
3324 "Non-nil means, add section numbers to headlines when exporting.
3326 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3327 :group 'org-export-general
3328 :type 'boolean)
3330 (defcustom org-export-with-toc t
3331 "Non-nil means, create a table of contents in exported files.
3332 The TOC contains headlines with levels up to`org-export-headline-levels'.
3333 When an integer, include levels up to N in the toc, this may then be
3334 different from `org-export-headline-levels', but it will not be allowed
3335 to be larger than the number of headline levels.
3336 When nil, no table of contents is made.
3338 Headlines which contain any TODO items will be marked with \"(*)\" in
3339 ASCII export, and with red color in HTML output, if the option
3340 `org-export-mark-todo-in-toc' is set.
3342 In HTML output, the TOC will be clickable.
3344 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3345 or \"toc:3\"."
3346 :group 'org-export-general
3347 :type '(choice
3348 (const :tag "No Table of Contents" nil)
3349 (const :tag "Full Table of Contents" t)
3350 (integer :tag "TOC to level")))
3352 (defcustom org-export-mark-todo-in-toc nil
3353 "Non-nil means, mark TOC lines that contain any open TODO items."
3354 :group 'org-export-general
3355 :type 'boolean)
3357 (defcustom org-export-preserve-breaks nil
3358 "Non-nil means, preserve all line breaks when exporting.
3359 Normally, in HTML output paragraphs will be reformatted. In ASCII
3360 export, line breaks will always be preserved, regardless of this variable.
3362 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3363 :group 'org-export-general
3364 :type 'boolean)
3366 (defcustom org-export-with-archived-trees 'headline
3367 "Whether subtrees with the ARCHIVE tag should be exported.
3368 This can have three different values
3369 nil Do not export, pretend this tree is not present
3370 t Do export the entire tree
3371 headline Only export the headline, but skip the tree below it."
3372 :group 'org-export-general
3373 :group 'org-archive
3374 :type '(choice
3375 (const :tag "not at all" nil)
3376 (const :tag "headline only" 'headline)
3377 (const :tag "entirely" t)))
3379 (defcustom org-export-author-info t
3380 "Non-nil means, insert author name and email into the exported file.
3382 This option can also be set with the +OPTIONS line,
3383 e.g. \"author-info:nil\"."
3384 :group 'org-export-general
3385 :type 'boolean)
3387 (defcustom org-export-time-stamp-file t
3388 "Non-nil means, insert a time stamp into the exported file.
3389 The time stamp shows when the file was created.
3391 This option can also be set with the +OPTIONS line,
3392 e.g. \"timestamp:nil\"."
3393 :group 'org-export-general
3394 :type 'boolean)
3396 (defcustom org-export-with-timestamps t
3397 "If nil, do not export time stamps and associated keywords."
3398 :group 'org-export-general
3399 :type 'boolean)
3401 (defcustom org-export-remove-timestamps-from-toc t
3402 "If nil, remove timestamps from the table of contents entries."
3403 :group 'org-export-general
3404 :type 'boolean)
3406 (defcustom org-export-with-tags 'not-in-toc
3407 "If nil, do not export tags, just remove them from headlines.
3408 If this is the symbol `not-in-toc', tags will be removed from table of
3409 contents entries, but still be shown in the headlines of the document.
3411 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3412 :group 'org-export-general
3413 :type '(choice
3414 (const :tag "Off" nil)
3415 (const :tag "Not in TOC" not-in-toc)
3416 (const :tag "On" t)))
3418 (defcustom org-export-with-drawers nil
3419 "Non-nil means, export with drawers like the property drawer.
3420 When t, all drawers are exported. This may also be a list of
3421 drawer names to export."
3422 :group 'org-export-general
3423 :type '(choice
3424 (const :tag "All drawers" t)
3425 (const :tag "None" nil)
3426 (repeat :tag "Selected drawers"
3427 (string :tag "Drawer name"))))
3429 (defgroup org-export-translation nil
3430 "Options for translating special ascii sequences for the export backends."
3431 :tag "Org Export Translation"
3432 :group 'org-export)
3434 (defcustom org-export-with-emphasize t
3435 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3436 If the export target supports emphasizing text, the word will be
3437 typeset in bold, italic, or underlined, respectively. Works only for
3438 single words, but you can say: I *really* *mean* *this*.
3439 Not all export backends support this.
3441 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3442 :group 'org-export-translation
3443 :type 'boolean)
3445 (defcustom org-export-with-footnotes t
3446 "If nil, export [1] as a footnote marker.
3447 Lines starting with [1] will be formatted as footnotes.
3449 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3450 :group 'org-export-translation
3451 :type 'boolean)
3453 (defcustom org-export-with-sub-superscripts t
3454 "Non-nil means, interpret \"_\" and \"^\" for export.
3455 When this option is turned on, you can use TeX-like syntax for sub- and
3456 superscripts. Several characters after \"_\" or \"^\" will be
3457 considered as a single item - so grouping with {} is normally not
3458 needed. For example, the following things will be parsed as single
3459 sub- or superscripts.
3461 10^24 or 10^tau several digits will be considered 1 item.
3462 10^-12 or 10^-tau a leading sign with digits or a word
3463 x^2-y^3 will be read as x^2 - y^3, because items are
3464 terminated by almost any nonword/nondigit char.
3465 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3467 Still, ambiguity is possible - so when in doubt use {} to enclose the
3468 sub/superscript. If you set this variable to the symbol `{}',
3469 the braces are *required* in order to trigger interpretations as
3470 sub/superscript. This can be helpful in documents that need \"_\"
3471 frequently in plain text.
3473 Not all export backends support this, but HTML does.
3475 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3476 :group 'org-export-translation
3477 :type '(choice
3478 (const :tag "Always interpret" t)
3479 (const :tag "Only with braces" {})
3480 (const :tag "Never interpret" nil)))
3482 (defcustom org-export-with-special-strings t
3483 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3484 When this option is turned on, these strings will be exported as:
3486 \\- : &shy;
3487 -- : &ndash;
3488 --- : &mdash;
3490 Not all export backends support this, but HTML does.
3492 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3493 :group 'org-export-translation
3494 :type 'boolean)
3496 (defcustom org-export-with-TeX-macros t
3497 "Non-nil means, interpret simple TeX-like macros when exporting.
3498 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3499 No only real TeX macros will work here, but the standard HTML entities
3500 for math can be used as macro names as well. For a list of supported
3501 names in HTML export, see the constant `org-html-entities'.
3502 Not all export backends support this.
3504 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3505 :group 'org-export-translation
3506 :group 'org-export-latex
3507 :type 'boolean)
3509 (defcustom org-export-with-LaTeX-fragments nil
3510 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3511 When set, the exporter will find LaTeX environments if the \\begin line is
3512 the first non-white thing on a line. It will also find the math delimiters
3513 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3514 display math.
3516 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3517 :group 'org-export-translation
3518 :group 'org-export-latex
3519 :type 'boolean)
3521 (defcustom org-export-with-fixed-width t
3522 "Non-nil means, lines starting with \":\" will be in fixed width font.
3523 This can be used to have pre-formatted text, fragments of code etc. For
3524 example:
3525 : ;; Some Lisp examples
3526 : (while (defc cnt)
3527 : (ding))
3528 will be looking just like this in also HTML. See also the QUOTE keyword.
3529 Not all export backends support this.
3531 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3532 :group 'org-export-translation
3533 :type 'boolean)
3535 (defcustom org-match-sexp-depth 3
3536 "Number of stacked braces for sub/superscript matching.
3537 This has to be set before loading org.el to be effective."
3538 :group 'org-export-translation
3539 :type 'integer)
3541 (defgroup org-export-tables nil
3542 "Options for exporting tables in Org-mode."
3543 :tag "Org Export Tables"
3544 :group 'org-export)
3546 (defcustom org-export-with-tables t
3547 "If non-nil, lines starting with \"|\" define a table.
3548 For example:
3550 | Name | Address | Birthday |
3551 |-------------+----------+-----------|
3552 | Arthur Dent | England | 29.2.2100 |
3554 Not all export backends support this.
3556 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3557 :group 'org-export-tables
3558 :type 'boolean)
3560 (defcustom org-export-highlight-first-table-line t
3561 "Non-nil means, highlight the first table line.
3562 In HTML export, this means use <th> instead of <td>.
3563 In tables created with table.el, this applies to the first table line.
3564 In Org-mode tables, all lines before the first horizontal separator
3565 line will be formatted with <th> tags."
3566 :group 'org-export-tables
3567 :type 'boolean)
3569 (defcustom org-export-table-remove-special-lines t
3570 "Remove special lines and marking characters in calculating tables.
3571 This removes the special marking character column from tables that are set
3572 up for spreadsheet calculations. It also removes the entire lines
3573 marked with `!', `_', or `^'. The lines with `$' are kept, because
3574 the values of constants may be useful to have."
3575 :group 'org-export-tables
3576 :type 'boolean)
3578 (defcustom org-export-prefer-native-exporter-for-tables nil
3579 "Non-nil means, always export tables created with table.el natively.
3580 Natively means, use the HTML code generator in table.el.
3581 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3582 the table does not use row- or column-spanning). This has the
3583 advantage, that the automatic HTML conversions for math symbols and
3584 sub/superscripts can be applied. Org-mode's HTML generator is also
3585 much faster."
3586 :group 'org-export-tables
3587 :type 'boolean)
3589 (defgroup org-export-ascii nil
3590 "Options specific for ASCII export of Org-mode files."
3591 :tag "Org Export ASCII"
3592 :group 'org-export)
3594 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3595 "Characters for underlining headings in ASCII export.
3596 In the given sequence, these characters will be used for level 1, 2, ..."
3597 :group 'org-export-ascii
3598 :type '(repeat character))
3600 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3601 "Bullet characters for headlines converted to lists in ASCII export.
3602 The first character is used for the first lest level generated in this
3603 way, and so on. If there are more levels than characters given here,
3604 the list will be repeated.
3605 Note that plain lists will keep the same bullets as the have in the
3606 Org-mode file."
3607 :group 'org-export-ascii
3608 :type '(repeat character))
3610 (defgroup org-export-xml nil
3611 "Options specific for XML export of Org-mode files."
3612 :tag "Org Export XML"
3613 :group 'org-export)
3615 (defgroup org-export-html nil
3616 "Options specific for HTML export of Org-mode files."
3617 :tag "Org Export HTML"
3618 :group 'org-export)
3620 (defcustom org-export-html-coding-system nil
3622 :group 'org-export-html
3623 :type 'coding-system)
3625 (defcustom org-export-html-extension "html"
3626 "The extension for exported HTML files."
3627 :group 'org-export-html
3628 :type 'string)
3630 (defcustom org-export-html-style
3631 "<style type=\"text/css\">
3632 html {
3633 font-family: Times, serif;
3634 font-size: 12pt;
3636 .title { text-align: center; }
3637 .todo { color: red; }
3638 .done { color: green; }
3639 .timestamp { color: grey }
3640 .timestamp-kwd { color: CadetBlue }
3641 .tag { background-color:lightblue; font-weight:normal }
3642 .target { background-color: lavender; }
3643 pre {
3644 border: 1pt solid #AEBDCC;
3645 background-color: #F3F5F7;
3646 padding: 5pt;
3647 font-family: courier, monospace;
3649 table { border-collapse: collapse; }
3650 td, th {
3651 vertical-align: top;
3652 <!--border: 1pt solid #ADB9CC;-->
3654 </style>"
3655 "The default style specification for exported HTML files.
3656 Since there are different ways of setting style information, this variable
3657 needs to contain the full HTML structure to provide a style, including the
3658 surrounding HTML tags. The style specifications should include definitions
3659 for new classes todo, done, title, and deadline. For example, valid values
3660 would be:
3662 <style type=\"text/css\">
3663 p { font-weight: normal; color: gray; }
3664 h1 { color: black; }
3665 .title { text-align: center; }
3666 .todo, .deadline { color: red; }
3667 .done { color: green; }
3668 </style>
3670 or, if you want to keep the style in a file,
3672 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3674 As the value of this option simply gets inserted into the HTML <head> header,
3675 you can \"misuse\" it to add arbitrary text to the header."
3676 :group 'org-export-html
3677 :type 'string)
3680 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3681 "Format for typesetting the document title in HTML export."
3682 :group 'org-export-html
3683 :type 'string)
3685 (defcustom org-export-html-toplevel-hlevel 2
3686 "The <H> level for level 1 headings in HTML export."
3687 :group 'org-export-html
3688 :type 'string)
3690 (defcustom org-export-html-link-org-files-as-html t
3691 "Non-nil means, make file links to `file.org' point to `file.html'.
3692 When org-mode is exporting an org-mode file to HTML, links to
3693 non-html files are directly put into a href tag in HTML.
3694 However, links to other Org-mode files (recognized by the
3695 extension `.org.) should become links to the corresponding html
3696 file, assuming that the linked org-mode file will also be
3697 converted to HTML.
3698 When nil, the links still point to the plain `.org' file."
3699 :group 'org-export-html
3700 :type 'boolean)
3702 (defcustom org-export-html-inline-images 'maybe
3703 "Non-nil means, inline images into exported HTML pages.
3704 This is done using an <img> tag. When nil, an anchor with href is used to
3705 link to the image. If this option is `maybe', then images in links with
3706 an empty description will be inlined, while images with a description will
3707 be linked only."
3708 :group 'org-export-html
3709 :type '(choice (const :tag "Never" nil)
3710 (const :tag "Always" t)
3711 (const :tag "When there is no description" maybe)))
3713 ;; FIXME: rename
3714 (defcustom org-export-html-expand t
3715 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3716 When nil, these tags will be exported as plain text and therefore
3717 not be interpreted by a browser.
3719 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3720 :group 'org-export-html
3721 :type 'boolean)
3723 (defcustom org-export-html-table-tag
3724 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3725 "The HTML tag that is used to start a table.
3726 This must be a <table> tag, but you may change the options like
3727 borders and spacing."
3728 :group 'org-export-html
3729 :type 'string)
3731 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3732 "The opening tag for table header fields.
3733 This is customizable so that alignment options can be specified."
3734 :group 'org-export-tables
3735 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3737 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3738 "The opening tag for table data fields.
3739 This is customizable so that alignment options can be specified."
3740 :group 'org-export-tables
3741 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3743 (defcustom org-export-html-with-timestamp nil
3744 "If non-nil, write `org-export-html-html-helper-timestamp'
3745 into the exported HTML text. Otherwise, the buffer will just be saved
3746 to a file."
3747 :group 'org-export-html
3748 :type 'boolean)
3750 (defcustom org-export-html-html-helper-timestamp
3751 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3752 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3753 :group 'org-export-html
3754 :type 'string)
3756 (defgroup org-export-icalendar nil
3757 "Options specific for iCalendar export of Org-mode files."
3758 :tag "Org Export iCalendar"
3759 :group 'org-export)
3761 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3762 "The file name for the iCalendar file covering all agenda files.
3763 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3764 The file name should be absolute, the file will be overwritten without warning."
3765 :group 'org-export-icalendar
3766 :type 'file)
3768 (defcustom org-icalendar-include-todo nil
3769 "Non-nil means, export to iCalendar files should also cover TODO items."
3770 :group 'org-export-icalendar
3771 :type '(choice
3772 (const :tag "None" nil)
3773 (const :tag "Unfinished" t)
3774 (const :tag "All" all)))
3776 (defcustom org-icalendar-include-sexps t
3777 "Non-nil means, export to iCalendar files should also cover sexp entries.
3778 These are entries like in the diary, but directly in an Org-mode file."
3779 :group 'org-export-icalendar
3780 :type 'boolean)
3782 (defcustom org-icalendar-include-body 100
3783 "Amount of text below headline to be included in iCalendar export.
3784 This is a number of characters that should maximally be included.
3785 Properties, scheduling and clocking lines will always be removed.
3786 The text will be inserted into the DESCRIPTION field."
3787 :group 'org-export-icalendar
3788 :type '(choice
3789 (const :tag "Nothing" nil)
3790 (const :tag "Everything" t)
3791 (integer :tag "Max characters")))
3793 (defcustom org-icalendar-combined-name "OrgMode"
3794 "Calendar name for the combined iCalendar representing all agenda files."
3795 :group 'org-export-icalendar
3796 :type 'string)
3798 (defgroup org-font-lock nil
3799 "Font-lock settings for highlighting in Org-mode."
3800 :tag "Org Font Lock"
3801 :group 'org)
3803 (defcustom org-level-color-stars-only nil
3804 "Non-nil means fontify only the stars in each headline.
3805 When nil, the entire headline is fontified.
3806 Changing it requires restart of `font-lock-mode' to become effective
3807 also in regions already fontified."
3808 :group 'org-font-lock
3809 :type 'boolean)
3811 (defcustom org-hide-leading-stars nil
3812 "Non-nil means, hide the first N-1 stars in a headline.
3813 This works by using the face `org-hide' for these stars. This
3814 face is white for a light background, and black for a dark
3815 background. You may have to customize the face `org-hide' to
3816 make this work.
3817 Changing it requires restart of `font-lock-mode' to become effective
3818 also in regions already fontified.
3819 You may also set this on a per-file basis by adding one of the following
3820 lines to the buffer:
3822 #+STARTUP: hidestars
3823 #+STARTUP: showstars"
3824 :group 'org-font-lock
3825 :type 'boolean)
3827 (defcustom org-fontify-done-headline nil
3828 "Non-nil means, change the face of a headline if it is marked DONE.
3829 Normally, only the TODO/DONE keyword indicates the state of a headline.
3830 When this is non-nil, the headline after the keyword is set to the
3831 `org-headline-done' as an additional indication."
3832 :group 'org-font-lock
3833 :type 'boolean)
3835 (defcustom org-fontify-emphasized-text t
3836 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3837 Changing this variable requires a restart of Emacs to take effect."
3838 :group 'org-font-lock
3839 :type 'boolean)
3841 (defcustom org-highlight-latex-fragments-and-specials nil
3842 "Non-nil means, fontify what is treated specially by the exporters."
3843 :group 'org-font-lock
3844 :type 'boolean)
3846 (defcustom org-hide-emphasis-markers nil
3847 "Non-nil mean font-lock should hide the emphasis marker characters."
3848 :group 'org-font-lock
3849 :type 'boolean)
3851 (defvar org-emph-re nil
3852 "Regular expression for matching emphasis.")
3853 (defvar org-verbatim-re nil
3854 "Regular expression for matching verbatim text.")
3855 (defvar org-emphasis-regexp-components) ; defined just below
3856 (defvar org-emphasis-alist) ; defined just below
3857 (defun org-set-emph-re (var val)
3858 "Set variable and compute the emphasis regular expression."
3859 (set var val)
3860 (when (and (boundp 'org-emphasis-alist)
3861 (boundp 'org-emphasis-regexp-components)
3862 org-emphasis-alist org-emphasis-regexp-components)
3863 (let* ((e org-emphasis-regexp-components)
3864 (pre (car e))
3865 (post (nth 1 e))
3866 (border (nth 2 e))
3867 (body (nth 3 e))
3868 (nl (nth 4 e))
3869 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3870 (body1 (concat body "*?"))
3871 (markers (mapconcat 'car org-emphasis-alist ""))
3872 (vmarkers (mapconcat
3873 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3874 org-emphasis-alist "")))
3875 ;; make sure special characters appear at the right position in the class
3876 (if (string-match "\\^" markers)
3877 (setq markers (concat (replace-match "" t t markers) "^")))
3878 (if (string-match "-" markers)
3879 (setq markers (concat (replace-match "" t t markers) "-")))
3880 (if (string-match "\\^" vmarkers)
3881 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3882 (if (string-match "-" vmarkers)
3883 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3884 (if (> nl 0)
3885 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3886 (int-to-string nl) "\\}")))
3887 ;; Make the regexp
3888 (setq org-emph-re
3889 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3890 "\\("
3891 "\\([" markers "]\\)"
3892 "\\("
3893 "[^" border "]\\|"
3894 "[^" border (if (and nil stacked) markers) "]"
3895 body1
3896 "[^" border (if (and nil stacked) markers) "]"
3897 "\\)"
3898 "\\3\\)"
3899 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3900 (setq org-verbatim-re
3901 (concat "\\([" pre "]\\|^\\)"
3902 "\\("
3903 "\\([" vmarkers "]\\)"
3904 "\\("
3905 "[^" border "]\\|"
3906 "[^" border "]"
3907 body1
3908 "[^" border "]"
3909 "\\)"
3910 "\\3\\)"
3911 "\\([" post "]\\|$\\)")))))
3913 (defcustom org-emphasis-regexp-components
3914 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3915 "Components used to build the regular expression for emphasis.
3916 This is a list with 6 entries. Terminology: In an emphasis string
3917 like \" *strong word* \", we call the initial space PREMATCH, the final
3918 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3919 and \"trong wor\" is the body. The different components in this variable
3920 specify what is allowed/forbidden in each part:
3922 pre Chars allowed as prematch. Beginning of line will be allowed too.
3923 post Chars allowed as postmatch. End of line will be allowed too.
3924 border The chars *forbidden* as border characters.
3925 body-regexp A regexp like \".\" to match a body character. Don't use
3926 non-shy groups here, and don't allow newline here.
3927 newline The maximum number of newlines allowed in an emphasis exp.
3929 Use customize to modify this, or restart Emacs after changing it."
3930 :group 'org-font-lock
3931 :set 'org-set-emph-re
3932 :type '(list
3933 (sexp :tag "Allowed chars in pre ")
3934 (sexp :tag "Allowed chars in post ")
3935 (sexp :tag "Forbidden chars in border ")
3936 (sexp :tag "Regexp for body ")
3937 (integer :tag "number of newlines allowed")
3938 (option (boolean :tag "Stacking (DISABLED) "))))
3940 (defcustom org-emphasis-alist
3941 '(("*" bold "<b>" "</b>")
3942 ("/" italic "<i>" "</i>")
3943 ("_" underline "<u>" "</u>")
3944 ("=" org-code "<code>" "</code>" verbatim)
3945 ("~" org-verbatim "" "" verbatim)
3946 ("+" (:strike-through t) "<del>" "</del>")
3948 "Special syntax for emphasized text.
3949 Text starting and ending with a special character will be emphasized, for
3950 example *bold*, _underlined_ and /italic/. This variable sets the marker
3951 characters, the face to be used by font-lock for highlighting in Org-mode
3952 Emacs buffers, and the HTML tags to be used for this.
3953 Use customize to modify this, or restart Emacs after changing it."
3954 :group 'org-font-lock
3955 :set 'org-set-emph-re
3956 :type '(repeat
3957 (list
3958 (string :tag "Marker character")
3959 (choice
3960 (face :tag "Font-lock-face")
3961 (plist :tag "Face property list"))
3962 (string :tag "HTML start tag")
3963 (string :tag "HTML end tag")
3964 (option (const verbatim)))))
3966 ;;; The faces
3968 (defgroup org-faces nil
3969 "Faces in Org-mode."
3970 :tag "Org Faces"
3971 :group 'org-font-lock)
3973 (defun org-compatible-face (inherits specs)
3974 "Make a compatible face specification.
3975 If INHERITS is an existing face and if the Emacs version supports it,
3976 just inherit the face. If not, use SPECS to define the face.
3977 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3978 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3979 to the top of the list. The `min-colors' attribute will be removed from
3980 any other entries, and any resulting duplicates will be removed entirely."
3981 (cond
3982 ((and inherits (facep inherits)
3983 (not (featurep 'xemacs)) (> emacs-major-version 22))
3984 ;; In Emacs 23, we use inheritance where possible.
3985 ;; We only do this in Emacs 23, because only there the outline
3986 ;; faces have been changed to the original org-mode-level-faces.
3987 (list (list t :inherit inherits)))
3988 ((or (featurep 'xemacs) (< emacs-major-version 22))
3989 ;; These do not understand the `min-colors' attribute.
3990 (let (r e a)
3991 (while (setq e (pop specs))
3992 (cond
3993 ((memq (car e) '(t default)) (push e r))
3994 ((setq a (member '(min-colors 8) (car e)))
3995 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3996 (cdr e)))))
3997 ((setq a (assq 'min-colors (car e)))
3998 (setq e (cons (delq a (car e)) (cdr e)))
3999 (or (assoc (car e) r) (push e r)))
4000 (t (or (assoc (car e) r) (push e r)))))
4001 (nreverse r)))
4002 (t specs)))
4003 (put 'org-compatible-face 'lisp-indent-function 1)
4005 (defface org-hide
4006 '((((background light)) (:foreground "white"))
4007 (((background dark)) (:foreground "black")))
4008 "Face used to hide leading stars in headlines.
4009 The forground color of this face should be equal to the background
4010 color of the frame."
4011 :group 'org-faces)
4013 (defface org-level-1 ;; font-lock-function-name-face
4014 (org-compatible-face 'outline-1
4015 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4016 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4017 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4018 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4019 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4020 (t (:bold t))))
4021 "Face used for level 1 headlines."
4022 :group 'org-faces)
4024 (defface org-level-2 ;; font-lock-variable-name-face
4025 (org-compatible-face 'outline-2
4026 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4027 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4028 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
4029 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
4030 (t (:bold t))))
4031 "Face used for level 2 headlines."
4032 :group 'org-faces)
4034 (defface org-level-3 ;; font-lock-keyword-face
4035 (org-compatible-face 'outline-3
4036 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
4037 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
4038 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
4039 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
4040 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
4041 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
4042 (t (:bold t))))
4043 "Face used for level 3 headlines."
4044 :group 'org-faces)
4046 (defface org-level-4 ;; font-lock-comment-face
4047 (org-compatible-face 'outline-4
4048 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4049 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4050 (((class color) (min-colors 16) (background light)) (:foreground "red"))
4051 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
4052 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4053 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4054 (t (:bold t))))
4055 "Face used for level 4 headlines."
4056 :group 'org-faces)
4058 (defface org-level-5 ;; font-lock-type-face
4059 (org-compatible-face 'outline-5
4060 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
4061 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
4062 (((class color) (min-colors 8)) (:foreground "green"))))
4063 "Face used for level 5 headlines."
4064 :group 'org-faces)
4066 (defface org-level-6 ;; font-lock-constant-face
4067 (org-compatible-face 'outline-6
4068 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
4069 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
4070 (((class color) (min-colors 8)) (:foreground "magenta"))))
4071 "Face used for level 6 headlines."
4072 :group 'org-faces)
4074 (defface org-level-7 ;; font-lock-builtin-face
4075 (org-compatible-face 'outline-7
4076 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
4077 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
4078 (((class color) (min-colors 8)) (:foreground "blue"))))
4079 "Face used for level 7 headlines."
4080 :group 'org-faces)
4082 (defface org-level-8 ;; font-lock-string-face
4083 (org-compatible-face 'outline-8
4084 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4085 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4086 (((class color) (min-colors 8)) (:foreground "green"))))
4087 "Face used for level 8 headlines."
4088 :group 'org-faces)
4090 (defface org-special-keyword ;; font-lock-string-face
4091 (org-compatible-face nil
4092 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4093 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4094 (t (:italic t))))
4095 "Face used for special keywords."
4096 :group 'org-faces)
4098 (defface org-drawer ;; font-lock-function-name-face
4099 (org-compatible-face nil
4100 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4101 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4102 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4103 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4104 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4105 (t (:bold t))))
4106 "Face used for drawers."
4107 :group 'org-faces)
4109 (defface org-property-value nil
4110 "Face used for the value of a property."
4111 :group 'org-faces)
4113 (defface org-column
4114 (org-compatible-face nil
4115 '((((class color) (min-colors 16) (background light))
4116 (:background "grey90"))
4117 (((class color) (min-colors 16) (background dark))
4118 (:background "grey30"))
4119 (((class color) (min-colors 8))
4120 (:background "cyan" :foreground "black"))
4121 (t (:inverse-video t))))
4122 "Face for column display of entry properties."
4123 :group 'org-faces)
4125 (when (fboundp 'set-face-attribute)
4126 ;; Make sure that a fixed-width face is used when we have a column table.
4127 (set-face-attribute 'org-column nil
4128 :height (face-attribute 'default :height)
4129 :family (face-attribute 'default :family)))
4131 (defface org-warning
4132 (org-compatible-face 'font-lock-warning-face
4133 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4134 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4135 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4136 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4137 (t (:bold t))))
4138 "Face for deadlines and TODO keywords."
4139 :group 'org-faces)
4141 (defface org-archived ; similar to shadow
4142 (org-compatible-face 'shadow
4143 '((((class color grayscale) (min-colors 88) (background light))
4144 (:foreground "grey50"))
4145 (((class color grayscale) (min-colors 88) (background dark))
4146 (:foreground "grey70"))
4147 (((class color) (min-colors 8) (background light))
4148 (:foreground "green"))
4149 (((class color) (min-colors 8) (background dark))
4150 (:foreground "yellow"))))
4151 "Face for headline with the ARCHIVE tag."
4152 :group 'org-faces)
4154 (defface org-link
4155 '((((class color) (background light)) (:foreground "Purple" :underline t))
4156 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4157 (t (:underline t)))
4158 "Face for links."
4159 :group 'org-faces)
4161 (defface org-ellipsis
4162 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
4163 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
4164 (t (:strike-through t)))
4165 "Face for the ellipsis in folded text."
4166 :group 'org-faces)
4168 (defface org-target
4169 '((((class color) (background light)) (:underline t))
4170 (((class color) (background dark)) (:underline t))
4171 (t (:underline t)))
4172 "Face for links."
4173 :group 'org-faces)
4175 (defface org-date
4176 '((((class color) (background light)) (:foreground "Purple" :underline t))
4177 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4178 (t (:underline t)))
4179 "Face for links."
4180 :group 'org-faces)
4182 (defface org-sexp-date
4183 '((((class color) (background light)) (:foreground "Purple"))
4184 (((class color) (background dark)) (:foreground "Cyan"))
4185 (t (:underline t)))
4186 "Face for links."
4187 :group 'org-faces)
4189 (defface org-tag
4190 '((t (:bold t)))
4191 "Face for tags."
4192 :group 'org-faces)
4194 (defface org-todo ; font-lock-warning-face
4195 (org-compatible-face nil
4196 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4197 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4198 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4199 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4200 (t (:inverse-video t :bold t))))
4201 "Face for TODO keywords."
4202 :group 'org-faces)
4204 (defface org-done ;; font-lock-type-face
4205 (org-compatible-face nil
4206 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
4207 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
4208 (((class color) (min-colors 8)) (:foreground "green"))
4209 (t (:bold t))))
4210 "Face used for todo keywords that indicate DONE items."
4211 :group 'org-faces)
4213 (defface org-headline-done ;; font-lock-string-face
4214 (org-compatible-face nil
4215 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4216 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4217 (((class color) (min-colors 8) (background light)) (:bold nil))))
4218 "Face used to indicate that a headline is DONE.
4219 This face is only used if `org-fontify-done-headline' is set. If applies
4220 to the part of the headline after the DONE keyword."
4221 :group 'org-faces)
4223 (defcustom org-todo-keyword-faces nil
4224 "Faces for specific TODO keywords.
4225 This is a list of cons cells, with TODO keywords in the car
4226 and faces in the cdr. The face can be a symbol, or a property
4227 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
4228 :group 'org-faces
4229 :group 'org-todo
4230 :type '(repeat
4231 (cons
4232 (string :tag "keyword")
4233 (sexp :tag "face"))))
4235 (defface org-table ;; font-lock-function-name-face
4236 (org-compatible-face nil
4237 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4238 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4239 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4240 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4241 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
4242 (((class color) (min-colors 8) (background dark)))))
4243 "Face used for tables."
4244 :group 'org-faces)
4246 (defface org-formula
4247 (org-compatible-face nil
4248 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4249 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4250 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4251 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4252 (t (:bold t :italic t))))
4253 "Face for formulas."
4254 :group 'org-faces)
4256 (defface org-code
4257 (org-compatible-face nil
4258 '((((class color grayscale) (min-colors 88) (background light))
4259 (:foreground "grey50"))
4260 (((class color grayscale) (min-colors 88) (background dark))
4261 (:foreground "grey70"))
4262 (((class color) (min-colors 8) (background light))
4263 (:foreground "green"))
4264 (((class color) (min-colors 8) (background dark))
4265 (:foreground "yellow"))))
4266 "Face for fixed-with text like code snippets."
4267 :group 'org-faces
4268 :version "22.1")
4270 (defface org-verbatim
4271 (org-compatible-face nil
4272 '((((class color grayscale) (min-colors 88) (background light))
4273 (:foreground "grey50" :underline t))
4274 (((class color grayscale) (min-colors 88) (background dark))
4275 (:foreground "grey70" :underline t))
4276 (((class color) (min-colors 8) (background light))
4277 (:foreground "green" :underline t))
4278 (((class color) (min-colors 8) (background dark))
4279 (:foreground "yellow" :underline t))))
4280 "Face for fixed-with text like code snippets."
4281 :group 'org-faces
4282 :version "22.1")
4284 (defface org-agenda-structure ;; font-lock-function-name-face
4285 (org-compatible-face nil
4286 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4287 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4288 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4289 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4290 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4291 (t (:bold t))))
4292 "Face used in agenda for captions and dates."
4293 :group 'org-faces)
4295 (defface org-scheduled-today
4296 (org-compatible-face nil
4297 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4298 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4299 (((class color) (min-colors 8)) (:foreground "green"))
4300 (t (:bold t :italic t))))
4301 "Face for items scheduled for a certain day."
4302 :group 'org-faces)
4304 (defface org-scheduled-previously
4305 (org-compatible-face nil
4306 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4307 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4308 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4309 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4310 (t (:bold t))))
4311 "Face for items scheduled previously, and not yet done."
4312 :group 'org-faces)
4314 (defface org-upcoming-deadline
4315 (org-compatible-face nil
4316 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4317 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4318 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4319 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4320 (t (:bold t))))
4321 "Face for items scheduled previously, and not yet done."
4322 :group 'org-faces)
4324 (defcustom org-agenda-deadline-faces
4325 '((1.0 . org-warning)
4326 (0.5 . org-upcoming-deadline)
4327 (0.0 . default))
4328 "Faces for showing deadlines in the agenda.
4329 This is a list of cons cells. The cdr of each cell is a face to be used,
4330 and it can also just be like '(:foreground \"yellow\").
4331 Each car is a fraction of the head-warning time that must have passed for
4332 this the face in the cdr to be used for display. The numbers must be
4333 given in descending order. The head-warning time is normally taken
4334 from `org-deadline-warning-days', but can also be specified in the deadline
4335 timestamp itself, like this:
4337 DEADLINE: <2007-08-13 Mon -8d>
4339 You may use d for days, w for weeks, m for months and y for years. Months
4340 and years will only be treated in an approximate fashion (30.4 days for a
4341 month and 365.24 days for a year)."
4342 :group 'org-faces
4343 :group 'org-agenda-daily/weekly
4344 :type '(repeat
4345 (cons
4346 (number :tag "Fraction of head-warning time passed")
4347 (sexp :tag "Face"))))
4349 ;; FIXME: this is not a good face yet.
4350 (defface org-agenda-restriction-lock
4351 (org-compatible-face nil
4352 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4353 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4354 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4355 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4356 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4357 (t (:inverse-video t))))
4358 "Face for showing the agenda restriction lock."
4359 :group 'org-faces)
4361 (defface org-time-grid ;; font-lock-variable-name-face
4362 (org-compatible-face nil
4363 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4364 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4365 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4366 "Face used for time grids."
4367 :group 'org-faces)
4369 (defconst org-level-faces
4370 '(org-level-1 org-level-2 org-level-3 org-level-4
4371 org-level-5 org-level-6 org-level-7 org-level-8
4374 (defcustom org-n-level-faces (length org-level-faces)
4375 "The number of different faces to be used for headlines.
4376 Org-mode defines 8 different headline faces, so this can be at most 8.
4377 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4378 :type 'number
4379 :group 'org-faces)
4381 ;;; Functions and variables from ther packages
4382 ;; Declared here to avoid compiler warnings
4384 (eval-and-compile
4385 (unless (fboundp 'declare-function)
4386 (defmacro declare-function (fn file &optional arglist fileonly))))
4388 ;; XEmacs only
4389 (defvar outline-mode-menu-heading)
4390 (defvar outline-mode-menu-show)
4391 (defvar outline-mode-menu-hide)
4392 (defvar zmacs-regions) ; XEmacs regions
4394 ;; Emacs only
4395 (defvar mark-active)
4397 ;; Various packages
4398 ;; FIXME: get the argument lists for the UNKNOWN stuff
4399 (declare-function add-to-diary-list "diary-lib"
4400 (date string specifier &optional marker globcolor literal))
4401 (declare-function table--at-cell-p "table" (position &optional object at-column))
4402 (declare-function bibtex-beginning-of-entry "bibtex" ())
4403 (declare-function bibtex-generate-autokey "bibtex" ())
4404 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4405 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4406 (defvar calc-embedded-close-formula)
4407 (defvar calc-embedded-open-formula)
4408 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4409 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4410 (declare-function calendar-check-holidays "holidays" (date))
4411 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4412 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4413 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4414 (declare-function calendar-forward-day "cal-move" (arg))
4415 (declare-function calendar-french-date-string "cal-french" (&optional date))
4416 (declare-function calendar-goto-date "cal-move" (date))
4417 (declare-function calendar-goto-today "cal-move" ())
4418 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4419 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4420 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4421 (declare-function calendar-iso-from-absolute "cal-iso" (&optional date))
4422 (declare-function calendar-absolute-from-iso "cal-iso" (&optional date))
4423 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4424 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4425 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4426 (defvar calendar-mode-map)
4427 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4428 (declare-function cdlatex-tab "ext:cdlatex" ())
4429 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4430 (defvar font-lock-unfontify-region-function)
4431 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4432 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4433 (declare-function parse-time-string "parse-time" (string))
4434 (declare-function remember "remember" (&optional initial))
4435 (declare-function remember-buffer-desc "remember" ())
4436 (declare-function remember-finalize "remember" ())
4437 (defvar remember-save-after-remembering)
4438 (defvar remember-data-file)
4439 (defvar remember-register)
4440 (defvar remember-buffer)
4441 (defvar remember-handler-functions)
4442 (defvar remember-annotation-functions)
4443 (defvar texmathp-why)
4444 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4446 (defvar w3m-current-url)
4447 (defvar w3m-current-title)
4449 (defvar org-latex-regexps)
4450 (defvar constants-unit-system)
4452 ;;; Variables for pre-computed regular expressions, all buffer local
4454 (defvar org-drawer-regexp nil
4455 "Matches first line of a hidden block.")
4456 (make-variable-buffer-local 'org-drawer-regexp)
4457 (defvar org-todo-regexp nil
4458 "Matches any of the TODO state keywords.")
4459 (make-variable-buffer-local 'org-todo-regexp)
4460 (defvar org-not-done-regexp nil
4461 "Matches any of the TODO state keywords except the last one.")
4462 (make-variable-buffer-local 'org-not-done-regexp)
4463 (defvar org-todo-line-regexp nil
4464 "Matches a headline and puts TODO state into group 2 if present.")
4465 (make-variable-buffer-local 'org-todo-line-regexp)
4466 (defvar org-complex-heading-regexp nil
4467 "Matches a headline and puts everything into groups:
4468 group 1: the stars
4469 group 2: The todo keyword, maybe
4470 group 3: Priority cookie
4471 group 4: True headline
4472 group 5: Tags")
4473 (make-variable-buffer-local 'org-complex-heading-regexp)
4474 (defvar org-todo-line-tags-regexp nil
4475 "Matches a headline and puts TODO state into group 2 if present.
4476 Also put tags into group 4 if tags are present.")
4477 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4478 (defvar org-nl-done-regexp nil
4479 "Matches newline followed by a headline with the DONE keyword.")
4480 (make-variable-buffer-local 'org-nl-done-regexp)
4481 (defvar org-looking-at-done-regexp nil
4482 "Matches the DONE keyword a point.")
4483 (make-variable-buffer-local 'org-looking-at-done-regexp)
4484 (defvar org-ds-keyword-length 12
4485 "Maximum length of the Deadline and SCHEDULED keywords.")
4486 (make-variable-buffer-local 'org-ds-keyword-length)
4487 (defvar org-deadline-regexp nil
4488 "Matches the DEADLINE keyword.")
4489 (make-variable-buffer-local 'org-deadline-regexp)
4490 (defvar org-deadline-time-regexp nil
4491 "Matches the DEADLINE keyword together with a time stamp.")
4492 (make-variable-buffer-local 'org-deadline-time-regexp)
4493 (defvar org-deadline-line-regexp nil
4494 "Matches the DEADLINE keyword and the rest of the line.")
4495 (make-variable-buffer-local 'org-deadline-line-regexp)
4496 (defvar org-scheduled-regexp nil
4497 "Matches the SCHEDULED keyword.")
4498 (make-variable-buffer-local 'org-scheduled-regexp)
4499 (defvar org-scheduled-time-regexp nil
4500 "Matches the SCHEDULED keyword together with a time stamp.")
4501 (make-variable-buffer-local 'org-scheduled-time-regexp)
4502 (defvar org-closed-time-regexp nil
4503 "Matches the CLOSED keyword together with a time stamp.")
4504 (make-variable-buffer-local 'org-closed-time-regexp)
4506 (defvar org-keyword-time-regexp nil
4507 "Matches any of the 4 keywords, together with the time stamp.")
4508 (make-variable-buffer-local 'org-keyword-time-regexp)
4509 (defvar org-keyword-time-not-clock-regexp nil
4510 "Matches any of the 3 keywords, together with the time stamp.")
4511 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4512 (defvar org-maybe-keyword-time-regexp nil
4513 "Matches a timestamp, possibly preceeded by a keyword.")
4514 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4515 (defvar org-planning-or-clock-line-re nil
4516 "Matches a line with planning or clock info.")
4517 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4519 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4520 rear-nonsticky t mouse-map t fontified t)
4521 "Properties to remove when a string without properties is wanted.")
4523 (defsubst org-match-string-no-properties (num &optional string)
4524 (if (featurep 'xemacs)
4525 (let ((s (match-string num string)))
4526 (remove-text-properties 0 (length s) org-rm-props s)
4528 (match-string-no-properties num string)))
4530 (defsubst org-no-properties (s)
4531 (if (fboundp 'set-text-properties)
4532 (set-text-properties 0 (length s) nil s)
4533 (remove-text-properties 0 (length s) org-rm-props s))
4536 (defsubst org-get-alist-option (option key)
4537 (cond ((eq key t) t)
4538 ((eq option t) t)
4539 ((assoc key option) (cdr (assoc key option)))
4540 (t (cdr (assq 'default option)))))
4542 (defsubst org-inhibit-invisibility ()
4543 "Modified `buffer-invisibility-spec' for Emacs 21.
4544 Some ops with invisible text do not work correctly on Emacs 21. For these
4545 we turn off invisibility temporarily. Use this in a `let' form."
4546 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4548 (defsubst org-set-local (var value)
4549 "Make VAR local in current buffer and set it to VALUE."
4550 (set (make-variable-buffer-local var) value))
4552 (defsubst org-mode-p ()
4553 "Check if the current buffer is in Org-mode."
4554 (eq major-mode 'org-mode))
4556 (defsubst org-last (list)
4557 "Return the last element of LIST."
4558 (car (last list)))
4560 (defun org-let (list &rest body)
4561 (eval (cons 'let (cons list body))))
4562 (put 'org-let 'lisp-indent-function 1)
4564 (defun org-let2 (list1 list2 &rest body)
4565 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4566 (put 'org-let2 'lisp-indent-function 2)
4567 (defconst org-startup-options
4568 '(("fold" org-startup-folded t)
4569 ("overview" org-startup-folded t)
4570 ("nofold" org-startup-folded nil)
4571 ("showall" org-startup-folded nil)
4572 ("content" org-startup-folded content)
4573 ("hidestars" org-hide-leading-stars t)
4574 ("showstars" org-hide-leading-stars nil)
4575 ("odd" org-odd-levels-only t)
4576 ("oddeven" org-odd-levels-only nil)
4577 ("align" org-startup-align-all-tables t)
4578 ("noalign" org-startup-align-all-tables nil)
4579 ("customtime" org-display-custom-times t)
4580 ("logdone" org-log-done time)
4581 ("lognotedone" org-log-done note)
4582 ("nologdone" org-log-done nil)
4583 ("lognoteclock-out" org-log-note-clock-out t)
4584 ("nolognoteclock-out" org-log-note-clock-out nil)
4585 ("logrepeat" org-log-repeat state)
4586 ("lognoterepeat" org-log-repeat note)
4587 ("nologrepeat" org-log-repeat nil)
4588 ("constcgs" constants-unit-system cgs)
4589 ("constSI" constants-unit-system SI))
4590 "Variable associated with STARTUP options for org-mode.
4591 Each element is a list of three items: The startup options as written
4592 in the #+STARTUP line, the corresponding variable, and the value to
4593 set this variable to if the option is found. An optional forth element PUSH
4594 means to push this value onto the list in the variable.")
4596 (defun org-set-regexps-and-options ()
4597 "Precompute regular expressions for current buffer."
4598 (when (org-mode-p)
4599 (org-set-local 'org-todo-kwd-alist nil)
4600 (org-set-local 'org-todo-key-alist nil)
4601 (org-set-local 'org-todo-key-trigger nil)
4602 (org-set-local 'org-todo-keywords-1 nil)
4603 (org-set-local 'org-done-keywords nil)
4604 (org-set-local 'org-todo-heads nil)
4605 (org-set-local 'org-todo-sets nil)
4606 (org-set-local 'org-todo-log-states nil)
4607 (let ((re (org-make-options-regexp
4608 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4609 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4610 "CONSTANTS" "PROPERTY" "DRAWERS")))
4611 (splitre "[ \t]+")
4612 kwds kws0 kwsa key log value cat arch tags const links hw dws
4613 tail sep kws1 prio props drawers)
4614 (save-excursion
4615 (save-restriction
4616 (widen)
4617 (goto-char (point-min))
4618 (while (re-search-forward re nil t)
4619 (setq key (match-string 1) value (org-match-string-no-properties 2))
4620 (cond
4621 ((equal key "CATEGORY")
4622 (if (string-match "[ \t]+$" value)
4623 (setq value (replace-match "" t t value)))
4624 (setq cat value))
4625 ((member key '("SEQ_TODO" "TODO"))
4626 (push (cons 'sequence (org-split-string value splitre)) kwds))
4627 ((equal key "TYP_TODO")
4628 (push (cons 'type (org-split-string value splitre)) kwds))
4629 ((equal key "TAGS")
4630 (setq tags (append tags (org-split-string value splitre))))
4631 ((equal key "COLUMNS")
4632 (org-set-local 'org-columns-default-format value))
4633 ((equal key "LINK")
4634 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4635 (push (cons (match-string 1 value)
4636 (org-trim (match-string 2 value)))
4637 links)))
4638 ((equal key "PRIORITIES")
4639 (setq prio (org-split-string value " +")))
4640 ((equal key "PROPERTY")
4641 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4642 (push (cons (match-string 1 value) (match-string 2 value))
4643 props)))
4644 ((equal key "DRAWERS")
4645 (setq drawers (org-split-string value splitre)))
4646 ((equal key "CONSTANTS")
4647 (setq const (append const (org-split-string value splitre))))
4648 ((equal key "STARTUP")
4649 (let ((opts (org-split-string value splitre))
4650 l var val)
4651 (while (setq l (pop opts))
4652 (when (setq l (assoc l org-startup-options))
4653 (setq var (nth 1 l) val (nth 2 l))
4654 (if (not (nth 3 l))
4655 (set (make-local-variable var) val)
4656 (if (not (listp (symbol-value var)))
4657 (set (make-local-variable var) nil))
4658 (set (make-local-variable var) (symbol-value var))
4659 (add-to-list var val))))))
4660 ((equal key "ARCHIVE")
4661 (string-match " *$" value)
4662 (setq arch (replace-match "" t t value))
4663 (remove-text-properties 0 (length arch)
4664 '(face t fontified t) arch)))
4666 (when cat
4667 (org-set-local 'org-category (intern cat))
4668 (push (cons "CATEGORY" cat) props))
4669 (when prio
4670 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4671 (setq prio (mapcar 'string-to-char prio))
4672 (org-set-local 'org-highest-priority (nth 0 prio))
4673 (org-set-local 'org-lowest-priority (nth 1 prio))
4674 (org-set-local 'org-default-priority (nth 2 prio)))
4675 (and props (org-set-local 'org-local-properties (nreverse props)))
4676 (and drawers (org-set-local 'org-drawers drawers))
4677 (and arch (org-set-local 'org-archive-location arch))
4678 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4679 ;; Process the TODO keywords
4680 (unless kwds
4681 ;; Use the global values as if they had been given locally.
4682 (setq kwds (default-value 'org-todo-keywords))
4683 (if (stringp (car kwds))
4684 (setq kwds (list (cons org-todo-interpretation
4685 (default-value 'org-todo-keywords)))))
4686 (setq kwds (reverse kwds)))
4687 (setq kwds (nreverse kwds))
4688 (let (inter kws kw)
4689 (while (setq kws (pop kwds))
4690 (setq inter (pop kws) sep (member "|" kws)
4691 kws0 (delete "|" (copy-sequence kws))
4692 kwsa nil
4693 kws1 (mapcar
4694 (lambda (x)
4695 ;; 1 2
4696 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4697 (progn
4698 (setq kw (match-string 1 x)
4699 key (and (match-end 2) (match-string 2 x))
4700 log (org-extract-log-state-settings x))
4701 (push (cons kw (and key (string-to-char key))) kwsa)
4702 (and log (push log org-todo-log-states))
4704 (error "Invalid TODO keyword %s" x)))
4705 kws0)
4706 kwsa (if kwsa (append '((:startgroup))
4707 (nreverse kwsa)
4708 '((:endgroup))))
4709 hw (car kws1)
4710 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4711 tail (list inter hw (car dws) (org-last dws)))
4712 (add-to-list 'org-todo-heads hw 'append)
4713 (push kws1 org-todo-sets)
4714 (setq org-done-keywords (append org-done-keywords dws nil))
4715 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4716 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4717 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4718 (setq org-todo-sets (nreverse org-todo-sets)
4719 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4720 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4721 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4722 ;; Process the constants
4723 (when const
4724 (let (e cst)
4725 (while (setq e (pop const))
4726 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4727 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4728 (setq org-table-formula-constants-local cst)))
4730 ;; Process the tags.
4731 (when tags
4732 (let (e tgs)
4733 (while (setq e (pop tags))
4734 (cond
4735 ((equal e "{") (push '(:startgroup) tgs))
4736 ((equal e "}") (push '(:endgroup) tgs))
4737 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4738 (push (cons (match-string 1 e)
4739 (string-to-char (match-string 2 e)))
4740 tgs))
4741 (t (push (list e) tgs))))
4742 (org-set-local 'org-tag-alist nil)
4743 (while (setq e (pop tgs))
4744 (or (and (stringp (car e))
4745 (assoc (car e) org-tag-alist))
4746 (push e org-tag-alist))))))
4748 ;; Compute the regular expressions and other local variables
4749 (if (not org-done-keywords)
4750 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4751 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4752 (length org-scheduled-string)))
4753 org-drawer-regexp
4754 (concat "^[ \t]*:\\("
4755 (mapconcat 'regexp-quote org-drawers "\\|")
4756 "\\):[ \t]*$")
4757 org-not-done-keywords
4758 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4759 org-todo-regexp
4760 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4761 "\\|") "\\)\\>")
4762 org-not-done-regexp
4763 (concat "\\<\\("
4764 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4765 "\\)\\>")
4766 org-todo-line-regexp
4767 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4768 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4769 "\\)\\>\\)?[ \t]*\\(.*\\)")
4770 org-complex-heading-regexp
4771 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4772 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4773 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4774 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4775 org-nl-done-regexp
4776 (concat "\n\\*+[ \t]+"
4777 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4778 "\\)" "\\>")
4779 org-todo-line-tags-regexp
4780 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4781 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4782 (org-re
4783 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4784 org-looking-at-done-regexp
4785 (concat "^" "\\(?:"
4786 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4787 "\\>")
4788 org-deadline-regexp (concat "\\<" org-deadline-string)
4789 org-deadline-time-regexp
4790 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4791 org-deadline-line-regexp
4792 (concat "\\<\\(" org-deadline-string "\\).*")
4793 org-scheduled-regexp
4794 (concat "\\<" org-scheduled-string)
4795 org-scheduled-time-regexp
4796 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4797 org-closed-time-regexp
4798 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4799 org-keyword-time-regexp
4800 (concat "\\<\\(" org-scheduled-string
4801 "\\|" org-deadline-string
4802 "\\|" org-closed-string
4803 "\\|" org-clock-string "\\)"
4804 " *[[<]\\([^]>]+\\)[]>]")
4805 org-keyword-time-not-clock-regexp
4806 (concat "\\<\\(" org-scheduled-string
4807 "\\|" org-deadline-string
4808 "\\|" org-closed-string
4809 "\\)"
4810 " *[[<]\\([^]>]+\\)[]>]")
4811 org-maybe-keyword-time-regexp
4812 (concat "\\(\\<\\(" org-scheduled-string
4813 "\\|" org-deadline-string
4814 "\\|" org-closed-string
4815 "\\|" org-clock-string "\\)\\)?"
4816 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4817 org-planning-or-clock-line-re
4818 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4819 "\\|" org-deadline-string
4820 "\\|" org-closed-string "\\|" org-clock-string
4821 "\\)\\>\\)")
4823 (org-compute-latex-and-specials-regexp)
4824 (org-set-font-lock-defaults)))
4826 (defun org-extract-log-state-settings (x)
4827 "Extract the log state setting from a TODO keyword string.
4828 This will extract info from a string like \"WAIT(w@/!)\"."
4829 (let (kw key log1 log2)
4830 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4831 (setq kw (match-string 1 x)
4832 key (and (match-end 2) (match-string 2 x))
4833 log1 (and (match-end 3) (match-string 3 x))
4834 log2 (and (match-end 4) (match-string 4 x)))
4835 (and (or log1 log2)
4836 (list kw
4837 (and log1 (if (equal log1 "!") 'time 'note))
4838 (and log2 (if (equal log2 "!") 'time 'note)))))))
4840 (defun org-remove-keyword-keys (list)
4841 "Remove a pair of parenthesis at the end of each string in LIST."
4842 (mapcar (lambda (x)
4843 (if (string-match "(.*)$" x)
4844 (substring x 0 (match-beginning 0))
4846 list))
4848 ;; FIXME: this could be done much better, using second characters etc.
4849 (defun org-assign-fast-keys (alist)
4850 "Assign fast keys to a keyword-key alist.
4851 Respect keys that are already there."
4852 (let (new e k c c1 c2 (char ?a))
4853 (while (setq e (pop alist))
4854 (cond
4855 ((equal e '(:startgroup)) (push e new))
4856 ((equal e '(:endgroup)) (push e new))
4858 (setq k (car e) c2 nil)
4859 (if (cdr e)
4860 (setq c (cdr e))
4861 ;; automatically assign a character.
4862 (setq c1 (string-to-char
4863 (downcase (substring
4864 k (if (= (string-to-char k) ?@) 1 0)))))
4865 (if (or (rassoc c1 new) (rassoc c1 alist))
4866 (while (or (rassoc char new) (rassoc char alist))
4867 (setq char (1+ char)))
4868 (setq c2 c1))
4869 (setq c (or c2 char)))
4870 (push (cons k c) new))))
4871 (nreverse new)))
4873 ;;; Some variables ujsed in various places
4875 (defvar org-window-configuration nil
4876 "Used in various places to store a window configuration.")
4877 (defvar org-finish-function nil
4878 "Function to be called when `C-c C-c' is used.
4879 This is for getting out of special buffers like remember.")
4882 ;; FIXME: Occasionally check by commenting these, to make sure
4883 ;; no other functions uses these, forgetting to let-bind them.
4884 (defvar entry)
4885 (defvar state)
4886 (defvar last-state)
4887 (defvar date)
4888 (defvar description)
4890 ;; Defined somewhere in this file, but used before definition.
4891 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4892 (defvar org-agenda-buffer-name)
4893 (defvar org-agenda-undo-list)
4894 (defvar org-agenda-pending-undo-list)
4895 (defvar org-agenda-overriding-header)
4896 (defvar orgtbl-mode)
4897 (defvar org-html-entities)
4898 (defvar org-struct-menu)
4899 (defvar org-org-menu)
4900 (defvar org-tbl-menu)
4901 (defvar org-agenda-keymap)
4903 ;;;; Emacs/XEmacs compatibility
4905 ;; Overlay compatibility functions
4906 (defun org-make-overlay (beg end &optional buffer)
4907 (if (featurep 'xemacs)
4908 (make-extent beg end buffer)
4909 (make-overlay beg end buffer)))
4910 (defun org-delete-overlay (ovl)
4911 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4912 (defun org-detach-overlay (ovl)
4913 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4914 (defun org-move-overlay (ovl beg end &optional buffer)
4915 (if (featurep 'xemacs)
4916 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4917 (move-overlay ovl beg end buffer)))
4918 (defun org-overlay-put (ovl prop value)
4919 (if (featurep 'xemacs)
4920 (set-extent-property ovl prop value)
4921 (overlay-put ovl prop value)))
4922 (defun org-overlay-display (ovl text &optional face evap)
4923 "Make overlay OVL display TEXT with face FACE."
4924 (if (featurep 'xemacs)
4925 (let ((gl (make-glyph text)))
4926 (and face (set-glyph-face gl face))
4927 (set-extent-property ovl 'invisible t)
4928 (set-extent-property ovl 'end-glyph gl))
4929 (overlay-put ovl 'display text)
4930 (if face (overlay-put ovl 'face face))
4931 (if evap (overlay-put ovl 'evaporate t))))
4932 (defun org-overlay-before-string (ovl text &optional face evap)
4933 "Make overlay OVL display TEXT with face FACE."
4934 (if (featurep 'xemacs)
4935 (let ((gl (make-glyph text)))
4936 (and face (set-glyph-face gl face))
4937 (set-extent-property ovl 'begin-glyph gl))
4938 (if face (org-add-props text nil 'face face))
4939 (overlay-put ovl 'before-string text)
4940 (if evap (overlay-put ovl 'evaporate t))))
4941 (defun org-overlay-get (ovl prop)
4942 (if (featurep 'xemacs)
4943 (extent-property ovl prop)
4944 (overlay-get ovl prop)))
4945 (defun org-overlays-at (pos)
4946 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4947 (defun org-overlays-in (&optional start end)
4948 (if (featurep 'xemacs)
4949 (extent-list nil start end)
4950 (overlays-in start end)))
4951 (defun org-overlay-start (o)
4952 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4953 (defun org-overlay-end (o)
4954 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4955 (defun org-find-overlays (prop &optional pos delete)
4956 "Find all overlays specifying PROP at POS or point.
4957 If DELETE is non-nil, delete all those overlays."
4958 (let ((overlays (org-overlays-at (or pos (point))))
4959 ov found)
4960 (while (setq ov (pop overlays))
4961 (if (org-overlay-get ov prop)
4962 (if delete (org-delete-overlay ov) (push ov found))))
4963 found))
4965 ;; Region compatibility
4967 (defun org-add-hook (hook function &optional append local)
4968 "Add-hook, compatible with both Emacsen."
4969 (if (and local (featurep 'xemacs))
4970 (add-local-hook hook function append)
4971 (add-hook hook function append local)))
4973 (defvar org-ignore-region nil
4974 "To temporarily disable the active region.")
4976 (defun org-region-active-p ()
4977 "Is `transient-mark-mode' on and the region active?
4978 Works on both Emacs and XEmacs."
4979 (if org-ignore-region
4981 (if (featurep 'xemacs)
4982 (and zmacs-regions (region-active-p))
4983 (if (fboundp 'use-region-p)
4984 (use-region-p)
4985 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4987 ;; Invisibility compatibility
4989 (defun org-add-to-invisibility-spec (arg)
4990 "Add elements to `buffer-invisibility-spec'.
4991 See documentation for `buffer-invisibility-spec' for the kind of elements
4992 that can be added."
4993 (cond
4994 ((fboundp 'add-to-invisibility-spec)
4995 (add-to-invisibility-spec arg))
4996 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4997 (setq buffer-invisibility-spec (list arg)))
4999 (setq buffer-invisibility-spec
5000 (cons arg buffer-invisibility-spec)))))
5002 (defun org-remove-from-invisibility-spec (arg)
5003 "Remove elements from `buffer-invisibility-spec'."
5004 (if (fboundp 'remove-from-invisibility-spec)
5005 (remove-from-invisibility-spec arg)
5006 (if (consp buffer-invisibility-spec)
5007 (setq buffer-invisibility-spec
5008 (delete arg buffer-invisibility-spec)))))
5010 (defun org-in-invisibility-spec-p (arg)
5011 "Is ARG a member of `buffer-invisibility-spec'?"
5012 (if (consp buffer-invisibility-spec)
5013 (member arg buffer-invisibility-spec)
5014 nil))
5016 ;;;; Define the Org-mode
5018 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5019 (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."))
5022 ;; We use a before-change function to check if a table might need
5023 ;; an update.
5024 (defvar org-table-may-need-update t
5025 "Indicates that a table might need an update.
5026 This variable is set by `org-before-change-function'.
5027 `org-table-align' sets it back to nil.")
5028 (defvar org-mode-map)
5029 (defvar org-mode-hook nil)
5030 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5031 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5032 (defvar org-table-buffer-is-an nil)
5033 (defconst org-outline-regexp "\\*+ ")
5035 ;;;###autoload
5036 (define-derived-mode org-mode outline-mode "Org"
5037 "Outline-based notes management and organizer, alias
5038 \"Carsten's outline-mode for keeping track of everything.\"
5040 Org-mode develops organizational tasks around a NOTES file which
5041 contains information about projects as plain text. Org-mode is
5042 implemented on top of outline-mode, which is ideal to keep the content
5043 of large files well structured. It supports ToDo items, deadlines and
5044 time stamps, which magically appear in the diary listing of the Emacs
5045 calendar. Tables are easily created with a built-in table editor.
5046 Plain text URL-like links connect to websites, emails (VM), Usenet
5047 messages (Gnus), BBDB entries, and any files related to the project.
5048 For printing and sharing of notes, an Org-mode file (or a part of it)
5049 can be exported as a structured ASCII or HTML file.
5051 The following commands are available:
5053 \\{org-mode-map}"
5055 ;; Get rid of Outline menus, they are not needed
5056 ;; Need to do this here because define-derived-mode sets up
5057 ;; the keymap so late. Still, it is a waste to call this each time
5058 ;; we switch another buffer into org-mode.
5059 (if (featurep 'xemacs)
5060 (when (boundp 'outline-mode-menu-heading)
5061 ;; Assume this is Greg's port, it used easymenu
5062 (easy-menu-remove outline-mode-menu-heading)
5063 (easy-menu-remove outline-mode-menu-show)
5064 (easy-menu-remove outline-mode-menu-hide))
5065 (define-key org-mode-map [menu-bar headings] 'undefined)
5066 (define-key org-mode-map [menu-bar hide] 'undefined)
5067 (define-key org-mode-map [menu-bar show] 'undefined))
5069 (org-load-modules-maybe)
5070 (easy-menu-add org-org-menu)
5071 (easy-menu-add org-tbl-menu)
5072 (org-install-agenda-files-menu)
5073 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
5074 (org-add-to-invisibility-spec '(org-cwidth))
5075 (when (featurep 'xemacs)
5076 (org-set-local 'line-move-ignore-invisible t))
5077 (org-set-local 'outline-regexp org-outline-regexp)
5078 (org-set-local 'outline-level 'org-outline-level)
5079 (when (and org-ellipsis
5080 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5081 (fboundp 'make-glyph-code))
5082 (unless org-display-table
5083 (setq org-display-table (make-display-table)))
5084 (set-display-table-slot
5085 org-display-table 4
5086 (vconcat (mapcar
5087 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5088 org-ellipsis)))
5089 (if (stringp org-ellipsis) org-ellipsis "..."))))
5090 (setq buffer-display-table org-display-table))
5091 (org-set-regexps-and-options)
5092 ;; Calc embedded
5093 (org-set-local 'calc-embedded-open-mode "# ")
5094 (modify-syntax-entry ?# "<")
5095 (modify-syntax-entry ?@ "w")
5096 (if org-startup-truncated (setq truncate-lines t))
5097 (org-set-local 'font-lock-unfontify-region-function
5098 'org-unfontify-region)
5099 ;; Activate before-change-function
5100 (org-set-local 'org-table-may-need-update t)
5101 (org-add-hook 'before-change-functions 'org-before-change-function nil
5102 'local)
5103 ;; Check for running clock before killing a buffer
5104 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5105 ;; Paragraphs and auto-filling
5106 (org-set-autofill-regexps)
5107 (setq indent-line-function 'org-indent-line-function)
5108 (org-update-radio-target-regexp)
5110 ;; Comment characters
5111 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
5112 (org-set-local 'comment-padding " ")
5114 ;; Align options lines
5115 (org-set-local
5116 'align-mode-rules-list
5117 '((org-in-buffer-settings
5118 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5119 (modes . '(org-mode)))))
5121 ;; Imenu
5122 (org-set-local 'imenu-create-index-function
5123 'org-imenu-get-tree)
5125 ;; Make isearch reveal context
5126 (if (or (featurep 'xemacs)
5127 (not (boundp 'outline-isearch-open-invisible-function)))
5128 ;; Emacs 21 and XEmacs make use of the hook
5129 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5130 ;; Emacs 22 deals with this through a special variable
5131 (org-set-local 'outline-isearch-open-invisible-function
5132 (lambda (&rest ignore) (org-show-context 'isearch))))
5134 ;; If empty file that did not turn on org-mode automatically, make it to.
5135 (if (and org-insert-mode-line-in-empty-file
5136 (interactive-p)
5137 (= (point-min) (point-max)))
5138 (insert "# -*- mode: org -*-\n\n"))
5140 (unless org-inhibit-startup
5141 (when org-startup-align-all-tables
5142 (let ((bmp (buffer-modified-p)))
5143 (org-table-map-tables 'org-table-align)
5144 (set-buffer-modified-p bmp)))
5145 (org-cycle-hide-drawers 'all)
5146 (cond
5147 ((eq org-startup-folded t)
5148 (org-cycle '(4)))
5149 ((eq org-startup-folded 'content)
5150 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5151 (org-cycle '(4)) (org-cycle '(4)))))))
5153 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5155 (defsubst org-call-with-arg (command arg)
5156 "Call COMMAND interactively, but pretend prefix are was ARG."
5157 (let ((current-prefix-arg arg)) (call-interactively command)))
5159 (defsubst org-current-line (&optional pos)
5160 (save-excursion
5161 (and pos (goto-char pos))
5162 ;; works also in narrowed buffer, because we start at 1, not point-min
5163 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
5165 (defun org-current-time ()
5166 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5167 (if (> (car org-time-stamp-rounding-minutes) 1)
5168 (let ((r (car org-time-stamp-rounding-minutes))
5169 (time (decode-time)))
5170 (apply 'encode-time
5171 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5172 (nthcdr 2 time))))
5173 (current-time)))
5175 (defun org-add-props (string plist &rest props)
5176 "Add text properties to entire string, from beginning to end.
5177 PLIST may be a list of properties, PROPS are individual properties and values
5178 that will be added to PLIST. Returns the string that was modified."
5179 (add-text-properties
5180 0 (length string) (if props (append plist props) plist) string)
5181 string)
5182 (put 'org-add-props 'lisp-indent-function 2)
5185 ;;;; Font-Lock stuff, including the activators
5187 (defvar org-mouse-map (make-sparse-keymap))
5188 (org-defkey org-mouse-map
5189 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
5190 (org-defkey org-mouse-map
5191 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
5192 (when org-mouse-1-follows-link
5193 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5194 (when org-tab-follows-link
5195 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5196 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5197 (when org-return-follows-link
5198 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
5199 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5201 (require 'font-lock)
5203 (defconst org-non-link-chars "]\t\n\r<>")
5204 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5205 "shell" "elisp"))
5206 (defvar org-link-re-with-space nil
5207 "Matches a link with spaces, optional angular brackets around it.")
5208 (defvar org-link-re-with-space2 nil
5209 "Matches a link with spaces, optional angular brackets around it.")
5210 (defvar org-angle-link-re nil
5211 "Matches link with angular brackets, spaces are allowed.")
5212 (defvar org-plain-link-re nil
5213 "Matches plain link, without spaces.")
5214 (defvar org-bracket-link-regexp nil
5215 "Matches a link in double brackets.")
5216 (defvar org-bracket-link-analytic-regexp nil
5217 "Regular expression used to analyze links.
5218 Here is what the match groups contain after a match:
5219 1: http:
5220 2: http
5221 3: path
5222 4: [desc]
5223 5: desc")
5224 (defvar org-any-link-re nil
5225 "Regular expression matching any link.")
5227 (defun org-make-link-regexps ()
5228 "Update the link regular expressions.
5229 This should be called after the variable `org-link-types' has changed."
5230 (setq org-link-re-with-space
5231 (concat
5232 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5233 "\\([^" org-non-link-chars " ]"
5234 "[^" org-non-link-chars "]*"
5235 "[^" org-non-link-chars " ]\\)>?")
5236 org-link-re-with-space2
5237 (concat
5238 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5239 "\\([^" org-non-link-chars " ]"
5240 "[^]\t\n\r]*"
5241 "[^" org-non-link-chars " ]\\)>?")
5242 org-angle-link-re
5243 (concat
5244 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5245 "\\([^" org-non-link-chars " ]"
5246 "[^" org-non-link-chars "]*"
5247 "\\)>")
5248 org-plain-link-re
5249 (concat
5250 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5251 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5252 org-bracket-link-regexp
5253 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5254 org-bracket-link-analytic-regexp
5255 (concat
5256 "\\[\\["
5257 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5258 "\\([^]]+\\)"
5259 "\\]"
5260 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5261 "\\]")
5262 org-any-link-re
5263 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5264 org-angle-link-re "\\)\\|\\("
5265 org-plain-link-re "\\)")))
5267 (org-make-link-regexps)
5269 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5270 "Regular expression for fast time stamp matching.")
5271 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5272 "Regular expression for fast time stamp matching.")
5273 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5274 "Regular expression matching time strings for analysis.
5275 This one does not require the space after the date, so it can be used
5276 on a string that terminates immediately after the date.")
5277 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5278 "Regular expression matching time strings for analysis.")
5279 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5280 "Regular expression matching time stamps, with groups.")
5281 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5282 "Regular expression matching time stamps (also [..]), with groups.")
5283 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5284 "Regular expression matching a time stamp range.")
5285 (defconst org-tr-regexp-both
5286 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5287 "Regular expression matching a time stamp range.")
5288 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5289 org-ts-regexp "\\)?")
5290 "Regular expression matching a time stamp or time stamp range.")
5291 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5292 org-ts-regexp-both "\\)?")
5293 "Regular expression matching a time stamp or time stamp range.
5294 The time stamps may be either active or inactive.")
5296 (defvar org-emph-face nil)
5298 (defun org-do-emphasis-faces (limit)
5299 "Run through the buffer and add overlays to links."
5300 (let (rtn)
5301 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5302 (if (not (= (char-after (match-beginning 3))
5303 (char-after (match-beginning 4))))
5304 (progn
5305 (setq rtn t)
5306 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5307 'face
5308 (nth 1 (assoc (match-string 3)
5309 org-emphasis-alist)))
5310 (add-text-properties (match-beginning 2) (match-end 2)
5311 '(font-lock-multiline t))
5312 (when org-hide-emphasis-markers
5313 (add-text-properties (match-end 4) (match-beginning 5)
5314 '(invisible org-link))
5315 (add-text-properties (match-beginning 3) (match-end 3)
5316 '(invisible org-link)))))
5317 (backward-char 1))
5318 rtn))
5320 (defun org-emphasize (&optional char)
5321 "Insert or change an emphasis, i.e. a font like bold or italic.
5322 If there is an active region, change that region to a new emphasis.
5323 If there is no region, just insert the marker characters and position
5324 the cursor between them.
5325 CHAR should be either the marker character, or the first character of the
5326 HTML tag associated with that emphasis. If CHAR is a space, the means
5327 to remove the emphasis of the selected region.
5328 If char is not given (for example in an interactive call) it
5329 will be prompted for."
5330 (interactive)
5331 (let ((eal org-emphasis-alist) e det
5332 (erc org-emphasis-regexp-components)
5333 (prompt "")
5334 (string "") beg end move tag c s)
5335 (if (org-region-active-p)
5336 (setq beg (region-beginning) end (region-end)
5337 string (buffer-substring beg end))
5338 (setq move t))
5340 (while (setq e (pop eal))
5341 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5342 c (aref tag 0))
5343 (push (cons c (string-to-char (car e))) det)
5344 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5345 (substring tag 1)))))
5346 (unless char
5347 (message "%s" (concat "Emphasis marker or tag:" prompt))
5348 (setq char (read-char-exclusive)))
5349 (setq char (or (cdr (assoc char det)) char))
5350 (if (equal char ?\ )
5351 (setq s "" move nil)
5352 (unless (assoc (char-to-string char) org-emphasis-alist)
5353 (error "No such emphasis marker: \"%c\"" char))
5354 (setq s (char-to-string char)))
5355 (while (and (> (length string) 1)
5356 (equal (substring string 0 1) (substring string -1))
5357 (assoc (substring string 0 1) org-emphasis-alist))
5358 (setq string (substring string 1 -1)))
5359 (setq string (concat s string s))
5360 (if beg (delete-region beg end))
5361 (unless (or (bolp)
5362 (string-match (concat "[" (nth 0 erc) "\n]")
5363 (char-to-string (char-before (point)))))
5364 (insert " "))
5365 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5366 (char-to-string (char-after (point))))
5367 (insert " ") (backward-char 1))
5368 (insert string)
5369 (and move (backward-char 1))))
5371 (defconst org-nonsticky-props
5372 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5375 (defun org-activate-plain-links (limit)
5376 "Run through the buffer and add overlays to links."
5377 (catch 'exit
5378 (let (f)
5379 (while (re-search-forward org-plain-link-re limit t)
5380 (setq f (get-text-property (match-beginning 0) 'face))
5381 (if (or (eq f 'org-tag)
5382 (and (listp f) (memq 'org-tag f)))
5384 (add-text-properties (match-beginning 0) (match-end 0)
5385 (list 'mouse-face 'highlight
5386 'rear-nonsticky org-nonsticky-props
5387 'keymap org-mouse-map
5389 (throw 'exit t))))))
5391 (defun org-activate-code (limit)
5392 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5393 (unless (get-text-property (match-beginning 1) 'face)
5394 (remove-text-properties (match-beginning 0) (match-end 0)
5395 '(display t invisible t intangible t))
5396 t)))
5398 (defun org-activate-angle-links (limit)
5399 "Run through the buffer and add overlays to links."
5400 (if (re-search-forward org-angle-link-re limit t)
5401 (progn
5402 (add-text-properties (match-beginning 0) (match-end 0)
5403 (list 'mouse-face 'highlight
5404 'rear-nonsticky org-nonsticky-props
5405 'keymap org-mouse-map
5407 t)))
5409 (defmacro org-maybe-intangible (props)
5410 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5411 In emacs 21, invisible text is not avoided by the command loop, so the
5412 intangible property is needed to make sure point skips this text.
5413 In Emacs 22, this is not necessary. The intangible text property has
5414 led to problems with flyspell. These problems are fixed in flyspell.el,
5415 but we still avoid setting the property in Emacs 22 and later.
5416 We use a macro so that the test can happen at compilation time."
5417 (if (< emacs-major-version 22)
5418 `(append '(intangible t) ,props)
5419 props))
5421 (defun org-activate-bracket-links (limit)
5422 "Run through the buffer and add overlays to bracketed links."
5423 (if (re-search-forward org-bracket-link-regexp limit t)
5424 (let* ((help (concat "LINK: "
5425 (org-match-string-no-properties 1)))
5426 ;; FIXME: above we should remove the escapes.
5427 ;; but that requires another match, protecting match data,
5428 ;; a lot of overhead for font-lock.
5429 (ip (org-maybe-intangible
5430 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5431 'keymap org-mouse-map 'mouse-face 'highlight
5432 'font-lock-multiline t 'help-echo help)))
5433 (vp (list 'rear-nonsticky org-nonsticky-props
5434 'keymap org-mouse-map 'mouse-face 'highlight
5435 ' font-lock-multiline t 'help-echo help)))
5436 ;; We need to remove the invisible property here. Table narrowing
5437 ;; may have made some of this invisible.
5438 (remove-text-properties (match-beginning 0) (match-end 0)
5439 '(invisible nil))
5440 (if (match-end 3)
5441 (progn
5442 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5443 (add-text-properties (match-beginning 3) (match-end 3) vp)
5444 (add-text-properties (match-end 3) (match-end 0) ip))
5445 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5446 (add-text-properties (match-beginning 1) (match-end 1) vp)
5447 (add-text-properties (match-end 1) (match-end 0) ip))
5448 t)))
5450 (defun org-activate-dates (limit)
5451 "Run through the buffer and add overlays to dates."
5452 (if (re-search-forward org-tsr-regexp-both limit t)
5453 (progn
5454 (add-text-properties (match-beginning 0) (match-end 0)
5455 (list 'mouse-face 'highlight
5456 'rear-nonsticky org-nonsticky-props
5457 'keymap org-mouse-map))
5458 (when org-display-custom-times
5459 (if (match-end 3)
5460 (org-display-custom-time (match-beginning 3) (match-end 3)))
5461 (org-display-custom-time (match-beginning 1) (match-end 1)))
5462 t)))
5464 (defvar org-target-link-regexp nil
5465 "Regular expression matching radio targets in plain text.")
5466 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5467 "Regular expression matching a link target.")
5468 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5469 "Regular expression matching a radio target.")
5470 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5471 "Regular expression matching any target.")
5473 (defun org-activate-target-links (limit)
5474 "Run through the buffer and add overlays to target matches."
5475 (when org-target-link-regexp
5476 (let ((case-fold-search t))
5477 (if (re-search-forward org-target-link-regexp limit t)
5478 (progn
5479 (add-text-properties (match-beginning 0) (match-end 0)
5480 (list 'mouse-face 'highlight
5481 'rear-nonsticky org-nonsticky-props
5482 'keymap org-mouse-map
5483 'help-echo "Radio target link"
5484 'org-linked-text t))
5485 t)))))
5487 (defun org-update-radio-target-regexp ()
5488 "Find all radio targets in this file and update the regular expression."
5489 (interactive)
5490 (when (memq 'radio org-activate-links)
5491 (setq org-target-link-regexp
5492 (org-make-target-link-regexp (org-all-targets 'radio)))
5493 (org-restart-font-lock)))
5495 (defun org-hide-wide-columns (limit)
5496 (let (s e)
5497 (setq s (text-property-any (point) (or limit (point-max))
5498 'org-cwidth t))
5499 (when s
5500 (setq e (next-single-property-change s 'org-cwidth))
5501 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5502 (goto-char e)
5503 t)))
5505 (defvar org-latex-and-specials-regexp nil
5506 "Regular expression for highlighting export special stuff.")
5507 (defvar org-match-substring-regexp)
5508 (defvar org-match-substring-with-braces-regexp)
5509 (defvar org-export-html-special-string-regexps)
5511 (defun org-compute-latex-and-specials-regexp ()
5512 "Compute regular expression for stuff treated specially by exporters."
5513 (if (not org-highlight-latex-fragments-and-specials)
5514 (org-set-local 'org-latex-and-specials-regexp nil)
5515 (let*
5516 ((matchers (plist-get org-format-latex-options :matchers))
5517 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5518 org-latex-regexps)))
5519 (options (org-combine-plists (org-default-export-plist)
5520 (org-infile-export-plist)))
5521 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5522 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5523 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5524 (org-export-html-expand (plist-get options :expand-quoted-html))
5525 (org-export-with-special-strings (plist-get options :special-strings))
5526 (re-sub
5527 (cond
5528 ((equal org-export-with-sub-superscripts '{})
5529 (list org-match-substring-with-braces-regexp))
5530 (org-export-with-sub-superscripts
5531 (list org-match-substring-regexp))
5532 (t nil)))
5533 (re-latex
5534 (if org-export-with-LaTeX-fragments
5535 (mapcar (lambda (x) (nth 1 x)) latexs)))
5536 (re-macros
5537 (if org-export-with-TeX-macros
5538 (list (concat "\\\\"
5539 (regexp-opt
5540 (append (mapcar 'car org-html-entities)
5541 (if (boundp 'org-latex-entities)
5542 org-latex-entities nil))
5543 'words))) ; FIXME
5545 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5546 (re-special (if org-export-with-special-strings
5547 (mapcar (lambda (x) (car x))
5548 org-export-html-special-string-regexps)))
5549 (re-rest
5550 (delq nil
5551 (list
5552 (if org-export-html-expand "@<[^>\n]+>")
5553 ))))
5554 (org-set-local
5555 'org-latex-and-specials-regexp
5556 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5557 re-rest) "\\|")))))
5559 (defface org-latex-and-export-specials
5560 (let ((font (cond ((assq :inherit custom-face-attributes)
5561 '(:inherit underline))
5562 (t '(:underline t)))))
5563 `((((class grayscale) (background light))
5564 (:foreground "DimGray" ,@font))
5565 (((class grayscale) (background dark))
5566 (:foreground "LightGray" ,@font))
5567 (((class color) (background light))
5568 (:foreground "SaddleBrown"))
5569 (((class color) (background dark))
5570 (:foreground "burlywood"))
5571 (t (,@font))))
5572 "Face used to highlight math latex and other special exporter stuff."
5573 :group 'org-faces)
5575 (defun org-do-latex-and-special-faces (limit)
5576 "Run through the buffer and add overlays to links."
5577 (when org-latex-and-specials-regexp
5578 (let (rtn d)
5579 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5580 limit t))
5581 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5582 'face))
5583 '(org-code org-verbatim underline)))
5584 (progn
5585 (setq rtn t
5586 d (cond ((member (char-after (1+ (match-beginning 0)))
5587 '(?_ ?^)) 1)
5588 (t 0)))
5589 (font-lock-prepend-text-property
5590 (+ d (match-beginning 0)) (match-end 0)
5591 'face 'org-latex-and-export-specials)
5592 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5593 '(font-lock-multiline t)))))
5594 rtn)))
5596 (defun org-restart-font-lock ()
5597 "Restart font-lock-mode, to force refontification."
5598 (when (and (boundp 'font-lock-mode) font-lock-mode)
5599 (font-lock-mode -1)
5600 (font-lock-mode 1)))
5602 (defun org-all-targets (&optional radio)
5603 "Return a list of all targets in this file.
5604 With optional argument RADIO, only find radio targets."
5605 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5606 rtn)
5607 (save-excursion
5608 (goto-char (point-min))
5609 (while (re-search-forward re nil t)
5610 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5611 rtn)))
5613 (defun org-make-target-link-regexp (targets)
5614 "Make regular expression matching all strings in TARGETS.
5615 The regular expression finds the targets also if there is a line break
5616 between words."
5617 (and targets
5618 (concat
5619 "\\<\\("
5620 (mapconcat
5621 (lambda (x)
5622 (while (string-match " +" x)
5623 (setq x (replace-match "\\s-+" t t x)))
5625 targets
5626 "\\|")
5627 "\\)\\>")))
5629 (defun org-activate-tags (limit)
5630 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5631 (progn
5632 (add-text-properties (match-beginning 1) (match-end 1)
5633 (list 'mouse-face 'highlight
5634 'rear-nonsticky org-nonsticky-props
5635 'keymap org-mouse-map))
5636 t)))
5638 (defun org-outline-level ()
5639 (save-excursion
5640 (looking-at outline-regexp)
5641 (if (match-beginning 1)
5642 (+ (org-get-string-indentation (match-string 1)) 1000)
5643 (1- (- (match-end 0) (match-beginning 0))))))
5645 (defvar org-font-lock-keywords nil)
5647 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5648 "Regular expression matching a property line.")
5650 (defun org-set-font-lock-defaults ()
5651 (let* ((em org-fontify-emphasized-text)
5652 (lk org-activate-links)
5653 (org-font-lock-extra-keywords
5654 (list
5655 ;; Headlines
5656 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5657 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5658 ;; Table lines
5659 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5660 (1 'org-table t))
5661 ;; Table internals
5662 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5663 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5664 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5665 ;; Drawers
5666 (list org-drawer-regexp '(0 'org-special-keyword t))
5667 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5668 ;; Properties
5669 (list org-property-re
5670 '(1 'org-special-keyword t)
5671 '(3 'org-property-value t))
5672 (if org-format-transports-properties-p
5673 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5674 ;; Links
5675 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5676 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5677 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5678 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5679 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5680 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5681 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5682 '(org-hide-wide-columns (0 nil append))
5683 ;; TODO lines
5684 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5685 '(1 (org-get-todo-face 1) t))
5686 ;; DONE
5687 (if org-fontify-done-headline
5688 (list (concat "^[*]+ +\\<\\("
5689 (mapconcat 'regexp-quote org-done-keywords "\\|")
5690 "\\)\\(.*\\)")
5691 '(2 'org-headline-done t))
5692 nil)
5693 ;; Priorities
5694 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5695 ;; Special keywords
5696 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5697 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5698 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5699 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5700 ;; Emphasis
5701 (if em
5702 (if (featurep 'xemacs)
5703 '(org-do-emphasis-faces (0 nil append))
5704 '(org-do-emphasis-faces)))
5705 ;; Checkboxes
5706 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5707 2 'bold prepend)
5708 (if org-provide-checkbox-statistics
5709 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5710 (0 (org-get-checkbox-statistics-face) t)))
5711 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5712 '(1 'org-archived prepend))
5713 ;; Specials
5714 '(org-do-latex-and-special-faces)
5715 ;; Code
5716 '(org-activate-code (1 'org-code t))
5717 ;; COMMENT
5718 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5719 "\\|" org-quote-string "\\)\\>")
5720 '(1 'org-special-keyword t))
5721 '("^#.*" (0 'font-lock-comment-face t))
5723 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5724 ;; Now set the full font-lock-keywords
5725 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5726 (org-set-local 'font-lock-defaults
5727 '(org-font-lock-keywords t nil nil backward-paragraph))
5728 (kill-local-variable 'font-lock-keywords) nil))
5730 (defvar org-m nil)
5731 (defvar org-l nil)
5732 (defvar org-f nil)
5733 (defun org-get-level-face (n)
5734 "Get the right face for match N in font-lock matching of healdines."
5735 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5736 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5737 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5738 (cond
5739 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5740 ((eq n 2) org-f)
5741 (t (if org-level-color-stars-only nil org-f))))
5743 (defun org-get-todo-face (kwd)
5744 "Get the right face for a TODO keyword KWD.
5745 If KWD is a number, get the corresponding match group."
5746 (if (numberp kwd) (setq kwd (match-string kwd)))
5747 (or (cdr (assoc kwd org-todo-keyword-faces))
5748 (and (member kwd org-done-keywords) 'org-done)
5749 'org-todo))
5751 (defun org-unfontify-region (beg end &optional maybe_loudly)
5752 "Remove fontification and activation overlays from links."
5753 (font-lock-default-unfontify-region beg end)
5754 (let* ((buffer-undo-list t)
5755 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5756 (inhibit-modification-hooks t)
5757 deactivate-mark buffer-file-name buffer-file-truename)
5758 (remove-text-properties beg end
5759 '(mouse-face t keymap t org-linked-text t
5760 invisible t intangible t))))
5762 ;;;; Visibility cycling, including org-goto and indirect buffer
5764 ;;; Cycling
5766 (defvar org-cycle-global-status nil)
5767 (make-variable-buffer-local 'org-cycle-global-status)
5768 (defvar org-cycle-subtree-status nil)
5769 (make-variable-buffer-local 'org-cycle-subtree-status)
5771 ;;;###autoload
5772 (defun org-cycle (&optional arg)
5773 "Visibility cycling for Org-mode.
5775 - When this function is called with a prefix argument, rotate the entire
5776 buffer through 3 states (global cycling)
5777 1. OVERVIEW: Show only top-level headlines.
5778 2. CONTENTS: Show all headlines of all levels, but no body text.
5779 3. SHOW ALL: Show everything.
5781 - When point is at the beginning of a headline, rotate the subtree started
5782 by this line through 3 different states (local cycling)
5783 1. FOLDED: Only the main headline is shown.
5784 2. CHILDREN: The main headline and the direct children are shown.
5785 From this state, you can move to one of the children
5786 and zoom in further.
5787 3. SUBTREE: Show the entire subtree, including body text.
5789 - When there is a numeric prefix, go up to a heading with level ARG, do
5790 a `show-subtree' and return to the previous cursor position. If ARG
5791 is negative, go up that many levels.
5793 - When point is not at the beginning of a headline, execute
5794 `indent-relative', like TAB normally does. See the option
5795 `org-cycle-emulate-tab' for details.
5797 - Special case: if point is at the beginning of the buffer and there is
5798 no headline in line 1, this function will act as if called with prefix arg.
5799 But only if also the variable `org-cycle-global-at-bob' is t."
5800 (interactive "P")
5801 (org-load-modules-maybe)
5802 (let* ((outline-regexp
5803 (if (and (org-mode-p) org-cycle-include-plain-lists)
5804 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5805 outline-regexp))
5806 (bob-special (and org-cycle-global-at-bob (bobp)
5807 (not (looking-at outline-regexp))))
5808 (org-cycle-hook
5809 (if bob-special
5810 (delq 'org-optimize-window-after-visibility-change
5811 (copy-sequence org-cycle-hook))
5812 org-cycle-hook))
5813 (pos (point)))
5815 (if (or bob-special (equal arg '(4)))
5816 ;; special case: use global cycling
5817 (setq arg t))
5819 (cond
5821 ((org-at-table-p 'any)
5822 ;; Enter the table or move to the next field in the table
5823 (or (org-table-recognize-table.el)
5824 (progn
5825 (if arg (org-table-edit-field t)
5826 (org-table-justify-field-maybe)
5827 (call-interactively 'org-table-next-field)))))
5829 ((eq arg t) ;; Global cycling
5831 (cond
5832 ((and (eq last-command this-command)
5833 (eq org-cycle-global-status 'overview))
5834 ;; We just created the overview - now do table of contents
5835 ;; This can be slow in very large buffers, so indicate action
5836 (message "CONTENTS...")
5837 (org-content)
5838 (message "CONTENTS...done")
5839 (setq org-cycle-global-status 'contents)
5840 (run-hook-with-args 'org-cycle-hook 'contents))
5842 ((and (eq last-command this-command)
5843 (eq org-cycle-global-status 'contents))
5844 ;; We just showed the table of contents - now show everything
5845 (show-all)
5846 (message "SHOW ALL")
5847 (setq org-cycle-global-status 'all)
5848 (run-hook-with-args 'org-cycle-hook 'all))
5851 ;; Default action: go to overview
5852 (org-overview)
5853 (message "OVERVIEW")
5854 (setq org-cycle-global-status 'overview)
5855 (run-hook-with-args 'org-cycle-hook 'overview))))
5857 ((and org-drawers org-drawer-regexp
5858 (save-excursion
5859 (beginning-of-line 1)
5860 (looking-at org-drawer-regexp)))
5861 ;; Toggle block visibility
5862 (org-flag-drawer
5863 (not (get-char-property (match-end 0) 'invisible))))
5865 ((integerp arg)
5866 ;; Show-subtree, ARG levels up from here.
5867 (save-excursion
5868 (org-back-to-heading)
5869 (outline-up-heading (if (< arg 0) (- arg)
5870 (- (funcall outline-level) arg)))
5871 (org-show-subtree)))
5873 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5874 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5875 ;; At a heading: rotate between three different views
5876 (org-back-to-heading)
5877 (let ((goal-column 0) eoh eol eos)
5878 ;; First, some boundaries
5879 (save-excursion
5880 (org-back-to-heading)
5881 (save-excursion
5882 (beginning-of-line 2)
5883 (while (and (not (eobp)) ;; this is like `next-line'
5884 (get-char-property (1- (point)) 'invisible))
5885 (beginning-of-line 2)) (setq eol (point)))
5886 (outline-end-of-heading) (setq eoh (point))
5887 (org-end-of-subtree t)
5888 (unless (eobp)
5889 (skip-chars-forward " \t\n")
5890 (beginning-of-line 1) ; in case this is an item
5892 (setq eos (1- (point))))
5893 ;; Find out what to do next and set `this-command'
5894 (cond
5895 ((= eos eoh)
5896 ;; Nothing is hidden behind this heading
5897 (message "EMPTY ENTRY")
5898 (setq org-cycle-subtree-status nil)
5899 (save-excursion
5900 (goto-char eos)
5901 (outline-next-heading)
5902 (if (org-invisible-p) (org-flag-heading nil))))
5903 ((or (>= eol eos)
5904 (not (string-match "\\S-" (buffer-substring eol eos))))
5905 ;; Entire subtree is hidden in one line: open it
5906 (org-show-entry)
5907 (show-children)
5908 (message "CHILDREN")
5909 (save-excursion
5910 (goto-char eos)
5911 (outline-next-heading)
5912 (if (org-invisible-p) (org-flag-heading nil)))
5913 (setq org-cycle-subtree-status 'children)
5914 (run-hook-with-args 'org-cycle-hook 'children))
5915 ((and (eq last-command this-command)
5916 (eq org-cycle-subtree-status 'children))
5917 ;; We just showed the children, now show everything.
5918 (org-show-subtree)
5919 (message "SUBTREE")
5920 (setq org-cycle-subtree-status 'subtree)
5921 (run-hook-with-args 'org-cycle-hook 'subtree))
5923 ;; Default action: hide the subtree.
5924 (hide-subtree)
5925 (message "FOLDED")
5926 (setq org-cycle-subtree-status 'folded)
5927 (run-hook-with-args 'org-cycle-hook 'folded)))))
5929 ;; TAB emulation
5930 (buffer-read-only (org-back-to-heading))
5932 ((org-try-cdlatex-tab))
5934 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5935 (or (not (bolp))
5936 (not (looking-at outline-regexp))))
5937 (call-interactively (global-key-binding "\t")))
5939 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5940 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5941 (or (and (eq org-cycle-emulate-tab 'white)
5942 (= (match-end 0) (point-at-eol)))
5943 (and (eq org-cycle-emulate-tab 'whitestart)
5944 (>= (match-end 0) pos))))
5946 (eq org-cycle-emulate-tab t))
5947 ; (if (and (looking-at "[ \n\r\t]")
5948 ; (string-match "^[ \t]*$" (buffer-substring
5949 ; (point-at-bol) (point))))
5950 ; (progn
5951 ; (beginning-of-line 1)
5952 ; (and (looking-at "[ \t]+") (replace-match ""))))
5953 (call-interactively (global-key-binding "\t")))
5955 (t (save-excursion
5956 (org-back-to-heading)
5957 (org-cycle))))))
5959 ;;;###autoload
5960 (defun org-global-cycle (&optional arg)
5961 "Cycle the global visibility. For details see `org-cycle'."
5962 (interactive "P")
5963 (let ((org-cycle-include-plain-lists
5964 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5965 (if (integerp arg)
5966 (progn
5967 (show-all)
5968 (hide-sublevels arg)
5969 (setq org-cycle-global-status 'contents))
5970 (org-cycle '(4)))))
5972 (defun org-overview ()
5973 "Switch to overview mode, shoing only top-level headlines.
5974 Really, this shows all headlines with level equal or greater than the level
5975 of the first headline in the buffer. This is important, because if the
5976 first headline is not level one, then (hide-sublevels 1) gives confusing
5977 results."
5978 (interactive)
5979 (let ((level (save-excursion
5980 (goto-char (point-min))
5981 (if (re-search-forward (concat "^" outline-regexp) nil t)
5982 (progn
5983 (goto-char (match-beginning 0))
5984 (funcall outline-level))))))
5985 (and level (hide-sublevels level))))
5987 (defun org-content (&optional arg)
5988 "Show all headlines in the buffer, like a table of contents.
5989 With numerical argument N, show content up to level N."
5990 (interactive "P")
5991 (save-excursion
5992 ;; Visit all headings and show their offspring
5993 (and (integerp arg) (org-overview))
5994 (goto-char (point-max))
5995 (catch 'exit
5996 (while (and (progn (condition-case nil
5997 (outline-previous-visible-heading 1)
5998 (error (goto-char (point-min))))
6000 (looking-at outline-regexp))
6001 (if (integerp arg)
6002 (show-children (1- arg))
6003 (show-branches))
6004 (if (bobp) (throw 'exit nil))))))
6007 (defun org-optimize-window-after-visibility-change (state)
6008 "Adjust the window after a change in outline visibility.
6009 This function is the default value of the hook `org-cycle-hook'."
6010 (when (get-buffer-window (current-buffer))
6011 (cond
6012 ; ((eq state 'overview) (org-first-headline-recenter 1))
6013 ; ((eq state 'overview) (org-beginning-of-line))
6014 ((eq state 'content) nil)
6015 ((eq state 'all) nil)
6016 ((eq state 'folded) nil)
6017 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6018 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6020 (defun org-compact-display-after-subtree-move ()
6021 (let (beg end)
6022 (save-excursion
6023 (if (org-up-heading-safe)
6024 (progn
6025 (hide-subtree)
6026 (show-entry)
6027 (show-children)
6028 (org-cycle-show-empty-lines 'children)
6029 (org-cycle-hide-drawers 'children))
6030 (org-overview)))))
6032 (defun org-cycle-show-empty-lines (state)
6033 "Show empty lines above all visible headlines.
6034 The region to be covered depends on STATE when called through
6035 `org-cycle-hook'. Lisp program can use t for STATE to get the
6036 entire buffer covered. Note that an empty line is only shown if there
6037 are at least `org-cycle-separator-lines' empty lines before the headeline."
6038 (when (> org-cycle-separator-lines 0)
6039 (save-excursion
6040 (let* ((n org-cycle-separator-lines)
6041 (re (cond
6042 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6043 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6044 (t (let ((ns (number-to-string (- n 2))))
6045 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6046 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6047 beg end)
6048 (cond
6049 ((memq state '(overview contents t))
6050 (setq beg (point-min) end (point-max)))
6051 ((memq state '(children folded))
6052 (setq beg (point) end (progn (org-end-of-subtree t t)
6053 (beginning-of-line 2)
6054 (point)))))
6055 (when beg
6056 (goto-char beg)
6057 (while (re-search-forward re end t)
6058 (if (not (get-char-property (match-end 1) 'invisible))
6059 (outline-flag-region
6060 (match-beginning 1) (match-end 1) nil)))))))
6061 ;; Never hide empty lines at the end of the file.
6062 (save-excursion
6063 (goto-char (point-max))
6064 (outline-previous-heading)
6065 (outline-end-of-heading)
6066 (if (and (looking-at "[ \t\n]+")
6067 (= (match-end 0) (point-max)))
6068 (outline-flag-region (point) (match-end 0) nil))))
6070 (defun org-subtree-end-visible-p ()
6071 "Is the end of the current subtree visible?"
6072 (pos-visible-in-window-p
6073 (save-excursion (org-end-of-subtree t) (point))))
6075 (defun org-first-headline-recenter (&optional N)
6076 "Move cursor to the first headline and recenter the headline.
6077 Optional argument N means, put the headline into the Nth line of the window."
6078 (goto-char (point-min))
6079 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6080 (beginning-of-line)
6081 (recenter (prefix-numeric-value N))))
6083 ;;; Org-goto
6085 (defvar org-goto-window-configuration nil)
6086 (defvar org-goto-marker nil)
6087 (defvar org-goto-map
6088 (let ((map (make-sparse-keymap)))
6089 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6090 (while (setq cmd (pop cmds))
6091 (substitute-key-definition cmd cmd map global-map)))
6092 (suppress-keymap map)
6093 (org-defkey map "\C-m" 'org-goto-ret)
6094 (org-defkey map [(return)] 'org-goto-ret)
6095 (org-defkey map [(left)] 'org-goto-left)
6096 (org-defkey map [(right)] 'org-goto-right)
6097 (org-defkey map [(control ?g)] 'org-goto-quit)
6098 (org-defkey map "\C-i" 'org-cycle)
6099 (org-defkey map [(tab)] 'org-cycle)
6100 (org-defkey map [(down)] 'outline-next-visible-heading)
6101 (org-defkey map [(up)] 'outline-previous-visible-heading)
6102 (if org-goto-auto-isearch
6103 (if (fboundp 'define-key-after)
6104 (define-key-after map [t] 'org-goto-local-auto-isearch)
6105 nil)
6106 (org-defkey map "q" 'org-goto-quit)
6107 (org-defkey map "n" 'outline-next-visible-heading)
6108 (org-defkey map "p" 'outline-previous-visible-heading)
6109 (org-defkey map "f" 'outline-forward-same-level)
6110 (org-defkey map "b" 'outline-backward-same-level)
6111 (org-defkey map "u" 'outline-up-heading))
6112 (org-defkey map "/" 'org-occur)
6113 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6114 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6115 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6116 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6117 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6118 map))
6120 (defconst org-goto-help
6121 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6122 RET=jump to location [Q]uit and return to previous location
6123 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6125 (defvar org-goto-start-pos) ; dynamically scoped parameter
6127 (defun org-goto (&optional alternative-interface)
6128 "Look up a different location in the current file, keeping current visibility.
6130 When you want look-up or go to a different location in a document, the
6131 fastest way is often to fold the entire buffer and then dive into the tree.
6132 This method has the disadvantage, that the previous location will be folded,
6133 which may not be what you want.
6135 This command works around this by showing a copy of the current buffer
6136 in an indirect buffer, in overview mode. You can dive into the tree in
6137 that copy, use org-occur and incremental search to find a location.
6138 When pressing RET or `Q', the command returns to the original buffer in
6139 which the visibility is still unchanged. After RET is will also jump to
6140 the location selected in the indirect buffer and expose the
6141 the headline hierarchy above."
6142 (interactive "P")
6143 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
6144 (org-refile-use-outline-path t)
6145 (interface
6146 (if (not alternative-interface)
6147 org-goto-interface
6148 (if (eq org-goto-interface 'outline)
6149 'outline-path-completion
6150 'outline)))
6151 (org-goto-start-pos (point))
6152 (selected-point
6153 (if (eq interface 'outline)
6154 (car (org-get-location (current-buffer) org-goto-help))
6155 (nth 3 (org-refile-get-location "Goto: ")))))
6156 (if selected-point
6157 (progn
6158 (org-mark-ring-push org-goto-start-pos)
6159 (goto-char selected-point)
6160 (if (or (org-invisible-p) (org-invisible-p2))
6161 (org-show-context 'org-goto)))
6162 (message "Quit"))))
6164 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6165 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6166 (defvar org-goto-local-auto-isearch-map) ; defined below
6168 (defun org-get-location (buf help)
6169 "Let the user select a location in the Org-mode buffer BUF.
6170 This function uses a recursive edit. It returns the selected position
6171 or nil."
6172 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6173 (isearch-hide-immediately nil)
6174 (isearch-search-fun-function
6175 (lambda () 'org-goto-local-search-forward-headings))
6176 (org-goto-selected-point org-goto-exit-command))
6177 (save-excursion
6178 (save-window-excursion
6179 (delete-other-windows)
6180 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6181 (switch-to-buffer
6182 (condition-case nil
6183 (make-indirect-buffer (current-buffer) "*org-goto*")
6184 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6185 (with-output-to-temp-buffer "*Help*"
6186 (princ help))
6187 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
6188 (setq buffer-read-only nil)
6189 (let ((org-startup-truncated t)
6190 (org-startup-folded nil)
6191 (org-startup-align-all-tables nil))
6192 (org-mode)
6193 (org-overview))
6194 (setq buffer-read-only t)
6195 (if (and (boundp 'org-goto-start-pos)
6196 (integer-or-marker-p org-goto-start-pos))
6197 (let ((org-show-hierarchy-above t)
6198 (org-show-siblings t)
6199 (org-show-following-heading t))
6200 (goto-char org-goto-start-pos)
6201 (and (org-invisible-p) (org-show-context)))
6202 (goto-char (point-min)))
6203 (org-beginning-of-line)
6204 (message "Select location and press RET")
6205 (use-local-map org-goto-map)
6206 (recursive-edit)
6208 (kill-buffer "*org-goto*")
6209 (cons org-goto-selected-point org-goto-exit-command)))
6211 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6212 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6213 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6214 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6216 (defun org-goto-local-search-forward-headings (string bound noerror)
6217 "Search and make sure that anu matches are in headlines."
6218 (catch 'return
6219 (while (search-forward string bound noerror)
6220 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6221 (and (member :headline context)
6222 (not (member :tags context))))
6223 (throw 'return (point))))))
6225 (defun org-goto-local-auto-isearch ()
6226 "Start isearch."
6227 (interactive)
6228 (goto-char (point-min))
6229 (let ((keys (this-command-keys)))
6230 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6231 (isearch-mode t)
6232 (isearch-process-search-char (string-to-char keys)))))
6234 (defun org-goto-ret (&optional arg)
6235 "Finish `org-goto' by going to the new location."
6236 (interactive "P")
6237 (setq org-goto-selected-point (point)
6238 org-goto-exit-command 'return)
6239 (throw 'exit nil))
6241 (defun org-goto-left ()
6242 "Finish `org-goto' by going to the new location."
6243 (interactive)
6244 (if (org-on-heading-p)
6245 (progn
6246 (beginning-of-line 1)
6247 (setq org-goto-selected-point (point)
6248 org-goto-exit-command 'left)
6249 (throw 'exit nil))
6250 (error "Not on a heading")))
6252 (defun org-goto-right ()
6253 "Finish `org-goto' by going to the new location."
6254 (interactive)
6255 (if (org-on-heading-p)
6256 (progn
6257 (setq org-goto-selected-point (point)
6258 org-goto-exit-command 'right)
6259 (throw 'exit nil))
6260 (error "Not on a heading")))
6262 (defun org-goto-quit ()
6263 "Finish `org-goto' without cursor motion."
6264 (interactive)
6265 (setq org-goto-selected-point nil)
6266 (setq org-goto-exit-command 'quit)
6267 (throw 'exit nil))
6269 ;;; Indirect buffer display of subtrees
6271 (defvar org-indirect-dedicated-frame nil
6272 "This is the frame being used for indirect tree display.")
6273 (defvar org-last-indirect-buffer nil)
6275 (defun org-tree-to-indirect-buffer (&optional arg)
6276 "Create indirect buffer and narrow it to current subtree.
6277 With numerical prefix ARG, go up to this level and then take that tree.
6278 If ARG is negative, go up that many levels.
6279 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6280 indirect buffer previously made with this command, to avoid proliferation of
6281 indirect buffers. However, when you call the command with a `C-u' prefix, or
6282 when `org-indirect-buffer-display' is `new-frame', the last buffer
6283 is kept so that you can work with several indirect buffers at the same time.
6284 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6285 requests that a new frame be made for the new buffer, so that the dedicated
6286 frame is not changed."
6287 (interactive "P")
6288 (let ((cbuf (current-buffer))
6289 (cwin (selected-window))
6290 (pos (point))
6291 beg end level heading ibuf)
6292 (save-excursion
6293 (org-back-to-heading t)
6294 (when (numberp arg)
6295 (setq level (org-outline-level))
6296 (if (< arg 0) (setq arg (+ level arg)))
6297 (while (> (setq level (org-outline-level)) arg)
6298 (outline-up-heading 1 t)))
6299 (setq beg (point)
6300 heading (org-get-heading))
6301 (org-end-of-subtree t) (setq end (point)))
6302 (if (and (buffer-live-p org-last-indirect-buffer)
6303 (not (eq org-indirect-buffer-display 'new-frame))
6304 (not arg))
6305 (kill-buffer org-last-indirect-buffer))
6306 (setq ibuf (org-get-indirect-buffer cbuf)
6307 org-last-indirect-buffer ibuf)
6308 (cond
6309 ((or (eq org-indirect-buffer-display 'new-frame)
6310 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6311 (select-frame (make-frame))
6312 (delete-other-windows)
6313 (switch-to-buffer ibuf)
6314 (org-set-frame-title heading))
6315 ((eq org-indirect-buffer-display 'dedicated-frame)
6316 (raise-frame
6317 (select-frame (or (and org-indirect-dedicated-frame
6318 (frame-live-p org-indirect-dedicated-frame)
6319 org-indirect-dedicated-frame)
6320 (setq org-indirect-dedicated-frame (make-frame)))))
6321 (delete-other-windows)
6322 (switch-to-buffer ibuf)
6323 (org-set-frame-title (concat "Indirect: " heading)))
6324 ((eq org-indirect-buffer-display 'current-window)
6325 (switch-to-buffer ibuf))
6326 ((eq org-indirect-buffer-display 'other-window)
6327 (pop-to-buffer ibuf))
6328 (t (error "Invalid value.")))
6329 (if (featurep 'xemacs)
6330 (save-excursion (org-mode) (turn-on-font-lock)))
6331 (narrow-to-region beg end)
6332 (show-all)
6333 (goto-char pos)
6334 (and (window-live-p cwin) (select-window cwin))))
6336 (defun org-get-indirect-buffer (&optional buffer)
6337 (setq buffer (or buffer (current-buffer)))
6338 (let ((n 1) (base (buffer-name buffer)) bname)
6339 (while (buffer-live-p
6340 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6341 (setq n (1+ n)))
6342 (condition-case nil
6343 (make-indirect-buffer buffer bname 'clone)
6344 (error (make-indirect-buffer buffer bname)))))
6346 (defun org-set-frame-title (title)
6347 "Set the title of the current frame to the string TITLE."
6348 ;; FIXME: how to name a single frame in XEmacs???
6349 (unless (featurep 'xemacs)
6350 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6352 ;;;; Structure editing
6354 ;;; Inserting headlines
6356 (defun org-insert-heading (&optional force-heading)
6357 "Insert a new heading or item with same depth at point.
6358 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6359 If point is at the beginning of a headline, insert a sibling before the
6360 current headline. If point is not at the beginning, do not split the line,
6361 but create the new hedline after the current line."
6362 (interactive "P")
6363 (if (= (buffer-size) 0)
6364 (insert "\n* ")
6365 (when (or force-heading (not (org-insert-item)))
6366 (let* ((head (save-excursion
6367 (condition-case nil
6368 (progn
6369 (org-back-to-heading)
6370 (match-string 0))
6371 (error "*"))))
6372 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6373 pos)
6374 (cond
6375 ((and (org-on-heading-p) (bolp)
6376 (or (bobp)
6377 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6378 ;; insert before the current line
6379 (open-line (if blank 2 1)))
6380 ((and (bolp)
6381 (or (bobp)
6382 (save-excursion
6383 (backward-char 1) (not (org-invisible-p)))))
6384 ;; insert right here
6385 nil)
6387 ; ;; in the middle of the line
6388 ; (org-show-entry)
6389 ; (if (org-get-alist-option org-M-RET-may-split-line 'headline)
6390 ; (if (and
6391 ; (org-on-heading-p)
6392 ; (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \r\n]"))
6393 ; ;; protect the tags
6394 ;; (let ((tags (match-string 2)) pos)
6395 ; (delete-region (match-beginning 1) (match-end 1))
6396 ; (setq pos (point-at-bol))
6397 ; (newline (if blank 2 1))
6398 ; (save-excursion
6399 ; (goto-char pos)
6400 ; (end-of-line 1)
6401 ; (insert " " tags)
6402 ; (org-set-tags nil 'align)))
6403 ; (newline (if blank 2 1)))
6404 ; (newline (if blank 2 1))))
6407 ;; in the middle of the line
6408 (org-show-entry)
6409 (let ((split
6410 (org-get-alist-option org-M-RET-may-split-line 'headline))
6411 tags pos)
6412 (if (org-on-heading-p)
6413 (progn
6414 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6415 (setq tags (and (match-end 2) (match-string 2)))
6416 (and (match-end 1)
6417 (delete-region (match-beginning 1) (match-end 1)))
6418 (setq pos (point-at-bol))
6419 (or split (end-of-line 1))
6420 (delete-horizontal-space)
6421 (newline (if blank 2 1))
6422 (when tags
6423 (save-excursion
6424 (goto-char pos)
6425 (end-of-line 1)
6426 (insert " " tags)
6427 (org-set-tags nil 'align))))
6428 (or split (end-of-line 1))
6429 (newline (if blank 2 1))))))
6430 (insert head) (just-one-space)
6431 (setq pos (point))
6432 (end-of-line 1)
6433 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6434 (run-hooks 'org-insert-heading-hook)))))
6436 (defun org-insert-heading-after-current ()
6437 "Insert a new heading with same level as current, after current subtree."
6438 (interactive)
6439 (org-back-to-heading)
6440 (org-insert-heading)
6441 (org-move-subtree-down)
6442 (end-of-line 1))
6444 (defun org-insert-todo-heading (arg)
6445 "Insert a new heading with the same level and TODO state as current heading.
6446 If the heading has no TODO state, or if the state is DONE, use the first
6447 state (TODO by default). Also with prefix arg, force first state."
6448 (interactive "P")
6449 (when (not (org-insert-item 'checkbox))
6450 (org-insert-heading)
6451 (save-excursion
6452 (org-back-to-heading)
6453 (outline-previous-heading)
6454 (looking-at org-todo-line-regexp))
6455 (if (or arg
6456 (not (match-beginning 2))
6457 (member (match-string 2) org-done-keywords))
6458 (insert (car org-todo-keywords-1) " ")
6459 (insert (match-string 2) " "))))
6461 (defun org-insert-subheading (arg)
6462 "Insert a new subheading and demote it.
6463 Works for outline headings and for plain lists alike."
6464 (interactive "P")
6465 (org-insert-heading arg)
6466 (cond
6467 ((org-on-heading-p) (org-do-demote))
6468 ((org-at-item-p) (org-indent-item 1))))
6470 (defun org-insert-todo-subheading (arg)
6471 "Insert a new subheading with TODO keyword or checkbox and demote it.
6472 Works for outline headings and for plain lists alike."
6473 (interactive "P")
6474 (org-insert-todo-heading arg)
6475 (cond
6476 ((org-on-heading-p) (org-do-demote))
6477 ((org-at-item-p) (org-indent-item 1))))
6479 ;;; Promotion and Demotion
6481 (defun org-promote-subtree ()
6482 "Promote the entire subtree.
6483 See also `org-promote'."
6484 (interactive)
6485 (save-excursion
6486 (org-map-tree 'org-promote))
6487 (org-fix-position-after-promote))
6489 (defun org-demote-subtree ()
6490 "Demote the entire subtree. See `org-demote'.
6491 See also `org-promote'."
6492 (interactive)
6493 (save-excursion
6494 (org-map-tree 'org-demote))
6495 (org-fix-position-after-promote))
6498 (defun org-do-promote ()
6499 "Promote the current heading higher up the tree.
6500 If the region is active in `transient-mark-mode', promote all headings
6501 in the region."
6502 (interactive)
6503 (save-excursion
6504 (if (org-region-active-p)
6505 (org-map-region 'org-promote (region-beginning) (region-end))
6506 (org-promote)))
6507 (org-fix-position-after-promote))
6509 (defun org-do-demote ()
6510 "Demote the current heading lower down the tree.
6511 If the region is active in `transient-mark-mode', demote all headings
6512 in the region."
6513 (interactive)
6514 (save-excursion
6515 (if (org-region-active-p)
6516 (org-map-region 'org-demote (region-beginning) (region-end))
6517 (org-demote)))
6518 (org-fix-position-after-promote))
6520 (defun org-fix-position-after-promote ()
6521 "Make sure that after pro/demotion cursor position is right."
6522 (let ((pos (point)))
6523 (when (save-excursion
6524 (beginning-of-line 1)
6525 (looking-at org-todo-line-regexp)
6526 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6527 (cond ((eobp) (insert " "))
6528 ((eolp) (insert " "))
6529 ((equal (char-after) ?\ ) (forward-char 1))))))
6531 (defun org-reduced-level (l)
6532 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6534 (defun org-get-valid-level (level &optional change)
6535 "Rectify a level change under the influence of `org-odd-levels-only'
6536 LEVEL is a current level, CHANGE is by how much the level should be
6537 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6538 even level numbers will become the next higher odd number."
6539 (if org-odd-levels-only
6540 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6541 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6542 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6543 (max 1 (+ level change))))
6545 (if (featurep 'xemacs)
6546 (define-obsolete-function-alias 'org-get-legal-level
6547 'org-get-valid-level)
6548 (define-obsolete-function-alias 'org-get-legal-level
6549 'org-get-valid-level "23.1"))
6551 (defun org-promote ()
6552 "Promote the current heading higher up the tree.
6553 If the region is active in `transient-mark-mode', promote all headings
6554 in the region."
6555 (org-back-to-heading t)
6556 (let* ((level (save-match-data (funcall outline-level)))
6557 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6558 (diff (abs (- level (length up-head) -1))))
6559 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6560 (replace-match up-head nil t)
6561 ;; Fixup tag positioning
6562 (and org-auto-align-tags (org-set-tags nil t))
6563 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6565 (defun org-demote ()
6566 "Demote the current heading lower down the tree.
6567 If the region is active in `transient-mark-mode', demote all headings
6568 in the region."
6569 (org-back-to-heading t)
6570 (let* ((level (save-match-data (funcall outline-level)))
6571 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6572 (diff (abs (- level (length down-head) -1))))
6573 (replace-match down-head nil t)
6574 ;; Fixup tag positioning
6575 (and org-auto-align-tags (org-set-tags nil t))
6576 (if org-adapt-indentation (org-fixup-indentation diff))))
6578 (defun org-map-tree (fun)
6579 "Call FUN for every heading underneath the current one."
6580 (org-back-to-heading)
6581 (let ((level (funcall outline-level)))
6582 (save-excursion
6583 (funcall fun)
6584 (while (and (progn
6585 (outline-next-heading)
6586 (> (funcall outline-level) level))
6587 (not (eobp)))
6588 (funcall fun)))))
6590 (defun org-map-region (fun beg end)
6591 "Call FUN for every heading between BEG and END."
6592 (let ((org-ignore-region t))
6593 (save-excursion
6594 (setq end (copy-marker end))
6595 (goto-char beg)
6596 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6597 (< (point) end))
6598 (funcall fun))
6599 (while (and (progn
6600 (outline-next-heading)
6601 (< (point) end))
6602 (not (eobp)))
6603 (funcall fun)))))
6605 (defun org-fixup-indentation (diff)
6606 "Change the indentation in the current entry by DIFF
6607 However, if any line in the current entry has no indentation, or if it
6608 would end up with no indentation after the change, nothing at all is done."
6609 (save-excursion
6610 (let ((end (save-excursion (outline-next-heading)
6611 (point-marker)))
6612 (prohibit (if (> diff 0)
6613 "^\\S-"
6614 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6615 col)
6616 (unless (save-excursion (end-of-line 1)
6617 (re-search-forward prohibit end t))
6618 (while (and (< (point) end)
6619 (re-search-forward "^[ \t]+" end t))
6620 (goto-char (match-end 0))
6621 (setq col (current-column))
6622 (if (< diff 0) (replace-match ""))
6623 (indent-to (+ diff col))))
6624 (move-marker end nil))))
6626 (defun org-convert-to-odd-levels ()
6627 "Convert an org-mode file with all levels allowed to one with odd levels.
6628 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6629 level 5 etc."
6630 (interactive)
6631 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6632 (let ((org-odd-levels-only nil) n)
6633 (save-excursion
6634 (goto-char (point-min))
6635 (while (re-search-forward "^\\*\\*+ " nil t)
6636 (setq n (- (length (match-string 0)) 2))
6637 (while (>= (setq n (1- n)) 0)
6638 (org-demote))
6639 (end-of-line 1))))))
6642 (defun org-convert-to-oddeven-levels ()
6643 "Convert an org-mode file with only odd levels to one with odd and even levels.
6644 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6645 section with an even level, conversion would destroy the structure of the file. An error
6646 is signaled in this case."
6647 (interactive)
6648 (goto-char (point-min))
6649 ;; First check if there are no even levels
6650 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6651 (org-show-context t)
6652 (error "Not all levels are odd in this file. Conversion not possible."))
6653 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6654 (let ((org-odd-levels-only nil) n)
6655 (save-excursion
6656 (goto-char (point-min))
6657 (while (re-search-forward "^\\*\\*+ " nil t)
6658 (setq n (/ (1- (length (match-string 0))) 2))
6659 (while (>= (setq n (1- n)) 0)
6660 (org-promote))
6661 (end-of-line 1))))))
6663 (defun org-tr-level (n)
6664 "Make N odd if required."
6665 (if org-odd-levels-only (1+ (/ n 2)) n))
6667 ;;; Vertical tree motion, cutting and pasting of subtrees
6669 (defun org-move-subtree-up (&optional arg)
6670 "Move the current subtree up past ARG headlines of the same level."
6671 (interactive "p")
6672 (org-move-subtree-down (- (prefix-numeric-value arg))))
6674 (defun org-move-subtree-down (&optional arg)
6675 "Move the current subtree down past ARG headlines of the same level."
6676 (interactive "p")
6677 (setq arg (prefix-numeric-value arg))
6678 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6679 'outline-get-last-sibling))
6680 (ins-point (make-marker))
6681 (cnt (abs arg))
6682 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6683 ;; Select the tree
6684 (org-back-to-heading)
6685 (setq beg0 (point))
6686 (save-excursion
6687 (setq ne-beg (org-back-over-empty-lines))
6688 (setq beg (point)))
6689 (save-match-data
6690 (save-excursion (outline-end-of-heading)
6691 (setq folded (org-invisible-p)))
6692 (outline-end-of-subtree))
6693 (outline-next-heading)
6694 (setq ne-end (org-back-over-empty-lines))
6695 (setq end (point))
6696 (goto-char beg0)
6697 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6698 ;; include less whitespace
6699 (save-excursion
6700 (goto-char beg)
6701 (forward-line (- ne-beg ne-end))
6702 (setq beg (point))))
6703 ;; Find insertion point, with error handling
6704 (while (> cnt 0)
6705 (or (and (funcall movfunc) (looking-at outline-regexp))
6706 (progn (goto-char beg0)
6707 (error "Cannot move past superior level or buffer limit")))
6708 (setq cnt (1- cnt)))
6709 (if (> arg 0)
6710 ;; Moving forward - still need to move over subtree
6711 (progn (org-end-of-subtree t t)
6712 (save-excursion
6713 (org-back-over-empty-lines)
6714 (or (bolp) (newline)))))
6715 (setq ne-ins (org-back-over-empty-lines))
6716 (move-marker ins-point (point))
6717 (setq txt (buffer-substring beg end))
6718 (delete-region beg end)
6719 (outline-flag-region (1- beg) beg nil)
6720 (outline-flag-region (1- (point)) (point) nil)
6721 (insert txt)
6722 (or (bolp) (insert "\n"))
6723 (setq ins-end (point))
6724 (goto-char ins-point)
6725 (org-skip-whitespace)
6726 (when (and (< arg 0)
6727 (org-first-sibling-p)
6728 (> ne-ins ne-beg))
6729 ;; Move whitespace back to beginning
6730 (save-excursion
6731 (goto-char ins-end)
6732 (let ((kill-whole-line t))
6733 (kill-line (- ne-ins ne-beg)) (point)))
6734 (insert (make-string (- ne-ins ne-beg) ?\n)))
6735 (move-marker ins-point nil)
6736 (org-compact-display-after-subtree-move)
6737 (unless folded
6738 (org-show-entry)
6739 (show-children)
6740 (org-cycle-hide-drawers 'children))))
6742 (defvar org-subtree-clip ""
6743 "Clipboard for cut and paste of subtrees.
6744 This is actually only a copy of the kill, because we use the normal kill
6745 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6747 (defvar org-subtree-clip-folded nil
6748 "Was the last copied subtree folded?
6749 This is used to fold the tree back after pasting.")
6751 (defun org-cut-subtree (&optional n)
6752 "Cut the current subtree into the clipboard.
6753 With prefix arg N, cut this many sequential subtrees.
6754 This is a short-hand for marking the subtree and then cutting it."
6755 (interactive "p")
6756 (org-copy-subtree n 'cut))
6758 (defun org-copy-subtree (&optional n cut)
6759 "Cut the current subtree into the clipboard.
6760 With prefix arg N, cut this many sequential subtrees.
6761 This is a short-hand for marking the subtree and then copying it.
6762 If CUT is non-nil, actually cut the subtree."
6763 (interactive "p")
6764 (let (beg end folded (beg0 (point)))
6765 (if (interactive-p)
6766 (org-back-to-heading nil) ; take what looks like a subtree
6767 (org-back-to-heading t)) ; take what is really there
6768 (org-back-over-empty-lines)
6769 (setq beg (point))
6770 (skip-chars-forward " \t\r\n")
6771 (save-match-data
6772 (save-excursion (outline-end-of-heading)
6773 (setq folded (org-invisible-p)))
6774 (condition-case nil
6775 (outline-forward-same-level (1- n))
6776 (error nil))
6777 (org-end-of-subtree t t))
6778 (org-back-over-empty-lines)
6779 (setq end (point))
6780 (goto-char beg0)
6781 (when (> end beg)
6782 (setq org-subtree-clip-folded folded)
6783 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6784 (setq org-subtree-clip (current-kill 0))
6785 (message "%s: Subtree(s) with %d characters"
6786 (if cut "Cut" "Copied")
6787 (length org-subtree-clip)))))
6789 (defun org-paste-subtree (&optional level tree)
6790 "Paste the clipboard as a subtree, with modification of headline level.
6791 The entire subtree is promoted or demoted in order to match a new headline
6792 level. By default, the new level is derived from the visible headings
6793 before and after the insertion point, and taken to be the inferior headline
6794 level of the two. So if the previous visible heading is level 3 and the
6795 next is level 4 (or vice versa), level 4 will be used for insertion.
6796 This makes sure that the subtree remains an independent subtree and does
6797 not swallow low level entries.
6799 You can also force a different level, either by using a numeric prefix
6800 argument, or by inserting the heading marker by hand. For example, if the
6801 cursor is after \"*****\", then the tree will be shifted to level 5.
6803 If you want to insert the tree as is, just use \\[yank].
6805 If optional TREE is given, use this text instead of the kill ring."
6806 (interactive "P")
6807 (unless (org-kill-is-subtree-p tree)
6808 (error "%s"
6809 (substitute-command-keys
6810 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6811 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6812 (^re (concat "^\\(" outline-regexp "\\)"))
6813 (re (concat "\\(" outline-regexp "\\)"))
6814 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6816 (old-level (if (string-match ^re txt)
6817 (- (match-end 0) (match-beginning 0) 1)
6818 -1))
6819 (force-level (cond (level (prefix-numeric-value level))
6820 ((string-match
6821 ^re_ (buffer-substring (point-at-bol) (point)))
6822 (- (match-end 1) (match-beginning 1)))
6823 (t nil)))
6824 (previous-level (save-excursion
6825 (condition-case nil
6826 (progn
6827 (outline-previous-visible-heading 1)
6828 (if (looking-at re)
6829 (- (match-end 0) (match-beginning 0) 1)
6831 (error 1))))
6832 (next-level (save-excursion
6833 (condition-case nil
6834 (progn
6835 (or (looking-at outline-regexp)
6836 (outline-next-visible-heading 1))
6837 (if (looking-at re)
6838 (- (match-end 0) (match-beginning 0) 1)
6840 (error 1))))
6841 (new-level (or force-level (max previous-level next-level)))
6842 (shift (if (or (= old-level -1)
6843 (= new-level -1)
6844 (= old-level new-level))
6846 (- new-level old-level)))
6847 (delta (if (> shift 0) -1 1))
6848 (func (if (> shift 0) 'org-demote 'org-promote))
6849 (org-odd-levels-only nil)
6850 beg end)
6851 ;; Remove the forced level indicator
6852 (if force-level
6853 (delete-region (point-at-bol) (point)))
6854 ;; Paste
6855 (beginning-of-line 1)
6856 (org-back-over-empty-lines) ;; FIXME: correct fix????
6857 (setq beg (point))
6858 (insert-before-markers txt) ;; FIXME: correct fix????
6859 (unless (string-match "\n\\'" txt) (insert "\n"))
6860 (setq end (point))
6861 (goto-char beg)
6862 (skip-chars-forward " \t\n\r")
6863 (setq beg (point))
6864 ;; Shift if necessary
6865 (unless (= shift 0)
6866 (save-restriction
6867 (narrow-to-region beg end)
6868 (while (not (= shift 0))
6869 (org-map-region func (point-min) (point-max))
6870 (setq shift (+ delta shift)))
6871 (goto-char (point-min))))
6872 (when (interactive-p)
6873 (message "Clipboard pasted as level %d subtree" new-level))
6874 (if (and kill-ring
6875 (eq org-subtree-clip (current-kill 0))
6876 org-subtree-clip-folded)
6877 ;; The tree was folded before it was killed/copied
6878 (hide-subtree))))
6880 (defun org-kill-is-subtree-p (&optional txt)
6881 "Check if the current kill is an outline subtree, or a set of trees.
6882 Returns nil if kill does not start with a headline, or if the first
6883 headline level is not the largest headline level in the tree.
6884 So this will actually accept several entries of equal levels as well,
6885 which is OK for `org-paste-subtree'.
6886 If optional TXT is given, check this string instead of the current kill."
6887 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6888 (start-level (and kill
6889 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6890 org-outline-regexp "\\)")
6891 kill)
6892 (- (match-end 2) (match-beginning 2) 1)))
6893 (re (concat "^" org-outline-regexp))
6894 (start (1+ (match-beginning 2))))
6895 (if (not start-level)
6896 (progn
6897 nil) ;; does not even start with a heading
6898 (catch 'exit
6899 (while (setq start (string-match re kill (1+ start)))
6900 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6901 (throw 'exit nil)))
6902 t))))
6904 (defun org-narrow-to-subtree ()
6905 "Narrow buffer to the current subtree."
6906 (interactive)
6907 (save-excursion
6908 (save-match-data
6909 (narrow-to-region
6910 (progn (org-back-to-heading) (point))
6911 (progn (org-end-of-subtree t t) (point))))))
6914 ;;; Outline Sorting
6916 (defun org-sort (with-case)
6917 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6918 Optional argument WITH-CASE means sort case-sensitively."
6919 (interactive "P")
6920 (if (org-at-table-p)
6921 (org-call-with-arg 'org-table-sort-lines with-case)
6922 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6924 (defvar org-priority-regexp) ; defined later in the file
6926 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6927 "Sort entries on a certain level of an outline tree.
6928 If there is an active region, the entries in the region are sorted.
6929 Else, if the cursor is before the first entry, sort the top-level items.
6930 Else, the children of the entry at point are sorted.
6932 Sorting can be alphabetically, numerically, and by date/time as given by
6933 the first time stamp in the entry. The command prompts for the sorting
6934 type unless it has been given to the function through the SORTING-TYPE
6935 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6936 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6937 called with point at the beginning of the record. It must return either
6938 a string or a number that should serve as the sorting key for that record.
6940 Comparing entries ignores case by default. However, with an optional argument
6941 WITH-CASE, the sorting considers case as well."
6942 (interactive "P")
6943 (let ((case-func (if with-case 'identity 'downcase))
6944 start beg end stars re re2
6945 txt what tmp plain-list-p)
6946 ;; Find beginning and end of region to sort
6947 (cond
6948 ((org-region-active-p)
6949 ;; we will sort the region
6950 (setq end (region-end)
6951 what "region")
6952 (goto-char (region-beginning))
6953 (if (not (org-on-heading-p)) (outline-next-heading))
6954 (setq start (point)))
6955 ((org-at-item-p)
6956 ;; we will sort this plain list
6957 (org-beginning-of-item-list) (setq start (point))
6958 (org-end-of-item-list) (setq end (point))
6959 (goto-char start)
6960 (setq plain-list-p t
6961 what "plain list"))
6962 ((or (org-on-heading-p)
6963 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6964 ;; we will sort the children of the current headline
6965 (org-back-to-heading)
6966 (setq start (point)
6967 end (progn (org-end-of-subtree t t)
6968 (org-back-over-empty-lines)
6969 (point))
6970 what "children")
6971 (goto-char start)
6972 (show-subtree)
6973 (outline-next-heading))
6975 ;; we will sort the top-level entries in this file
6976 (goto-char (point-min))
6977 (or (org-on-heading-p) (outline-next-heading))
6978 (setq start (point) end (point-max) what "top-level")
6979 (goto-char start)
6980 (show-all)))
6982 (setq beg (point))
6983 (if (>= beg end) (error "Nothing to sort"))
6985 (unless plain-list-p
6986 (looking-at "\\(\\*+\\)")
6987 (setq stars (match-string 1)
6988 re (concat "^" (regexp-quote stars) " +")
6989 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6990 txt (buffer-substring beg end))
6991 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6992 (if (and (not (equal stars "*")) (string-match re2 txt))
6993 (error "Region to sort contains a level above the first entry")))
6995 (unless sorting-type
6996 (message
6997 (if plain-list-p
6998 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6999 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
7000 what)
7001 (setq sorting-type (read-char-exclusive))
7003 (and (= (downcase sorting-type) ?f)
7004 (setq getkey-func
7005 (completing-read "Sort using function: "
7006 obarray 'fboundp t nil nil))
7007 (setq getkey-func (intern getkey-func)))
7009 (and (= (downcase sorting-type) ?r)
7010 (setq property
7011 (completing-read "Property: "
7012 (mapcar 'list (org-buffer-property-keys t))
7013 nil t))))
7015 (message "Sorting entries...")
7017 (save-restriction
7018 (narrow-to-region start end)
7020 (let ((dcst (downcase sorting-type))
7021 (now (current-time)))
7022 (sort-subr
7023 (/= dcst sorting-type)
7024 ;; This function moves to the beginning character of the "record" to
7025 ;; be sorted.
7026 (if plain-list-p
7027 (lambda nil
7028 (if (org-at-item-p) t (goto-char (point-max))))
7029 (lambda nil
7030 (if (re-search-forward re nil t)
7031 (goto-char (match-beginning 0))
7032 (goto-char (point-max)))))
7033 ;; This function moves to the last character of the "record" being
7034 ;; sorted.
7035 (if plain-list-p
7036 'org-end-of-item
7037 (lambda nil
7038 (save-match-data
7039 (condition-case nil
7040 (outline-forward-same-level 1)
7041 (error
7042 (goto-char (point-max)))))))
7044 ;; This function returns the value that gets sorted against.
7045 (if plain-list-p
7046 (lambda nil
7047 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7048 (cond
7049 ((= dcst ?n)
7050 (string-to-number (buffer-substring (match-end 0)
7051 (point-at-eol))))
7052 ((= dcst ?a)
7053 (buffer-substring (match-end 0) (point-at-eol)))
7054 ((= dcst ?t)
7055 (if (re-search-forward org-ts-regexp
7056 (point-at-eol) t)
7057 (org-time-string-to-time (match-string 0))
7058 now))
7059 ((= dcst ?f)
7060 (if getkey-func
7061 (progn
7062 (setq tmp (funcall getkey-func))
7063 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7064 tmp)
7065 (error "Invalid key function `%s'" getkey-func)))
7066 (t (error "Invalid sorting type `%c'" sorting-type)))))
7067 (lambda nil
7068 (cond
7069 ((= dcst ?n)
7070 (if (looking-at outline-regexp)
7071 (string-to-number (buffer-substring (match-end 0)
7072 (point-at-eol)))
7073 nil))
7074 ((= dcst ?a)
7075 (funcall case-func (buffer-substring (point-at-bol)
7076 (point-at-eol))))
7077 ((= dcst ?t)
7078 (if (re-search-forward org-ts-regexp
7079 (save-excursion
7080 (forward-line 2)
7081 (point)) t)
7082 (org-time-string-to-time (match-string 0))
7083 now))
7084 ((= dcst ?p)
7085 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7086 (string-to-char (match-string 2))
7087 org-default-priority))
7088 ((= dcst ?r)
7089 (or (org-entry-get nil property) ""))
7090 ((= dcst ?f)
7091 (if getkey-func
7092 (progn
7093 (setq tmp (funcall getkey-func))
7094 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7095 tmp)
7096 (error "Invalid key function `%s'" getkey-func)))
7097 (t (error "Invalid sorting type `%c'" sorting-type)))))
7099 (cond
7100 ((= dcst ?a) 'string<)
7101 ((= dcst ?t) 'time-less-p)
7102 (t nil)))))
7103 (message "Sorting entries...done")))
7105 (defun org-do-sort (table what &optional with-case sorting-type)
7106 "Sort TABLE of WHAT according to SORTING-TYPE.
7107 The user will be prompted for the SORTING-TYPE if the call to this
7108 function does not specify it. WHAT is only for the prompt, to indicate
7109 what is being sorted. The sorting key will be extracted from
7110 the car of the elements of the table.
7111 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7112 (unless sorting-type
7113 (message
7114 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7115 what)
7116 (setq sorting-type (read-char-exclusive)))
7117 (let ((dcst (downcase sorting-type))
7118 extractfun comparefun)
7119 ;; Define the appropriate functions
7120 (cond
7121 ((= dcst ?n)
7122 (setq extractfun 'string-to-number
7123 comparefun (if (= dcst sorting-type) '< '>)))
7124 ((= dcst ?a)
7125 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7126 (lambda(x) (downcase (org-sort-remove-invisible x))))
7127 comparefun (if (= dcst sorting-type)
7128 'string<
7129 (lambda (a b) (and (not (string< a b))
7130 (not (string= a b)))))))
7131 ((= dcst ?t)
7132 (setq extractfun
7133 (lambda (x)
7134 (if (string-match org-ts-regexp x)
7135 (time-to-seconds
7136 (org-time-string-to-time (match-string 0 x)))
7138 comparefun (if (= dcst sorting-type) '< '>)))
7139 (t (error "Invalid sorting type `%c'" sorting-type)))
7141 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7142 table)
7143 (lambda (a b) (funcall comparefun (car a) (car b))))))
7145 ;;;; Plain list items, including checkboxes
7147 ;;; Plain list items
7149 (defun org-at-item-p ()
7150 "Is point in a line starting a hand-formatted item?"
7151 (let ((llt org-plain-list-ordered-item-terminator))
7152 (save-excursion
7153 (goto-char (point-at-bol))
7154 (looking-at
7155 (cond
7156 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7157 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7158 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7159 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
7161 (defun org-in-item-p ()
7162 "It the cursor inside a plain list item.
7163 Does not have to be the first line."
7164 (save-excursion
7165 (condition-case nil
7166 (progn
7167 (org-beginning-of-item)
7168 (org-at-item-p)
7170 (error nil))))
7172 (defun org-insert-item (&optional checkbox)
7173 "Insert a new item at the current level.
7174 Return t when things worked, nil when we are not in an item."
7175 (when (save-excursion
7176 (condition-case nil
7177 (progn
7178 (org-beginning-of-item)
7179 (org-at-item-p)
7180 (if (org-invisible-p) (error "Invisible item"))
7182 (error nil)))
7183 (let* ((bul (match-string 0))
7184 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
7185 (match-end 0)))
7186 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
7187 pos)
7188 (cond
7189 ((and (org-at-item-p) (<= (point) eow))
7190 ;; before the bullet
7191 (beginning-of-line 1)
7192 (open-line (if blank 2 1)))
7193 ((<= (point) eow)
7194 (beginning-of-line 1))
7196 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
7197 (end-of-line 1)
7198 (delete-horizontal-space))
7199 (newline (if blank 2 1))))
7200 (insert bul (if checkbox "[ ]" ""))
7201 (just-one-space)
7202 (setq pos (point))
7203 (end-of-line 1)
7204 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
7205 (org-maybe-renumber-ordered-list)
7206 (and checkbox (org-update-checkbox-count-maybe))
7209 ;;; Checkboxes
7211 (defun org-at-item-checkbox-p ()
7212 "Is point at a line starting a plain-list item with a checklet?"
7213 (and (org-at-item-p)
7214 (save-excursion
7215 (goto-char (match-end 0))
7216 (skip-chars-forward " \t")
7217 (looking-at "\\[[- X]\\]"))))
7219 (defun org-toggle-checkbox (&optional arg)
7220 "Toggle the checkbox in the current line."
7221 (interactive "P")
7222 (catch 'exit
7223 (let (beg end status (firstnew 'unknown))
7224 (cond
7225 ((org-region-active-p)
7226 (setq beg (region-beginning) end (region-end)))
7227 ((org-on-heading-p)
7228 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
7229 ((org-at-item-checkbox-p)
7230 (let ((pos (point)))
7231 (replace-match
7232 (cond (arg "[-]")
7233 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
7234 (t "[ ]"))
7235 t t)
7236 (goto-char pos))
7237 (throw 'exit t))
7238 (t (error "Not at a checkbox or heading, and no active region")))
7239 (save-excursion
7240 (goto-char beg)
7241 (while (< (point) end)
7242 (when (org-at-item-checkbox-p)
7243 (setq status (equal (match-string 0) "[X]"))
7244 (when (eq firstnew 'unknown)
7245 (setq firstnew (not status)))
7246 (replace-match
7247 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
7248 (beginning-of-line 2)))))
7249 (org-update-checkbox-count-maybe))
7251 (defun org-update-checkbox-count-maybe ()
7252 "Update checkbox statistics unless turned off by user."
7253 (when org-provide-checkbox-statistics
7254 (org-update-checkbox-count)))
7256 (defun org-update-checkbox-count (&optional all)
7257 "Update the checkbox statistics in the current section.
7258 This will find all statistic cookies like [57%] and [6/12] and update them
7259 with the current numbers. With optional prefix argument ALL, do this for
7260 the whole buffer."
7261 (interactive "P")
7262 (save-excursion
7263 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7264 (beg (condition-case nil
7265 (progn (outline-back-to-heading) (point))
7266 (error (point-min))))
7267 (end (move-marker (make-marker)
7268 (progn (outline-next-heading) (point))))
7269 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7270 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7271 (re-find (concat re "\\|" re-box))
7272 beg-cookie end-cookie is-percent c-on c-off lim
7273 eline curr-ind next-ind continue-from startsearch
7274 (cstat 0)
7276 (when all
7277 (goto-char (point-min))
7278 (outline-next-heading)
7279 (setq beg (point) end (point-max)))
7280 (goto-char end)
7281 ;; find each statistic cookie
7282 (while (re-search-backward re-find beg t)
7283 (setq beg-cookie (match-beginning 1)
7284 end-cookie (match-end 1)
7285 cstat (+ cstat (if end-cookie 1 0))
7286 startsearch (point-at-eol)
7287 continue-from (point-at-bol)
7288 is-percent (match-beginning 2)
7289 lim (cond
7290 ((org-on-heading-p) (outline-next-heading) (point))
7291 ((org-at-item-p) (org-end-of-item) (point))
7292 (t nil))
7293 c-on 0
7294 c-off 0)
7295 (when lim
7296 ;; find first checkbox for this cookie and gather
7297 ;; statistics from all that are at this indentation level
7298 (goto-char startsearch)
7299 (if (re-search-forward re-box lim t)
7300 (progn
7301 (org-beginning-of-item)
7302 (setq curr-ind (org-get-indentation))
7303 (setq next-ind curr-ind)
7304 (while (= curr-ind next-ind)
7305 (save-excursion (end-of-line) (setq eline (point)))
7306 (if (re-search-forward re-box eline t)
7307 (if (member (match-string 2) '("[ ]" "[-]"))
7308 (setq c-off (1+ c-off))
7309 (setq c-on (1+ c-on))
7312 (org-end-of-item)
7313 (setq next-ind (org-get-indentation))
7315 (goto-char continue-from)
7316 ;; update cookie
7317 (when end-cookie
7318 (delete-region beg-cookie end-cookie)
7319 (goto-char beg-cookie)
7320 (insert
7321 (if is-percent
7322 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7323 (format "[%d/%d]" c-on (+ c-on c-off)))))
7324 ;; update items checkbox if it has one
7325 (when (org-at-item-p)
7326 (org-beginning-of-item)
7327 (when (and (> (+ c-on c-off) 0)
7328 (re-search-forward re-box (point-at-eol) t))
7329 (setq beg-cookie (match-beginning 2)
7330 end-cookie (match-end 2))
7331 (delete-region beg-cookie end-cookie)
7332 (goto-char beg-cookie)
7333 (cond ((= c-off 0) (insert "[X]"))
7334 ((= c-on 0) (insert "[ ]"))
7335 (t (insert "[-]")))
7337 (goto-char continue-from))
7338 (when (interactive-p)
7339 (message "Checkbox satistics updated %s (%d places)"
7340 (if all "in entire file" "in current outline entry") cstat)))))
7342 (defun org-get-checkbox-statistics-face ()
7343 "Select the face for checkbox statistics.
7344 The face will be `org-done' when all relevant boxes are checked. Otherwise
7345 it will be `org-todo'."
7346 (if (match-end 1)
7347 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7348 (if (and (> (match-end 2) (match-beginning 2))
7349 (equal (match-string 2) (match-string 3)))
7350 'org-done
7351 'org-todo)))
7353 (defun org-get-indentation (&optional line)
7354 "Get the indentation of the current line, interpreting tabs.
7355 When LINE is given, assume it represents a line and compute its indentation."
7356 (if line
7357 (if (string-match "^ *" (org-remove-tabs line))
7358 (match-end 0))
7359 (save-excursion
7360 (beginning-of-line 1)
7361 (skip-chars-forward " \t")
7362 (current-column))))
7364 (defun org-remove-tabs (s &optional width)
7365 "Replace tabulators in S with spaces.
7366 Assumes that s is a single line, starting in column 0."
7367 (setq width (or width tab-width))
7368 (while (string-match "\t" s)
7369 (setq s (replace-match
7370 (make-string
7371 (- (* width (/ (+ (match-beginning 0) width) width))
7372 (match-beginning 0)) ?\ )
7373 t t s)))
7376 (defun org-fix-indentation (line ind)
7377 "Fix indentation in LINE.
7378 IND is a cons cell with target and minimum indentation.
7379 If the current indenation in LINE is smaller than the minimum,
7380 leave it alone. If it is larger than ind, set it to the target."
7381 (let* ((l (org-remove-tabs line))
7382 (i (org-get-indentation l))
7383 (i1 (car ind)) (i2 (cdr ind)))
7384 (if (>= i i2) (setq l (substring line i2)))
7385 (if (> i1 0)
7386 (concat (make-string i1 ?\ ) l)
7387 l)))
7389 (defcustom org-empty-line-terminates-plain-lists nil
7390 "Non-nil means, an empty line ends all plain list levels.
7391 When nil, empty lines are part of the preceeding item."
7392 :group 'org-plain-lists
7393 :type 'boolean)
7395 (defun org-beginning-of-item ()
7396 "Go to the beginning of the current hand-formatted item.
7397 If the cursor is not in an item, throw an error."
7398 (interactive)
7399 (let ((pos (point))
7400 (limit (save-excursion
7401 (condition-case nil
7402 (progn
7403 (org-back-to-heading)
7404 (beginning-of-line 2) (point))
7405 (error (point-min)))))
7406 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7407 ind ind1)
7408 (if (org-at-item-p)
7409 (beginning-of-line 1)
7410 (beginning-of-line 1)
7411 (skip-chars-forward " \t")
7412 (setq ind (current-column))
7413 (if (catch 'exit
7414 (while t
7415 (beginning-of-line 0)
7416 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7418 (if (looking-at "[ \t]*$")
7419 (setq ind1 ind-empty)
7420 (skip-chars-forward " \t")
7421 (setq ind1 (current-column)))
7422 (if (< ind1 ind)
7423 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7425 (goto-char pos)
7426 (error "Not in an item")))))
7428 (defun org-end-of-item ()
7429 "Go to the end of the current hand-formatted item.
7430 If the cursor is not in an item, throw an error."
7431 (interactive)
7432 (let* ((pos (point))
7433 ind1
7434 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7435 (limit (save-excursion (outline-next-heading) (point)))
7436 (ind (save-excursion
7437 (org-beginning-of-item)
7438 (skip-chars-forward " \t")
7439 (current-column)))
7440 (end (catch 'exit
7441 (while t
7442 (beginning-of-line 2)
7443 (if (eobp) (throw 'exit (point)))
7444 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7445 (if (looking-at "[ \t]*$")
7446 (setq ind1 ind-empty)
7447 (skip-chars-forward " \t")
7448 (setq ind1 (current-column)))
7449 (if (<= ind1 ind)
7450 (throw 'exit (point-at-bol)))))))
7451 (if end
7452 (goto-char end)
7453 (goto-char pos)
7454 (error "Not in an item"))))
7456 (defun org-next-item ()
7457 "Move to the beginning of the next item in the current plain list.
7458 Error if not at a plain list, or if this is the last item in the list."
7459 (interactive)
7460 (let (ind ind1 (pos (point)))
7461 (org-beginning-of-item)
7462 (setq ind (org-get-indentation))
7463 (org-end-of-item)
7464 (setq ind1 (org-get-indentation))
7465 (unless (and (org-at-item-p) (= ind ind1))
7466 (goto-char pos)
7467 (error "On last item"))))
7469 (defun org-previous-item ()
7470 "Move to the beginning of the previous item in the current plain list.
7471 Error if not at a plain list, or if this is the first item in the list."
7472 (interactive)
7473 (let (beg ind ind1 (pos (point)))
7474 (org-beginning-of-item)
7475 (setq beg (point))
7476 (setq ind (org-get-indentation))
7477 (goto-char beg)
7478 (catch 'exit
7479 (while t
7480 (beginning-of-line 0)
7481 (if (looking-at "[ \t]*$")
7483 (if (<= (setq ind1 (org-get-indentation)) ind)
7484 (throw 'exit t)))))
7485 (condition-case nil
7486 (if (or (not (org-at-item-p))
7487 (< ind1 (1- ind)))
7488 (error "")
7489 (org-beginning-of-item))
7490 (error (goto-char pos)
7491 (error "On first item")))))
7493 (defun org-first-list-item-p ()
7494 "Is this heading the item in a plain list?"
7495 (unless (org-at-item-p)
7496 (error "Not at a plain list item"))
7497 (org-beginning-of-item)
7498 (= (point) (save-excursion (org-beginning-of-item-list))))
7500 (defun org-move-item-down ()
7501 "Move the plain list item at point down, i.e. swap with following item.
7502 Subitems (items with larger indentation) are considered part of the item,
7503 so this really moves item trees."
7504 (interactive)
7505 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7506 (org-beginning-of-item)
7507 (setq beg0 (point))
7508 (save-excursion
7509 (setq ne-beg (org-back-over-empty-lines))
7510 (setq beg (point)))
7511 (goto-char beg0)
7512 (setq ind (org-get-indentation))
7513 (org-end-of-item)
7514 (setq end0 (point))
7515 (setq ind1 (org-get-indentation))
7516 (setq ne-end (org-back-over-empty-lines))
7517 (setq end (point))
7518 (goto-char beg0)
7519 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7520 ;; include less whitespace
7521 (save-excursion
7522 (goto-char beg)
7523 (forward-line (- ne-beg ne-end))
7524 (setq beg (point))))
7525 (goto-char end0)
7526 (if (and (org-at-item-p) (= ind ind1))
7527 (progn
7528 (org-end-of-item)
7529 (org-back-over-empty-lines)
7530 (setq txt (buffer-substring beg end))
7531 (save-excursion
7532 (delete-region beg end))
7533 (setq pos (point))
7534 (insert txt)
7535 (goto-char pos) (org-skip-whitespace)
7536 (org-maybe-renumber-ordered-list))
7537 (goto-char pos)
7538 (error "Cannot move this item further down"))))
7540 (defun org-move-item-up (arg)
7541 "Move the plain list item at point up, i.e. swap with previous item.
7542 Subitems (items with larger indentation) are considered part of the item,
7543 so this really moves item trees."
7544 (interactive "p")
7545 (let (beg beg0 end ind ind1 (pos (point)) txt
7546 ne-beg ne-ins ins-end)
7547 (org-beginning-of-item)
7548 (setq beg0 (point))
7549 (setq ind (org-get-indentation))
7550 (save-excursion
7551 (setq ne-beg (org-back-over-empty-lines))
7552 (setq beg (point)))
7553 (goto-char beg0)
7554 (org-end-of-item)
7555 (setq end (point))
7556 (goto-char beg0)
7557 (catch 'exit
7558 (while t
7559 (beginning-of-line 0)
7560 (if (looking-at "[ \t]*$")
7561 (if org-empty-line-terminates-plain-lists
7562 (progn
7563 (goto-char pos)
7564 (error "Cannot move this item further up"))
7565 nil)
7566 (if (<= (setq ind1 (org-get-indentation)) ind)
7567 (throw 'exit t)))))
7568 (condition-case nil
7569 (org-beginning-of-item)
7570 (error (goto-char beg)
7571 (error "Cannot move this item further up")))
7572 (setq ind1 (org-get-indentation))
7573 (if (and (org-at-item-p) (= ind ind1))
7574 (progn
7575 (setq ne-ins (org-back-over-empty-lines))
7576 (setq txt (buffer-substring beg end))
7577 (save-excursion
7578 (delete-region beg end))
7579 (setq pos (point))
7580 (insert txt)
7581 (setq ins-end (point))
7582 (goto-char pos) (org-skip-whitespace)
7584 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7585 ;; Move whitespace back to beginning
7586 (save-excursion
7587 (goto-char ins-end)
7588 (let ((kill-whole-line t))
7589 (kill-line (- ne-ins ne-beg)) (point)))
7590 (insert (make-string (- ne-ins ne-beg) ?\n)))
7592 (org-maybe-renumber-ordered-list))
7593 (goto-char pos)
7594 (error "Cannot move this item further up"))))
7596 (defun org-maybe-renumber-ordered-list ()
7597 "Renumber the ordered list at point if setup allows it.
7598 This tests the user option `org-auto-renumber-ordered-lists' before
7599 doing the renumbering."
7600 (interactive)
7601 (when (and org-auto-renumber-ordered-lists
7602 (org-at-item-p))
7603 (if (match-beginning 3)
7604 (org-renumber-ordered-list 1)
7605 (org-fix-bullet-type))))
7607 (defun org-maybe-renumber-ordered-list-safe ()
7608 (condition-case nil
7609 (save-excursion
7610 (org-maybe-renumber-ordered-list))
7611 (error nil)))
7613 (defun org-cycle-list-bullet (&optional which)
7614 "Cycle through the different itemize/enumerate bullets.
7615 This cycle the entire list level through the sequence:
7617 `-' -> `+' -> `*' -> `1.' -> `1)'
7619 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7620 0 meand `-', 1 means `+' etc."
7621 (interactive "P")
7622 (org-preserve-lc
7623 (org-beginning-of-item-list)
7624 (org-at-item-p)
7625 (beginning-of-line 1)
7626 (let ((current (match-string 0))
7627 (prevp (eq which 'previous))
7628 new)
7629 (setq new (cond
7630 ((and (numberp which)
7631 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7632 ((string-match "-" current) (if prevp "1)" "+"))
7633 ((string-match "\\+" current)
7634 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7635 ((string-match "\\*" current) (if prevp "+" "1."))
7636 ((string-match "\\." current) (if prevp "*" "1)"))
7637 ((string-match ")" current) (if prevp "1." "-"))
7638 (t (error "This should not happen"))))
7639 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7640 (org-fix-bullet-type)
7641 (org-maybe-renumber-ordered-list))))
7643 (defun org-get-string-indentation (s)
7644 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7645 (let ((n -1) (i 0) (w tab-width) c)
7646 (catch 'exit
7647 (while (< (setq n (1+ n)) (length s))
7648 (setq c (aref s n))
7649 (cond ((= c ?\ ) (setq i (1+ i)))
7650 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7651 (t (throw 'exit t)))))
7654 (defun org-renumber-ordered-list (arg)
7655 "Renumber an ordered plain list.
7656 Cursor needs to be in the first line of an item, the line that starts
7657 with something like \"1.\" or \"2)\"."
7658 (interactive "p")
7659 (unless (and (org-at-item-p)
7660 (match-beginning 3))
7661 (error "This is not an ordered list"))
7662 (let ((line (org-current-line))
7663 (col (current-column))
7664 (ind (org-get-string-indentation
7665 (buffer-substring (point-at-bol) (match-beginning 3))))
7666 ;; (term (substring (match-string 3) -1))
7667 ind1 (n (1- arg))
7668 fmt)
7669 ;; find where this list begins
7670 (org-beginning-of-item-list)
7671 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7672 (setq fmt (concat "%d" (match-string 1)))
7673 (beginning-of-line 0)
7674 ;; walk forward and replace these numbers
7675 (catch 'exit
7676 (while t
7677 (catch 'next
7678 (beginning-of-line 2)
7679 (if (eobp) (throw 'exit nil))
7680 (if (looking-at "[ \t]*$") (throw 'next nil))
7681 (skip-chars-forward " \t") (setq ind1 (current-column))
7682 (if (> ind1 ind) (throw 'next t))
7683 (if (< ind1 ind) (throw 'exit t))
7684 (if (not (org-at-item-p)) (throw 'exit nil))
7685 (delete-region (match-beginning 2) (match-end 2))
7686 (goto-char (match-beginning 2))
7687 (insert (format fmt (setq n (1+ n)))))))
7688 (goto-line line)
7689 (move-to-column col)))
7691 (defun org-fix-bullet-type ()
7692 "Make sure all items in this list have the same bullet as the firsst item."
7693 (interactive)
7694 (unless (org-at-item-p) (error "This is not a list"))
7695 (let ((line (org-current-line))
7696 (col (current-column))
7697 (ind (current-indentation))
7698 ind1 bullet)
7699 ;; find where this list begins
7700 (org-beginning-of-item-list)
7701 (beginning-of-line 1)
7702 ;; find out what the bullet type is
7703 (looking-at "[ \t]*\\(\\S-+\\)")
7704 (setq bullet (match-string 1))
7705 ;; walk forward and replace these numbers
7706 (beginning-of-line 0)
7707 (catch 'exit
7708 (while t
7709 (catch 'next
7710 (beginning-of-line 2)
7711 (if (eobp) (throw 'exit nil))
7712 (if (looking-at "[ \t]*$") (throw 'next nil))
7713 (skip-chars-forward " \t") (setq ind1 (current-column))
7714 (if (> ind1 ind) (throw 'next t))
7715 (if (< ind1 ind) (throw 'exit t))
7716 (if (not (org-at-item-p)) (throw 'exit nil))
7717 (skip-chars-forward " \t")
7718 (looking-at "\\S-+")
7719 (replace-match bullet))))
7720 (goto-line line)
7721 (move-to-column col)
7722 (if (string-match "[0-9]" bullet)
7723 (org-renumber-ordered-list 1))))
7725 (defun org-beginning-of-item-list ()
7726 "Go to the beginning of the current item list.
7727 I.e. to the first item in this list."
7728 (interactive)
7729 (org-beginning-of-item)
7730 (let ((pos (point-at-bol))
7731 (ind (org-get-indentation))
7732 ind1)
7733 ;; find where this list begins
7734 (catch 'exit
7735 (while t
7736 (catch 'next
7737 (beginning-of-line 0)
7738 (if (looking-at "[ \t]*$")
7739 (throw (if (bobp) 'exit 'next) t))
7740 (skip-chars-forward " \t") (setq ind1 (current-column))
7741 (if (or (< ind1 ind)
7742 (and (= ind1 ind)
7743 (not (org-at-item-p)))
7744 (bobp))
7745 (throw 'exit t)
7746 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7747 (goto-char pos)))
7750 (defun org-end-of-item-list ()
7751 "Go to the end of the current item list.
7752 I.e. to the text after the last item."
7753 (interactive)
7754 (org-beginning-of-item)
7755 (let ((pos (point-at-bol))
7756 (ind (org-get-indentation))
7757 ind1)
7758 ;; find where this list begins
7759 (catch 'exit
7760 (while t
7761 (catch 'next
7762 (beginning-of-line 2)
7763 (if (looking-at "[ \t]*$")
7764 (throw (if (eobp) 'exit 'next) t))
7765 (skip-chars-forward " \t") (setq ind1 (current-column))
7766 (if (or (< ind1 ind)
7767 (and (= ind1 ind)
7768 (not (org-at-item-p)))
7769 (eobp))
7770 (progn
7771 (setq pos (point-at-bol))
7772 (throw 'exit t))))))
7773 (goto-char pos)))
7776 (defvar org-last-indent-begin-marker (make-marker))
7777 (defvar org-last-indent-end-marker (make-marker))
7779 (defun org-outdent-item (arg)
7780 "Outdent a local list item."
7781 (interactive "p")
7782 (org-indent-item (- arg)))
7784 (defun org-indent-item (arg)
7785 "Indent a local list item."
7786 (interactive "p")
7787 (unless (org-at-item-p)
7788 (error "Not on an item"))
7789 (save-excursion
7790 (let (beg end ind ind1 tmp delta ind-down ind-up)
7791 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7792 (setq beg org-last-indent-begin-marker
7793 end org-last-indent-end-marker)
7794 (org-beginning-of-item)
7795 (setq beg (move-marker org-last-indent-begin-marker (point)))
7796 (org-end-of-item)
7797 (setq end (move-marker org-last-indent-end-marker (point))))
7798 (goto-char beg)
7799 (setq tmp (org-item-indent-positions)
7800 ind (car tmp)
7801 ind-down (nth 2 tmp)
7802 ind-up (nth 1 tmp)
7803 delta (if (> arg 0)
7804 (if ind-down (- ind-down ind) 2)
7805 (if ind-up (- ind-up ind) -2)))
7806 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7807 (while (< (point) end)
7808 (beginning-of-line 1)
7809 (skip-chars-forward " \t") (setq ind1 (current-column))
7810 (delete-region (point-at-bol) (point))
7811 (or (eolp) (indent-to-column (+ ind1 delta)))
7812 (beginning-of-line 2))))
7813 (org-fix-bullet-type)
7814 (org-maybe-renumber-ordered-list-safe)
7815 (save-excursion
7816 (beginning-of-line 0)
7817 (condition-case nil (org-beginning-of-item) (error nil))
7818 (org-maybe-renumber-ordered-list-safe)))
7820 (defun org-item-indent-positions ()
7821 "Return indentation for plain list items.
7822 This returns a list with three values: The current indentation, the
7823 parent indentation and the indentation a child should habe.
7824 Assumes cursor in item line."
7825 (let* ((bolpos (point-at-bol))
7826 (ind (org-get-indentation))
7827 ind-down ind-up pos)
7828 (save-excursion
7829 (org-beginning-of-item-list)
7830 (skip-chars-backward "\n\r \t")
7831 (when (org-in-item-p)
7832 (org-beginning-of-item)
7833 (setq ind-up (org-get-indentation))))
7834 (setq pos (point))
7835 (save-excursion
7836 (cond
7837 ((and (condition-case nil (progn (org-previous-item) t)
7838 (error nil))
7839 (or (forward-char 1) t)
7840 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7841 (setq ind-down (org-get-indentation)))
7842 ((and (goto-char pos)
7843 (org-at-item-p))
7844 (goto-char (match-end 0))
7845 (skip-chars-forward " \t")
7846 (setq ind-down (current-column)))))
7847 (list ind ind-up ind-down)))
7849 ;;; The orgstruct minor mode
7851 ;; Define a minor mode which can be used in other modes in order to
7852 ;; integrate the org-mode structure editing commands.
7854 ;; This is really a hack, because the org-mode structure commands use
7855 ;; keys which normally belong to the major mode. Here is how it
7856 ;; works: The minor mode defines all the keys necessary to operate the
7857 ;; structure commands, but wraps the commands into a function which
7858 ;; tests if the cursor is currently at a headline or a plain list
7859 ;; item. If that is the case, the structure command is used,
7860 ;; temporarily setting many Org-mode variables like regular
7861 ;; expressions for filling etc. However, when any of those keys is
7862 ;; used at a different location, function uses `key-binding' to look
7863 ;; up if the key has an associated command in another currently active
7864 ;; keymap (minor modes, major mode, global), and executes that
7865 ;; command. There might be problems if any of the keys is otherwise
7866 ;; used as a prefix key.
7868 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7869 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7870 ;; addresses this by checking explicitly for both bindings.
7872 (defvar orgstruct-mode-map (make-sparse-keymap)
7873 "Keymap for the minor `orgstruct-mode'.")
7875 (defvar org-local-vars nil
7876 "List of local variables, for use by `orgstruct-mode'")
7878 ;;;###autoload
7879 (define-minor-mode orgstruct-mode
7880 "Toggle the minor more `orgstruct-mode'.
7881 This mode is for using Org-mode structure commands in other modes.
7882 The following key behave as if Org-mode was active, if the cursor
7883 is on a headline, or on a plain list item (both in the definition
7884 of Org-mode).
7886 M-up Move entry/item up
7887 M-down Move entry/item down
7888 M-left Promote
7889 M-right Demote
7890 M-S-up Move entry/item up
7891 M-S-down Move entry/item down
7892 M-S-left Promote subtree
7893 M-S-right Demote subtree
7894 M-q Fill paragraph and items like in Org-mode
7895 C-c ^ Sort entries
7896 C-c - Cycle list bullet
7897 TAB Cycle item visibility
7898 M-RET Insert new heading/item
7899 S-M-RET Insert new TODO heading / Chekbox item
7900 C-c C-c Set tags / toggle checkbox"
7901 nil " OrgStruct" nil
7902 (org-load-modules-maybe)
7903 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7905 ;;;###autoload
7906 (defun turn-on-orgstruct ()
7907 "Unconditionally turn on `orgstruct-mode'."
7908 (orgstruct-mode 1))
7910 ;;;###autoload
7911 (defun turn-on-orgstruct++ ()
7912 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7913 In addition to setting orgstruct-mode, this also exports all indentation and
7914 autofilling variables from org-mode into the buffer. Note that turning
7915 off orgstruct-mode will *not* remove these additional settings."
7916 (orgstruct-mode 1)
7917 (let (var val)
7918 (mapc
7919 (lambda (x)
7920 (when (string-match
7921 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7922 (symbol-name (car x)))
7923 (setq var (car x) val (nth 1 x))
7924 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7925 org-local-vars)))
7927 (defun orgstruct-error ()
7928 "Error when there is no default binding for a structure key."
7929 (interactive)
7930 (error "This key has no function outside structure elements"))
7932 (defun orgstruct-setup ()
7933 "Setup orgstruct keymaps."
7934 (let ((nfunc 0)
7935 (bindings
7936 (list
7937 '([(meta up)] org-metaup)
7938 '([(meta down)] org-metadown)
7939 '([(meta left)] org-metaleft)
7940 '([(meta right)] org-metaright)
7941 '([(meta shift up)] org-shiftmetaup)
7942 '([(meta shift down)] org-shiftmetadown)
7943 '([(meta shift left)] org-shiftmetaleft)
7944 '([(meta shift right)] org-shiftmetaright)
7945 '([(shift up)] org-shiftup)
7946 '([(shift down)] org-shiftdown)
7947 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7948 '("\M-q" fill-paragraph)
7949 '("\C-c^" org-sort)
7950 '("\C-c-" org-cycle-list-bullet)))
7951 elt key fun cmd)
7952 (while (setq elt (pop bindings))
7953 (setq nfunc (1+ nfunc))
7954 (setq key (org-key (car elt))
7955 fun (nth 1 elt)
7956 cmd (orgstruct-make-binding fun nfunc key))
7957 (org-defkey orgstruct-mode-map key cmd))
7959 ;; Special treatment needed for TAB and RET
7960 (org-defkey orgstruct-mode-map [(tab)]
7961 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7962 (org-defkey orgstruct-mode-map "\C-i"
7963 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7965 (org-defkey orgstruct-mode-map "\M-\C-m"
7966 (orgstruct-make-binding 'org-insert-heading 105
7967 "\M-\C-m" [(meta return)]))
7968 (org-defkey orgstruct-mode-map [(meta return)]
7969 (orgstruct-make-binding 'org-insert-heading 106
7970 [(meta return)] "\M-\C-m"))
7972 (org-defkey orgstruct-mode-map [(shift meta return)]
7973 (orgstruct-make-binding 'org-insert-todo-heading 107
7974 [(meta return)] "\M-\C-m"))
7976 (unless org-local-vars
7977 (setq org-local-vars (org-get-local-variables)))
7981 (defun orgstruct-make-binding (fun n &rest keys)
7982 "Create a function for binding in the structure minor mode.
7983 FUN is the command to call inside a table. N is used to create a unique
7984 command name. KEYS are keys that should be checked in for a command
7985 to execute outside of tables."
7986 (eval
7987 (list 'defun
7988 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7989 '(arg)
7990 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7991 "Outside of structure, run the binding of `"
7992 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7993 "'.")
7994 '(interactive "p")
7995 (list 'if
7996 '(org-context-p 'headline 'item)
7997 (list 'org-run-like-in-org-mode (list 'quote fun))
7998 (list 'let '(orgstruct-mode)
7999 (list 'call-interactively
8000 (append '(or)
8001 (mapcar (lambda (k)
8002 (list 'key-binding k))
8003 keys)
8004 '('orgstruct-error))))))))
8006 (defun org-context-p (&rest contexts)
8007 "Check if local context is and of CONTEXTS.
8008 Possible values in the list of contexts are `table', `headline', and `item'."
8009 (let ((pos (point)))
8010 (goto-char (point-at-bol))
8011 (prog1 (or (and (memq 'table contexts)
8012 (looking-at "[ \t]*|"))
8013 (and (memq 'headline contexts)
8014 (looking-at "\\*+"))
8015 (and (memq 'item contexts)
8016 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
8017 (goto-char pos))))
8019 (defun org-get-local-variables ()
8020 "Return a list of all local variables in an org-mode buffer."
8021 (let (varlist)
8022 (with-current-buffer (get-buffer-create "*Org tmp*")
8023 (erase-buffer)
8024 (org-mode)
8025 (setq varlist (buffer-local-variables)))
8026 (kill-buffer "*Org tmp*")
8027 (delq nil
8028 (mapcar
8029 (lambda (x)
8030 (setq x
8031 (if (symbolp x)
8032 (list x)
8033 (list (car x) (list 'quote (cdr x)))))
8034 (if (string-match
8035 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8036 (symbol-name (car x)))
8037 x nil))
8038 varlist))))
8040 ;;;###autoload
8041 (defun org-run-like-in-org-mode (cmd)
8042 (org-load-modules-maybe)
8043 (unless org-local-vars
8044 (setq org-local-vars (org-get-local-variables)))
8045 (eval (list 'let org-local-vars
8046 (list 'call-interactively (list 'quote cmd)))))
8048 ;;;; Archiving
8050 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
8052 (defun org-archive-subtree (&optional find-done)
8053 "Move the current subtree to the archive.
8054 The archive can be a certain top-level heading in the current file, or in
8055 a different file. The tree will be moved to that location, the subtree
8056 heading be marked DONE, and the current time will be added.
8058 When called with prefix argument FIND-DONE, find whole trees without any
8059 open TODO items and archive them (after getting confirmation from the user).
8060 If the cursor is not at a headline when this comand is called, try all level
8061 1 trees. If the cursor is on a headline, only try the direct children of
8062 this heading."
8063 (interactive "P")
8064 (if find-done
8065 (org-archive-all-done)
8066 ;; Save all relevant TODO keyword-relatex variables
8068 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
8069 (tr-org-todo-keywords-1 org-todo-keywords-1)
8070 (tr-org-todo-kwd-alist org-todo-kwd-alist)
8071 (tr-org-done-keywords org-done-keywords)
8072 (tr-org-todo-regexp org-todo-regexp)
8073 (tr-org-todo-line-regexp org-todo-line-regexp)
8074 (tr-org-odd-levels-only org-odd-levels-only)
8075 (this-buffer (current-buffer))
8076 (org-archive-location org-archive-location)
8077 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
8078 ;; start of variables that will be used for saving context
8079 ;; The compiler complains about them - keep them anyway!
8080 (file (abbreviate-file-name (buffer-file-name)))
8081 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
8082 (time (format-time-string
8083 (substring (cdr org-time-stamp-formats) 1 -1)
8084 (current-time)))
8085 afile heading buffer level newfile-p
8086 category todo priority
8087 ;; start of variables that will be used for savind context
8088 ltags itags prop)
8090 ;; Try to find a local archive location
8091 (save-excursion
8092 (save-restriction
8093 (widen)
8094 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
8095 (if (and prop (string-match "\\S-" prop))
8096 (setq org-archive-location prop)
8097 (if (or (re-search-backward re nil t)
8098 (re-search-forward re nil t))
8099 (setq org-archive-location (match-string 1))))))
8101 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
8102 (progn
8103 (setq afile (format (match-string 1 org-archive-location)
8104 (file-name-nondirectory buffer-file-name))
8105 heading (match-string 2 org-archive-location)))
8106 (error "Invalid `org-archive-location'"))
8107 (if (> (length afile) 0)
8108 (setq newfile-p (not (file-exists-p afile))
8109 buffer (find-file-noselect afile))
8110 (setq buffer (current-buffer)))
8111 (unless buffer
8112 (error "Cannot access file \"%s\"" afile))
8113 (if (and (> (length heading) 0)
8114 (string-match "^\\*+" heading))
8115 (setq level (match-end 0))
8116 (setq heading nil level 0))
8117 (save-excursion
8118 (org-back-to-heading t)
8119 ;; Get context information that will be lost by moving the tree
8120 (org-refresh-category-properties)
8121 (setq category (org-get-category)
8122 todo (and (looking-at org-todo-line-regexp)
8123 (match-string 2))
8124 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
8125 ltags (org-get-tags)
8126 itags (org-delete-all ltags (org-get-tags-at)))
8127 (setq ltags (mapconcat 'identity ltags " ")
8128 itags (mapconcat 'identity itags " "))
8129 ;; We first only copy, in case something goes wrong
8130 ;; we need to protect this-command, to avoid kill-region sets it,
8131 ;; which would lead to duplication of subtrees
8132 (let (this-command) (org-copy-subtree))
8133 (set-buffer buffer)
8134 ;; Enforce org-mode for the archive buffer
8135 (if (not (org-mode-p))
8136 ;; Force the mode for future visits.
8137 (let ((org-insert-mode-line-in-empty-file t)
8138 (org-inhibit-startup t))
8139 (call-interactively 'org-mode)))
8140 (when newfile-p
8141 (goto-char (point-max))
8142 (insert (format "\nArchived entries from file %s\n\n"
8143 (buffer-file-name this-buffer))))
8144 ;; Force the TODO keywords of the original buffer
8145 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
8146 (org-todo-keywords-1 tr-org-todo-keywords-1)
8147 (org-todo-kwd-alist tr-org-todo-kwd-alist)
8148 (org-done-keywords tr-org-done-keywords)
8149 (org-todo-regexp tr-org-todo-regexp)
8150 (org-todo-line-regexp tr-org-todo-line-regexp)
8151 (org-odd-levels-only
8152 (if (local-variable-p 'org-odd-levels-only (current-buffer))
8153 org-odd-levels-only
8154 tr-org-odd-levels-only)))
8155 (goto-char (point-min))
8156 (show-all)
8157 (if heading
8158 (progn
8159 (if (re-search-forward
8160 (concat "^" (regexp-quote heading)
8161 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
8162 nil t)
8163 (goto-char (match-end 0))
8164 ;; Heading not found, just insert it at the end
8165 (goto-char (point-max))
8166 (or (bolp) (insert "\n"))
8167 (insert "\n" heading "\n")
8168 (end-of-line 0))
8169 ;; Make the subtree visible
8170 (show-subtree)
8171 (org-end-of-subtree t)
8172 (skip-chars-backward " \t\r\n")
8173 (and (looking-at "[ \t\r\n]*")
8174 (replace-match "\n\n")))
8175 ;; No specific heading, just go to end of file.
8176 (goto-char (point-max)) (insert "\n"))
8177 ;; Paste
8178 (org-paste-subtree (org-get-valid-level level 1))
8180 ;; Mark the entry as done
8181 (when (and org-archive-mark-done
8182 (looking-at org-todo-line-regexp)
8183 (or (not (match-end 2))
8184 (not (member (match-string 2) org-done-keywords))))
8185 (let (org-log-done org-todo-log-states)
8186 (org-todo
8187 (car (or (member org-archive-mark-done org-done-keywords)
8188 org-done-keywords)))))
8190 ;; Add the context info
8191 (when org-archive-save-context-info
8192 (let ((l org-archive-save-context-info) e n v)
8193 (while (setq e (pop l))
8194 (when (and (setq v (symbol-value e))
8195 (stringp v) (string-match "\\S-" v))
8196 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
8197 (org-entry-put (point) n v)))))
8199 ;; Save and kill the buffer, if it is not the same buffer.
8200 (if (not (eq this-buffer buffer))
8201 (progn (save-buffer) (kill-buffer buffer)))))
8202 ;; Here we are back in the original buffer. Everything seems to have
8203 ;; worked. So now cut the tree and finish up.
8204 (let (this-command) (org-cut-subtree))
8205 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
8206 (message "Subtree archived %s"
8207 (if (eq this-buffer buffer)
8208 (concat "under heading: " heading)
8209 (concat "in file: " (abbreviate-file-name afile)))))))
8211 (defun org-refresh-category-properties ()
8212 "Refresh category text properties in teh buffer."
8213 (let ((def-cat (cond
8214 ((null org-category)
8215 (if buffer-file-name
8216 (file-name-sans-extension
8217 (file-name-nondirectory buffer-file-name))
8218 "???"))
8219 ((symbolp org-category) (symbol-name org-category))
8220 (t org-category)))
8221 beg end cat pos optionp)
8222 (org-unmodified
8223 (save-excursion
8224 (save-restriction
8225 (widen)
8226 (goto-char (point-min))
8227 (put-text-property (point) (point-max) 'org-category def-cat)
8228 (while (re-search-forward
8229 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8230 (setq pos (match-end 0)
8231 optionp (equal (char-after (match-beginning 0)) ?#)
8232 cat (org-trim (match-string 2)))
8233 (if optionp
8234 (setq beg (point-at-bol) end (point-max))
8235 (org-back-to-heading t)
8236 (setq beg (point) end (org-end-of-subtree t t)))
8237 (put-text-property beg end 'org-category cat)
8238 (goto-char pos)))))))
8240 (defun org-archive-all-done (&optional tag)
8241 "Archive sublevels of the current tree without open TODO items.
8242 If the cursor is not on a headline, try all level 1 trees. If
8243 it is on a headline, try all direct children.
8244 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
8245 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
8246 (rea (concat ".*:" org-archive-tag ":"))
8247 (begm (make-marker))
8248 (endm (make-marker))
8249 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
8250 "Move subtree to archive (no open TODO items)? "))
8251 beg end (cntarch 0))
8252 (if (org-on-heading-p)
8253 (progn
8254 (setq re1 (concat "^" (regexp-quote
8255 (make-string
8256 (1+ (- (match-end 0) (match-beginning 0) 1))
8257 ?*))
8258 " "))
8259 (move-marker begm (point))
8260 (move-marker endm (org-end-of-subtree t)))
8261 (setq re1 "^* ")
8262 (move-marker begm (point-min))
8263 (move-marker endm (point-max)))
8264 (save-excursion
8265 (goto-char begm)
8266 (while (re-search-forward re1 endm t)
8267 (setq beg (match-beginning 0)
8268 end (save-excursion (org-end-of-subtree t) (point)))
8269 (goto-char beg)
8270 (if (re-search-forward re end t)
8271 (goto-char end)
8272 (goto-char beg)
8273 (if (and (or (not tag) (not (looking-at rea)))
8274 (y-or-n-p question))
8275 (progn
8276 (if tag
8277 (org-toggle-tag org-archive-tag 'on)
8278 (org-archive-subtree))
8279 (setq cntarch (1+ cntarch)))
8280 (goto-char end)))))
8281 (message "%d trees archived" cntarch)))
8283 (defun org-cycle-hide-drawers (state)
8284 "Re-hide all drawers after a visibility state change."
8285 (when (and (org-mode-p)
8286 (not (memq state '(overview folded))))
8287 (save-excursion
8288 (let* ((globalp (memq state '(contents all)))
8289 (beg (if globalp (point-min) (point)))
8290 (end (if globalp (point-max) (org-end-of-subtree t))))
8291 (goto-char beg)
8292 (while (re-search-forward org-drawer-regexp end t)
8293 (org-flag-drawer t))))))
8295 (defun org-flag-drawer (flag)
8296 (save-excursion
8297 (beginning-of-line 1)
8298 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8299 (let ((b (match-end 0))
8300 (outline-regexp org-outline-regexp))
8301 (if (re-search-forward
8302 "^[ \t]*:END:"
8303 (save-excursion (outline-next-heading) (point)) t)
8304 (outline-flag-region b (point-at-eol) flag)
8305 (error ":END: line missing"))))))
8307 (defun org-cycle-hide-archived-subtrees (state)
8308 "Re-hide all archived subtrees after a visibility state change."
8309 (when (and (not org-cycle-open-archived-trees)
8310 (not (memq state '(overview folded))))
8311 (save-excursion
8312 (let* ((globalp (memq state '(contents all)))
8313 (beg (if globalp (point-min) (point)))
8314 (end (if globalp (point-max) (org-end-of-subtree t))))
8315 (org-hide-archived-subtrees beg end)
8316 (goto-char beg)
8317 (if (looking-at (concat ".*:" org-archive-tag ":"))
8318 (message "%s" (substitute-command-keys
8319 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8321 (defun org-force-cycle-archived ()
8322 "Cycle subtree even if it is archived."
8323 (interactive)
8324 (setq this-command 'org-cycle)
8325 (let ((org-cycle-open-archived-trees t))
8326 (call-interactively 'org-cycle)))
8328 (defun org-hide-archived-subtrees (beg end)
8329 "Re-hide all archived subtrees after a visibility state change."
8330 (save-excursion
8331 (let* ((re (concat ":" org-archive-tag ":")))
8332 (goto-char beg)
8333 (while (re-search-forward re end t)
8334 (and (org-on-heading-p) (hide-subtree))
8335 (org-end-of-subtree t)))))
8337 (defun org-toggle-tag (tag &optional onoff)
8338 "Toggle the tag TAG for the current line.
8339 If ONOFF is `on' or `off', don't toggle but set to this state."
8340 (unless (org-on-heading-p t) (error "Not on headling"))
8341 (let (res current)
8342 (save-excursion
8343 (beginning-of-line)
8344 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8345 (point-at-eol) t)
8346 (progn
8347 (setq current (match-string 1))
8348 (replace-match ""))
8349 (setq current ""))
8350 (setq current (nreverse (org-split-string current ":")))
8351 (cond
8352 ((eq onoff 'on)
8353 (setq res t)
8354 (or (member tag current) (push tag current)))
8355 ((eq onoff 'off)
8356 (or (not (member tag current)) (setq current (delete tag current))))
8357 (t (if (member tag current)
8358 (setq current (delete tag current))
8359 (setq res t)
8360 (push tag current))))
8361 (end-of-line 1)
8362 (if current
8363 (progn
8364 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8365 (org-set-tags nil t))
8366 (delete-horizontal-space))
8367 (run-hooks 'org-after-tags-change-hook))
8368 res))
8370 (defun org-toggle-archive-tag (&optional arg)
8371 "Toggle the archive tag for the current headline.
8372 With prefix ARG, check all children of current headline and offer tagging
8373 the children that do not contain any open TODO items."
8374 (interactive "P")
8375 (if arg
8376 (org-archive-all-done 'tag)
8377 (let (set)
8378 (save-excursion
8379 (org-back-to-heading t)
8380 (setq set (org-toggle-tag org-archive-tag))
8381 (when set (hide-subtree)))
8382 (and set (beginning-of-line 1))
8383 (message "Subtree %s" (if set "archived" "unarchived")))))
8386 ;;;; Tables
8388 ;;; The table editor
8390 ;; Watch out: Here we are talking about two different kind of tables.
8391 ;; Most of the code is for the tables created with the Org-mode table editor.
8392 ;; Sometimes, we talk about tables created and edited with the table.el
8393 ;; Emacs package. We call the former org-type tables, and the latter
8394 ;; table.el-type tables.
8396 (defun org-before-change-function (beg end)
8397 "Every change indicates that a table might need an update."
8398 (setq org-table-may-need-update t))
8400 (defconst org-table-line-regexp "^[ \t]*|"
8401 "Detects an org-type table line.")
8402 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8403 "Detects an org-type table line.")
8404 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8405 "Detects a table line marked for automatic recalculation.")
8406 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8407 "Detects a table line marked for automatic recalculation.")
8408 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8409 "Detects a table line marked for automatic recalculation.")
8410 (defconst org-table-hline-regexp "^[ \t]*|-"
8411 "Detects an org-type table hline.")
8412 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8413 "Detects a table-type table hline.")
8414 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8415 "Detects an org-type or table-type table.")
8416 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8417 "Searching from within a table (any type) this finds the first line
8418 outside the table.")
8419 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8420 "Searching from within a table (any type) this finds the first line
8421 outside the table.")
8423 (defvar org-table-last-highlighted-reference nil)
8424 (defvar org-table-formula-history nil)
8426 (defvar org-table-column-names nil
8427 "Alist with column names, derived from the `!' line.")
8428 (defvar org-table-column-name-regexp nil
8429 "Regular expression matching the current column names.")
8430 (defvar org-table-local-parameters nil
8431 "Alist with parameter names, derived from the `$' line.")
8432 (defvar org-table-named-field-locations nil
8433 "Alist with locations of named fields.")
8435 (defvar org-table-current-line-types nil
8436 "Table row types, non-nil only for the duration of a comand.")
8437 (defvar org-table-current-begin-line nil
8438 "Table begin line, non-nil only for the duration of a comand.")
8439 (defvar org-table-current-begin-pos nil
8440 "Table begin position, non-nil only for the duration of a comand.")
8441 (defvar org-table-dlines nil
8442 "Vector of data line line numbers in the current table.")
8443 (defvar org-table-hlines nil
8444 "Vector of hline line numbers in the current table.")
8446 (defconst org-table-range-regexp
8447 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8448 ;; 1 2 3 4 5
8449 "Regular expression for matching ranges in formulas.")
8451 (defconst org-table-range-regexp2
8452 (concat
8453 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8454 "\\.\\."
8455 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8456 "Match a range for reference display.")
8458 (defconst org-table-translate-regexp
8459 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8460 "Match a reference that needs translation, for reference display.")
8462 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8464 (defun org-table-create-with-table.el ()
8465 "Use the table.el package to insert a new table.
8466 If there is already a table at point, convert between Org-mode tables
8467 and table.el tables."
8468 (interactive)
8469 (require 'table)
8470 (cond
8471 ((org-at-table.el-p)
8472 (if (y-or-n-p "Convert table to Org-mode table? ")
8473 (org-table-convert)))
8474 ((org-at-table-p)
8475 (if (y-or-n-p "Convert table to table.el table? ")
8476 (org-table-convert)))
8477 (t (call-interactively 'table-insert))))
8479 (defun org-table-create-or-convert-from-region (arg)
8480 "Convert region to table, or create an empty table.
8481 If there is an active region, convert it to a table, using the function
8482 `org-table-convert-region'. See the documentation of that function
8483 to learn how the prefix argument is interpreted to determine the field
8484 separator.
8485 If there is no such region, create an empty table with `org-table-create'."
8486 (interactive "P")
8487 (if (org-region-active-p)
8488 (org-table-convert-region (region-beginning) (region-end) arg)
8489 (org-table-create arg)))
8491 (defun org-table-create (&optional size)
8492 "Query for a size and insert a table skeleton.
8493 SIZE is a string Columns x Rows like for example \"3x2\"."
8494 (interactive "P")
8495 (unless size
8496 (setq size (read-string
8497 (concat "Table size Columns x Rows [e.g. "
8498 org-table-default-size "]: ")
8499 "" nil org-table-default-size)))
8501 (let* ((pos (point))
8502 (indent (make-string (current-column) ?\ ))
8503 (split (org-split-string size " *x *"))
8504 (rows (string-to-number (nth 1 split)))
8505 (columns (string-to-number (car split)))
8506 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8507 "\n")))
8508 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8509 (point-at-bol) (point)))
8510 (beginning-of-line 1)
8511 (newline))
8512 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8513 (dotimes (i rows) (insert line))
8514 (goto-char pos)
8515 (if (> rows 1)
8516 ;; Insert a hline after the first row.
8517 (progn
8518 (end-of-line 1)
8519 (insert "\n|-")
8520 (goto-char pos)))
8521 (org-table-align)))
8523 (defun org-table-convert-region (beg0 end0 &optional separator)
8524 "Convert region to a table.
8525 The region goes from BEG0 to END0, but these borders will be moved
8526 slightly, to make sure a beginning of line in the first line is included.
8528 SEPARATOR specifies the field separator in the lines. It can have the
8529 following values:
8531 '(4) Use the comma as a field separator
8532 '(16) Use a TAB as field separator
8533 integer When a number, use that many spaces as field separator
8534 nil When nil, the command tries to be smart and figure out the
8535 separator in the following way:
8536 - when each line contains a TAB, assume TAB-separated material
8537 - when each line contains a comme, assume CSV material
8538 - else, assume one or more SPACE charcters as separator."
8539 (interactive "rP")
8540 (let* ((beg (min beg0 end0))
8541 (end (max beg0 end0))
8543 (goto-char beg)
8544 (beginning-of-line 1)
8545 (setq beg (move-marker (make-marker) (point)))
8546 (goto-char end)
8547 (if (bolp) (backward-char 1) (end-of-line 1))
8548 (setq end (move-marker (make-marker) (point)))
8549 ;; Get the right field separator
8550 (unless separator
8551 (goto-char beg)
8552 (setq separator
8553 (cond
8554 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8555 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8556 (t 1))))
8557 (setq re (cond
8558 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8559 ((equal separator '(16)) "^\\|\t")
8560 ((integerp separator)
8561 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8562 (t (error "This should not happen"))))
8563 (goto-char beg)
8564 (while (re-search-forward re end t)
8565 (replace-match "| " t t))
8566 (goto-char beg)
8567 (insert " ")
8568 (org-table-align)))
8570 (defun org-table-import (file arg)
8571 "Import FILE as a table.
8572 The file is assumed to be tab-separated. Such files can be produced by most
8573 spreadsheet and database applications. If no tabs (at least one per line)
8574 are found, lines will be split on whitespace into fields."
8575 (interactive "f\nP")
8576 (or (bolp) (newline))
8577 (let ((beg (point))
8578 (pm (point-max)))
8579 (insert-file-contents file)
8580 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8582 (defun org-table-export ()
8583 "Export table as a tab-separated file.
8584 Such a file can be imported into a spreadsheet program like Excel."
8585 (interactive)
8586 (let* ((beg (org-table-begin))
8587 (end (org-table-end))
8588 (table (buffer-substring beg end))
8589 (file (read-file-name "Export table to: "))
8590 buf)
8591 (unless (or (not (file-exists-p file))
8592 (y-or-n-p (format "Overwrite file %s? " file)))
8593 (error "Abort"))
8594 (with-current-buffer (find-file-noselect file)
8595 (setq buf (current-buffer))
8596 (erase-buffer)
8597 (fundamental-mode)
8598 (insert table)
8599 (goto-char (point-min))
8600 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8601 (replace-match "" t t)
8602 (end-of-line 1))
8603 (goto-char (point-min))
8604 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8605 (replace-match "" t t)
8606 (goto-char (min (1+ (point)) (point-max))))
8607 (goto-char (point-min))
8608 (while (re-search-forward "^-[-+]*$" nil t)
8609 (replace-match "")
8610 (if (looking-at "\n")
8611 (delete-char 1)))
8612 (goto-char (point-min))
8613 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8614 (replace-match "\t" t t))
8615 (save-buffer))
8616 (kill-buffer buf)))
8618 (defvar org-table-aligned-begin-marker (make-marker)
8619 "Marker at the beginning of the table last aligned.
8620 Used to check if cursor still is in that table, to minimize realignment.")
8621 (defvar org-table-aligned-end-marker (make-marker)
8622 "Marker at the end of the table last aligned.
8623 Used to check if cursor still is in that table, to minimize realignment.")
8624 (defvar org-table-last-alignment nil
8625 "List of flags for flushright alignment, from the last re-alignment.
8626 This is being used to correctly align a single field after TAB or RET.")
8627 (defvar org-table-last-column-widths nil
8628 "List of max width of fields in each column.
8629 This is being used to correctly align a single field after TAB or RET.")
8630 (defvar org-table-overlay-coordinates nil
8631 "Overlay coordinates after each align of a table.")
8632 (make-variable-buffer-local 'org-table-overlay-coordinates)
8634 (defvar org-last-recalc-line nil)
8635 (defconst org-narrow-column-arrow "=>"
8636 "Used as display property in narrowed table columns.")
8638 (defun org-table-align ()
8639 "Align the table at point by aligning all vertical bars."
8640 (interactive)
8641 (let* (
8642 ;; Limits of table
8643 (beg (org-table-begin))
8644 (end (org-table-end))
8645 ;; Current cursor position
8646 (linepos (org-current-line))
8647 (colpos (org-table-current-column))
8648 (winstart (window-start))
8649 (winstartline (org-current-line (min winstart (1- (point-max)))))
8650 lines (new "") lengths l typenums ty fields maxfields i
8651 column
8652 (indent "") cnt frac
8653 rfmt hfmt
8654 (spaces '(1 . 1))
8655 (sp1 (car spaces))
8656 (sp2 (cdr spaces))
8657 (rfmt1 (concat
8658 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8659 (hfmt1 (concat
8660 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8661 emptystrings links dates emph narrow fmax f1 len c e)
8662 (untabify beg end)
8663 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8664 ;; Check if we have links or dates
8665 (goto-char beg)
8666 (setq links (re-search-forward org-bracket-link-regexp end t))
8667 (goto-char beg)
8668 (setq emph (and org-hide-emphasis-markers
8669 (re-search-forward org-emph-re end t)))
8670 (goto-char beg)
8671 (setq dates (and org-display-custom-times
8672 (re-search-forward org-ts-regexp-both end t)))
8673 ;; Make sure the link properties are right
8674 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8675 ;; Make sure the date properties are right
8676 (when dates (goto-char beg) (while (org-activate-dates end)))
8677 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8679 ;; Check if we are narrowing any columns
8680 (goto-char beg)
8681 (setq narrow (and org-format-transports-properties-p
8682 (re-search-forward "<[0-9]+>" end t)))
8683 ;; Get the rows
8684 (setq lines (org-split-string
8685 (buffer-substring beg end) "\n"))
8686 ;; Store the indentation of the first line
8687 (if (string-match "^ *" (car lines))
8688 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8689 ;; Mark the hlines by setting the corresponding element to nil
8690 ;; At the same time, we remove trailing space.
8691 (setq lines (mapcar (lambda (l)
8692 (if (string-match "^ *|-" l)
8694 (if (string-match "[ \t]+$" l)
8695 (substring l 0 (match-beginning 0))
8696 l)))
8697 lines))
8698 ;; Get the data fields by splitting the lines.
8699 (setq fields (mapcar
8700 (lambda (l)
8701 (org-split-string l " *| *"))
8702 (delq nil (copy-sequence lines))))
8703 ;; How many fields in the longest line?
8704 (condition-case nil
8705 (setq maxfields (apply 'max (mapcar 'length fields)))
8706 (error
8707 (kill-region beg end)
8708 (org-table-create org-table-default-size)
8709 (error "Empty table - created default table")))
8710 ;; A list of empty strings to fill any short rows on output
8711 (setq emptystrings (make-list maxfields ""))
8712 ;; Check for special formatting.
8713 (setq i -1)
8714 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8715 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8716 ;; Check if there is an explicit width specified
8717 (when narrow
8718 (setq c column fmax nil)
8719 (while c
8720 (setq e (pop c))
8721 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8722 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8723 ;; Find fields that are wider than fmax, and shorten them
8724 (when fmax
8725 (loop for xx in column do
8726 (when (and (stringp xx)
8727 (> (org-string-width xx) fmax))
8728 (org-add-props xx nil
8729 'help-echo
8730 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8731 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8732 (unless (> f1 1)
8733 (error "Cannot narrow field starting with wide link \"%s\""
8734 (match-string 0 xx)))
8735 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8736 (add-text-properties (- f1 2) f1
8737 (list 'display org-narrow-column-arrow)
8738 xx)))))
8739 ;; Get the maximum width for each column
8740 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8741 ;; Get the fraction of numbers, to decide about alignment of the column
8742 (setq cnt 0 frac 0.0)
8743 (loop for x in column do
8744 (if (equal x "")
8746 (setq frac ( / (+ (* frac cnt)
8747 (if (string-match org-table-number-regexp x) 1 0))
8748 (setq cnt (1+ cnt))))))
8749 (push (>= frac org-table-number-fraction) typenums))
8750 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8752 ;; Store the alignment of this table, for later editing of single fields
8753 (setq org-table-last-alignment typenums
8754 org-table-last-column-widths lengths)
8756 ;; With invisible characters, `format' does not get the field width right
8757 ;; So we need to make these fields wide by hand.
8758 (when (or links emph)
8759 (loop for i from 0 upto (1- maxfields) do
8760 (setq len (nth i lengths))
8761 (loop for j from 0 upto (1- (length fields)) do
8762 (setq c (nthcdr i (car (nthcdr j fields))))
8763 (if (and (stringp (car c))
8764 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8765 ; (string-match org-bracket-link-regexp (car c))
8766 (< (org-string-width (car c)) len))
8767 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8769 ;; Compute the formats needed for output of the table
8770 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8771 (while (setq l (pop lengths))
8772 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8773 (setq rfmt (concat rfmt (format rfmt1 ty l))
8774 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8775 (setq rfmt (concat rfmt "\n")
8776 hfmt (concat (substring hfmt 0 -1) "|\n"))
8778 (setq new (mapconcat
8779 (lambda (l)
8780 (if l (apply 'format rfmt
8781 (append (pop fields) emptystrings))
8782 hfmt))
8783 lines ""))
8784 ;; Replace the old one
8785 (delete-region beg end)
8786 (move-marker end nil)
8787 (move-marker org-table-aligned-begin-marker (point))
8788 (insert new)
8789 (move-marker org-table-aligned-end-marker (point))
8790 (when (and orgtbl-mode (not (org-mode-p)))
8791 (goto-char org-table-aligned-begin-marker)
8792 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8793 ;; Try to move to the old location
8794 (goto-line winstartline)
8795 (setq winstart (point-at-bol))
8796 (goto-line linepos)
8797 (set-window-start (selected-window) winstart 'noforce)
8798 (org-table-goto-column colpos)
8799 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8800 (setq org-table-may-need-update nil)
8803 (defun org-string-width (s)
8804 "Compute width of string, ignoring invisible characters.
8805 This ignores character with invisibility property `org-link', and also
8806 characters with property `org-cwidth', because these will become invisible
8807 upon the next fontification round."
8808 (let (b l)
8809 (when (or (eq t buffer-invisibility-spec)
8810 (assq 'org-link buffer-invisibility-spec))
8811 (while (setq b (text-property-any 0 (length s)
8812 'invisible 'org-link s))
8813 (setq s (concat (substring s 0 b)
8814 (substring s (or (next-single-property-change
8815 b 'invisible s) (length s)))))))
8816 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8817 (setq s (concat (substring s 0 b)
8818 (substring s (or (next-single-property-change
8819 b 'org-cwidth s) (length s))))))
8820 (setq l (string-width s) b -1)
8821 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8822 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8825 (defun org-table-begin (&optional table-type)
8826 "Find the beginning of the table and return its position.
8827 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8828 (save-excursion
8829 (if (not (re-search-backward
8830 (if table-type org-table-any-border-regexp
8831 org-table-border-regexp)
8832 nil t))
8833 (progn (goto-char (point-min)) (point))
8834 (goto-char (match-beginning 0))
8835 (beginning-of-line 2)
8836 (point))))
8838 (defun org-table-end (&optional table-type)
8839 "Find the end of the table and return its position.
8840 With argument TABLE-TYPE, go to the end of a table.el-type table."
8841 (save-excursion
8842 (if (not (re-search-forward
8843 (if table-type org-table-any-border-regexp
8844 org-table-border-regexp)
8845 nil t))
8846 (goto-char (point-max))
8847 (goto-char (match-beginning 0)))
8848 (point-marker)))
8850 (defun org-table-justify-field-maybe (&optional new)
8851 "Justify the current field, text to left, number to right.
8852 Optional argument NEW may specify text to replace the current field content."
8853 (cond
8854 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8855 ((org-at-table-hline-p))
8856 ((and (not new)
8857 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8858 (current-buffer)))
8859 (< (point) org-table-aligned-begin-marker)
8860 (>= (point) org-table-aligned-end-marker)))
8861 ;; This is not the same table, force a full re-align
8862 (setq org-table-may-need-update t))
8863 (t ;; realign the current field, based on previous full realign
8864 (let* ((pos (point)) s
8865 (col (org-table-current-column))
8866 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8867 l f n o e)
8868 (when (> col 0)
8869 (skip-chars-backward "^|\n")
8870 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8871 (progn
8872 (setq s (match-string 1)
8873 o (match-string 0)
8874 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8875 e (not (= (match-beginning 2) (match-end 2))))
8876 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8877 l (if e "|" (setq org-table-may-need-update t) ""))
8878 n (format f s))
8879 (if new
8880 (if (<= (length new) l) ;; FIXME: length -> str-width?
8881 (setq n (format f new))
8882 (setq n (concat new "|") org-table-may-need-update t)))
8883 (or (equal n o)
8884 (let (org-table-may-need-update)
8885 (replace-match n t t))))
8886 (setq org-table-may-need-update t))
8887 (goto-char pos))))))
8889 (defun org-table-next-field ()
8890 "Go to the next field in the current table, creating new lines as needed.
8891 Before doing so, re-align the table if necessary."
8892 (interactive)
8893 (org-table-maybe-eval-formula)
8894 (org-table-maybe-recalculate-line)
8895 (if (and org-table-automatic-realign
8896 org-table-may-need-update)
8897 (org-table-align))
8898 (let ((end (org-table-end)))
8899 (if (org-at-table-hline-p)
8900 (end-of-line 1))
8901 (condition-case nil
8902 (progn
8903 (re-search-forward "|" end)
8904 (if (looking-at "[ \t]*$")
8905 (re-search-forward "|" end))
8906 (if (and (looking-at "-")
8907 org-table-tab-jumps-over-hlines
8908 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8909 (goto-char (match-beginning 1)))
8910 (if (looking-at "-")
8911 (progn
8912 (beginning-of-line 0)
8913 (org-table-insert-row 'below))
8914 (if (looking-at " ") (forward-char 1))))
8915 (error
8916 (org-table-insert-row 'below)))))
8918 (defun org-table-previous-field ()
8919 "Go to the previous field in the table.
8920 Before doing so, re-align the table if necessary."
8921 (interactive)
8922 (org-table-justify-field-maybe)
8923 (org-table-maybe-recalculate-line)
8924 (if (and org-table-automatic-realign
8925 org-table-may-need-update)
8926 (org-table-align))
8927 (if (org-at-table-hline-p)
8928 (end-of-line 1))
8929 (re-search-backward "|" (org-table-begin))
8930 (re-search-backward "|" (org-table-begin))
8931 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8932 (re-search-backward "|" (org-table-begin)))
8933 (if (looking-at "| ?")
8934 (goto-char (match-end 0))))
8936 (defun org-table-next-row ()
8937 "Go to the next row (same column) in the current table.
8938 Before doing so, re-align the table if necessary."
8939 (interactive)
8940 (org-table-maybe-eval-formula)
8941 (org-table-maybe-recalculate-line)
8942 (if (or (looking-at "[ \t]*$")
8943 (save-excursion (skip-chars-backward " \t") (bolp)))
8944 (newline)
8945 (if (and org-table-automatic-realign
8946 org-table-may-need-update)
8947 (org-table-align))
8948 (let ((col (org-table-current-column)))
8949 (beginning-of-line 2)
8950 (if (or (not (org-at-table-p))
8951 (org-at-table-hline-p))
8952 (progn
8953 (beginning-of-line 0)
8954 (org-table-insert-row 'below)))
8955 (org-table-goto-column col)
8956 (skip-chars-backward "^|\n\r")
8957 (if (looking-at " ") (forward-char 1)))))
8959 (defun org-table-copy-down (n)
8960 "Copy a field down in the current column.
8961 If the field at the cursor is empty, copy into it the content of the nearest
8962 non-empty field above. With argument N, use the Nth non-empty field.
8963 If the current field is not empty, it is copied down to the next row, and
8964 the cursor is moved with it. Therefore, repeating this command causes the
8965 column to be filled row-by-row.
8966 If the variable `org-table-copy-increment' is non-nil and the field is an
8967 integer or a timestamp, it will be incremented while copying. In the case of
8968 a timestamp, if the cursor is on the year, change the year. If it is on the
8969 month or the day, change that. Point will stay on the current date field
8970 in order to easily repeat the interval."
8971 (interactive "p")
8972 (let* ((colpos (org-table-current-column))
8973 (col (current-column))
8974 (field (org-table-get-field))
8975 (non-empty (string-match "[^ \t]" field))
8976 (beg (org-table-begin))
8977 txt)
8978 (org-table-check-inside-data-field)
8979 (if non-empty
8980 (progn
8981 (setq txt (org-trim field))
8982 (org-table-next-row)
8983 (org-table-blank-field))
8984 (save-excursion
8985 (setq txt
8986 (catch 'exit
8987 (while (progn (beginning-of-line 1)
8988 (re-search-backward org-table-dataline-regexp
8989 beg t))
8990 (org-table-goto-column colpos t)
8991 (if (and (looking-at
8992 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8993 (= (setq n (1- n)) 0))
8994 (throw 'exit (match-string 1))))))))
8995 (if txt
8996 (progn
8997 (if (and org-table-copy-increment
8998 (string-match "^[0-9]+$" txt))
8999 (setq txt (format "%d" (+ (string-to-number txt) 1))))
9000 (insert txt)
9001 (move-to-column col)
9002 (if (and org-table-copy-increment (org-at-timestamp-p t))
9003 (org-timestamp-up 1)
9004 (org-table-maybe-recalculate-line))
9005 (org-table-align)
9006 (move-to-column col))
9007 (error "No non-empty field found"))))
9009 (defun org-table-check-inside-data-field ()
9010 "Is point inside a table data field?
9011 I.e. not on a hline or before the first or after the last column?
9012 This actually throws an error, so it aborts the current command."
9013 (if (or (not (org-at-table-p))
9014 (= (org-table-current-column) 0)
9015 (org-at-table-hline-p)
9016 (looking-at "[ \t]*$"))
9017 (error "Not in table data field")))
9019 (defvar org-table-clip nil
9020 "Clipboard for table regions.")
9022 (defun org-table-blank-field ()
9023 "Blank the current table field or active region."
9024 (interactive)
9025 (org-table-check-inside-data-field)
9026 (if (and (interactive-p) (org-region-active-p))
9027 (let (org-table-clip)
9028 (org-table-cut-region (region-beginning) (region-end)))
9029 (skip-chars-backward "^|")
9030 (backward-char 1)
9031 (if (looking-at "|[^|\n]+")
9032 (let* ((pos (match-beginning 0))
9033 (match (match-string 0))
9034 (len (org-string-width match)))
9035 (replace-match (concat "|" (make-string (1- len) ?\ )))
9036 (goto-char (+ 2 pos))
9037 (substring match 1)))))
9039 (defun org-table-get-field (&optional n replace)
9040 "Return the value of the field in column N of current row.
9041 N defaults to current field.
9042 If REPLACE is a string, replace field with this value. The return value
9043 is always the old value."
9044 (and n (org-table-goto-column n))
9045 (skip-chars-backward "^|\n")
9046 (backward-char 1)
9047 (if (looking-at "|[^|\r\n]*")
9048 (let* ((pos (match-beginning 0))
9049 (val (buffer-substring (1+ pos) (match-end 0))))
9050 (if replace
9051 (replace-match (concat "|" replace) t t))
9052 (goto-char (min (point-at-eol) (+ 2 pos)))
9053 val)
9054 (forward-char 1) ""))
9056 (defun org-table-field-info (arg)
9057 "Show info about the current field, and highlight any reference at point."
9058 (interactive "P")
9059 (org-table-get-specials)
9060 (save-excursion
9061 (let* ((pos (point))
9062 (col (org-table-current-column))
9063 (cname (car (rassoc (int-to-string col) org-table-column-names)))
9064 (name (car (rassoc (list (org-current-line) col)
9065 org-table-named-field-locations)))
9066 (eql (org-table-get-stored-formulas))
9067 (dline (org-table-current-dline))
9068 (ref (format "@%d$%d" dline col))
9069 (ref1 (org-table-convert-refs-to-an ref))
9070 (fequation (or (assoc name eql) (assoc ref eql)))
9071 (cequation (assoc (int-to-string col) eql))
9072 (eqn (or fequation cequation)))
9073 (goto-char pos)
9074 (condition-case nil
9075 (org-table-show-reference 'local)
9076 (error nil))
9077 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
9078 dline col
9079 (if cname (concat " or $" cname) "")
9080 dline col ref1
9081 (if name (concat " or $" name) "")
9082 ;; FIXME: formula info not correct if special table line
9083 (if eqn
9084 (concat ", formula: "
9085 (org-table-formula-to-user
9086 (concat
9087 (if (string-match "^[$@]"(car eqn)) "" "$")
9088 (car eqn) "=" (cdr eqn))))
9089 "")))))
9091 (defun org-table-current-column ()
9092 "Find out which column we are in.
9093 When called interactively, column is also displayed in echo area."
9094 (interactive)
9095 (if (interactive-p) (org-table-check-inside-data-field))
9096 (save-excursion
9097 (let ((cnt 0) (pos (point)))
9098 (beginning-of-line 1)
9099 (while (search-forward "|" pos t)
9100 (setq cnt (1+ cnt)))
9101 (if (interactive-p) (message "This is table column %d" cnt))
9102 cnt)))
9104 (defun org-table-current-dline ()
9105 "Find out what table data line we are in.
9106 Only datalins count for this."
9107 (interactive)
9108 (if (interactive-p) (org-table-check-inside-data-field))
9109 (save-excursion
9110 (let ((cnt 0) (pos (point)))
9111 (goto-char (org-table-begin))
9112 (while (<= (point) pos)
9113 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
9114 (beginning-of-line 2))
9115 (if (interactive-p) (message "This is table line %d" cnt))
9116 cnt)))
9118 (defun org-table-goto-column (n &optional on-delim force)
9119 "Move the cursor to the Nth column in the current table line.
9120 With optional argument ON-DELIM, stop with point before the left delimiter
9121 of the field.
9122 If there are less than N fields, just go to after the last delimiter.
9123 However, when FORCE is non-nil, create new columns if necessary."
9124 (interactive "p")
9125 (let ((pos (point-at-eol)))
9126 (beginning-of-line 1)
9127 (when (> n 0)
9128 (while (and (> (setq n (1- n)) -1)
9129 (or (search-forward "|" pos t)
9130 (and force
9131 (progn (end-of-line 1)
9132 (skip-chars-backward "^|")
9133 (insert " | "))))))
9134 ; (backward-char 2) t)))))
9135 (when (and force (not (looking-at ".*|")))
9136 (save-excursion (end-of-line 1) (insert " | ")))
9137 (if on-delim
9138 (backward-char 1)
9139 (if (looking-at " ") (forward-char 1))))))
9141 (defun org-at-table-p (&optional table-type)
9142 "Return t if the cursor is inside an org-type table.
9143 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9144 (if org-enable-table-editor
9145 (save-excursion
9146 (beginning-of-line 1)
9147 (looking-at (if table-type org-table-any-line-regexp
9148 org-table-line-regexp)))
9149 nil))
9151 (defun org-at-table.el-p ()
9152 "Return t if and only if we are at a table.el table."
9153 (and (org-at-table-p 'any)
9154 (save-excursion
9155 (goto-char (org-table-begin 'any))
9156 (looking-at org-table1-hline-regexp))))
9158 (defun org-table-recognize-table.el ()
9159 "If there is a table.el table nearby, recognize it and move into it."
9160 (if org-table-tab-recognizes-table.el
9161 (if (org-at-table.el-p)
9162 (progn
9163 (beginning-of-line 1)
9164 (if (looking-at org-table-dataline-regexp)
9166 (if (looking-at org-table1-hline-regexp)
9167 (progn
9168 (beginning-of-line 2)
9169 (if (looking-at org-table-any-border-regexp)
9170 (beginning-of-line -1)))))
9171 (if (re-search-forward "|" (org-table-end t) t)
9172 (progn
9173 (require 'table)
9174 (if (table--at-cell-p (point))
9176 (message "recognizing table.el table...")
9177 (table-recognize-table)
9178 (message "recognizing table.el table...done")))
9179 (error "This should not happen..."))
9181 nil)
9182 nil))
9184 (defun org-at-table-hline-p ()
9185 "Return t if the cursor is inside a hline in a table."
9186 (if org-enable-table-editor
9187 (save-excursion
9188 (beginning-of-line 1)
9189 (looking-at org-table-hline-regexp))
9190 nil))
9192 (defun org-table-insert-column ()
9193 "Insert a new column into the table."
9194 (interactive)
9195 (if (not (org-at-table-p))
9196 (error "Not at a table"))
9197 (org-table-find-dataline)
9198 (let* ((col (max 1 (org-table-current-column)))
9199 (beg (org-table-begin))
9200 (end (org-table-end))
9201 ;; Current cursor position
9202 (linepos (org-current-line))
9203 (colpos col))
9204 (goto-char beg)
9205 (while (< (point) end)
9206 (if (org-at-table-hline-p)
9208 (org-table-goto-column col t)
9209 (insert "| "))
9210 (beginning-of-line 2))
9211 (move-marker end nil)
9212 (goto-line linepos)
9213 (org-table-goto-column colpos)
9214 (org-table-align)
9215 (org-table-fix-formulas "$" nil (1- col) 1)))
9217 (defun org-table-find-dataline ()
9218 "Find a dataline in the current table, which is needed for column commands."
9219 (if (and (org-at-table-p)
9220 (not (org-at-table-hline-p)))
9222 (let ((col (current-column))
9223 (end (org-table-end)))
9224 (move-to-column col)
9225 (while (and (< (point) end)
9226 (or (not (= (current-column) col))
9227 (org-at-table-hline-p)))
9228 (beginning-of-line 2)
9229 (move-to-column col))
9230 (if (and (org-at-table-p)
9231 (not (org-at-table-hline-p)))
9233 (error
9234 "Please position cursor in a data line for column operations")))))
9236 (defun org-table-delete-column ()
9237 "Delete a column from the table."
9238 (interactive)
9239 (if (not (org-at-table-p))
9240 (error "Not at a table"))
9241 (org-table-find-dataline)
9242 (org-table-check-inside-data-field)
9243 (let* ((col (org-table-current-column))
9244 (beg (org-table-begin))
9245 (end (org-table-end))
9246 ;; Current cursor position
9247 (linepos (org-current-line))
9248 (colpos col))
9249 (goto-char beg)
9250 (while (< (point) end)
9251 (if (org-at-table-hline-p)
9253 (org-table-goto-column col t)
9254 (and (looking-at "|[^|\n]+|")
9255 (replace-match "|")))
9256 (beginning-of-line 2))
9257 (move-marker end nil)
9258 (goto-line linepos)
9259 (org-table-goto-column colpos)
9260 (org-table-align)
9261 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9262 col -1 col)))
9264 (defun org-table-move-column-right ()
9265 "Move column to the right."
9266 (interactive)
9267 (org-table-move-column nil))
9268 (defun org-table-move-column-left ()
9269 "Move column to the left."
9270 (interactive)
9271 (org-table-move-column 'left))
9273 (defun org-table-move-column (&optional left)
9274 "Move the current column to the right. With arg LEFT, move to the left."
9275 (interactive "P")
9276 (if (not (org-at-table-p))
9277 (error "Not at a table"))
9278 (org-table-find-dataline)
9279 (org-table-check-inside-data-field)
9280 (let* ((col (org-table-current-column))
9281 (col1 (if left (1- col) col))
9282 (beg (org-table-begin))
9283 (end (org-table-end))
9284 ;; Current cursor position
9285 (linepos (org-current-line))
9286 (colpos (if left (1- col) (1+ col))))
9287 (if (and left (= col 1))
9288 (error "Cannot move column further left"))
9289 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9290 (error "Cannot move column further right"))
9291 (goto-char beg)
9292 (while (< (point) end)
9293 (if (org-at-table-hline-p)
9295 (org-table-goto-column col1 t)
9296 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9297 (replace-match "|\\2|\\1|")))
9298 (beginning-of-line 2))
9299 (move-marker end nil)
9300 (goto-line linepos)
9301 (org-table-goto-column colpos)
9302 (org-table-align)
9303 (org-table-fix-formulas
9304 "$" (list (cons (number-to-string col) (number-to-string colpos))
9305 (cons (number-to-string colpos) (number-to-string col))))))
9307 (defun org-table-move-row-down ()
9308 "Move table row down."
9309 (interactive)
9310 (org-table-move-row nil))
9311 (defun org-table-move-row-up ()
9312 "Move table row up."
9313 (interactive)
9314 (org-table-move-row 'up))
9316 (defun org-table-move-row (&optional up)
9317 "Move the current table line down. With arg UP, move it up."
9318 (interactive "P")
9319 (let* ((col (current-column))
9320 (pos (point))
9321 (hline1p (save-excursion (beginning-of-line 1)
9322 (looking-at org-table-hline-regexp)))
9323 (dline1 (org-table-current-dline))
9324 (dline2 (+ dline1 (if up -1 1)))
9325 (tonew (if up 0 2))
9326 txt hline2p)
9327 (beginning-of-line tonew)
9328 (unless (org-at-table-p)
9329 (goto-char pos)
9330 (error "Cannot move row further"))
9331 (setq hline2p (looking-at org-table-hline-regexp))
9332 (goto-char pos)
9333 (beginning-of-line 1)
9334 (setq pos (point))
9335 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9336 (delete-region (point) (1+ (point-at-eol)))
9337 (beginning-of-line tonew)
9338 (insert txt)
9339 (beginning-of-line 0)
9340 (move-to-column col)
9341 (unless (or hline1p hline2p)
9342 (org-table-fix-formulas
9343 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9344 (cons (number-to-string dline2) (number-to-string dline1)))))))
9346 (defun org-table-insert-row (&optional arg)
9347 "Insert a new row above the current line into the table.
9348 With prefix ARG, insert below the current line."
9349 (interactive "P")
9350 (if (not (org-at-table-p))
9351 (error "Not at a table"))
9352 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9353 (new (org-table-clean-line line)))
9354 ;; Fix the first field if necessary
9355 (if (string-match "^[ \t]*| *[#$] *|" line)
9356 (setq new (replace-match (match-string 0 line) t t new)))
9357 (beginning-of-line (if arg 2 1))
9358 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9359 (beginning-of-line 0)
9360 (re-search-forward "| ?" (point-at-eol) t)
9361 (and (or org-table-may-need-update org-table-overlay-coordinates)
9362 (org-table-align))
9363 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9365 (defun org-table-insert-hline (&optional above)
9366 "Insert a horizontal-line below the current line into the table.
9367 With prefix ABOVE, insert above the current line."
9368 (interactive "P")
9369 (if (not (org-at-table-p))
9370 (error "Not at a table"))
9371 (let ((line (org-table-clean-line
9372 (buffer-substring (point-at-bol) (point-at-eol))))
9373 (col (current-column)))
9374 (while (string-match "|\\( +\\)|" line)
9375 (setq line (replace-match
9376 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9377 ?-) "|") t t line)))
9378 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9379 (beginning-of-line (if above 1 2))
9380 (insert line "\n")
9381 (beginning-of-line (if above 1 -1))
9382 (move-to-column col)
9383 (and org-table-overlay-coordinates (org-table-align))))
9385 (defun org-table-hline-and-move (&optional same-column)
9386 "Insert a hline and move to the row below that line."
9387 (interactive "P")
9388 (let ((col (org-table-current-column)))
9389 (org-table-maybe-eval-formula)
9390 (org-table-maybe-recalculate-line)
9391 (org-table-insert-hline)
9392 (end-of-line 2)
9393 (if (looking-at "\n[ \t]*|-")
9394 (progn (insert "\n|") (org-table-align))
9395 (org-table-next-field))
9396 (if same-column (org-table-goto-column col))))
9398 (defun org-table-clean-line (s)
9399 "Convert a table line S into a string with only \"|\" and space.
9400 In particular, this does handle wide and invisible characters."
9401 (if (string-match "^[ \t]*|-" s)
9402 ;; It's a hline, just map the characters
9403 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9404 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9405 (setq s (replace-match
9406 (concat "|" (make-string (org-string-width (match-string 1 s))
9407 ?\ ) "|")
9408 t t s)))
9411 (defun org-table-kill-row ()
9412 "Delete the current row or horizontal line from the table."
9413 (interactive)
9414 (if (not (org-at-table-p))
9415 (error "Not at a table"))
9416 (let ((col (current-column))
9417 (dline (org-table-current-dline)))
9418 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9419 (if (not (org-at-table-p)) (beginning-of-line 0))
9420 (move-to-column col)
9421 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9422 dline -1 dline)))
9424 (defun org-table-sort-lines (with-case &optional sorting-type)
9425 "Sort table lines according to the column at point.
9427 The position of point indicates the column to be used for
9428 sorting, and the range of lines is the range between the nearest
9429 horizontal separator lines, or the entire table of no such lines
9430 exist. If point is before the first column, you will be prompted
9431 for the sorting column. If there is an active region, the mark
9432 specifies the first line and the sorting column, while point
9433 should be in the last line to be included into the sorting.
9435 The command then prompts for the sorting type which can be
9436 alphabetically, numerically, or by time (as given in a time stamp
9437 in the field). Sorting in reverse order is also possible.
9439 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9441 If SORTING-TYPE is specified when this function is called from a Lisp
9442 program, no prompting will take place. SORTING-TYPE must be a character,
9443 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9444 should be done in reverse order."
9445 (interactive "P")
9446 (let* ((thisline (org-current-line))
9447 (thiscol (org-table-current-column))
9448 beg end bcol ecol tend tbeg column lns pos)
9449 (when (equal thiscol 0)
9450 (if (interactive-p)
9451 (setq thiscol
9452 (string-to-number
9453 (read-string "Use column N for sorting: ")))
9454 (setq thiscol 1))
9455 (org-table-goto-column thiscol))
9456 (org-table-check-inside-data-field)
9457 (if (org-region-active-p)
9458 (progn
9459 (setq beg (region-beginning) end (region-end))
9460 (goto-char beg)
9461 (setq column (org-table-current-column)
9462 beg (point-at-bol))
9463 (goto-char end)
9464 (setq end (point-at-bol 2)))
9465 (setq column (org-table-current-column)
9466 pos (point)
9467 tbeg (org-table-begin)
9468 tend (org-table-end))
9469 (if (re-search-backward org-table-hline-regexp tbeg t)
9470 (setq beg (point-at-bol 2))
9471 (goto-char tbeg)
9472 (setq beg (point-at-bol 1)))
9473 (goto-char pos)
9474 (if (re-search-forward org-table-hline-regexp tend t)
9475 (setq end (point-at-bol 1))
9476 (goto-char tend)
9477 (setq end (point-at-bol))))
9478 (setq beg (move-marker (make-marker) beg)
9479 end (move-marker (make-marker) end))
9480 (untabify beg end)
9481 (goto-char beg)
9482 (org-table-goto-column column)
9483 (skip-chars-backward "^|")
9484 (setq bcol (current-column))
9485 (org-table-goto-column (1+ column))
9486 (skip-chars-backward "^|")
9487 (setq ecol (1- (current-column)))
9488 (org-table-goto-column column)
9489 (setq lns (mapcar (lambda(x) (cons
9490 (org-sort-remove-invisible
9491 (nth (1- column)
9492 (org-split-string x "[ \t]*|[ \t]*")))
9494 (org-split-string (buffer-substring beg end) "\n")))
9495 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9496 (delete-region beg end)
9497 (move-marker beg nil)
9498 (move-marker end nil)
9499 (insert (mapconcat 'cdr lns "\n") "\n")
9500 (goto-line thisline)
9501 (org-table-goto-column thiscol)
9502 (message "%d lines sorted, based on column %d" (length lns) column)))
9504 ;; FIXME: maybe we will not need this? Table sorting is broken....
9505 (defun org-sort-remove-invisible (s)
9506 (remove-text-properties 0 (length s) org-rm-props s)
9507 (while (string-match org-bracket-link-regexp s)
9508 (setq s (replace-match (if (match-end 2)
9509 (match-string 3 s)
9510 (match-string 1 s)) t t s)))
9513 (defun org-table-cut-region (beg end)
9514 "Copy region in table to the clipboard and blank all relevant fields."
9515 (interactive "r")
9516 (org-table-copy-region beg end 'cut))
9518 (defun org-table-copy-region (beg end &optional cut)
9519 "Copy rectangular region in table to clipboard.
9520 A special clipboard is used which can only be accessed
9521 with `org-table-paste-rectangle'."
9522 (interactive "rP")
9523 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9524 region cols
9525 (rpl (if cut " " nil)))
9526 (goto-char beg)
9527 (org-table-check-inside-data-field)
9528 (setq l01 (org-current-line)
9529 c01 (org-table-current-column))
9530 (goto-char end)
9531 (org-table-check-inside-data-field)
9532 (setq l02 (org-current-line)
9533 c02 (org-table-current-column))
9534 (setq l1 (min l01 l02) l2 (max l01 l02)
9535 c1 (min c01 c02) c2 (max c01 c02))
9536 (catch 'exit
9537 (while t
9538 (catch 'nextline
9539 (if (> l1 l2) (throw 'exit t))
9540 (goto-line l1)
9541 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9542 (setq cols nil ic1 c1 ic2 c2)
9543 (while (< ic1 (1+ ic2))
9544 (push (org-table-get-field ic1 rpl) cols)
9545 (setq ic1 (1+ ic1)))
9546 (push (nreverse cols) region)
9547 (setq l1 (1+ l1)))))
9548 (setq org-table-clip (nreverse region))
9549 (if cut (org-table-align))
9550 org-table-clip))
9552 (defun org-table-paste-rectangle ()
9553 "Paste a rectangular region into a table.
9554 The upper right corner ends up in the current field. All involved fields
9555 will be overwritten. If the rectangle does not fit into the present table,
9556 the table is enlarged as needed. The process ignores horizontal separator
9557 lines."
9558 (interactive)
9559 (unless (and org-table-clip (listp org-table-clip))
9560 (error "First cut/copy a region to paste!"))
9561 (org-table-check-inside-data-field)
9562 (let* ((clip org-table-clip)
9563 (line (org-current-line))
9564 (col (org-table-current-column))
9565 (org-enable-table-editor t)
9566 (org-table-automatic-realign nil)
9567 c cols field)
9568 (while (setq cols (pop clip))
9569 (while (org-at-table-hline-p) (beginning-of-line 2))
9570 (if (not (org-at-table-p))
9571 (progn (end-of-line 0) (org-table-next-field)))
9572 (setq c col)
9573 (while (setq field (pop cols))
9574 (org-table-goto-column c nil 'force)
9575 (org-table-get-field nil field)
9576 (setq c (1+ c)))
9577 (beginning-of-line 2))
9578 (goto-line line)
9579 (org-table-goto-column col)
9580 (org-table-align)))
9582 (defun org-table-convert ()
9583 "Convert from `org-mode' table to table.el and back.
9584 Obviously, this only works within limits. When an Org-mode table is
9585 converted to table.el, all horizontal separator lines get lost, because
9586 table.el uses these as cell boundaries and has no notion of horizontal lines.
9587 A table.el table can be converted to an Org-mode table only if it does not
9588 do row or column spanning. Multiline cells will become multiple cells.
9589 Beware, Org-mode does not test if the table can be successfully converted - it
9590 blindly applies a recipe that works for simple tables."
9591 (interactive)
9592 (require 'table)
9593 (if (org-at-table.el-p)
9594 ;; convert to Org-mode table
9595 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9596 (end (move-marker (make-marker) (org-table-end t))))
9597 (table-unrecognize-region beg end)
9598 (goto-char beg)
9599 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9600 (replace-match ""))
9601 (goto-char beg))
9602 (if (org-at-table-p)
9603 ;; convert to table.el table
9604 (let ((beg (move-marker (make-marker) (org-table-begin)))
9605 (end (move-marker (make-marker) (org-table-end))))
9606 ;; first, get rid of all horizontal lines
9607 (goto-char beg)
9608 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9609 (replace-match ""))
9610 ;; insert a hline before first
9611 (goto-char beg)
9612 (org-table-insert-hline 'above)
9613 (beginning-of-line -1)
9614 ;; insert a hline after each line
9615 (while (progn (beginning-of-line 3) (< (point) end))
9616 (org-table-insert-hline))
9617 (goto-char beg)
9618 (setq end (move-marker end (org-table-end)))
9619 ;; replace "+" at beginning and ending of hlines
9620 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9621 (replace-match "\\1+-"))
9622 (goto-char beg)
9623 (while (re-search-forward "-|[ \t]*$" end t)
9624 (replace-match "-+"))
9625 (goto-char beg)))))
9627 (defun org-table-wrap-region (arg)
9628 "Wrap several fields in a column like a paragraph.
9629 This is useful if you'd like to spread the contents of a field over several
9630 lines, in order to keep the table compact.
9632 If there is an active region, and both point and mark are in the same column,
9633 the text in the column is wrapped to minimum width for the given number of
9634 lines. Generally, this makes the table more compact. A prefix ARG may be
9635 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9636 formats the selected text to two lines. If the region was longer than two
9637 lines, the remaining lines remain empty. A negative prefix argument reduces
9638 the current number of lines by that amount. The wrapped text is pasted back
9639 into the table. If you formatted it to more lines than it was before, fields
9640 further down in the table get overwritten - so you might need to make space in
9641 the table first.
9643 If there is no region, the current field is split at the cursor position and
9644 the text fragment to the right of the cursor is prepended to the field one
9645 line down.
9647 If there is no region, but you specify a prefix ARG, the current field gets
9648 blank, and the content is appended to the field above."
9649 (interactive "P")
9650 (org-table-check-inside-data-field)
9651 (if (org-region-active-p)
9652 ;; There is a region: fill as a paragraph
9653 (let* ((beg (region-beginning))
9654 (cline (save-excursion (goto-char beg) (org-current-line)))
9655 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9656 nlines)
9657 (org-table-cut-region (region-beginning) (region-end))
9658 (if (> (length (car org-table-clip)) 1)
9659 (error "Region must be limited to single column"))
9660 (setq nlines (if arg
9661 (if (< arg 1)
9662 (+ (length org-table-clip) arg)
9663 arg)
9664 (length org-table-clip)))
9665 (setq org-table-clip
9666 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9667 nil nlines)))
9668 (goto-line cline)
9669 (org-table-goto-column ccol)
9670 (org-table-paste-rectangle))
9671 ;; No region, split the current field at point
9672 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
9673 (skip-chars-forward "^\r\n|"))
9674 (if arg
9675 ;; combine with field above
9676 (let ((s (org-table-blank-field))
9677 (col (org-table-current-column)))
9678 (beginning-of-line 0)
9679 (while (org-at-table-hline-p) (beginning-of-line 0))
9680 (org-table-goto-column col)
9681 (skip-chars-forward "^|")
9682 (skip-chars-backward " ")
9683 (insert " " (org-trim s))
9684 (org-table-align))
9685 ;; split field
9686 (if (looking-at "\\([^|]+\\)+|")
9687 (let ((s (match-string 1)))
9688 (replace-match " |")
9689 (goto-char (match-beginning 0))
9690 (org-table-next-row)
9691 (insert (org-trim s) " ")
9692 (org-table-align))
9693 (org-table-next-row)))))
9695 (defvar org-field-marker nil)
9697 (defun org-table-edit-field (arg)
9698 "Edit table field in a different window.
9699 This is mainly useful for fields that contain hidden parts.
9700 When called with a \\[universal-argument] prefix, just make the full field visible so that
9701 it can be edited in place."
9702 (interactive "P")
9703 (if arg
9704 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9705 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9706 (remove-text-properties b e '(org-cwidth t invisible t
9707 display t intangible t))
9708 (if (and (boundp 'font-lock-mode) font-lock-mode)
9709 (font-lock-fontify-block)))
9710 (let ((pos (move-marker (make-marker) (point)))
9711 (field (org-table-get-field))
9712 (cw (current-window-configuration))
9714 (org-switch-to-buffer-other-window "*Org tmp*")
9715 (erase-buffer)
9716 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9717 (let ((org-inhibit-startup t)) (org-mode))
9718 (goto-char (setq p (point-max)))
9719 (insert (org-trim field))
9720 (remove-text-properties p (point-max)
9721 '(invisible t org-cwidth t display t
9722 intangible t))
9723 (goto-char p)
9724 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9725 (org-set-local 'org-window-configuration cw)
9726 (org-set-local 'org-field-marker pos)
9727 (message "Edit and finish with C-c C-c"))))
9729 (defun org-table-finish-edit-field ()
9730 "Finish editing a table data field.
9731 Remove all newline characters, insert the result into the table, realign
9732 the table and kill the editing buffer."
9733 (let ((pos org-field-marker)
9734 (cw org-window-configuration)
9735 (cb (current-buffer))
9736 text)
9737 (goto-char (point-min))
9738 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9739 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9740 (replace-match " "))
9741 (setq text (org-trim (buffer-string)))
9742 (set-window-configuration cw)
9743 (kill-buffer cb)
9744 (select-window (get-buffer-window (marker-buffer pos)))
9745 (goto-char pos)
9746 (move-marker pos nil)
9747 (org-table-check-inside-data-field)
9748 (org-table-get-field nil text)
9749 (org-table-align)
9750 (message "New field value inserted")))
9752 (defun org-trim (s)
9753 "Remove whitespace at beginning and end of string."
9754 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9755 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9758 (defun org-wrap (string &optional width lines)
9759 "Wrap string to either a number of lines, or a width in characters.
9760 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9761 that costs. If there is a word longer than WIDTH, the text is actually
9762 wrapped to the length of that word.
9763 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9764 many lines, whatever width that takes.
9765 The return value is a list of lines, without newlines at the end."
9766 (let* ((words (org-split-string string "[ \t\n]+"))
9767 (maxword (apply 'max (mapcar 'org-string-width words)))
9768 w ll)
9769 (cond (width
9770 (org-do-wrap words (max maxword width)))
9771 (lines
9772 (setq w maxword)
9773 (setq ll (org-do-wrap words maxword))
9774 (if (<= (length ll) lines)
9776 (setq ll words)
9777 (while (> (length ll) lines)
9778 (setq w (1+ w))
9779 (setq ll (org-do-wrap words w)))
9780 ll))
9781 (t (error "Cannot wrap this")))))
9784 (defun org-do-wrap (words width)
9785 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9786 (let (lines line)
9787 (while words
9788 (setq line (pop words))
9789 (while (and words (< (+ (length line) (length (car words))) width))
9790 (setq line (concat line " " (pop words))))
9791 (setq lines (push line lines)))
9792 (nreverse lines)))
9794 (defun org-split-string (string &optional separators)
9795 "Splits STRING into substrings at SEPARATORS.
9796 No empty strings are returned if there are matches at the beginning
9797 and end of string."
9798 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9799 (start 0)
9800 notfirst
9801 (list nil))
9802 (while (and (string-match rexp string
9803 (if (and notfirst
9804 (= start (match-beginning 0))
9805 (< start (length string)))
9806 (1+ start) start))
9807 (< (match-beginning 0) (length string)))
9808 (setq notfirst t)
9809 (or (eq (match-beginning 0) 0)
9810 (and (eq (match-beginning 0) (match-end 0))
9811 (eq (match-beginning 0) start))
9812 (setq list
9813 (cons (substring string start (match-beginning 0))
9814 list)))
9815 (setq start (match-end 0)))
9816 (or (eq start (length string))
9817 (setq list
9818 (cons (substring string start)
9819 list)))
9820 (nreverse list)))
9822 (defun org-table-map-tables (function)
9823 "Apply FUNCTION to the start of all tables in the buffer."
9824 (save-excursion
9825 (save-restriction
9826 (widen)
9827 (goto-char (point-min))
9828 (while (re-search-forward org-table-any-line-regexp nil t)
9829 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9830 (beginning-of-line 1)
9831 (if (looking-at org-table-line-regexp)
9832 (save-excursion (funcall function)))
9833 (re-search-forward org-table-any-border-regexp nil 1))))
9834 (message "Mapping tables: done"))
9836 (defvar org-timecnt) ; dynamically scoped parameter
9838 (defun org-table-sum (&optional beg end nlast)
9839 "Sum numbers in region of current table column.
9840 The result will be displayed in the echo area, and will be available
9841 as kill to be inserted with \\[yank].
9843 If there is an active region, it is interpreted as a rectangle and all
9844 numbers in that rectangle will be summed. If there is no active
9845 region and point is located in a table column, sum all numbers in that
9846 column.
9848 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9849 numbers are assumed to be times as well (in decimal hours) and the
9850 numbers are added as such.
9852 If NLAST is a number, only the NLAST fields will actually be summed."
9853 (interactive)
9854 (save-excursion
9855 (let (col (org-timecnt 0) diff h m s org-table-clip)
9856 (cond
9857 ((and beg end)) ; beg and end given explicitly
9858 ((org-region-active-p)
9859 (setq beg (region-beginning) end (region-end)))
9861 (setq col (org-table-current-column))
9862 (goto-char (org-table-begin))
9863 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9864 (error "No table data"))
9865 (org-table-goto-column col)
9866 (setq beg (point))
9867 (goto-char (org-table-end))
9868 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9869 (error "No table data"))
9870 (org-table-goto-column col)
9871 (setq end (point))))
9872 (let* ((items (apply 'append (org-table-copy-region beg end)))
9873 (items1 (cond ((not nlast) items)
9874 ((>= nlast (length items)) items)
9875 (t (setq items (reverse items))
9876 (setcdr (nthcdr (1- nlast) items) nil)
9877 (nreverse items))))
9878 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9879 items1)))
9880 (res (apply '+ numbers))
9881 (sres (if (= org-timecnt 0)
9882 (format "%g" res)
9883 (setq diff (* 3600 res)
9884 h (floor (/ diff 3600)) diff (mod diff 3600)
9885 m (floor (/ diff 60)) diff (mod diff 60)
9886 s diff)
9887 (format "%d:%02d:%02d" h m s))))
9888 (kill-new sres)
9889 (if (interactive-p)
9890 (message "%s"
9891 (substitute-command-keys
9892 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9893 (length numbers) sres))))
9894 sres))))
9896 (defun org-table-get-number-for-summing (s)
9897 (let (n)
9898 (if (string-match "^ *|? *" s)
9899 (setq s (replace-match "" nil nil s)))
9900 (if (string-match " *|? *$" s)
9901 (setq s (replace-match "" nil nil s)))
9902 (setq n (string-to-number s))
9903 (cond
9904 ((and (string-match "0" s)
9905 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9906 ((string-match "\\`[ \t]+\\'" s) nil)
9907 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9908 (let ((h (string-to-number (or (match-string 1 s) "0")))
9909 (m (string-to-number (or (match-string 2 s) "0")))
9910 (s (string-to-number (or (match-string 4 s) "0"))))
9911 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9912 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9913 ((equal n 0) nil)
9914 (t n))))
9916 (defun org-table-current-field-formula (&optional key noerror)
9917 "Return the formula active for the current field.
9918 Assumes that specials are in place.
9919 If KEY is given, return the key to this formula.
9920 Otherwise return the formula preceeded with \"=\" or \":=\"."
9921 (let* ((name (car (rassoc (list (org-current-line)
9922 (org-table-current-column))
9923 org-table-named-field-locations)))
9924 (col (org-table-current-column))
9925 (scol (int-to-string col))
9926 (ref (format "@%d$%d" (org-table-current-dline) col))
9927 (stored-list (org-table-get-stored-formulas noerror))
9928 (ass (or (assoc name stored-list)
9929 (assoc ref stored-list)
9930 (assoc scol stored-list))))
9931 (if key
9932 (car ass)
9933 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9934 (cdr ass))))))
9936 (defun org-table-get-formula (&optional equation named)
9937 "Read a formula from the minibuffer, offer stored formula as default.
9938 When NAMED is non-nil, look for a named equation."
9939 (let* ((stored-list (org-table-get-stored-formulas))
9940 (name (car (rassoc (list (org-current-line)
9941 (org-table-current-column))
9942 org-table-named-field-locations)))
9943 (ref (format "@%d$%d" (org-table-current-dline)
9944 (org-table-current-column)))
9945 (refass (assoc ref stored-list))
9946 (scol (if named
9947 (if name name ref)
9948 (int-to-string (org-table-current-column))))
9949 (dummy (and (or name refass) (not named)
9950 (not (y-or-n-p "Replace field formula with column formula? " ))
9951 (error "Abort")))
9952 (name (or name ref))
9953 (org-table-may-need-update nil)
9954 (stored (cdr (assoc scol stored-list)))
9955 (eq (cond
9956 ((and stored equation (string-match "^ *=? *$" equation))
9957 stored)
9958 ((stringp equation)
9959 equation)
9960 (t (org-table-formula-from-user
9961 (read-string
9962 (org-table-formula-to-user
9963 (format "%s formula %s%s="
9964 (if named "Field" "Column")
9965 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9966 scol))
9967 (if stored (org-table-formula-to-user stored) "")
9968 'org-table-formula-history
9969 )))))
9970 mustsave)
9971 (when (not (string-match "\\S-" eq))
9972 ;; remove formula
9973 (setq stored-list (delq (assoc scol stored-list) stored-list))
9974 (org-table-store-formulas stored-list)
9975 (error "Formula removed"))
9976 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9977 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9978 (if (and name (not named))
9979 ;; We set the column equation, delete the named one.
9980 (setq stored-list (delq (assoc name stored-list) stored-list)
9981 mustsave t))
9982 (if stored
9983 (setcdr (assoc scol stored-list) eq)
9984 (setq stored-list (cons (cons scol eq) stored-list)))
9985 (if (or mustsave (not (equal stored eq)))
9986 (org-table-store-formulas stored-list))
9987 eq))
9989 (defun org-table-store-formulas (alist)
9990 "Store the list of formulas below the current table."
9991 (setq alist (sort alist 'org-table-formula-less-p))
9992 (save-excursion
9993 (goto-char (org-table-end))
9994 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9995 (progn
9996 ;; don't overwrite TBLFM, we might use text properties to store stuff
9997 (goto-char (match-beginning 2))
9998 (delete-region (match-beginning 2) (match-end 0)))
9999 (insert "#+TBLFM:"))
10000 (insert " "
10001 (mapconcat (lambda (x)
10002 (concat
10003 (if (equal (string-to-char (car x)) ?@) "" "$")
10004 (car x) "=" (cdr x)))
10005 alist "::")
10006 "\n")))
10008 (defsubst org-table-formula-make-cmp-string (a)
10009 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
10010 (concat
10011 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
10012 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
10013 (if (match-end 5) (concat "@@" (match-string 5 a))))))
10015 (defun org-table-formula-less-p (a b)
10016 "Compare two formulas for sorting."
10017 (let ((as (org-table-formula-make-cmp-string (car a)))
10018 (bs (org-table-formula-make-cmp-string (car b))))
10019 (and as bs (string< as bs))))
10021 (defun org-table-get-stored-formulas (&optional noerror)
10022 "Return an alist with the stored formulas directly after current table."
10023 (interactive)
10024 (let (scol eq eq-alist strings string seen)
10025 (save-excursion
10026 (goto-char (org-table-end))
10027 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
10028 (setq strings (org-split-string (match-string 2) " *:: *"))
10029 (while (setq string (pop strings))
10030 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
10031 (setq scol (if (match-end 2)
10032 (match-string 2 string)
10033 (match-string 1 string))
10034 eq (match-string 3 string)
10035 eq-alist (cons (cons scol eq) eq-alist))
10036 (if (member scol seen)
10037 (if noerror
10038 (progn
10039 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
10040 (ding)
10041 (sit-for 2))
10042 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
10043 (push scol seen))))))
10044 (nreverse eq-alist)))
10046 (defun org-table-fix-formulas (key replace &optional limit delta remove)
10047 "Modify the equations after the table structure has been edited.
10048 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
10049 For all numbers larger than LIMIT, shift them by DELTA."
10050 (save-excursion
10051 (goto-char (org-table-end))
10052 (when (looking-at "#\\+TBLFM:")
10053 (let ((re (concat key "\\([0-9]+\\)"))
10054 (re2
10055 (when remove
10056 (if (equal key "$")
10057 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
10058 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
10059 s n a)
10060 (when remove
10061 (while (re-search-forward re2 (point-at-eol) t)
10062 (replace-match "")))
10063 (while (re-search-forward re (point-at-eol) t)
10064 (setq s (match-string 1) n (string-to-number s))
10065 (cond
10066 ((setq a (assoc s replace))
10067 (replace-match (concat key (cdr a)) t t))
10068 ((and limit (> n limit))
10069 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
10071 (defun org-table-get-specials ()
10072 "Get the column names and local parameters for this table."
10073 (save-excursion
10074 (let ((beg (org-table-begin)) (end (org-table-end))
10075 names name fields fields1 field cnt
10076 c v l line col types dlines hlines)
10077 (setq org-table-column-names nil
10078 org-table-local-parameters nil
10079 org-table-named-field-locations nil
10080 org-table-current-begin-line nil
10081 org-table-current-begin-pos nil
10082 org-table-current-line-types nil)
10083 (goto-char beg)
10084 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
10085 (setq names (org-split-string (match-string 1) " *| *")
10086 cnt 1)
10087 (while (setq name (pop names))
10088 (setq cnt (1+ cnt))
10089 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
10090 (push (cons name (int-to-string cnt)) org-table-column-names))))
10091 (setq org-table-column-names (nreverse org-table-column-names))
10092 (setq org-table-column-name-regexp
10093 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
10094 (goto-char beg)
10095 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
10096 (setq fields (org-split-string (match-string 1) " *| *"))
10097 (while (setq field (pop fields))
10098 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
10099 (push (cons (match-string 1 field) (match-string 2 field))
10100 org-table-local-parameters))))
10101 (goto-char beg)
10102 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10103 (setq c (match-string 1)
10104 fields (org-split-string (match-string 2) " *| *"))
10105 (save-excursion
10106 (beginning-of-line (if (equal c "_") 2 0))
10107 (setq line (org-current-line) col 1)
10108 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10109 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10110 (while (and fields1 (setq field (pop fields)))
10111 (setq v (pop fields1) col (1+ col))
10112 (when (and (stringp field) (stringp v)
10113 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10114 (push (cons field v) org-table-local-parameters)
10115 (push (list field line col) org-table-named-field-locations))))
10116 ;; Analyse the line types
10117 (goto-char beg)
10118 (setq org-table-current-begin-line (org-current-line)
10119 org-table-current-begin-pos (point)
10120 l org-table-current-begin-line)
10121 (while (looking-at "[ \t]*|\\(-\\)?")
10122 (push (if (match-end 1) 'hline 'dline) types)
10123 (if (match-end 1) (push l hlines) (push l dlines))
10124 (beginning-of-line 2)
10125 (setq l (1+ l)))
10126 (setq org-table-current-line-types (apply 'vector (nreverse types))
10127 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
10128 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
10130 (defun org-table-maybe-eval-formula ()
10131 "Check if the current field starts with \"=\" or \":=\".
10132 If yes, store the formula and apply it."
10133 ;; We already know we are in a table. Get field will only return a formula
10134 ;; when appropriate. It might return a separator line, but no problem.
10135 (when org-table-formula-evaluate-inline
10136 (let* ((field (org-trim (or (org-table-get-field) "")))
10137 named eq)
10138 (when (string-match "^:?=\\(.*\\)" field)
10139 (setq named (equal (string-to-char field) ?:)
10140 eq (match-string 1 field))
10141 (if (or (fboundp 'calc-eval)
10142 (equal (substring eq 0 (min 2 (length eq))) "'("))
10143 (org-table-eval-formula (if named '(4) nil)
10144 (org-table-formula-from-user eq))
10145 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
10147 (defvar org-recalc-commands nil
10148 "List of commands triggering the recalculation of a line.
10149 Will be filled automatically during use.")
10151 (defvar org-recalc-marks
10152 '((" " . "Unmarked: no special line, no automatic recalculation")
10153 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10154 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10155 ("!" . "Column name definition line. Reference in formula as $name.")
10156 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10157 ("_" . "Names for values in row below this one.")
10158 ("^" . "Names for values in row above this one.")))
10160 (defun org-table-rotate-recalc-marks (&optional newchar)
10161 "Rotate the recalculation mark in the first column.
10162 If in any row, the first field is not consistent with a mark,
10163 insert a new column for the markers.
10164 When there is an active region, change all the lines in the region,
10165 after prompting for the marking character.
10166 After each change, a message will be displayed indicating the meaning
10167 of the new mark."
10168 (interactive)
10169 (unless (org-at-table-p) (error "Not at a table"))
10170 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10171 (beg (org-table-begin))
10172 (end (org-table-end))
10173 (l (org-current-line))
10174 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10175 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10176 (have-col
10177 (save-excursion
10178 (goto-char beg)
10179 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10180 (col (org-table-current-column))
10181 (forcenew (car (assoc newchar org-recalc-marks)))
10182 epos new)
10183 (when l1
10184 (message "Change region to what mark? Type # * ! $ or SPC: ")
10185 (setq newchar (char-to-string (read-char-exclusive))
10186 forcenew (car (assoc newchar org-recalc-marks))))
10187 (if (and newchar (not forcenew))
10188 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10189 newchar))
10190 (if l1 (goto-line l1))
10191 (save-excursion
10192 (beginning-of-line 1)
10193 (unless (looking-at org-table-dataline-regexp)
10194 (error "Not at a table data line")))
10195 (unless have-col
10196 (org-table-goto-column 1)
10197 (org-table-insert-column)
10198 (org-table-goto-column (1+ col)))
10199 (setq epos (point-at-eol))
10200 (save-excursion
10201 (beginning-of-line 1)
10202 (org-table-get-field
10203 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10204 (concat " "
10205 (setq new (or forcenew
10206 (cadr (member (match-string 1) marks))))
10207 " ")
10208 " # ")))
10209 (if (and l1 l2)
10210 (progn
10211 (goto-line l1)
10212 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10213 (and (looking-at org-table-dataline-regexp)
10214 (org-table-get-field 1 (concat " " new " "))))
10215 (goto-line l1)))
10216 (if (not (= epos (point-at-eol))) (org-table-align))
10217 (goto-line l)
10218 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
10220 (defun org-table-maybe-recalculate-line ()
10221 "Recompute the current line if marked for it, and if we haven't just done it."
10222 (interactive)
10223 (and org-table-allow-automatic-line-recalculation
10224 (not (and (memq last-command org-recalc-commands)
10225 (equal org-last-recalc-line (org-current-line))))
10226 (save-excursion (beginning-of-line 1)
10227 (looking-at org-table-auto-recalculate-regexp))
10228 (org-table-recalculate) t))
10230 (defvar org-table-formula-debug nil
10231 "Non-nil means, debug table formulas.
10232 When nil, simply write \"#ERROR\" in corrupted fields.")
10233 (make-variable-buffer-local 'org-table-formula-debug)
10235 (defvar modes)
10236 (defsubst org-set-calc-mode (var &optional value)
10237 (if (stringp var)
10238 (setq var (assoc var '(("D" calc-angle-mode deg)
10239 ("R" calc-angle-mode rad)
10240 ("F" calc-prefer-frac t)
10241 ("S" calc-symbolic-mode t)))
10242 value (nth 2 var) var (nth 1 var)))
10243 (if (memq var modes)
10244 (setcar (cdr (memq var modes)) value)
10245 (cons var (cons value modes)))
10246 modes)
10248 (defun org-table-eval-formula (&optional arg equation
10249 suppress-align suppress-const
10250 suppress-store suppress-analysis)
10251 "Replace the table field value at the cursor by the result of a calculation.
10253 This function makes use of Dave Gillespie's Calc package, in my view the
10254 most exciting program ever written for GNU Emacs. So you need to have Calc
10255 installed in order to use this function.
10257 In a table, this command replaces the value in the current field with the
10258 result of a formula. It also installs the formula as the \"current\" column
10259 formula, by storing it in a special line below the table. When called
10260 with a `C-u' prefix, the current field must ba a named field, and the
10261 formula is installed as valid in only this specific field.
10263 When called with two `C-u' prefixes, insert the active equation
10264 for the field back into the current field, so that it can be
10265 edited there. This is useful in order to use \\[org-table-show-reference]
10266 to check the referenced fields.
10268 When called, the command first prompts for a formula, which is read in
10269 the minibuffer. Previously entered formulas are available through the
10270 history list, and the last used formula is offered as a default.
10271 These stored formulas are adapted correctly when moving, inserting, or
10272 deleting columns with the corresponding commands.
10274 The formula can be any algebraic expression understood by the Calc package.
10275 For details, see the Org-mode manual.
10277 This function can also be called from Lisp programs and offers
10278 additional arguments: EQUATION can be the formula to apply. If this
10279 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10280 used to speed-up recursive calls by by-passing unnecessary aligns.
10281 SUPPRESS-CONST suppresses the interpretation of constants in the
10282 formula, assuming that this has been done already outside the function.
10283 SUPPRESS-STORE means the formula should not be stored, either because
10284 it is already stored, or because it is a modified equation that should
10285 not overwrite the stored one."
10286 (interactive "P")
10287 (org-table-check-inside-data-field)
10288 (or suppress-analysis (org-table-get-specials))
10289 (if (equal arg '(16))
10290 (let ((eq (org-table-current-field-formula)))
10291 (or eq (error "No equation active for current field"))
10292 (org-table-get-field nil eq)
10293 (org-table-align)
10294 (setq org-table-may-need-update t))
10295 (let* (fields
10296 (ndown (if (integerp arg) arg 1))
10297 (org-table-automatic-realign nil)
10298 (case-fold-search nil)
10299 (down (> ndown 1))
10300 (formula (if (and equation suppress-store)
10301 equation
10302 (org-table-get-formula equation (equal arg '(4)))))
10303 (n0 (org-table-current-column))
10304 (modes (copy-sequence org-calc-default-modes))
10305 (numbers nil) ; was a variable, now fixed default
10306 (keep-empty nil)
10307 n form form0 bw fmt x ev orig c lispp literal)
10308 ;; Parse the format string. Since we have a lot of modes, this is
10309 ;; a lot of work. However, I think calc still uses most of the time.
10310 (if (string-match ";" formula)
10311 (let ((tmp (org-split-string formula ";")))
10312 (setq formula (car tmp)
10313 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10314 (nth 1 tmp)))
10315 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10316 (setq c (string-to-char (match-string 1 fmt))
10317 n (string-to-number (match-string 2 fmt)))
10318 (if (= c ?p)
10319 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10320 (setq modes (org-set-calc-mode
10321 'calc-float-format
10322 (list (cdr (assoc c '((?n . float) (?f . fix)
10323 (?s . sci) (?e . eng))))
10324 n))))
10325 (setq fmt (replace-match "" t t fmt)))
10326 (if (string-match "[NT]" fmt)
10327 (setq numbers (equal (match-string 0 fmt) "N")
10328 fmt (replace-match "" t t fmt)))
10329 (if (string-match "L" fmt)
10330 (setq literal t
10331 fmt (replace-match "" t t fmt)))
10332 (if (string-match "E" fmt)
10333 (setq keep-empty t
10334 fmt (replace-match "" t t fmt)))
10335 (while (string-match "[DRFS]" fmt)
10336 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10337 (setq fmt (replace-match "" t t fmt)))
10338 (unless (string-match "\\S-" fmt)
10339 (setq fmt nil))))
10340 (if (and (not suppress-const) org-table-formula-use-constants)
10341 (setq formula (org-table-formula-substitute-names formula)))
10342 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10343 (while (> ndown 0)
10344 (setq fields (org-split-string
10345 (org-no-properties
10346 (buffer-substring (point-at-bol) (point-at-eol)))
10347 " *| *"))
10348 (if (eq numbers t)
10349 (setq fields (mapcar
10350 (lambda (x) (number-to-string (string-to-number x)))
10351 fields)))
10352 (setq ndown (1- ndown))
10353 (setq form (copy-sequence formula)
10354 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10355 (if (and lispp literal) (setq lispp 'literal))
10356 ;; Check for old vertical references
10357 (setq form (org-rewrite-old-row-references form))
10358 ;; Insert complex ranges
10359 (while (string-match org-table-range-regexp form)
10360 (setq form
10361 (replace-match
10362 (save-match-data
10363 (org-table-make-reference
10364 (org-table-get-range (match-string 0 form) nil n0)
10365 keep-empty numbers lispp))
10366 t t form)))
10367 ;; Insert simple ranges
10368 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10369 (setq form
10370 (replace-match
10371 (save-match-data
10372 (org-table-make-reference
10373 (org-sublist
10374 fields (string-to-number (match-string 1 form))
10375 (string-to-number (match-string 2 form)))
10376 keep-empty numbers lispp))
10377 t t form)))
10378 (setq form0 form)
10379 ;; Insert the references to fields in same row
10380 (while (string-match "\\$\\([0-9]+\\)" form)
10381 (setq n (string-to-number (match-string 1 form))
10382 x (nth (1- (if (= n 0) n0 n)) fields))
10383 (unless x (error "Invalid field specifier \"%s\""
10384 (match-string 0 form)))
10385 (setq form (replace-match
10386 (save-match-data
10387 (org-table-make-reference x nil numbers lispp))
10388 t t form)))
10390 (if lispp
10391 (setq ev (condition-case nil
10392 (eval (eval (read form)))
10393 (error "#ERROR"))
10394 ev (if (numberp ev) (number-to-string ev) ev))
10395 (or (fboundp 'calc-eval)
10396 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10397 (setq ev (calc-eval (cons form modes)
10398 (if numbers 'num))))
10400 (when org-table-formula-debug
10401 (with-output-to-temp-buffer "*Substitution History*"
10402 (princ (format "Substitution history of formula
10403 Orig: %s
10404 $xyz-> %s
10405 @r$c-> %s
10406 $1-> %s\n" orig formula form0 form))
10407 (if (listp ev)
10408 (princ (format " %s^\nError: %s"
10409 (make-string (car ev) ?\-) (nth 1 ev)))
10410 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10411 ev (or fmt "NONE")
10412 (if fmt (format fmt (string-to-number ev)) ev)))))
10413 (setq bw (get-buffer-window "*Substitution History*"))
10414 (shrink-window-if-larger-than-buffer bw)
10415 (unless (and (interactive-p) (not ndown))
10416 (unless (let (inhibit-redisplay)
10417 (y-or-n-p "Debugging Formula. Continue to next? "))
10418 (org-table-align)
10419 (error "Abort"))
10420 (delete-window bw)
10421 (message "")))
10422 (if (listp ev) (setq fmt nil ev "#ERROR"))
10423 (org-table-justify-field-maybe
10424 (if fmt (format fmt (string-to-number ev)) ev))
10425 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10426 (call-interactively 'org-return)
10427 (setq ndown 0)))
10428 (and down (org-table-maybe-recalculate-line))
10429 (or suppress-align (and org-table-may-need-update
10430 (org-table-align))))))
10432 (defun org-table-put-field-property (prop value)
10433 (save-excursion
10434 (put-text-property (progn (skip-chars-backward "^|") (point))
10435 (progn (skip-chars-forward "^|") (point))
10436 prop value)))
10438 (defun org-table-get-range (desc &optional tbeg col highlight)
10439 "Get a calc vector from a column, accorting to descriptor DESC.
10440 Optional arguments TBEG and COL can give the beginning of the table and
10441 the current column, to avoid unnecessary parsing.
10442 HIGHLIGHT means, just highlight the range."
10443 (if (not (equal (string-to-char desc) ?@))
10444 (setq desc (concat "@" desc)))
10445 (save-excursion
10446 (or tbeg (setq tbeg (org-table-begin)))
10447 (or col (setq col (org-table-current-column)))
10448 (let ((thisline (org-current-line))
10449 beg end c1 c2 r1 r2 rangep tmp)
10450 (unless (string-match org-table-range-regexp desc)
10451 (error "Invalid table range specifier `%s'" desc))
10452 (setq rangep (match-end 3)
10453 r1 (and (match-end 1) (match-string 1 desc))
10454 r2 (and (match-end 4) (match-string 4 desc))
10455 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10456 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10458 (and c1 (setq c1 (+ (string-to-number c1)
10459 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10460 (and c2 (setq c2 (+ (string-to-number c2)
10461 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10462 (if (equal r1 "") (setq r1 nil))
10463 (if (equal r2 "") (setq r2 nil))
10464 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10465 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10466 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10467 (if (not r1) (setq r1 thisline))
10468 (if (not r2) (setq r2 thisline))
10469 (if (not c1) (setq c1 col))
10470 (if (not c2) (setq c2 col))
10471 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10472 ;; just one field
10473 (progn
10474 (goto-line r1)
10475 (while (not (looking-at org-table-dataline-regexp))
10476 (beginning-of-line 2))
10477 (prog1 (org-trim (org-table-get-field c1))
10478 (if highlight (org-table-highlight-rectangle (point) (point)))))
10479 ;; A range, return a vector
10480 ;; First sort the numbers to get a regular ractangle
10481 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10482 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10483 (goto-line r1)
10484 (while (not (looking-at org-table-dataline-regexp))
10485 (beginning-of-line 2))
10486 (org-table-goto-column c1)
10487 (setq beg (point))
10488 (goto-line r2)
10489 (while (not (looking-at org-table-dataline-regexp))
10490 (beginning-of-line 0))
10491 (org-table-goto-column c2)
10492 (setq end (point))
10493 (if highlight
10494 (org-table-highlight-rectangle
10495 beg (progn (skip-chars-forward "^|\n") (point))))
10496 ;; return string representation of calc vector
10497 (mapcar 'org-trim
10498 (apply 'append (org-table-copy-region beg end)))))))
10500 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10501 "Analyze descriptor DESC and retrieve the corresponding line number.
10502 The cursor is currently in line CLINE, the table begins in line BLINE,
10503 and TABLE is a vector with line types."
10504 (if (string-match "^[0-9]+$" desc)
10505 (aref org-table-dlines (string-to-number desc))
10506 (setq cline (or cline (org-current-line))
10507 bline (or bline org-table-current-begin-line)
10508 table (or table org-table-current-line-types))
10509 (if (or
10510 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10511 ;; 1 2 3 4 5 6
10512 (and (not (match-end 3)) (not (match-end 6)))
10513 (and (match-end 3) (match-end 6) (not (match-end 5))))
10514 (error "invalid row descriptor `%s'" desc))
10515 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10516 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10517 (odir (and (match-end 5) (match-string 5 desc)))
10518 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10519 (i (- cline bline))
10520 (rel (and (match-end 6)
10521 (or (and (match-end 1) (not (match-end 3)))
10522 (match-end 5)))))
10523 (if (and hn (not hdir))
10524 (progn
10525 (setq i 0 hdir "+")
10526 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10527 (if (and (not hn) on (not odir))
10528 (error "should never happen");;(aref org-table-dlines on)
10529 (if (and hn (> hn 0))
10530 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10531 (if on
10532 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10533 (+ bline i)))))
10535 (defun org-find-row-type (table i type backwards relative n)
10536 (let ((l (length table)))
10537 (while (> n 0)
10538 (while (and (setq i (+ i (if backwards -1 1)))
10539 (>= i 0) (< i l)
10540 (not (eq (aref table i) type))
10541 (if (and relative (eq (aref table i) 'hline))
10542 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10543 t)))
10544 (setq n (1- n)))
10545 (if (or (< i 0) (>= i l))
10546 (error "Row descriptor leads outside table")
10547 i)))
10549 (defun org-rewrite-old-row-references (s)
10550 (if (string-match "&[-+0-9I]" s)
10551 (error "Formula contains old &row reference, please rewrite using @-syntax")
10554 (defun org-table-make-reference (elements keep-empty numbers lispp)
10555 "Convert list ELEMENTS to something appropriate to insert into formula.
10556 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10557 NUMBERS indicates that everything should be converted to numbers.
10558 LISPP means to return something appropriate for a Lisp list."
10559 (if (stringp elements) ; just a single val
10560 (if lispp
10561 (if (eq lispp 'literal)
10562 elements
10563 (prin1-to-string (if numbers (string-to-number elements) elements)))
10564 (if (equal elements "") (setq elements "0"))
10565 (if numbers (number-to-string (string-to-number elements)) elements))
10566 (unless keep-empty
10567 (setq elements
10568 (delq nil
10569 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10570 elements))))
10571 (setq elements (or elements '("0")))
10572 (if lispp
10573 (mapconcat
10574 (lambda (x)
10575 (if (eq lispp 'literal)
10577 (prin1-to-string (if numbers (string-to-number x) x))))
10578 elements " ")
10579 (concat "[" (mapconcat
10580 (lambda (x)
10581 (if numbers (number-to-string (string-to-number x)) x))
10582 elements
10583 ",") "]"))))
10585 (defun org-table-recalculate (&optional all noalign)
10586 "Recalculate the current table line by applying all stored formulas.
10587 With prefix arg ALL, do this for all lines in the table."
10588 (interactive "P")
10589 (or (memq this-command org-recalc-commands)
10590 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10591 (unless (org-at-table-p) (error "Not at a table"))
10592 (if (equal all '(16))
10593 (org-table-iterate)
10594 (org-table-get-specials)
10595 (let* ((eqlist (sort (org-table-get-stored-formulas)
10596 (lambda (a b) (string< (car a) (car b)))))
10597 (inhibit-redisplay (not debug-on-error))
10598 (line-re org-table-dataline-regexp)
10599 (thisline (org-current-line))
10600 (thiscol (org-table-current-column))
10601 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10602 ;; Insert constants in all formulas
10603 (setq eqlist
10604 (mapcar (lambda (x)
10605 (setcdr x (org-table-formula-substitute-names (cdr x)))
10607 eqlist))
10608 ;; Split the equation list
10609 (while (setq eq (pop eqlist))
10610 (if (<= (string-to-char (car eq)) ?9)
10611 (push eq eqlnum)
10612 (push eq eqlname)))
10613 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10614 (if all
10615 (progn
10616 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10617 (goto-char (setq beg (org-table-begin)))
10618 (if (re-search-forward org-table-calculate-mark-regexp end t)
10619 ;; This is a table with marked lines, compute selected lines
10620 (setq line-re org-table-recalculate-regexp)
10621 ;; Move forward to the first non-header line
10622 (if (and (re-search-forward org-table-dataline-regexp end t)
10623 (re-search-forward org-table-hline-regexp end t)
10624 (re-search-forward org-table-dataline-regexp end t))
10625 (setq beg (match-beginning 0))
10626 nil))) ;; just leave beg where it is
10627 (setq beg (point-at-bol)
10628 end (move-marker (make-marker) (1+ (point-at-eol)))))
10629 (goto-char beg)
10630 (and all (message "Re-applying formulas to full table..."))
10632 ;; First find the named fields, and mark them untouchanble
10633 (remove-text-properties beg end '(org-untouchable t))
10634 (while (setq eq (pop eqlname))
10635 (setq name (car eq)
10636 a (assoc name org-table-named-field-locations))
10637 (and (not a)
10638 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10639 (setq a (list name
10640 (aref org-table-dlines
10641 (string-to-number (match-string 1 name)))
10642 (string-to-number (match-string 2 name)))))
10643 (when (and a (or all (equal (nth 1 a) thisline)))
10644 (message "Re-applying formula to field: %s" name)
10645 (goto-line (nth 1 a))
10646 (org-table-goto-column (nth 2 a))
10647 (push (append a (list (cdr eq))) eqlname1)
10648 (org-table-put-field-property :org-untouchable t)))
10650 ;; Now evauluate the column formulas, but skip fields covered by
10651 ;; field formulas
10652 (goto-char beg)
10653 (while (re-search-forward line-re end t)
10654 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10655 ;; Unprotected line, recalculate
10656 (and all (message "Re-applying formulas to full table...(line %d)"
10657 (setq cnt (1+ cnt))))
10658 (setq org-last-recalc-line (org-current-line))
10659 (setq eql eqlnum)
10660 (while (setq entry (pop eql))
10661 (goto-line org-last-recalc-line)
10662 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10663 (unless (get-text-property (point) :org-untouchable)
10664 (org-table-eval-formula nil (cdr entry)
10665 'noalign 'nocst 'nostore 'noanalysis)))))
10667 ;; Now evaluate the field formulas
10668 (while (setq eq (pop eqlname1))
10669 (message "Re-applying formula to field: %s" (car eq))
10670 (goto-line (nth 1 eq))
10671 (org-table-goto-column (nth 2 eq))
10672 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10673 'nostore 'noanalysis))
10675 (goto-line thisline)
10676 (org-table-goto-column thiscol)
10677 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10678 (or noalign (and org-table-may-need-update (org-table-align))
10679 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10681 ;; back to initial position
10682 (message "Re-applying formulas...done")
10683 (goto-line thisline)
10684 (org-table-goto-column thiscol)
10685 (or noalign (and org-table-may-need-update (org-table-align))
10686 (and all (message "Re-applying formulas...done"))))))
10688 (defun org-table-iterate (&optional arg)
10689 "Recalculate the table until it does not change anymore."
10690 (interactive "P")
10691 (let ((imax (if arg (prefix-numeric-value arg) 10))
10692 (i 0)
10693 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10694 thistbl)
10695 (catch 'exit
10696 (while (< i imax)
10697 (setq i (1+ i))
10698 (org-table-recalculate 'all)
10699 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10700 (if (not (string= lasttbl thistbl))
10701 (setq lasttbl thistbl)
10702 (if (> i 1)
10703 (message "Convergence after %d iterations" i)
10704 (message "Table was already stable"))
10705 (throw 'exit t)))
10706 (error "No convergence after %d iterations" i))))
10708 (defun org-table-formula-substitute-names (f)
10709 "Replace $const with values in string F."
10710 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10711 ;; First, check for column names
10712 (while (setq start (string-match org-table-column-name-regexp f start))
10713 (setq start (1+ start))
10714 (setq a (assoc (match-string 1 f) org-table-column-names))
10715 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10716 ;; Parameters and constants
10717 (setq start 0)
10718 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10719 (setq start (1+ start))
10720 (if (setq a (save-match-data
10721 (org-table-get-constant (match-string 1 f))))
10722 (setq f (replace-match
10723 (concat (if pp "(") a (if pp ")")) t t f))))
10724 (if org-table-formula-debug
10725 (put-text-property 0 (length f) :orig-formula f1 f))
10728 (defun org-table-get-constant (const)
10729 "Find the value for a parameter or constant in a formula.
10730 Parameters get priority."
10731 (or (cdr (assoc const org-table-local-parameters))
10732 (cdr (assoc const org-table-formula-constants-local))
10733 (cdr (assoc const org-table-formula-constants))
10734 (and (fboundp 'constants-get) (constants-get const))
10735 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10736 (org-entry-get nil (substring const 5) 'inherit))
10737 "#UNDEFINED_NAME"))
10739 (defvar org-table-fedit-map
10740 (let ((map (make-sparse-keymap)))
10741 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10742 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10743 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10744 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10745 (org-defkey map "\C-c?" 'org-table-show-reference)
10746 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10747 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10748 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10749 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10750 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10751 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10752 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10753 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10754 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10755 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10756 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10757 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10758 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10759 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10760 map))
10762 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10763 '("Edit-Formulas"
10764 ["Finish and Install" org-table-fedit-finish t]
10765 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10766 ["Abort" org-table-fedit-abort t]
10767 "--"
10768 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10769 ["Complete Lisp Symbol" lisp-complete-symbol t]
10770 "--"
10771 "Shift Reference at Point"
10772 ["Up" org-table-fedit-ref-up t]
10773 ["Down" org-table-fedit-ref-down t]
10774 ["Left" org-table-fedit-ref-left t]
10775 ["Right" org-table-fedit-ref-right t]
10777 "Change Test Row for Column Formulas"
10778 ["Up" org-table-fedit-line-up t]
10779 ["Down" org-table-fedit-line-down t]
10780 "--"
10781 ["Scroll Table Window" org-table-fedit-scroll t]
10782 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10783 ["Show Table Grid" org-table-fedit-toggle-coordinates
10784 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10785 org-table-overlay-coordinates)]
10786 "--"
10787 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10788 :style toggle :selected org-table-buffer-is-an]))
10790 (defvar org-pos)
10792 (defun org-table-edit-formulas ()
10793 "Edit the formulas of the current table in a separate buffer."
10794 (interactive)
10795 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10796 (beginning-of-line 0))
10797 (unless (org-at-table-p) (error "Not at a table"))
10798 (org-table-get-specials)
10799 (let ((key (org-table-current-field-formula 'key 'noerror))
10800 (eql (sort (org-table-get-stored-formulas 'noerror)
10801 'org-table-formula-less-p))
10802 (pos (move-marker (make-marker) (point)))
10803 (startline 1)
10804 (wc (current-window-configuration))
10805 (titles '((column . "# Column Formulas\n")
10806 (field . "# Field Formulas\n")
10807 (named . "# Named Field Formulas\n")))
10808 entry s type title)
10809 (org-switch-to-buffer-other-window "*Edit Formulas*")
10810 (erase-buffer)
10811 ;; Keep global-font-lock-mode from turning on font-lock-mode
10812 (let ((font-lock-global-modes '(not fundamental-mode)))
10813 (fundamental-mode))
10814 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10815 (org-set-local 'org-pos pos)
10816 (org-set-local 'org-window-configuration wc)
10817 (use-local-map org-table-fedit-map)
10818 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10819 (easy-menu-add org-table-fedit-menu)
10820 (setq startline (org-current-line))
10821 (while (setq entry (pop eql))
10822 (setq type (cond
10823 ((equal (string-to-char (car entry)) ?@) 'field)
10824 ((string-match "^[0-9]" (car entry)) 'column)
10825 (t 'named)))
10826 (when (setq title (assq type titles))
10827 (or (bobp) (insert "\n"))
10828 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10829 (setq titles (delq title titles)))
10830 (if (equal key (car entry)) (setq startline (org-current-line)))
10831 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10832 (car entry) " = " (cdr entry) "\n"))
10833 (remove-text-properties 0 (length s) '(face nil) s)
10834 (insert s))
10835 (if (eq org-table-use-standard-references t)
10836 (org-table-fedit-toggle-ref-type))
10837 (goto-line startline)
10838 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10840 (defun org-table-fedit-post-command ()
10841 (when (not (memq this-command '(lisp-complete-symbol)))
10842 (let ((win (selected-window)))
10843 (save-excursion
10844 (condition-case nil
10845 (org-table-show-reference)
10846 (error nil))
10847 (select-window win)))))
10849 (defun org-table-formula-to-user (s)
10850 "Convert a formula from internal to user representation."
10851 (if (eq org-table-use-standard-references t)
10852 (org-table-convert-refs-to-an s)
10855 (defun org-table-formula-from-user (s)
10856 "Convert a formula from user to internal representation."
10857 (if org-table-use-standard-references
10858 (org-table-convert-refs-to-rc s)
10861 (defun org-table-convert-refs-to-rc (s)
10862 "Convert spreadsheet references from AB7 to @7$28.
10863 Works for single references, but also for entire formulas and even the
10864 full TBLFM line."
10865 (let ((start 0))
10866 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10867 (cond
10868 ((match-end 3)
10869 ;; format match, just advance
10870 (setq start (match-end 0)))
10871 ((and (> (match-beginning 0) 0)
10872 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10873 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10874 ;; 3.e5 or something like this.
10875 (setq start (match-end 0)))
10877 (setq start (match-beginning 0)
10878 s (replace-match
10879 (if (equal (match-string 2 s) "&")
10880 (format "$%d" (org-letters-to-number (match-string 1 s)))
10881 (format "@%d$%d"
10882 (string-to-number (match-string 2 s))
10883 (org-letters-to-number (match-string 1 s))))
10884 t t s)))))
10887 (defun org-table-convert-refs-to-an (s)
10888 "Convert spreadsheet references from to @7$28 to AB7.
10889 Works for single references, but also for entire formulas and even the
10890 full TBLFM line."
10891 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10892 (setq s (replace-match
10893 (format "%s%d"
10894 (org-number-to-letters
10895 (string-to-number (match-string 2 s)))
10896 (string-to-number (match-string 1 s)))
10897 t t s)))
10898 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10899 (setq s (replace-match (concat "\\1"
10900 (org-number-to-letters
10901 (string-to-number (match-string 2 s))) "&")
10902 t nil s)))
10905 (defun org-letters-to-number (s)
10906 "Convert a base 26 number represented by letters into an integer.
10907 For example: AB -> 28."
10908 (let ((n 0))
10909 (setq s (upcase s))
10910 (while (> (length s) 0)
10911 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10912 s (substring s 1)))
10915 (defun org-number-to-letters (n)
10916 "Convert an integer into a base 26 number represented by letters.
10917 For example: 28 -> AB."
10918 (let ((s ""))
10919 (while (> n 0)
10920 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10921 n (/ (1- n) 26)))
10924 (defun org-table-fedit-convert-buffer (function)
10925 "Convert all references in this buffer, using FUNTION."
10926 (let ((line (org-current-line)))
10927 (goto-char (point-min))
10928 (while (not (eobp))
10929 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10930 (delete-region (point) (point-at-eol))
10931 (or (eobp) (forward-char 1)))
10932 (goto-line line)))
10934 (defun org-table-fedit-toggle-ref-type ()
10935 "Convert all references in the buffer from B3 to @3$2 and back."
10936 (interactive)
10937 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10938 (org-table-fedit-convert-buffer
10939 (if org-table-buffer-is-an
10940 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10941 (message "Reference type switched to %s"
10942 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10944 (defun org-table-fedit-ref-up ()
10945 "Shift the reference at point one row/hline up."
10946 (interactive)
10947 (org-table-fedit-shift-reference 'up))
10948 (defun org-table-fedit-ref-down ()
10949 "Shift the reference at point one row/hline down."
10950 (interactive)
10951 (org-table-fedit-shift-reference 'down))
10952 (defun org-table-fedit-ref-left ()
10953 "Shift the reference at point one field to the left."
10954 (interactive)
10955 (org-table-fedit-shift-reference 'left))
10956 (defun org-table-fedit-ref-right ()
10957 "Shift the reference at point one field to the right."
10958 (interactive)
10959 (org-table-fedit-shift-reference 'right))
10961 (defun org-table-fedit-shift-reference (dir)
10962 (cond
10963 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10964 (if (memq dir '(left right))
10965 (org-rematch-and-replace 1 (eq dir 'left))
10966 (error "Cannot shift reference in this direction")))
10967 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10968 ;; A B3-like reference
10969 (if (memq dir '(up down))
10970 (org-rematch-and-replace 2 (eq dir 'up))
10971 (org-rematch-and-replace 1 (eq dir 'left))))
10972 ((org-at-regexp-p
10973 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10974 ;; An internal reference
10975 (if (memq dir '(up down))
10976 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10977 (org-rematch-and-replace 5 (eq dir 'left))))))
10979 (defun org-rematch-and-replace (n &optional decr hline)
10980 "Re-match the group N, and replace it with the shifted refrence."
10981 (or (match-end n) (error "Cannot shift reference in this direction"))
10982 (goto-char (match-beginning n))
10983 (and (looking-at (regexp-quote (match-string n)))
10984 (replace-match (org-shift-refpart (match-string 0) decr hline)
10985 t t)))
10987 (defun org-shift-refpart (ref &optional decr hline)
10988 "Shift a refrence part REF.
10989 If DECR is set, decrease the references row/column, else increase.
10990 If HLINE is set, this may be a hline reference, it certainly is not
10991 a translation reference."
10992 (save-match-data
10993 (let* ((sign (string-match "^[-+]" ref)) n)
10995 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10996 (cond
10997 ((and hline (string-match "^I+" ref))
10998 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10999 (setq n (+ n (if decr -1 1)))
11000 (if (= n 0) (setq n (+ n (if decr -1 1))))
11001 (if sign
11002 (setq sign (if (< n 0) "-" "+") n (abs n))
11003 (setq n (max 1 n)))
11004 (concat sign (make-string n ?I)))
11006 ((string-match "^[0-9]+" ref)
11007 (setq n (string-to-number (concat sign ref)))
11008 (setq n (+ n (if decr -1 1)))
11009 (if sign
11010 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
11011 (number-to-string (max 1 n))))
11013 ((string-match "^[a-zA-Z]+" ref)
11014 (org-number-to-letters
11015 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
11017 (t (error "Cannot shift reference"))))))
11019 (defun org-table-fedit-toggle-coordinates ()
11020 "Toggle the display of coordinates in the refrenced table."
11021 (interactive)
11022 (let ((pos (marker-position org-pos)))
11023 (with-current-buffer (marker-buffer org-pos)
11024 (save-excursion
11025 (goto-char pos)
11026 (org-table-toggle-coordinate-overlays)))))
11028 (defun org-table-fedit-finish (&optional arg)
11029 "Parse the buffer for formula definitions and install them.
11030 With prefix ARG, apply the new formulas to the table."
11031 (interactive "P")
11032 (org-table-remove-rectangle-highlight)
11033 (if org-table-use-standard-references
11034 (progn
11035 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
11036 (setq org-table-buffer-is-an nil)))
11037 (let ((pos org-pos) eql var form)
11038 (goto-char (point-min))
11039 (while (re-search-forward
11040 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
11041 nil t)
11042 (setq var (if (match-end 2) (match-string 2) (match-string 1))
11043 form (match-string 3))
11044 (setq form (org-trim form))
11045 (when (not (equal form ""))
11046 (while (string-match "[ \t]*\n[ \t]*" form)
11047 (setq form (replace-match " " t t form)))
11048 (when (assoc var eql)
11049 (error "Double formulas for %s" var))
11050 (push (cons var form) eql)))
11051 (setq org-pos nil)
11052 (set-window-configuration org-window-configuration)
11053 (select-window (get-buffer-window (marker-buffer pos)))
11054 (goto-char pos)
11055 (unless (org-at-table-p)
11056 (error "Lost table position - cannot install formulae"))
11057 (org-table-store-formulas eql)
11058 (move-marker pos nil)
11059 (kill-buffer "*Edit Formulas*")
11060 (if arg
11061 (org-table-recalculate 'all)
11062 (message "New formulas installed - press C-u C-c C-c to apply."))))
11064 (defun org-table-fedit-abort ()
11065 "Abort editing formulas, without installing the changes."
11066 (interactive)
11067 (org-table-remove-rectangle-highlight)
11068 (let ((pos org-pos))
11069 (set-window-configuration org-window-configuration)
11070 (select-window (get-buffer-window (marker-buffer pos)))
11071 (goto-char pos)
11072 (move-marker pos nil)
11073 (message "Formula editing aborted without installing changes")))
11075 (defun org-table-fedit-lisp-indent ()
11076 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
11077 (interactive)
11078 (let ((pos (point)) beg end ind)
11079 (beginning-of-line 1)
11080 (cond
11081 ((looking-at "[ \t]")
11082 (goto-char pos)
11083 (call-interactively 'lisp-indent-line))
11084 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
11085 ((not (fboundp 'pp-buffer))
11086 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
11087 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
11088 (goto-char (- (match-end 0) 2))
11089 (setq beg (point))
11090 (setq ind (make-string (current-column) ?\ ))
11091 (condition-case nil (forward-sexp 1)
11092 (error
11093 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
11094 (setq end (point))
11095 (save-restriction
11096 (narrow-to-region beg end)
11097 (if (eq last-command this-command)
11098 (progn
11099 (goto-char (point-min))
11100 (setq this-command nil)
11101 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
11102 (replace-match " ")))
11103 (pp-buffer)
11104 (untabify (point-min) (point-max))
11105 (goto-char (1+ (point-min)))
11106 (while (re-search-forward "^." nil t)
11107 (beginning-of-line 1)
11108 (insert ind))
11109 (goto-char (point-max))
11110 (backward-delete-char 1)))
11111 (goto-char beg))
11112 (t nil))))
11114 (defvar org-show-positions nil)
11116 (defun org-table-show-reference (&optional local)
11117 "Show the location/value of the $ expression at point."
11118 (interactive)
11119 (org-table-remove-rectangle-highlight)
11120 (catch 'exit
11121 (let ((pos (if local (point) org-pos))
11122 (face2 'highlight)
11123 (org-inhibit-highlight-removal t)
11124 (win (selected-window))
11125 (org-show-positions nil)
11126 var name e what match dest)
11127 (if local (org-table-get-specials))
11128 (setq what (cond
11129 ((or (org-at-regexp-p org-table-range-regexp2)
11130 (org-at-regexp-p org-table-translate-regexp)
11131 (org-at-regexp-p org-table-range-regexp))
11132 (setq match
11133 (save-match-data
11134 (org-table-convert-refs-to-rc (match-string 0))))
11135 'range)
11136 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
11137 ((org-at-regexp-p "\\$[0-9]+") 'column)
11138 ((not local) nil)
11139 (t (error "No reference at point")))
11140 match (and what (or match (match-string 0))))
11141 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
11142 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
11143 'secondary-selection))
11144 (org-add-hook 'before-change-functions
11145 'org-table-remove-rectangle-highlight)
11146 (if (eq what 'name) (setq var (substring match 1)))
11147 (when (eq what 'range)
11148 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
11149 (setq match (org-table-formula-substitute-names match)))
11150 (unless local
11151 (save-excursion
11152 (end-of-line 1)
11153 (re-search-backward "^\\S-" nil t)
11154 (beginning-of-line 1)
11155 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
11156 (setq dest
11157 (save-match-data
11158 (org-table-convert-refs-to-rc (match-string 1))))
11159 (org-table-add-rectangle-overlay
11160 (match-beginning 1) (match-end 1) face2))))
11161 (if (and (markerp pos) (marker-buffer pos))
11162 (if (get-buffer-window (marker-buffer pos))
11163 (select-window (get-buffer-window (marker-buffer pos)))
11164 (org-switch-to-buffer-other-window (get-buffer-window
11165 (marker-buffer pos)))))
11166 (goto-char pos)
11167 (org-table-force-dataline)
11168 (when dest
11169 (setq name (substring dest 1))
11170 (cond
11171 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
11172 (setq e (assoc name org-table-named-field-locations))
11173 (goto-line (nth 1 e))
11174 (org-table-goto-column (nth 2 e)))
11175 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
11176 (let ((l (string-to-number (match-string 1 dest)))
11177 (c (string-to-number (match-string 2 dest))))
11178 (goto-line (aref org-table-dlines l))
11179 (org-table-goto-column c)))
11180 (t (org-table-goto-column (string-to-number name))))
11181 (move-marker pos (point))
11182 (org-table-highlight-rectangle nil nil face2))
11183 (cond
11184 ((equal dest match))
11185 ((not match))
11186 ((eq what 'range)
11187 (condition-case nil
11188 (save-excursion
11189 (org-table-get-range match nil nil 'highlight))
11190 (error nil)))
11191 ((setq e (assoc var org-table-named-field-locations))
11192 (goto-line (nth 1 e))
11193 (org-table-goto-column (nth 2 e))
11194 (org-table-highlight-rectangle (point) (point))
11195 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11196 ((setq e (assoc var org-table-column-names))
11197 (org-table-goto-column (string-to-number (cdr e)))
11198 (org-table-highlight-rectangle (point) (point))
11199 (goto-char (org-table-begin))
11200 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11201 (org-table-end) t)
11202 (progn
11203 (goto-char (match-beginning 1))
11204 (org-table-highlight-rectangle)
11205 (message "Named column (column %s)" (cdr e)))
11206 (error "Column name not found")))
11207 ((eq what 'column)
11208 ;; column number
11209 (org-table-goto-column (string-to-number (substring match 1)))
11210 (org-table-highlight-rectangle (point) (point))
11211 (message "Column %s" (substring match 1)))
11212 ((setq e (assoc var org-table-local-parameters))
11213 (goto-char (org-table-begin))
11214 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11215 (progn
11216 (goto-char (match-beginning 1))
11217 (org-table-highlight-rectangle)
11218 (message "Local parameter."))
11219 (error "Parameter not found")))
11221 (cond
11222 ((not var) (error "No reference at point"))
11223 ((setq e (assoc var org-table-formula-constants-local))
11224 (message "Local Constant: $%s=%s in #+CONSTANTS line."
11225 var (cdr e)))
11226 ((setq e (assoc var org-table-formula-constants))
11227 (message "Constant: $%s=%s in `org-table-formula-constants'."
11228 var (cdr e)))
11229 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11230 (message "Constant: $%s=%s, from `constants.el'%s."
11231 var e (format " (%s units)" constants-unit-system)))
11232 (t (error "Undefined name $%s" var)))))
11233 (goto-char pos)
11234 (when (and org-show-positions
11235 (not (memq this-command '(org-table-fedit-scroll
11236 org-table-fedit-scroll-down))))
11237 (push pos org-show-positions)
11238 (push org-table-current-begin-pos org-show-positions)
11239 (let ((min (apply 'min org-show-positions))
11240 (max (apply 'max org-show-positions)))
11241 (goto-char min) (recenter 0)
11242 (goto-char max)
11243 (or (pos-visible-in-window-p max) (recenter -1))))
11244 (select-window win))))
11246 (defun org-table-force-dataline ()
11247 "Make sure the cursor is in a dataline in a table."
11248 (unless (save-excursion
11249 (beginning-of-line 1)
11250 (looking-at org-table-dataline-regexp))
11251 (let* ((re org-table-dataline-regexp)
11252 (p1 (save-excursion (re-search-forward re nil 'move)))
11253 (p2 (save-excursion (re-search-backward re nil 'move))))
11254 (cond ((and p1 p2)
11255 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
11256 p1 p2)))
11257 ((or p1 p2) (goto-char (or p1 p2)))
11258 (t (error "No table dataline around here"))))))
11260 (defun org-table-fedit-line-up ()
11261 "Move cursor one line up in the window showing the table."
11262 (interactive)
11263 (org-table-fedit-move 'previous-line))
11265 (defun org-table-fedit-line-down ()
11266 "Move cursor one line down in the window showing the table."
11267 (interactive)
11268 (org-table-fedit-move 'next-line))
11270 (defun org-table-fedit-move (command)
11271 "Move the cursor in the window shoinw the table.
11272 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11273 (let ((org-table-allow-automatic-line-recalculation nil)
11274 (pos org-pos) (win (selected-window)) p)
11275 (select-window (get-buffer-window (marker-buffer org-pos)))
11276 (setq p (point))
11277 (call-interactively command)
11278 (while (and (org-at-table-p)
11279 (org-at-table-hline-p))
11280 (call-interactively command))
11281 (or (org-at-table-p) (goto-char p))
11282 (move-marker pos (point))
11283 (select-window win)))
11285 (defun org-table-fedit-scroll (N)
11286 (interactive "p")
11287 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11288 (scroll-other-window N)))
11290 (defun org-table-fedit-scroll-down (N)
11291 (interactive "p")
11292 (org-table-fedit-scroll (- N)))
11294 (defvar org-table-rectangle-overlays nil)
11296 (defun org-table-add-rectangle-overlay (beg end &optional face)
11297 "Add a new overlay."
11298 (let ((ov (org-make-overlay beg end)))
11299 (org-overlay-put ov 'face (or face 'secondary-selection))
11300 (push ov org-table-rectangle-overlays)))
11302 (defun org-table-highlight-rectangle (&optional beg end face)
11303 "Highlight rectangular region in a table."
11304 (setq beg (or beg (point)) end (or end (point)))
11305 (let ((b (min beg end))
11306 (e (max beg end))
11307 l1 c1 l2 c2 tmp)
11308 (and (boundp 'org-show-positions)
11309 (setq org-show-positions (cons b (cons e org-show-positions))))
11310 (goto-char (min beg end))
11311 (setq l1 (org-current-line)
11312 c1 (org-table-current-column))
11313 (goto-char (max beg end))
11314 (setq l2 (org-current-line)
11315 c2 (org-table-current-column))
11316 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11317 (goto-line l1)
11318 (beginning-of-line 1)
11319 (loop for line from l1 to l2 do
11320 (when (looking-at org-table-dataline-regexp)
11321 (org-table-goto-column c1)
11322 (skip-chars-backward "^|\n") (setq beg (point))
11323 (org-table-goto-column c2)
11324 (skip-chars-forward "^|\n") (setq end (point))
11325 (org-table-add-rectangle-overlay beg end face))
11326 (beginning-of-line 2))
11327 (goto-char b))
11328 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11330 (defun org-table-remove-rectangle-highlight (&rest ignore)
11331 "Remove the rectangle overlays."
11332 (unless org-inhibit-highlight-removal
11333 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11334 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11335 (setq org-table-rectangle-overlays nil)))
11337 (defvar org-table-coordinate-overlays nil
11338 "Collects the cooordinate grid overlays, so that they can be removed.")
11339 (make-variable-buffer-local 'org-table-coordinate-overlays)
11341 (defun org-table-overlay-coordinates ()
11342 "Add overlays to the table at point, to show row/column coordinates."
11343 (interactive)
11344 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11345 (setq org-table-coordinate-overlays nil)
11346 (save-excursion
11347 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11348 (goto-char (org-table-begin))
11349 (while (org-at-table-p)
11350 (setq eol (point-at-eol))
11351 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11352 (push ov org-table-coordinate-overlays)
11353 (setq hline (looking-at org-table-hline-regexp))
11354 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11355 (format "%4d" (setq id (1+ id)))))
11356 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11357 (when hline
11358 (setq ic 0)
11359 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11360 (setq beg (1+ (match-beginning 0))
11361 ic (1+ ic)
11362 s1 (concat "$" (int-to-string ic))
11363 s2 (org-number-to-letters ic)
11364 str (if (eq org-table-use-standard-references t) s2 s1))
11365 (setq ov (org-make-overlay beg (+ beg (length str))))
11366 (push ov org-table-coordinate-overlays)
11367 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11368 (beginning-of-line 2)))))
11370 (defun org-table-toggle-coordinate-overlays ()
11371 "Toggle the display of Row/Column numbers in tables."
11372 (interactive)
11373 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11374 (message "Row/Column number display turned %s"
11375 (if org-table-overlay-coordinates "on" "off"))
11376 (if (and (org-at-table-p) org-table-overlay-coordinates)
11377 (org-table-align))
11378 (unless org-table-overlay-coordinates
11379 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11380 (setq org-table-coordinate-overlays nil)))
11382 (defun org-table-toggle-formula-debugger ()
11383 "Toggle the formula debugger in tables."
11384 (interactive)
11385 (setq org-table-formula-debug (not org-table-formula-debug))
11386 (message "Formula debugging has been turned %s"
11387 (if org-table-formula-debug "on" "off")))
11389 ;;; The orgtbl minor mode
11391 ;; Define a minor mode which can be used in other modes in order to
11392 ;; integrate the org-mode table editor.
11394 ;; This is really a hack, because the org-mode table editor uses several
11395 ;; keys which normally belong to the major mode, for example the TAB and
11396 ;; RET keys. Here is how it works: The minor mode defines all the keys
11397 ;; necessary to operate the table editor, but wraps the commands into a
11398 ;; function which tests if the cursor is currently inside a table. If that
11399 ;; is the case, the table editor command is executed. However, when any of
11400 ;; those keys is used outside a table, the function uses `key-binding' to
11401 ;; look up if the key has an associated command in another currently active
11402 ;; keymap (minor modes, major mode, global), and executes that command.
11403 ;; There might be problems if any of the keys used by the table editor is
11404 ;; otherwise used as a prefix key.
11406 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11407 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11408 ;; addresses this by checking explicitly for both bindings.
11410 ;; The optimized version (see variable `orgtbl-optimized') takes over
11411 ;; all keys which are bound to `self-insert-command' in the *global map*.
11412 ;; Some modes bind other commands to simple characters, for example
11413 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11414 ;; active, this binding is ignored inside tables and replaced with a
11415 ;; modified self-insert.
11417 (defvar orgtbl-mode nil
11418 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11419 table editor in arbitrary modes.")
11420 (make-variable-buffer-local 'orgtbl-mode)
11422 (defvar orgtbl-mode-map (make-keymap)
11423 "Keymap for `orgtbl-mode'.")
11425 ;;;###autoload
11426 (defun turn-on-orgtbl ()
11427 "Unconditionally turn on `orgtbl-mode'."
11428 (orgtbl-mode 1))
11430 (defvar org-old-auto-fill-inhibit-regexp nil
11431 "Local variable used by `orgtbl-mode'")
11433 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11434 "Matches a line belonging to an orgtbl.")
11436 (defconst orgtbl-extra-font-lock-keywords
11437 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11438 0 (quote 'org-table) 'prepend))
11439 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11441 ;;;###autoload
11442 (defun orgtbl-mode (&optional arg)
11443 "The `org-mode' table editor as a minor mode for use in other modes."
11444 (interactive)
11445 (org-load-modules-maybe)
11446 (if (org-mode-p)
11447 ;; Exit without error, in case some hook functions calls this
11448 ;; by accident in org-mode.
11449 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11450 (setq orgtbl-mode
11451 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11452 (if orgtbl-mode
11453 (progn
11454 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11455 ;; Make sure we are first in minor-mode-map-alist
11456 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11457 (and c (setq minor-mode-map-alist
11458 (cons c (delq c minor-mode-map-alist)))))
11459 (org-set-local (quote org-table-may-need-update) t)
11460 (org-add-hook 'before-change-functions 'org-before-change-function
11461 nil 'local)
11462 (org-set-local 'org-old-auto-fill-inhibit-regexp
11463 auto-fill-inhibit-regexp)
11464 (org-set-local 'auto-fill-inhibit-regexp
11465 (if auto-fill-inhibit-regexp
11466 (concat orgtbl-line-start-regexp "\\|"
11467 auto-fill-inhibit-regexp)
11468 orgtbl-line-start-regexp))
11469 (org-add-to-invisibility-spec '(org-cwidth))
11470 (when (fboundp 'font-lock-add-keywords)
11471 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11472 (org-restart-font-lock))
11473 (easy-menu-add orgtbl-mode-menu)
11474 (run-hooks 'orgtbl-mode-hook))
11475 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11476 (org-cleanup-narrow-column-properties)
11477 (org-remove-from-invisibility-spec '(org-cwidth))
11478 (remove-hook 'before-change-functions 'org-before-change-function t)
11479 (when (fboundp 'font-lock-remove-keywords)
11480 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11481 (org-restart-font-lock))
11482 (easy-menu-remove orgtbl-mode-menu)
11483 (force-mode-line-update 'all))))
11485 (defun org-cleanup-narrow-column-properties ()
11486 "Remove all properties related to narrow-column invisibility."
11487 (let ((s 1))
11488 (while (setq s (text-property-any s (point-max)
11489 'display org-narrow-column-arrow))
11490 (remove-text-properties s (1+ s) '(display t)))
11491 (setq s 1)
11492 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11493 (remove-text-properties s (1+ s) '(org-cwidth t)))
11494 (setq s 1)
11495 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11496 (remove-text-properties s (1+ s) '(invisible t)))))
11498 ;; Install it as a minor mode.
11499 (put 'orgtbl-mode :included t)
11500 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11501 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11503 (defun orgtbl-make-binding (fun n &rest keys)
11504 "Create a function for binding in the table minor mode.
11505 FUN is the command to call inside a table. N is used to create a unique
11506 command name. KEYS are keys that should be checked in for a command
11507 to execute outside of tables."
11508 (eval
11509 (list 'defun
11510 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11511 '(arg)
11512 (concat "In tables, run `" (symbol-name fun) "'.\n"
11513 "Outside of tables, run the binding of `"
11514 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11515 "'.")
11516 '(interactive "p")
11517 (list 'if
11518 '(org-at-table-p)
11519 (list 'call-interactively (list 'quote fun))
11520 (list 'let '(orgtbl-mode)
11521 (list 'call-interactively
11522 (append '(or)
11523 (mapcar (lambda (k)
11524 (list 'key-binding k))
11525 keys)
11526 '('orgtbl-error))))))))
11528 (defun orgtbl-error ()
11529 "Error when there is no default binding for a table key."
11530 (interactive)
11531 (error "This key has no function outside tables"))
11533 (defun orgtbl-setup ()
11534 "Setup orgtbl keymaps."
11535 (let ((nfunc 0)
11536 (bindings
11537 (list
11538 '([(meta shift left)] org-table-delete-column)
11539 '([(meta left)] org-table-move-column-left)
11540 '([(meta right)] org-table-move-column-right)
11541 '([(meta shift right)] org-table-insert-column)
11542 '([(meta shift up)] org-table-kill-row)
11543 '([(meta shift down)] org-table-insert-row)
11544 '([(meta up)] org-table-move-row-up)
11545 '([(meta down)] org-table-move-row-down)
11546 '("\C-c\C-w" org-table-cut-region)
11547 '("\C-c\M-w" org-table-copy-region)
11548 '("\C-c\C-y" org-table-paste-rectangle)
11549 '("\C-c-" org-table-insert-hline)
11550 '("\C-c}" org-table-toggle-coordinate-overlays)
11551 '("\C-c{" org-table-toggle-formula-debugger)
11552 '("\C-m" org-table-next-row)
11553 '([(shift return)] org-table-copy-down)
11554 '("\C-c\C-q" org-table-wrap-region)
11555 '("\C-c?" org-table-field-info)
11556 '("\C-c " org-table-blank-field)
11557 '("\C-c+" org-table-sum)
11558 '("\C-c=" org-table-eval-formula)
11559 '("\C-c'" org-table-edit-formulas)
11560 '("\C-c`" org-table-edit-field)
11561 '("\C-c*" org-table-recalculate)
11562 '("\C-c|" org-table-create-or-convert-from-region)
11563 '("\C-c^" org-table-sort-lines)
11564 '([(control ?#)] org-table-rotate-recalc-marks)))
11565 elt key fun cmd)
11566 (while (setq elt (pop bindings))
11567 (setq nfunc (1+ nfunc))
11568 (setq key (org-key (car elt))
11569 fun (nth 1 elt)
11570 cmd (orgtbl-make-binding fun nfunc key))
11571 (org-defkey orgtbl-mode-map key cmd))
11573 ;; Special treatment needed for TAB and RET
11574 (org-defkey orgtbl-mode-map [(return)]
11575 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11576 (org-defkey orgtbl-mode-map "\C-m"
11577 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11579 (org-defkey orgtbl-mode-map [(tab)]
11580 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11581 (org-defkey orgtbl-mode-map "\C-i"
11582 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11584 (org-defkey orgtbl-mode-map [(shift tab)]
11585 (orgtbl-make-binding 'org-table-previous-field 104
11586 [(shift tab)] [(tab)] "\C-i"))
11588 (org-defkey orgtbl-mode-map "\M-\C-m"
11589 (orgtbl-make-binding 'org-table-wrap-region 105
11590 "\M-\C-m" [(meta return)]))
11591 (org-defkey orgtbl-mode-map [(meta return)]
11592 (orgtbl-make-binding 'org-table-wrap-region 106
11593 [(meta return)] "\M-\C-m"))
11595 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11596 (when orgtbl-optimized
11597 ;; If the user wants maximum table support, we need to hijack
11598 ;; some standard editing functions
11599 (org-remap orgtbl-mode-map
11600 'self-insert-command 'orgtbl-self-insert-command
11601 'delete-char 'org-delete-char
11602 'delete-backward-char 'org-delete-backward-char)
11603 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11604 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11605 '("OrgTbl"
11606 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11607 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11608 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11609 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11610 "--"
11611 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11612 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11613 ["Copy Field from Above"
11614 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11615 "--"
11616 ("Column"
11617 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11618 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11619 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11620 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11621 ("Row"
11622 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11623 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11624 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11625 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11626 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
11627 "--"
11628 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11629 ("Rectangle"
11630 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11631 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11632 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11633 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11634 "--"
11635 ("Radio tables"
11636 ["Insert table template" orgtbl-insert-radio-table
11637 (assq major-mode orgtbl-radio-table-templates)]
11638 ["Comment/uncomment table" orgtbl-toggle-comment t])
11639 "--"
11640 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11641 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11642 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11643 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11644 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11645 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11646 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11647 ["Sum Column/Rectangle" org-table-sum
11648 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11649 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11650 ["Debug Formulas"
11651 org-table-toggle-formula-debugger :active (org-at-table-p)
11652 :keys "C-c {"
11653 :style toggle :selected org-table-formula-debug]
11654 ["Show Col/Row Numbers"
11655 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11656 :keys "C-c }"
11657 :style toggle :selected org-table-overlay-coordinates]
11661 (defun orgtbl-ctrl-c-ctrl-c (arg)
11662 "If the cursor is inside a table, realign the table.
11663 It it is a table to be sent away to a receiver, do it.
11664 With prefix arg, also recompute table."
11665 (interactive "P")
11666 (let ((pos (point)) action)
11667 (save-excursion
11668 (beginning-of-line 1)
11669 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11670 ((looking-at "[ \t]*|") pos)
11671 ((looking-at "#\\+TBLFM:") 'recalc))))
11672 (cond
11673 ((integerp action)
11674 (goto-char action)
11675 (org-table-maybe-eval-formula)
11676 (if arg
11677 (call-interactively 'org-table-recalculate)
11678 (org-table-maybe-recalculate-line))
11679 (call-interactively 'org-table-align)
11680 (orgtbl-send-table 'maybe))
11681 ((eq action 'recalc)
11682 (save-excursion
11683 (beginning-of-line 1)
11684 (skip-chars-backward " \r\n\t")
11685 (if (org-at-table-p)
11686 (org-call-with-arg 'org-table-recalculate t))))
11687 (t (let (orgtbl-mode)
11688 (call-interactively (key-binding "\C-c\C-c")))))))
11690 (defun orgtbl-tab (arg)
11691 "Justification and field motion for `orgtbl-mode'."
11692 (interactive "P")
11693 (if arg (org-table-edit-field t)
11694 (org-table-justify-field-maybe)
11695 (org-table-next-field)))
11697 (defun orgtbl-ret ()
11698 "Justification and field motion for `orgtbl-mode'."
11699 (interactive)
11700 (org-table-justify-field-maybe)
11701 (org-table-next-row))
11703 (defun orgtbl-self-insert-command (N)
11704 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11705 If the cursor is in a table looking at whitespace, the whitespace is
11706 overwritten, and the table is not marked as requiring realignment."
11707 (interactive "p")
11708 (if (and (org-at-table-p)
11710 (and org-table-auto-blank-field
11711 (member last-command
11712 '(orgtbl-hijacker-command-100
11713 orgtbl-hijacker-command-101
11714 orgtbl-hijacker-command-102
11715 orgtbl-hijacker-command-103
11716 orgtbl-hijacker-command-104
11717 orgtbl-hijacker-command-105))
11718 (org-table-blank-field))
11720 (eq N 1)
11721 (looking-at "[^|\n]* +|"))
11722 (let (org-table-may-need-update)
11723 (goto-char (1- (match-end 0)))
11724 (delete-backward-char 1)
11725 (goto-char (match-beginning 0))
11726 (self-insert-command N))
11727 (setq org-table-may-need-update t)
11728 (let (orgtbl-mode)
11729 (call-interactively (key-binding (vector last-input-event))))))
11731 (defun org-force-self-insert (N)
11732 "Needed to enforce self-insert under remapping."
11733 (interactive "p")
11734 (self-insert-command N))
11736 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11737 "Regula expression matching exponentials as produced by calc.")
11739 (defvar org-table-clean-did-remove-column nil)
11741 (defun orgtbl-export (table target)
11742 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11743 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11744 org-table-last-alignment org-table-last-column-widths
11745 maxcol column)
11746 (if (not (fboundp func))
11747 (error "Cannot export orgtbl table to %s" target))
11748 (setq lines (org-table-clean-before-export lines))
11749 (setq table
11750 (mapcar
11751 (lambda (x)
11752 (if (string-match org-table-hline-regexp x)
11753 'hline
11754 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11755 lines))
11756 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11757 table)))
11758 (loop for i from (1- maxcol) downto 0 do
11759 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11760 (setq column (delq nil column))
11761 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11762 (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))
11763 (funcall func table nil)))
11765 (defun orgtbl-send-table (&optional maybe)
11766 "Send a tranformed version of this table to the receiver position.
11767 With argument MAYBE, fail quietly if no transformation is defined for
11768 this table."
11769 (interactive)
11770 (catch 'exit
11771 (unless (org-at-table-p) (error "Not at a table"))
11772 ;; when non-interactive, we assume align has just happened.
11773 (when (interactive-p) (org-table-align))
11774 (save-excursion
11775 (goto-char (org-table-begin))
11776 (beginning-of-line 0)
11777 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11778 (if maybe
11779 (throw 'exit nil)
11780 (error "Don't know how to transform this table."))))
11781 (let* ((name (match-string 1))
11783 (transform (intern (match-string 2)))
11784 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11785 (skip (plist-get params :skip))
11786 (skipcols (plist-get params :skipcols))
11787 (txt (buffer-substring-no-properties
11788 (org-table-begin) (org-table-end)))
11789 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11790 (lines (org-table-clean-before-export lines))
11791 (i0 (if org-table-clean-did-remove-column 2 1))
11792 (table (mapcar
11793 (lambda (x)
11794 (if (string-match org-table-hline-regexp x)
11795 'hline
11796 (org-remove-by-index
11797 (org-split-string (org-trim x) "\\s-*|\\s-*")
11798 skipcols i0)))
11799 lines))
11800 (fun (if (= i0 2) 'cdr 'identity))
11801 (org-table-last-alignment
11802 (org-remove-by-index (funcall fun org-table-last-alignment)
11803 skipcols i0))
11804 (org-table-last-column-widths
11805 (org-remove-by-index (funcall fun org-table-last-column-widths)
11806 skipcols i0)))
11808 (unless (fboundp transform)
11809 (error "No such transformation function %s" transform))
11810 (setq txt (funcall transform table params))
11811 ;; Find the insertion place
11812 (save-excursion
11813 (goto-char (point-min))
11814 (unless (re-search-forward
11815 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11816 (error "Don't know where to insert translated table"))
11817 (goto-char (match-beginning 0))
11818 (beginning-of-line 2)
11819 (setq beg (point))
11820 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11821 (error "Cannot find end of insertion region"))
11822 (beginning-of-line 1)
11823 (delete-region beg (point))
11824 (goto-char beg)
11825 (insert txt "\n"))
11826 (message "Table converted and installed at receiver location"))))
11828 (defun org-remove-by-index (list indices &optional i0)
11829 "Remove the elements in LIST with indices in INDICES.
11830 First element has index 0, or I0 if given."
11831 (if (not indices)
11832 list
11833 (if (integerp indices) (setq indices (list indices)))
11834 (setq i0 (1- (or i0 0)))
11835 (delq :rm (mapcar (lambda (x)
11836 (setq i0 (1+ i0))
11837 (if (memq i0 indices) :rm x))
11838 list))))
11840 (defun orgtbl-toggle-comment ()
11841 "Comment or uncomment the orgtbl at point."
11842 (interactive)
11843 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11844 (re2 (concat "^" orgtbl-line-start-regexp))
11845 (commented (save-excursion (beginning-of-line 1)
11846 (cond ((looking-at re1) t)
11847 ((looking-at re2) nil)
11848 (t (error "Not at an org table")))))
11849 (re (if commented re1 re2))
11850 beg end)
11851 (save-excursion
11852 (beginning-of-line 1)
11853 (while (looking-at re) (beginning-of-line 0))
11854 (beginning-of-line 2)
11855 (setq beg (point))
11856 (while (looking-at re) (beginning-of-line 2))
11857 (setq end (point)))
11858 (comment-region beg end (if commented '(4) nil))))
11860 (defun orgtbl-insert-radio-table ()
11861 "Insert a radio table template appropriate for this major mode."
11862 (interactive)
11863 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11864 (txt (nth 1 e))
11865 name pos)
11866 (unless e (error "No radio table setup defined for %s" major-mode))
11867 (setq name (read-string "Table name: "))
11868 (while (string-match "%n" txt)
11869 (setq txt (replace-match name t t txt)))
11870 (or (bolp) (insert "\n"))
11871 (setq pos (point))
11872 (insert txt)
11873 (goto-char pos)))
11875 (defun org-get-param (params header i sym &optional hsym)
11876 "Get parameter value for symbol SYM.
11877 If this is a header line, actually get the value for the symbol with an
11878 additional \"h\" inserted after the colon.
11879 If the value is a protperty list, get the element for the current column.
11880 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11881 (let ((val (plist-get params sym)))
11882 (and hsym header (setq val (or (plist-get params hsym) val)))
11883 (if (consp val) (plist-get val i) val)))
11885 (defun orgtbl-to-generic (table params)
11886 "Convert the orgtbl-mode TABLE to some other format.
11887 This generic routine can be used for many standard cases.
11888 TABLE is a list, each entry either the symbol `hline' for a horizontal
11889 separator line, or a list of fields for that line.
11890 PARAMS is a property list of parameters that can influence the conversion.
11891 For the generic converter, some parameters are obligatory: You need to
11892 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11893 :splice, you must have :tstart and :tend.
11895 Valid parameters are
11897 :tstart String to start the table. Ignored when :splice is t.
11898 :tend String to end the table. Ignored when :splice is t.
11900 :splice When set to t, return only table body lines, don't wrap
11901 them into :tstart and :tend. Default is nil.
11903 :hline String to be inserted on horizontal separation lines.
11904 May be nil to ignore hlines.
11906 :lstart String to start a new table line.
11907 :lend String to end a table line
11908 :sep Separator between two fields
11909 :lfmt Format for entire line, with enough %s to capture all fields.
11910 If this is present, :lstart, :lend, and :sep are ignored.
11911 :fmt A format to be used to wrap the field, should contain
11912 %s for the original field value. For example, to wrap
11913 everything in dollars, you could use :fmt \"$%s$\".
11914 This may also be a property list with column numbers and
11915 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11917 :hlstart :hlend :hlsep :hlfmt :hfmt
11918 Same as above, specific for the header lines in the table.
11919 All lines before the first hline are treated as header.
11920 If any of these is not present, the data line value is used.
11922 :efmt Use this format to print numbers with exponentials.
11923 The format should have %s twice for inserting mantissa
11924 and exponent, for example \"%s\\\\times10^{%s}\". This
11925 may also be a property list with column numbers and
11926 formats. :fmt will still be applied after :efmt.
11928 In addition to this, the parameters :skip and :skipcols are always handled
11929 directly by `orgtbl-send-table'. See manual."
11930 (interactive)
11931 (let* ((p params)
11932 (splicep (plist-get p :splice))
11933 (hline (plist-get p :hline))
11934 rtn line i fm efm lfmt h)
11936 ;; Do we have a header?
11937 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11938 (setq h t))
11940 ;; Put header
11941 (unless splicep
11942 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11944 ;; Now loop over all lines
11945 (while (setq line (pop table))
11946 (if (eq line 'hline)
11947 ;; A horizontal separator line
11948 (progn (if hline (push hline rtn))
11949 (setq h nil)) ; no longer in header
11950 ;; A normal line. Convert the fields, push line onto the result list
11951 (setq i 0)
11952 (setq line
11953 (mapcar
11954 (lambda (f)
11955 (setq i (1+ i)
11956 fm (org-get-param p h i :fmt :hfmt)
11957 efm (org-get-param p h i :efmt))
11958 (if (and efm (string-match orgtbl-exp-regexp f))
11959 (setq f (format
11960 efm (match-string 1 f) (match-string 2 f))))
11961 (if fm (setq f (format fm f)))
11963 line))
11964 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11965 (push (apply 'format lfmt line) rtn)
11966 (push (concat
11967 (org-get-param p h i :lstart :hlstart)
11968 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11969 (org-get-param p h i :lend :hlend))
11970 rtn))))
11972 (unless splicep
11973 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11975 (mapconcat 'identity (nreverse rtn) "\n")))
11977 (defun orgtbl-to-latex (table params)
11978 "Convert the orgtbl-mode TABLE to LaTeX.
11979 TABLE is a list, each entry either the symbol `hline' for a horizontal
11980 separator line, or a list of fields for that line.
11981 PARAMS is a property list of parameters that can influence the conversion.
11982 Supports all parameters from `orgtbl-to-generic'. Most important for
11983 LaTeX are:
11985 :splice When set to t, return only table body lines, don't wrap
11986 them into a tabular environment. Default is nil.
11988 :fmt A format to be used to wrap the field, should contain %s for the
11989 original field value. For example, to wrap everything in dollars,
11990 use :fmt \"$%s$\". This may also be a property list with column
11991 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11993 :efmt Format for transforming numbers with exponentials. The format
11994 should have %s twice for inserting mantissa and exponent, for
11995 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11996 This may also be a property list with column numbers and formats.
11998 The general parameters :skip and :skipcols have already been applied when
11999 this function is called."
12000 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
12001 org-table-last-alignment ""))
12002 (params2
12003 (list
12004 :tstart (concat "\\begin{tabular}{" alignment "}")
12005 :tend "\\end{tabular}"
12006 :lstart "" :lend " \\\\" :sep " & "
12007 :efmt "%s\\,(%s)" :hline "\\hline")))
12008 (orgtbl-to-generic table (org-combine-plists params2 params))))
12010 (defun orgtbl-to-html (table params)
12011 "Convert the orgtbl-mode TABLE to LaTeX.
12012 TABLE is a list, each entry either the symbol `hline' for a horizontal
12013 separator line, or a list of fields for that line.
12014 PARAMS is a property list of parameters that can influence the conversion.
12015 Currently this function recognizes the following parameters:
12017 :splice When set to t, return only table body lines, don't wrap
12018 them into a <table> environment. Default is nil.
12020 The general parameters :skip and :skipcols have already been applied when
12021 this function is called. The function does *not* use `orgtbl-to-generic',
12022 so you cannot specify parameters for it."
12023 (let* ((splicep (plist-get params :splice))
12024 html)
12025 ;; Just call the formatter we already have
12026 ;; We need to make text lines for it, so put the fields back together.
12027 (setq html (org-format-org-table-html
12028 (mapcar
12029 (lambda (x)
12030 (if (eq x 'hline)
12031 "|----+----|"
12032 (concat "| " (mapconcat 'identity x " | ") " |")))
12033 table)
12034 splicep))
12035 (if (string-match "\n+\\'" html)
12036 (setq html (replace-match "" t t html)))
12037 html))
12039 (defun orgtbl-to-texinfo (table params)
12040 "Convert the orgtbl-mode TABLE to TeXInfo.
12041 TABLE is a list, each entry either the symbol `hline' for a horizontal
12042 separator line, or a list of fields for that line.
12043 PARAMS is a property list of parameters that can influence the conversion.
12044 Supports all parameters from `orgtbl-to-generic'. Most important for
12045 TeXInfo are:
12047 :splice nil/t When set to t, return only table body lines, don't wrap
12048 them into a multitable environment. Default is nil.
12050 :fmt fmt A format to be used to wrap the field, should contain
12051 %s for the original field value. For example, to wrap
12052 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
12053 This may also be a property list with column numbers and
12054 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
12056 :cf \"f1 f2..\" The column fractions for the table. By default these
12057 are computed automatically from the width of the columns
12058 under org-mode.
12060 The general parameters :skip and :skipcols have already been applied when
12061 this function is called."
12062 (let* ((total (float (apply '+ org-table-last-column-widths)))
12063 (colfrac (or (plist-get params :cf)
12064 (mapconcat
12065 (lambda (x) (format "%.3f" (/ (float x) total)))
12066 org-table-last-column-widths " ")))
12067 (params2
12068 (list
12069 :tstart (concat "@multitable @columnfractions " colfrac)
12070 :tend "@end multitable"
12071 :lstart "@item " :lend "" :sep " @tab "
12072 :hlstart "@headitem ")))
12073 (orgtbl-to-generic table (org-combine-plists params2 params))))
12075 ;;;; Link Stuff
12077 ;;; Link abbreviations
12079 (defun org-link-expand-abbrev (link)
12080 "Apply replacements as defined in `org-link-abbrev-alist."
12081 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
12082 (let* ((key (match-string 1 link))
12083 (as (or (assoc key org-link-abbrev-alist-local)
12084 (assoc key org-link-abbrev-alist)))
12085 (tag (and (match-end 2) (match-string 3 link)))
12086 rpl)
12087 (if (not as)
12088 link
12089 (setq rpl (cdr as))
12090 (cond
12091 ((symbolp rpl) (funcall rpl tag))
12092 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
12093 (t (concat rpl tag)))))
12094 link))
12096 ;;; Storing and inserting links
12098 (defvar org-insert-link-history nil
12099 "Minibuffer history for links inserted with `org-insert-link'.")
12101 (defvar org-stored-links nil
12102 "Contains the links stored with `org-store-link'.")
12104 (defvar org-store-link-plist nil
12105 "Plist with info about the most recently link created with `org-store-link'.")
12107 (defvar org-link-protocols nil
12108 "Link protocols added to Org-mode using `org-add-link-type'.")
12110 (defvar org-store-link-functions nil
12111 "List of functions that are called to create and store a link.
12112 Each function will be called in turn until one returns a non-nil
12113 value. Each function should check if it is responsible for creating
12114 this link (for example by looking at the major mode).
12115 If not, it must exit and return nil.
12116 If yes, it should return a non-nil value after a calling
12117 `org-store-link-props' with a list of properties and values.
12118 Special properties are:
12120 :type The link prefix. like \"http\". This must be given.
12121 :link The link, like \"http://www.astro.uva.nl/~dominik\".
12122 This is obligatory as well.
12123 :description Optional default description for the second pair
12124 of brackets in an Org-mode link. The user can still change
12125 this when inserting this link into an Org-mode buffer.
12127 In addition to these, any additional properties can be specified
12128 and then used in remember templates.")
12130 (defun org-add-link-type (type &optional follow export)
12131 "Add TYPE to the list of `org-link-types'.
12132 Re-compute all regular expressions depending on `org-link-types'
12134 FOLLOW and EXPORT are two functions.
12136 FOLLOW should take the link path as the single argument and do whatever
12137 is necessary to follow the link, for example find a file or display
12138 a mail message.
12140 EXPORT should format the link path for export to one of the export formats.
12141 It should be a function accepting three arguments:
12143 path the path of the link, the text after the prefix (like \"http:\")
12144 desc the description of the link, if any, nil if there was no descripton
12145 format the export format, a symbol like `html' or `latex'.
12147 The function may use the FORMAT information to return different values
12148 depending on the format. The return value will be put literally into
12149 the exported file.
12150 Org-mode has a built-in default for exporting links. If you are happy with
12151 this default, there is no need to define an export function for the link
12152 type. For a simple example of an export function, see `org-bbdb.el'."
12153 (add-to-list 'org-link-types type t)
12154 (org-make-link-regexps)
12155 (if (assoc type org-link-protocols)
12156 (setcdr (assoc type org-link-protocols) (list follow export))
12157 (push (list type follow export) org-link-protocols)))
12160 (defun org-add-agenda-custom-command (entry)
12161 "Replace or add a command in `org-agenda-custom-commands'.
12162 This is mostly for hacking and trying a new command - once the command
12163 works you probably want to add it to `org-agenda-custom-commands' for good."
12164 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
12165 (if ass
12166 (setcdr ass (cdr entry))
12167 (push entry org-agenda-custom-commands))))
12169 ;;;###autoload
12170 (defun org-store-link (arg)
12171 "\\<org-mode-map>Store an org-link to the current location.
12172 This link is added to `org-stored-links' and can later be inserted
12173 into an org-buffer with \\[org-insert-link].
12175 For some link types, a prefix arg is interpreted:
12176 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
12177 For file links, arg negates `org-context-in-file-links'."
12178 (interactive "P")
12179 (org-load-modules-maybe)
12180 (setq org-store-link-plist nil) ; reset
12181 (let (link cpltxt desc description search txt)
12182 (cond
12184 ((run-hook-with-args-until-success 'org-store-link-functions)
12185 (setq link (plist-get org-store-link-plist :link)
12186 desc (or (plist-get org-store-link-plist :description) link)))
12188 ((eq major-mode 'calendar-mode)
12189 (let ((cd (calendar-cursor-to-date)))
12190 (setq link
12191 (format-time-string
12192 (car org-time-stamp-formats)
12193 (apply 'encode-time
12194 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
12195 nil nil nil))))
12196 (org-store-link-props :type "calendar" :date cd)))
12198 ((eq major-mode 'w3-mode)
12199 (setq cpltxt (url-view-url t)
12200 link (org-make-link cpltxt))
12201 (org-store-link-props :type "w3" :url (url-view-url t)))
12203 ((eq major-mode 'w3m-mode)
12204 (setq cpltxt (or w3m-current-title w3m-current-url)
12205 link (org-make-link w3m-current-url))
12206 (org-store-link-props :type "w3m" :url (url-view-url t)))
12208 ((setq search (run-hook-with-args-until-success
12209 'org-create-file-search-functions))
12210 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12211 "::" search))
12212 (setq cpltxt (or description link)))
12214 ((eq major-mode 'image-mode)
12215 (setq cpltxt (concat "file:"
12216 (abbreviate-file-name buffer-file-name))
12217 link (org-make-link cpltxt))
12218 (org-store-link-props :type "image" :file buffer-file-name))
12220 ((eq major-mode 'dired-mode)
12221 ;; link to the file in the current line
12222 (setq cpltxt (concat "file:"
12223 (abbreviate-file-name
12224 (expand-file-name
12225 (dired-get-filename nil t))))
12226 link (org-make-link cpltxt)))
12228 ((and buffer-file-name (org-mode-p))
12229 ;; Just link to current headline
12230 (setq cpltxt (concat "file:"
12231 (abbreviate-file-name buffer-file-name)))
12232 ;; Add a context search string
12233 (when (org-xor org-context-in-file-links arg)
12234 ;; Check if we are on a target
12235 (if (org-in-regexp "<<\\(.*?\\)>>")
12236 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12237 (setq txt (cond
12238 ((org-on-heading-p) nil)
12239 ((org-region-active-p)
12240 (buffer-substring (region-beginning) (region-end)))
12241 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12242 (when (or (null txt) (string-match "\\S-" txt))
12243 (setq cpltxt
12244 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12245 desc "NONE"))))
12246 (if (string-match "::\\'" cpltxt)
12247 (setq cpltxt (substring cpltxt 0 -2)))
12248 (setq link (org-make-link cpltxt)))
12250 ((buffer-file-name (buffer-base-buffer))
12251 ;; Just link to this file here.
12252 (setq cpltxt (concat "file:"
12253 (abbreviate-file-name
12254 (buffer-file-name (buffer-base-buffer)))))
12255 ;; Add a context string
12256 (when (org-xor org-context-in-file-links arg)
12257 (setq txt (if (org-region-active-p)
12258 (buffer-substring (region-beginning) (region-end))
12259 (buffer-substring (point-at-bol) (point-at-eol))))
12260 ;; Only use search option if there is some text.
12261 (when (string-match "\\S-" txt)
12262 (setq cpltxt
12263 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12264 desc "NONE")))
12265 (setq link (org-make-link cpltxt)))
12267 ((interactive-p)
12268 (error "Cannot link to a buffer which is not visiting a file"))
12270 (t (setq link nil)))
12272 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12273 (setq link (or link cpltxt)
12274 desc (or desc cpltxt))
12275 (if (equal desc "NONE") (setq desc nil))
12277 (if (and (interactive-p) link)
12278 (progn
12279 (setq org-stored-links
12280 (cons (list link desc) org-stored-links))
12281 (message "Stored: %s" (or desc link)))
12282 (and link (org-make-link-string link desc)))))
12284 (defun org-store-link-props (&rest plist)
12285 "Store link properties, extract names and addresses."
12286 (let (x adr)
12287 (when (setq x (plist-get plist :from))
12288 (setq adr (mail-extract-address-components x))
12289 (plist-put plist :fromname (car adr))
12290 (plist-put plist :fromaddress (nth 1 adr)))
12291 (when (setq x (plist-get plist :to))
12292 (setq adr (mail-extract-address-components x))
12293 (plist-put plist :toname (car adr))
12294 (plist-put plist :toaddress (nth 1 adr))))
12295 (let ((from (plist-get plist :from))
12296 (to (plist-get plist :to)))
12297 (when (and from to org-from-is-user-regexp)
12298 (plist-put plist :fromto
12299 (if (string-match org-from-is-user-regexp from)
12300 (concat "to %t")
12301 (concat "from %f")))))
12302 (setq org-store-link-plist plist))
12304 (defun org-add-link-props (&rest plist)
12305 "Add these properties to the link property list."
12306 (let (key value)
12307 (while plist
12308 (setq key (pop plist) value (pop plist))
12309 (setq org-store-link-plist
12310 (plist-put org-store-link-plist key value)))))
12312 (defun org-email-link-description (&optional fmt)
12313 "Return the description part of an email link.
12314 This takes information from `org-store-link-plist' and formats it
12315 according to FMT (default from `org-email-link-description-format')."
12316 (setq fmt (or fmt org-email-link-description-format))
12317 (let* ((p org-store-link-plist)
12318 (to (plist-get p :toaddress))
12319 (from (plist-get p :fromaddress))
12320 (table
12321 (list
12322 (cons "%c" (plist-get p :fromto))
12323 (cons "%F" (plist-get p :from))
12324 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12325 (cons "%T" (plist-get p :to))
12326 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12327 (cons "%s" (plist-get p :subject))
12328 (cons "%m" (plist-get p :message-id)))))
12329 (when (string-match "%c" fmt)
12330 ;; Check if the user wrote this message
12331 (if (and org-from-is-user-regexp from to
12332 (save-match-data (string-match org-from-is-user-regexp from)))
12333 (setq fmt (replace-match "to %t" t t fmt))
12334 (setq fmt (replace-match "from %f" t t fmt))))
12335 (org-replace-escapes fmt table)))
12337 (defun org-make-org-heading-search-string (&optional string heading)
12338 "Make search string for STRING or current headline."
12339 (interactive)
12340 (let ((s (or string (org-get-heading))))
12341 (unless (and string (not heading))
12342 ;; We are using a headline, clean up garbage in there.
12343 (if (string-match org-todo-regexp s)
12344 (setq s (replace-match "" t t s)))
12345 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12346 (setq s (replace-match "" t t s)))
12347 (setq s (org-trim s))
12348 (if (string-match (concat "^\\(" org-quote-string "\\|"
12349 org-comment-string "\\)") s)
12350 (setq s (replace-match "" t t s)))
12351 (while (string-match org-ts-regexp s)
12352 (setq s (replace-match "" t t s))))
12353 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12354 (setq s (replace-match " " t t s)))
12355 (or string (setq s (concat "*" s))) ; Add * for headlines
12356 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12358 (defun org-make-link (&rest strings)
12359 "Concatenate STRINGS."
12360 (apply 'concat strings))
12362 (defun org-make-link-string (link &optional description)
12363 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12364 (unless (string-match "\\S-" link)
12365 (error "Empty link"))
12366 (when (stringp description)
12367 ;; Remove brackets from the description, they are fatal.
12368 (while (string-match "\\[" description)
12369 (setq description (replace-match "{" t t description)))
12370 (while (string-match "\\]" description)
12371 (setq description (replace-match "}" t t description))))
12372 (when (equal (org-link-escape link) description)
12373 ;; No description needed, it is identical
12374 (setq description nil))
12375 (when (and (not description)
12376 (not (equal link (org-link-escape link))))
12377 (setq description link))
12378 (concat "[[" (org-link-escape link) "]"
12379 (if description (concat "[" description "]") "")
12380 "]"))
12382 (defconst org-link-escape-chars
12383 '((?\ . "%20")
12384 (?\[ . "%5B")
12385 (?\] . "%5D")
12386 (?\340 . "%E0") ; `a
12387 (?\342 . "%E2") ; ^a
12388 (?\347 . "%E7") ; ,c
12389 (?\350 . "%E8") ; `e
12390 (?\351 . "%E9") ; 'e
12391 (?\352 . "%EA") ; ^e
12392 (?\356 . "%EE") ; ^i
12393 (?\364 . "%F4") ; ^o
12394 (?\371 . "%F9") ; `u
12395 (?\373 . "%FB") ; ^u
12396 (?\; . "%3B")
12397 (?? . "%3F")
12398 (?= . "%3D")
12399 (?+ . "%2B")
12401 "Association list of escapes for some characters problematic in links.
12402 This is the list that is used for internal purposes.")
12404 (defconst org-link-escape-chars-browser
12405 '((?\ . "%20")) ; 32 for the SPC char
12406 "Association list of escapes for some characters problematic in links.
12407 This is the list that is used before handing over to the browser.")
12409 (defun org-link-escape (text &optional table)
12410 "Escape charaters in TEXT that are problematic for links."
12411 (setq table (or table org-link-escape-chars))
12412 (when text
12413 (let ((re (mapconcat (lambda (x) (regexp-quote
12414 (char-to-string (car x))))
12415 table "\\|")))
12416 (while (string-match re text)
12417 (setq text
12418 (replace-match
12419 (cdr (assoc (string-to-char (match-string 0 text))
12420 table))
12421 t t text)))
12422 text)))
12424 (defun org-link-unescape (text &optional table)
12425 "Reverse the action of `org-link-escape'."
12426 (setq table (or table org-link-escape-chars))
12427 (when text
12428 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12429 table "\\|")))
12430 (while (string-match re text)
12431 (setq text
12432 (replace-match
12433 (char-to-string (car (rassoc (match-string 0 text) table)))
12434 t t text)))
12435 text)))
12437 (defun org-xor (a b)
12438 "Exclusive or."
12439 (if a (not b) b))
12441 (defun org-get-header (header)
12442 "Find a header field in the current buffer."
12443 (save-excursion
12444 (goto-char (point-min))
12445 (let ((case-fold-search t) s)
12446 (cond
12447 ((eq header 'from)
12448 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12449 (setq s (match-string 1)))
12450 (while (string-match "\"" s)
12451 (setq s (replace-match "" t t s)))
12452 (if (string-match "[<(].*" s)
12453 (setq s (replace-match "" t t s))))
12454 ((eq header 'message-id)
12455 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12456 (setq s (match-string 1))))
12457 ((eq header 'subject)
12458 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12459 (setq s (match-string 1)))))
12460 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12461 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12462 s)))
12465 (defun org-fixup-message-id-for-http (s)
12466 "Replace special characters in a message id, so it can be used in an http query."
12467 (while (string-match "<" s)
12468 (setq s (replace-match "%3C" t t s)))
12469 (while (string-match ">" s)
12470 (setq s (replace-match "%3E" t t s)))
12471 (while (string-match "@" s)
12472 (setq s (replace-match "%40" t t s)))
12475 ;;;###autoload
12476 (defun org-insert-link-global ()
12477 "Insert a link like Org-mode does.
12478 This command can be called in any mode to insert a link in Org-mode syntax."
12479 (interactive)
12480 (org-load-modules-maybe)
12481 (org-run-like-in-org-mode 'org-insert-link))
12483 (defun org-insert-link (&optional complete-file)
12484 "Insert a link. At the prompt, enter the link.
12486 Completion can be used to select a link previously stored with
12487 `org-store-link'. When the empty string is entered (i.e. if you just
12488 press RET at the prompt), the link defaults to the most recently
12489 stored link. As SPC triggers completion in the minibuffer, you need to
12490 use M-SPC or C-q SPC to force the insertion of a space character.
12492 You will also be prompted for a description, and if one is given, it will
12493 be displayed in the buffer instead of the link.
12495 If there is already a link at point, this command will allow you to edit link
12496 and description parts.
12498 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12499 selected using completion. The path to the file will be relative to
12500 the current directory if the file is in the current directory or a
12501 subdirectory. Otherwise, the link will be the absolute path as
12502 completed in the minibuffer (i.e. normally ~/path/to/file).
12504 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12505 is in the current directory or below.
12506 With three \\[universal-argument] prefixes, negate the meaning of
12507 `org-keep-stored-link-after-insertion'."
12508 (interactive "P")
12509 (let* ((wcf (current-window-configuration))
12510 (region (if (org-region-active-p)
12511 (buffer-substring (region-beginning) (region-end))))
12512 (remove (and region (list (region-beginning) (region-end))))
12513 (desc region)
12514 tmphist ; byte-compile incorrectly complains about this
12515 link entry file)
12516 (cond
12517 ((org-in-regexp org-bracket-link-regexp 1)
12518 ;; We do have a link at point, and we are going to edit it.
12519 (setq remove (list (match-beginning 0) (match-end 0)))
12520 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12521 (setq link (read-string "Link: "
12522 (org-link-unescape
12523 (org-match-string-no-properties 1)))))
12524 ((or (org-in-regexp org-angle-link-re)
12525 (org-in-regexp org-plain-link-re))
12526 ;; Convert to bracket link
12527 (setq remove (list (match-beginning 0) (match-end 0))
12528 link (read-string "Link: "
12529 (org-remove-angle-brackets (match-string 0)))))
12530 ((equal complete-file '(4))
12531 ;; Completing read for file names.
12532 (setq file (read-file-name "File: "))
12533 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12534 (pwd1 (file-name-as-directory (abbreviate-file-name
12535 (expand-file-name ".")))))
12536 (cond
12537 ((equal complete-file '(16))
12538 (setq link (org-make-link
12539 "file:"
12540 (abbreviate-file-name (expand-file-name file)))))
12541 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12542 (setq link (org-make-link "file:" (match-string 1 file))))
12543 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12544 (expand-file-name file))
12545 (setq link (org-make-link
12546 "file:" (match-string 1 (expand-file-name file)))))
12547 (t (setq link (org-make-link "file:" file))))))
12549 ;; Read link, with completion for stored links.
12550 (with-output-to-temp-buffer "*Org Links*"
12551 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12552 (when org-stored-links
12553 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12554 (princ (mapconcat
12555 (lambda (x)
12556 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12557 (reverse org-stored-links) "\n"))))
12558 (let ((cw (selected-window)))
12559 (select-window (get-buffer-window "*Org Links*"))
12560 (shrink-window-if-larger-than-buffer)
12561 (setq truncate-lines t)
12562 (select-window cw))
12563 ;; Fake a link history, containing the stored links.
12564 (setq tmphist (append (mapcar 'car org-stored-links)
12565 org-insert-link-history))
12566 (unwind-protect
12567 (setq link (org-completing-read
12568 "Link: "
12569 (append
12570 (mapcar (lambda (x) (list (concat (car x) ":")))
12571 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12572 (mapcar (lambda (x) (list (concat x ":")))
12573 org-link-types))
12574 nil nil nil
12575 'tmphist
12576 (or (car (car org-stored-links)))))
12577 (set-window-configuration wcf)
12578 (kill-buffer "*Org Links*"))
12579 (setq entry (assoc link org-stored-links))
12580 (or entry (push link org-insert-link-history))
12581 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12582 (not org-keep-stored-link-after-insertion))
12583 (setq org-stored-links (delq (assoc link org-stored-links)
12584 org-stored-links)))
12585 (setq desc (or desc (nth 1 entry)))))
12587 (if (string-match org-plain-link-re link)
12588 ;; URL-like link, normalize the use of angular brackets.
12589 (setq link (org-make-link (org-remove-angle-brackets link))))
12591 ;; Check if we are linking to the current file with a search option
12592 ;; If yes, simplify the link by using only the search option.
12593 (when (and buffer-file-name
12594 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12595 (let* ((path (match-string 1 link))
12596 (case-fold-search nil)
12597 (search (match-string 2 link)))
12598 (save-match-data
12599 (if (equal (file-truename buffer-file-name) (file-truename path))
12600 ;; We are linking to this same file, with a search option
12601 (setq link search)))))
12603 ;; Check if we can/should use a relative path. If yes, simplify the link
12604 (when (string-match "\\<file:\\(.*\\)" link)
12605 (let* ((path (match-string 1 link))
12606 (origpath path)
12607 (case-fold-search nil))
12608 (cond
12609 ((eq org-link-file-path-type 'absolute)
12610 (setq path (abbreviate-file-name (expand-file-name path))))
12611 ((eq org-link-file-path-type 'noabbrev)
12612 (setq path (expand-file-name path)))
12613 ((eq org-link-file-path-type 'relative)
12614 (setq path (file-relative-name path)))
12616 (save-match-data
12617 (if (string-match (concat "^" (regexp-quote
12618 (file-name-as-directory
12619 (expand-file-name "."))))
12620 (expand-file-name path))
12621 ;; We are linking a file with relative path name.
12622 (setq path (substring (expand-file-name path)
12623 (match-end 0)))))))
12624 (setq link (concat "file:" path))
12625 (if (equal desc origpath)
12626 (setq desc path))))
12628 (setq desc (read-string "Description: " desc))
12629 (unless (string-match "\\S-" desc) (setq desc nil))
12630 (if remove (apply 'delete-region remove))
12631 (insert (org-make-link-string link desc))))
12633 (defun org-completing-read (&rest args)
12634 (let ((minibuffer-local-completion-map
12635 (copy-keymap minibuffer-local-completion-map)))
12636 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12637 (apply 'completing-read args)))
12639 ;;; Opening/following a link
12640 (defvar org-link-search-failed nil)
12642 (defun org-next-link ()
12643 "Move forward to the next link.
12644 If the link is in hidden text, expose it."
12645 (interactive)
12646 (when (and org-link-search-failed (eq this-command last-command))
12647 (goto-char (point-min))
12648 (message "Link search wrapped back to beginning of buffer"))
12649 (setq org-link-search-failed nil)
12650 (let* ((pos (point))
12651 (ct (org-context))
12652 (a (assoc :link ct)))
12653 (if a (goto-char (nth 2 a)))
12654 (if (re-search-forward org-any-link-re nil t)
12655 (progn
12656 (goto-char (match-beginning 0))
12657 (if (org-invisible-p) (org-show-context)))
12658 (goto-char pos)
12659 (setq org-link-search-failed t)
12660 (error "No further link found"))))
12662 (defun org-previous-link ()
12663 "Move backward to the previous link.
12664 If the link is in hidden text, expose it."
12665 (interactive)
12666 (when (and org-link-search-failed (eq this-command last-command))
12667 (goto-char (point-max))
12668 (message "Link search wrapped back to end of buffer"))
12669 (setq org-link-search-failed nil)
12670 (let* ((pos (point))
12671 (ct (org-context))
12672 (a (assoc :link ct)))
12673 (if a (goto-char (nth 1 a)))
12674 (if (re-search-backward org-any-link-re nil t)
12675 (progn
12676 (goto-char (match-beginning 0))
12677 (if (org-invisible-p) (org-show-context)))
12678 (goto-char pos)
12679 (setq org-link-search-failed t)
12680 (error "No further link found"))))
12682 (defun org-find-file-at-mouse (ev)
12683 "Open file link or URL at mouse."
12684 (interactive "e")
12685 (mouse-set-point ev)
12686 (org-open-at-point 'in-emacs))
12688 (defun org-open-at-mouse (ev)
12689 "Open file link or URL at mouse."
12690 (interactive "e")
12691 (mouse-set-point ev)
12692 (org-open-at-point))
12694 (defvar org-window-config-before-follow-link nil
12695 "The window configuration before following a link.
12696 This is saved in case the need arises to restore it.")
12698 (defvar org-open-link-marker (make-marker)
12699 "Marker pointing to the location where `org-open-at-point; was called.")
12701 ;;;###autoload
12702 (defun org-open-at-point-global ()
12703 "Follow a link like Org-mode does.
12704 This command can be called in any mode to follow a link that has
12705 Org-mode syntax."
12706 (interactive)
12707 (org-run-like-in-org-mode 'org-open-at-point))
12709 (defun org-open-at-point (&optional in-emacs)
12710 "Open link at or after point.
12711 If there is no link at point, this function will search forward up to
12712 the end of the current subtree.
12713 Normally, files will be opened by an appropriate application. If the
12714 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12715 (interactive "P")
12716 (org-load-modules-maybe)
12717 (move-marker org-open-link-marker (point))
12718 (setq org-window-config-before-follow-link (current-window-configuration))
12719 (org-remove-occur-highlights nil nil t)
12720 (if (org-at-timestamp-p t)
12721 (org-follow-timestamp-link)
12722 (let (type path link line search (pos (point)))
12723 (catch 'match
12724 (save-excursion
12725 (skip-chars-forward "^]\n\r")
12726 (when (org-in-regexp org-bracket-link-regexp)
12727 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12728 (while (string-match " *\n *" link)
12729 (setq link (replace-match " " t t link)))
12730 (setq link (org-link-expand-abbrev link))
12731 (if (string-match org-link-re-with-space2 link)
12732 (setq type (match-string 1 link) path (match-string 2 link))
12733 (setq type "thisfile" path link))
12734 (throw 'match t)))
12736 (when (get-text-property (point) 'org-linked-text)
12737 (setq type "thisfile"
12738 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12739 (1+ (point)) (point))
12740 path (buffer-substring
12741 (previous-single-property-change pos 'org-linked-text)
12742 (next-single-property-change pos 'org-linked-text)))
12743 (throw 'match t))
12745 (save-excursion
12746 (when (or (org-in-regexp org-angle-link-re)
12747 (org-in-regexp org-plain-link-re))
12748 (setq type (match-string 1) path (match-string 2))
12749 (throw 'match t)))
12750 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12751 (setq type "tree-match"
12752 path (match-string 1))
12753 (throw 'match t))
12754 (save-excursion
12755 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12756 (setq type "tags"
12757 path (match-string 1))
12758 (while (string-match ":" path)
12759 (setq path (replace-match "+" t t path)))
12760 (throw 'match t))))
12761 (unless path
12762 (error "No link found"))
12763 ;; Remove any trailing spaces in path
12764 (if (string-match " +\\'" path)
12765 (setq path (replace-match "" t t path)))
12767 (cond
12769 ((assoc type org-link-protocols)
12770 (funcall (nth 1 (assoc type org-link-protocols)) path))
12772 ((equal type "mailto")
12773 (let ((cmd (car org-link-mailto-program))
12774 (args (cdr org-link-mailto-program)) args1
12775 (address path) (subject "") a)
12776 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12777 (setq address (match-string 1 path)
12778 subject (org-link-escape (match-string 2 path))))
12779 (while args
12780 (cond
12781 ((not (stringp (car args))) (push (pop args) args1))
12782 (t (setq a (pop args))
12783 (if (string-match "%a" a)
12784 (setq a (replace-match address t t a)))
12785 (if (string-match "%s" a)
12786 (setq a (replace-match subject t t a)))
12787 (push a args1))))
12788 (apply cmd (nreverse args1))))
12790 ((member type '("http" "https" "ftp" "news"))
12791 (browse-url (concat type ":" (org-link-escape
12792 path org-link-escape-chars-browser))))
12794 ((member type '("message"))
12795 (browse-url (concat type ":" path)))
12797 ((string= type "tags")
12798 (org-tags-view in-emacs path))
12799 ((string= type "thisfile")
12800 (if in-emacs
12801 (switch-to-buffer-other-window
12802 (org-get-buffer-for-internal-link (current-buffer)))
12803 (org-mark-ring-push))
12804 (let ((cmd `(org-link-search
12805 ,path
12806 ,(cond ((equal in-emacs '(4)) 'occur)
12807 ((equal in-emacs '(16)) 'org-occur)
12808 (t nil))
12809 ,pos)))
12810 (condition-case nil (eval cmd)
12811 (error (progn (widen) (eval cmd))))))
12813 ((string= type "tree-match")
12814 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12816 ((string= type "file")
12817 (if (string-match "::\\([0-9]+\\)\\'" path)
12818 (setq line (string-to-number (match-string 1 path))
12819 path (substring path 0 (match-beginning 0)))
12820 (if (string-match "::\\(.+\\)\\'" path)
12821 (setq search (match-string 1 path)
12822 path (substring path 0 (match-beginning 0)))))
12823 (if (string-match "[*?{]" (file-name-nondirectory path))
12824 (dired path)
12825 (org-open-file path in-emacs line search)))
12827 ((string= type "news")
12828 (require 'org-gnus)
12829 (org-gnus-follow-link path))
12831 ((string= type "shell")
12832 (let ((cmd path))
12833 (if (or (not org-confirm-shell-link-function)
12834 (funcall org-confirm-shell-link-function
12835 (format "Execute \"%s\" in shell? "
12836 (org-add-props cmd nil
12837 'face 'org-warning))))
12838 (progn
12839 (message "Executing %s" cmd)
12840 (shell-command cmd))
12841 (error "Abort"))))
12843 ((string= type "elisp")
12844 (let ((cmd path))
12845 (if (or (not org-confirm-elisp-link-function)
12846 (funcall org-confirm-elisp-link-function
12847 (format "Execute \"%s\" as elisp? "
12848 (org-add-props cmd nil
12849 'face 'org-warning))))
12850 (message "%s => %s" cmd (eval (read cmd)))
12851 (error "Abort"))))
12854 (browse-url-at-point)))))
12855 (move-marker org-open-link-marker nil)
12856 (run-hook-with-args 'org-follow-link-hook))
12858 ;;; File search
12860 (defvar org-create-file-search-functions nil
12861 "List of functions to construct the right search string for a file link.
12862 These functions are called in turn with point at the location to
12863 which the link should point.
12865 A function in the hook should first test if it would like to
12866 handle this file type, for example by checking the major-mode or
12867 the file extension. If it decides not to handle this file, it
12868 should just return nil to give other functions a chance. If it
12869 does handle the file, it must return the search string to be used
12870 when following the link. The search string will be part of the
12871 file link, given after a double colon, and `org-open-at-point'
12872 will automatically search for it. If special measures must be
12873 taken to make the search successful, another function should be
12874 added to the companion hook `org-execute-file-search-functions',
12875 which see.
12877 A function in this hook may also use `setq' to set the variable
12878 `description' to provide a suggestion for the descriptive text to
12879 be used for this link when it gets inserted into an Org-mode
12880 buffer with \\[org-insert-link].")
12882 (defvar org-execute-file-search-functions nil
12883 "List of functions to execute a file search triggered by a link.
12885 Functions added to this hook must accept a single argument, the
12886 search string that was part of the file link, the part after the
12887 double colon. The function must first check if it would like to
12888 handle this search, for example by checking the major-mode or the
12889 file extension. If it decides not to handle this search, it
12890 should just return nil to give other functions a chance. If it
12891 does handle the search, it must return a non-nil value to keep
12892 other functions from trying.
12894 Each function can access the current prefix argument through the
12895 variable `current-prefix-argument'. Note that a single prefix is
12896 used to force opening a link in Emacs, so it may be good to only
12897 use a numeric or double prefix to guide the search function.
12899 In case this is needed, a function in this hook can also restore
12900 the window configuration before `org-open-at-point' was called using:
12902 (set-window-configuration org-window-config-before-follow-link)")
12904 (defun org-link-search (s &optional type avoid-pos)
12905 "Search for a link search option.
12906 If S is surrounded by forward slashes, it is interpreted as a
12907 regular expression. In org-mode files, this will create an `org-occur'
12908 sparse tree. In ordinary files, `occur' will be used to list matches.
12909 If the current buffer is in `dired-mode', grep will be used to search
12910 in all files. If AVOID-POS is given, ignore matches near that position."
12911 (let ((case-fold-search t)
12912 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12913 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12914 (append '(("") (" ") ("\t") ("\n"))
12915 org-emphasis-alist)
12916 "\\|") "\\)"))
12917 (pos (point))
12918 (pre "") (post "")
12919 words re0 re1 re2 re3 re4 re5 re2a reall)
12920 (cond
12921 ;; First check if there are any special
12922 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12923 ;; Now try the builtin stuff
12924 ((save-excursion
12925 (goto-char (point-min))
12926 (and
12927 (re-search-forward
12928 (concat "<<" (regexp-quote s0) ">>") nil t)
12929 (setq pos (match-beginning 0))))
12930 ;; There is an exact target for this
12931 (goto-char pos))
12932 ((string-match "^/\\(.*\\)/$" s)
12933 ;; A regular expression
12934 (cond
12935 ((org-mode-p)
12936 (org-occur (match-string 1 s)))
12937 ;;((eq major-mode 'dired-mode)
12938 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12939 (t (org-do-occur (match-string 1 s)))))
12941 ;; A normal search strings
12942 (when (equal (string-to-char s) ?*)
12943 ;; Anchor on headlines, post may include tags.
12944 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12945 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12946 s (substring s 1)))
12947 (remove-text-properties
12948 0 (length s)
12949 '(face nil mouse-face nil keymap nil fontified nil) s)
12950 ;; Make a series of regular expressions to find a match
12951 (setq words (org-split-string s "[ \n\r\t]+")
12952 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12953 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12954 "\\)" markers)
12955 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12956 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12957 re1 (concat pre re2 post)
12958 re3 (concat pre re4 post)
12959 re5 (concat pre ".*" re4)
12960 re2 (concat pre re2)
12961 re2a (concat pre re2a)
12962 re4 (concat pre re4)
12963 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12964 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12965 re5 "\\)"
12967 (cond
12968 ((eq type 'org-occur) (org-occur reall))
12969 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12970 (t (goto-char (point-min))
12971 (if (or (org-search-not-self 1 re0 nil t)
12972 (org-search-not-self 1 re1 nil t)
12973 (org-search-not-self 1 re2 nil t)
12974 (org-search-not-self 1 re2a nil t)
12975 (org-search-not-self 1 re3 nil t)
12976 (org-search-not-self 1 re4 nil t)
12977 (org-search-not-self 1 re5 nil t)
12979 (goto-char (match-beginning 1))
12980 (goto-char pos)
12981 (error "No match")))))
12983 ;; Normal string-search
12984 (goto-char (point-min))
12985 (if (search-forward s nil t)
12986 (goto-char (match-beginning 0))
12987 (error "No match"))))
12988 (and (org-mode-p) (org-show-context 'link-search))))
12990 (defun org-search-not-self (group &rest args)
12991 "Execute `re-search-forward', but only accept matches that do not
12992 enclose the position of `org-open-link-marker'."
12993 (let ((m org-open-link-marker))
12994 (catch 'exit
12995 (while (apply 're-search-forward args)
12996 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12997 (goto-char (match-end group))
12998 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12999 (> (match-beginning 0) (marker-position m))
13000 (< (match-end 0) (marker-position m)))
13001 (save-match-data
13002 (or (not (org-in-regexp
13003 org-bracket-link-analytic-regexp 1))
13004 (not (match-end 4)) ; no description
13005 (and (<= (match-beginning 4) (point))
13006 (>= (match-end 4) (point))))))
13007 (throw 'exit (point))))))))
13009 (defun org-get-buffer-for-internal-link (buffer)
13010 "Return a buffer to be used for displaying the link target of internal links."
13011 (cond
13012 ((not org-display-internal-link-with-indirect-buffer)
13013 buffer)
13014 ((string-match "(Clone)$" (buffer-name buffer))
13015 (message "Buffer is already a clone, not making another one")
13016 ;; we also do not modify visibility in this case
13017 buffer)
13018 (t ; make a new indirect buffer for displaying the link
13019 (let* ((bn (buffer-name buffer))
13020 (ibn (concat bn "(Clone)"))
13021 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
13022 (with-current-buffer ib (org-overview))
13023 ib))))
13025 (defun org-do-occur (regexp &optional cleanup)
13026 "Call the Emacs command `occur'.
13027 If CLEANUP is non-nil, remove the printout of the regular expression
13028 in the *Occur* buffer. This is useful if the regex is long and not useful
13029 to read."
13030 (occur regexp)
13031 (when cleanup
13032 (let ((cwin (selected-window)) win beg end)
13033 (when (setq win (get-buffer-window "*Occur*"))
13034 (select-window win))
13035 (goto-char (point-min))
13036 (when (re-search-forward "match[a-z]+" nil t)
13037 (setq beg (match-end 0))
13038 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
13039 (setq end (1- (match-beginning 0)))))
13040 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
13041 (goto-char (point-min))
13042 (select-window cwin))))
13044 ;;; The mark ring for links jumps
13046 (defvar org-mark-ring nil
13047 "Mark ring for positions before jumps in Org-mode.")
13048 (defvar org-mark-ring-last-goto nil
13049 "Last position in the mark ring used to go back.")
13050 ;; Fill and close the ring
13051 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
13052 (loop for i from 1 to org-mark-ring-length do
13053 (push (make-marker) org-mark-ring))
13054 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
13055 org-mark-ring)
13057 (defun org-mark-ring-push (&optional pos buffer)
13058 "Put the current position or POS into the mark ring and rotate it."
13059 (interactive)
13060 (setq pos (or pos (point)))
13061 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
13062 (move-marker (car org-mark-ring)
13063 (or pos (point))
13064 (or buffer (current-buffer)))
13065 (message "%s"
13066 (substitute-command-keys
13067 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
13069 (defun org-mark-ring-goto (&optional n)
13070 "Jump to the previous position in the mark ring.
13071 With prefix arg N, jump back that many stored positions. When
13072 called several times in succession, walk through the entire ring.
13073 Org-mode commands jumping to a different position in the current file,
13074 or to another Org-mode file, automatically push the old position
13075 onto the ring."
13076 (interactive "p")
13077 (let (p m)
13078 (if (eq last-command this-command)
13079 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
13080 (setq p org-mark-ring))
13081 (setq org-mark-ring-last-goto p)
13082 (setq m (car p))
13083 (switch-to-buffer (marker-buffer m))
13084 (goto-char m)
13085 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
13087 (defun org-remove-angle-brackets (s)
13088 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
13089 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
13091 (defun org-add-angle-brackets (s)
13092 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
13093 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
13096 ;;; Following specific links
13098 (defun org-follow-timestamp-link ()
13099 (cond
13100 ((org-at-date-range-p t)
13101 (let ((org-agenda-start-on-weekday)
13102 (t1 (match-string 1))
13103 (t2 (match-string 2)))
13104 (setq t1 (time-to-days (org-time-string-to-time t1))
13105 t2 (time-to-days (org-time-string-to-time t2)))
13106 (org-agenda-list nil t1 (1+ (- t2 t1)))))
13107 ((org-at-timestamp-p t)
13108 (org-agenda-list nil (time-to-days (org-time-string-to-time
13109 (substring (match-string 1) 0 10)))
13111 (t (error "This should not happen"))))
13114 ;;; BibTeX links
13116 ;; Use the custom search meachnism to construct and use search strings for
13117 ;; file links to BibTeX database entries.
13119 (defun org-create-file-search-in-bibtex ()
13120 "Create the search string and description for a BibTeX database entry."
13121 (when (eq major-mode 'bibtex-mode)
13122 ;; yes, we want to construct this search string.
13123 ;; Make a good description for this entry, using names, year and the title
13124 ;; Put it into the `description' variable which is dynamically scoped.
13125 (let ((bibtex-autokey-names 1)
13126 (bibtex-autokey-names-stretch 1)
13127 (bibtex-autokey-name-case-convert-function 'identity)
13128 (bibtex-autokey-name-separator " & ")
13129 (bibtex-autokey-additional-names " et al.")
13130 (bibtex-autokey-year-length 4)
13131 (bibtex-autokey-name-year-separator " ")
13132 (bibtex-autokey-titlewords 3)
13133 (bibtex-autokey-titleword-separator " ")
13134 (bibtex-autokey-titleword-case-convert-function 'identity)
13135 (bibtex-autokey-titleword-length 'infty)
13136 (bibtex-autokey-year-title-separator ": "))
13137 (setq description (bibtex-generate-autokey)))
13138 ;; Now parse the entry, get the key and return it.
13139 (save-excursion
13140 (bibtex-beginning-of-entry)
13141 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13143 (defun org-execute-file-search-in-bibtex (s)
13144 "Find the link search string S as a key for a database entry."
13145 (when (eq major-mode 'bibtex-mode)
13146 ;; Yes, we want to do the search in this file.
13147 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13148 (goto-char (point-min))
13149 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13150 (regexp-quote s) "[ \t\n]*,") nil t)
13151 (goto-char (match-beginning 0)))
13152 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13153 ;; Use double prefix to indicate that any web link should be browsed
13154 (let ((b (current-buffer)) (p (point)))
13155 ;; Restore the window configuration because we just use the web link
13156 (set-window-configuration org-window-config-before-follow-link)
13157 (save-excursion (set-buffer b) (goto-char p)
13158 (bibtex-url)))
13159 (recenter 0)) ; Move entry start to beginning of window
13160 ;; return t to indicate that the search is done.
13163 ;; Finally add the functions to the right hooks.
13164 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13165 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13167 ;; end of Bibtex link setup
13169 ;;; Following file links
13171 (defun org-open-file (path &optional in-emacs line search)
13172 "Open the file at PATH.
13173 First, this expands any special file name abbreviations. Then the
13174 configuration variable `org-file-apps' is checked if it contains an
13175 entry for this file type, and if yes, the corresponding command is launched.
13176 If no application is found, Emacs simply visits the file.
13177 With optional argument IN-EMACS, Emacs will visit the file.
13178 Optional LINE specifies a line to go to, optional SEARCH a string to
13179 search for. If LINE or SEARCH is given, the file will always be
13180 opened in Emacs.
13181 If the file does not exist, an error is thrown."
13182 (setq in-emacs (or in-emacs line search))
13183 (let* ((file (if (equal path "")
13184 buffer-file-name
13185 (substitute-in-file-name (expand-file-name path))))
13186 (apps (append org-file-apps (org-default-apps)))
13187 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13188 (dirp (if remp nil (file-directory-p file)))
13189 (dfile (downcase file))
13190 (old-buffer (current-buffer))
13191 (old-pos (point))
13192 (old-mode major-mode)
13193 ext cmd)
13194 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13195 (setq ext (match-string 1 dfile))
13196 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13197 (setq ext (match-string 1 dfile))))
13198 (if in-emacs
13199 (setq cmd 'emacs)
13200 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13201 (and dirp (cdr (assoc 'directory apps)))
13202 (cdr (assoc ext apps))
13203 (cdr (assoc t apps)))))
13204 (when (eq cmd 'mailcap)
13205 (require 'mailcap)
13206 (mailcap-parse-mailcaps)
13207 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13208 (command (mailcap-mime-info mime-type)))
13209 (if (stringp command)
13210 (setq cmd command)
13211 (setq cmd 'emacs))))
13212 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13213 (not (file-exists-p file))
13214 (not org-open-non-existing-files))
13215 (error "No such file: %s" file))
13216 (cond
13217 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13218 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13219 (while (string-match "['\"]%s['\"]" cmd)
13220 (setq cmd (replace-match "%s" t t cmd)))
13221 (while (string-match "%s" cmd)
13222 (setq cmd (replace-match
13223 (save-match-data (shell-quote-argument file))
13224 t t cmd)))
13225 (save-window-excursion
13226 (start-process-shell-command cmd nil cmd)))
13227 ((or (stringp cmd)
13228 (eq cmd 'emacs))
13229 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13230 (widen)
13231 (if line (goto-line line)
13232 (if search (org-link-search search))))
13233 ((consp cmd)
13234 (eval cmd))
13235 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13236 (and (org-mode-p) (eq old-mode 'org-mode)
13237 (or (not (equal old-buffer (current-buffer)))
13238 (not (equal old-pos (point))))
13239 (org-mark-ring-push old-pos old-buffer))))
13241 (defun org-default-apps ()
13242 "Return the default applications for this operating system."
13243 (cond
13244 ((eq system-type 'darwin)
13245 org-file-apps-defaults-macosx)
13246 ((eq system-type 'windows-nt)
13247 org-file-apps-defaults-windowsnt)
13248 (t org-file-apps-defaults-gnu)))
13250 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13251 (defun org-file-remote-p (file)
13252 "Test whether FILE specifies a location on a remote system.
13253 Return non-nil if the location is indeed remote.
13255 For example, the filename \"/user@host:/foo\" specifies a location
13256 on the system \"/user@host:\"."
13257 (cond ((fboundp 'file-remote-p)
13258 (file-remote-p file))
13259 ((fboundp 'tramp-handle-file-remote-p)
13260 (tramp-handle-file-remote-p file))
13261 ((and (boundp 'ange-ftp-name-format)
13262 (string-match (car ange-ftp-name-format) file))
13264 (t nil)))
13267 ;;;; Hooks for remember.el, and refiling
13269 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13270 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13272 ;;;###autoload
13273 (defun org-remember-insinuate ()
13274 "Setup remember.el for use wiht Org-mode."
13275 (require 'remember)
13276 (setq remember-annotation-functions '(org-remember-annotation))
13277 (setq remember-handler-functions '(org-remember-handler))
13278 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13280 ;;;###autoload
13281 (defun org-remember-annotation ()
13282 "Return a link to the current location as an annotation for remember.el.
13283 If you are using Org-mode files as target for data storage with
13284 remember.el, then the annotations should include a link compatible with the
13285 conventions in Org-mode. This function returns such a link."
13286 (org-store-link nil))
13288 (defconst org-remember-help
13289 "Select a destination location for the note.
13290 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13291 RET on headline -> Store as sublevel entry to current headline
13292 RET at beg-of-buf -> Append to file as level 2 headline
13293 <left>/<right> -> before/after current headline, same headings level")
13295 (defvar org-remember-previous-location nil)
13296 (defvar org-force-remember-template-char) ;; dynamically scoped
13298 ;; Save the major mode of the buffer we called remember from
13299 (defvar org-select-template-temp-major-mode nil)
13301 ;; Temporary store the buffer where remember was called from
13302 (defvar org-select-template-original-buffer nil)
13304 (defun org-select-remember-template (&optional use-char)
13305 (when org-remember-templates
13306 (let* ((pre-selected-templates
13307 (mapcar
13308 (lambda (tpl)
13309 (let ((ctxt (nth 5 tpl))
13310 (mode org-select-template-temp-major-mode)
13311 (buf org-select-template-original-buffer))
13312 (and (or (not ctxt) (eq ctxt t)
13313 (and (listp ctxt) (memq mode ctxt))
13314 (and (functionp ctxt)
13315 (with-current-buffer buf
13316 ;; Protect the user-defined function from error
13317 (condition-case nil (funcall ctxt) (error nil)))))
13318 tpl)))
13319 org-remember-templates))
13320 ;; If no template at this point, add the default templates:
13321 (pre-selected-templates1
13322 (if (not (delq nil pre-selected-templates))
13323 (mapcar (lambda(x) (if (not (nth 5 x)) x))
13324 org-remember-templates)
13325 pre-selected-templates))
13326 ;; Then unconditionnally add template for any contexts
13327 (pre-selected-templates2
13328 (append (mapcar (lambda(x) (if (eq (nth 5 x) t) x))
13329 org-remember-templates)
13330 (delq nil pre-selected-templates1)))
13331 (templates (mapcar (lambda (x)
13332 (if (stringp (car x))
13333 (append (list (nth 1 x) (car x)) (cddr x))
13334 (append (list (car x) "") (cdr x))))
13335 (delq nil pre-selected-templates2)))
13336 (char (or use-char
13337 (cond
13338 ((= (length templates) 1)
13339 (caar templates))
13340 ((and (boundp 'org-force-remember-template-char)
13341 org-force-remember-template-char)
13342 (if (stringp org-force-remember-template-char)
13343 (string-to-char org-force-remember-template-char)
13344 org-force-remember-template-char))
13346 (message "Select template: %s"
13347 (mapconcat
13348 (lambda (x)
13349 (cond
13350 ((not (string-match "\\S-" (nth 1 x)))
13351 (format "[%c]" (car x)))
13352 ((equal (downcase (car x))
13353 (downcase (aref (nth 1 x) 0)))
13354 (format "[%c]%s" (car x)
13355 (substring (nth 1 x) 1)))
13356 (t (format "[%c]%s" (car x) (nth 1 x)))))
13357 templates " "))
13358 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13359 (when (equal char0 ?\C-g)
13360 (jump-to-register remember-register)
13361 (kill-buffer remember-buffer))
13362 char0))))))
13363 (cddr (assoc char templates)))))
13365 (defvar x-last-selected-text)
13366 (defvar x-last-selected-text-primary)
13368 ;;;###autoload
13369 (defun org-remember-apply-template (&optional use-char skip-interactive)
13370 "Initialize *remember* buffer with template, invoke `org-mode'.
13371 This function should be placed into `remember-mode-hook' and in fact requires
13372 to be run from that hook to function properly."
13373 (if org-remember-templates
13374 (let* ((entry (org-select-remember-template use-char))
13375 (tpl (car entry))
13376 (plist-p (if org-store-link-plist t nil))
13377 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13378 (string-match "\\S-" (nth 1 entry)))
13379 (nth 1 entry)
13380 org-default-notes-file))
13381 (headline (nth 2 entry))
13382 (v-c (or (and (eq window-system 'x)
13383 (fboundp 'x-cut-buffer-or-selection-value)
13384 (x-cut-buffer-or-selection-value))
13385 (org-bound-and-true-p x-last-selected-text)
13386 (org-bound-and-true-p x-last-selected-text-primary)
13387 (and (> (length kill-ring) 0) (current-kill 0))))
13388 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13389 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13390 (v-u (concat "[" (substring v-t 1 -1) "]"))
13391 (v-U (concat "[" (substring v-T 1 -1) "]"))
13392 ;; `initial' and `annotation' are bound in `remember'
13393 (v-i (if (boundp 'initial) initial))
13394 (v-a (if (and (boundp 'annotation) annotation)
13395 (if (equal annotation "[[]]") "" annotation)
13396 ""))
13397 (v-A (if (and v-a
13398 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13399 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13400 v-a))
13401 (v-n user-full-name)
13402 (org-startup-folded nil)
13403 org-time-was-given org-end-time-was-given x
13404 prompt completions char time pos default histvar)
13405 (setq org-store-link-plist
13406 (append (list :annotation v-a :initial v-i)
13407 org-store-link-plist))
13408 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13409 (erase-buffer)
13410 (insert (substitute-command-keys
13411 (format
13412 "## Filing location: Select interactively, default, or last used:
13413 ## %s to select file and header location interactively.
13414 ## %s \"%s\" -> \"* %s\"
13415 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13416 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13417 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13418 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13419 (abbreviate-file-name (or file org-default-notes-file))
13420 (or headline "")
13421 (or (car org-remember-previous-location) "???")
13422 (or (cdr org-remember-previous-location) "???"))))
13423 (insert tpl) (goto-char (point-min))
13424 ;; Simple %-escapes
13425 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13426 (when (and initial (equal (match-string 0) "%i"))
13427 (save-match-data
13428 (let* ((lead (buffer-substring
13429 (point-at-bol) (match-beginning 0))))
13430 (setq v-i (mapconcat 'identity
13431 (org-split-string initial "\n")
13432 (concat "\n" lead))))))
13433 (replace-match
13434 (or (eval (intern (concat "v-" (match-string 1)))) "")
13435 t t))
13437 ;; %[] Insert contents of a file.
13438 (goto-char (point-min))
13439 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13440 (let ((start (match-beginning 0))
13441 (end (match-end 0))
13442 (filename (expand-file-name (match-string 1))))
13443 (goto-char start)
13444 (delete-region start end)
13445 (condition-case error
13446 (insert-file-contents filename)
13447 (error (insert (format "%%![Couldn't insert %s: %s]"
13448 filename error))))))
13449 ;; %() embedded elisp
13450 (goto-char (point-min))
13451 (while (re-search-forward "%\\((.+)\\)" nil t)
13452 (goto-char (match-beginning 0))
13453 (let ((template-start (point)))
13454 (forward-char 1)
13455 (let ((result
13456 (condition-case error
13457 (eval (read (current-buffer)))
13458 (error (format "%%![Error: %s]" error)))))
13459 (delete-region template-start (point))
13460 (insert result))))
13462 ;; From the property list
13463 (when plist-p
13464 (goto-char (point-min))
13465 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13466 (and (setq x (or (plist-get org-store-link-plist
13467 (intern (match-string 1))) ""))
13468 (replace-match x t t))))
13470 ;; Turn on org-mode in the remember buffer, set local variables
13471 (org-mode)
13472 (org-set-local 'org-finish-function 'org-remember-finalize)
13473 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13474 (org-set-local 'org-default-notes-file file))
13475 (if (and headline (stringp headline) (string-match "\\S-" headline))
13476 (org-set-local 'org-remember-default-headline headline))
13477 ;; Interactive template entries
13478 (goto-char (point-min))
13479 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13480 (setq char (if (match-end 3) (match-string 3))
13481 prompt (if (match-end 2) (match-string 2)))
13482 (goto-char (match-beginning 0))
13483 (replace-match "")
13484 (setq completions nil default nil)
13485 (when prompt
13486 (setq completions (org-split-string prompt "|")
13487 prompt (pop completions)
13488 default (car completions)
13489 histvar (intern (concat
13490 "org-remember-template-prompt-history::"
13491 (or prompt "")))
13492 completions (mapcar 'list completions)))
13493 (cond
13494 ((member char '("G" "g"))
13495 (let* ((org-last-tags-completion-table
13496 (org-global-tags-completion-table
13497 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13498 (org-add-colon-after-tag-completion t)
13499 (ins (completing-read
13500 (if prompt (concat prompt ": ") "Tags: ")
13501 'org-tags-completion-function nil nil nil
13502 'org-tags-history)))
13503 (setq ins (mapconcat 'identity
13504 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13505 ":"))
13506 (when (string-match "\\S-" ins)
13507 (or (equal (char-before) ?:) (insert ":"))
13508 (insert ins)
13509 (or (equal (char-after) ?:) (insert ":")))))
13510 (char
13511 (setq org-time-was-given (equal (upcase char) char))
13512 (setq time (org-read-date (equal (upcase char) "U") t nil
13513 prompt))
13514 (org-insert-time-stamp time org-time-was-given
13515 (member char '("u" "U"))
13516 nil nil (list org-end-time-was-given)))
13518 (insert (org-completing-read
13519 (concat (if prompt prompt "Enter string")
13520 (if default (concat " [" default "]"))
13521 ": ")
13522 completions nil nil nil histvar default)))))
13523 (goto-char (point-min))
13524 (if (re-search-forward "%\\?" nil t)
13525 (replace-match "")
13526 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13527 (org-mode)
13528 (org-set-local 'org-finish-function 'org-remember-finalize))
13529 (when (save-excursion
13530 (goto-char (point-min))
13531 (re-search-forward "%!" nil t))
13532 (replace-match "")
13533 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13535 (defun org-remember-finish-immediately ()
13536 "File remember note immediately.
13537 This should be run in `post-command-hook' and will remove itself
13538 from that hook."
13539 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13540 (when org-finish-function
13541 (funcall org-finish-function)))
13543 (defvar org-clock-marker) ; Defined below
13544 (defun org-remember-finalize ()
13545 "Finalize the remember process."
13546 (unless (fboundp 'remember-finalize)
13547 (defalias 'remember-finalize 'remember-buffer))
13548 (when (and org-clock-marker
13549 (equal (marker-buffer org-clock-marker) (current-buffer)))
13550 ;; FIXME: test this, this is w/o notetaking!
13551 (let (org-log-note-clock-out) (org-clock-out)))
13552 (when buffer-file-name
13553 (save-buffer)
13554 (setq buffer-file-name nil))
13555 (remember-finalize))
13557 ;;;###autoload
13558 (defun org-remember (&optional goto org-force-remember-template-char)
13559 "Call `remember'. If this is already a remember buffer, re-apply template.
13560 If there is an active region, make sure remember uses it as initial content
13561 of the remember buffer.
13563 When called interactively with a `C-u' prefix argument GOTO, don't remember
13564 anything, just go to the file/headline where the selected template usually
13565 stores its notes. With a double prefix arg `C-u C-u', go to the last
13566 note stored by remember.
13568 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13569 associated with a template in `org-remember-templates'."
13570 (interactive "P")
13571 (cond
13572 ((equal goto '(4)) (org-go-to-remember-target))
13573 ((equal goto '(16)) (org-remember-goto-last-stored))
13575 ;; set temporary variables that will be needed in
13576 ;; `org-select-remember-template'
13577 (setq org-select-template-temp-major-mode major-mode)
13578 (setq org-select-template-original-buffer (current-buffer))
13579 (if (memq org-finish-function '(remember-buffer remember-finalize))
13580 (progn
13581 (when (< (length org-remember-templates) 2)
13582 (error "No other template available"))
13583 (erase-buffer)
13584 (let ((annotation (plist-get org-store-link-plist :annotation))
13585 (initial (plist-get org-store-link-plist :initial)))
13586 (org-remember-apply-template))
13587 (message "Press C-c C-c to remember data"))
13588 (if (org-region-active-p)
13589 (remember (buffer-substring (point) (mark)))
13590 (call-interactively 'remember))))))
13592 (defun org-remember-goto-last-stored ()
13593 "Go to the location where the last remember note was stored."
13594 (interactive)
13595 (bookmark-jump "org-remember-last-stored")
13596 (message "This is the last note stored by remember"))
13598 (defun org-go-to-remember-target (&optional template-key)
13599 "Go to the target location of a remember template.
13600 The user is queried for the template."
13601 (interactive)
13602 (let* (org-select-template-temp-major-mode
13603 (entry (org-select-remember-template template-key))
13604 (file (nth 1 entry))
13605 (heading (nth 2 entry))
13606 visiting)
13607 (unless (and file (stringp file) (string-match "\\S-" file))
13608 (setq file org-default-notes-file))
13609 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13610 (setq heading org-remember-default-headline))
13611 (setq visiting (org-find-base-buffer-visiting file))
13612 (if (not visiting) (find-file-noselect file))
13613 (switch-to-buffer (or visiting (get-file-buffer file)))
13614 (widen)
13615 (goto-char (point-min))
13616 (if (re-search-forward
13617 (concat "^\\*+[ \t]+" (regexp-quote heading)
13618 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13619 nil t)
13620 (goto-char (match-beginning 0))
13621 (error "Target headline not found: %s" heading))))
13623 (defvar org-note-abort nil) ; dynamically scoped
13625 ;;;###autoload
13626 (defun org-remember-handler ()
13627 "Store stuff from remember.el into an org file.
13628 First prompts for an org file. If the user just presses return, the value
13629 of `org-default-notes-file' is used.
13630 Then the command offers the headings tree of the selected file in order to
13631 file the text at a specific location.
13632 You can either immediately press RET to get the note appended to the
13633 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13634 find a better place. Then press RET or <left> or <right> in insert the note.
13636 Key Cursor position Note gets inserted
13637 -----------------------------------------------------------------------------
13638 RET buffer-start as level 1 heading at end of file
13639 RET on headline as sublevel of the heading at cursor
13640 RET no heading at cursor position, level taken from context.
13641 Or use prefix arg to specify level manually.
13642 <left> on headline as same level, before current heading
13643 <right> on headline as same level, after current heading
13645 So the fastest way to store the note is to press RET RET to append it to
13646 the default file. This way your current train of thought is not
13647 interrupted, in accordance with the principles of remember.el.
13648 You can also get the fast execution without prompting by using
13649 C-u C-c C-c to exit the remember buffer. See also the variable
13650 `org-remember-store-without-prompt'.
13652 Before being stored away, the function ensures that the text has a
13653 headline, i.e. a first line that starts with a \"*\". If not, a headline
13654 is constructed from the current date and some additional data.
13656 If the variable `org-adapt-indentation' is non-nil, the entire text is
13657 also indented so that it starts in the same column as the headline
13658 \(i.e. after the stars).
13660 See also the variable `org-reverse-note-order'."
13661 (goto-char (point-min))
13662 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13663 (replace-match ""))
13664 (goto-char (point-max))
13665 (beginning-of-line 1)
13666 (while (looking-at "[ \t]*$\\|##.*")
13667 (delete-region (1- (point)) (point-max))
13668 (beginning-of-line 1))
13669 (catch 'quit
13670 (if org-note-abort (throw 'quit nil))
13671 (let* ((txt (buffer-substring (point-min) (point-max)))
13672 (fastp (org-xor (equal current-prefix-arg '(4))
13673 org-remember-store-without-prompt))
13674 (file (cond
13675 (fastp org-default-notes-file)
13676 ((and (eq org-remember-interactive-interface 'refile)
13677 org-refile-targets)
13678 org-default-notes-file)
13679 ((not (and (equal current-prefix-arg '(16))
13680 org-remember-previous-location))
13681 (org-get-org-file))))
13682 (heading org-remember-default-headline)
13683 (visiting (and file (org-find-base-buffer-visiting file)))
13684 (org-startup-folded nil)
13685 (org-startup-align-all-tables nil)
13686 (org-goto-start-pos 1)
13687 spos exitcmd level indent reversed)
13688 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13689 (setq file (car org-remember-previous-location)
13690 heading (cdr org-remember-previous-location)
13691 fastp t))
13692 (setq current-prefix-arg nil)
13693 (if (string-match "[ \t\n]+\\'" txt)
13694 (setq txt (replace-match "" t t txt)))
13695 ;; Modify text so that it becomes a nice subtree which can be inserted
13696 ;; into an org tree.
13697 (let* ((lines (split-string txt "\n"))
13698 first)
13699 (setq first (car lines) lines (cdr lines))
13700 (if (string-match "^\\*+ " first)
13701 ;; Is already a headline
13702 (setq indent nil)
13703 ;; We need to add a headline: Use time and first buffer line
13704 (setq lines (cons first lines)
13705 first (concat "* " (current-time-string)
13706 " (" (remember-buffer-desc) ")")
13707 indent " "))
13708 (if (and org-adapt-indentation indent)
13709 (setq lines (mapcar
13710 (lambda (x)
13711 (if (string-match "\\S-" x)
13712 (concat indent x) x))
13713 lines)))
13714 (setq txt (concat first "\n"
13715 (mapconcat 'identity lines "\n"))))
13716 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13717 (setq txt (replace-match "\n\n" t t txt))
13718 (if (string-match "[ \t\n]*\\'" txt)
13719 (setq txt (replace-match "\n" t t txt))))
13720 ;; Put the modified text back into the remember buffer, for refile.
13721 (erase-buffer)
13722 (insert txt)
13723 (goto-char (point-min))
13724 (when (and (eq org-remember-interactive-interface 'refile)
13725 (not fastp))
13726 (org-refile nil (or visiting (find-file-noselect file)))
13727 (throw 'quit t))
13728 ;; Find the file
13729 (if (not visiting) (find-file-noselect file))
13730 (with-current-buffer (or visiting (get-file-buffer file))
13731 (unless (org-mode-p)
13732 (error "Target files for remember notes must be in Org-mode"))
13733 (save-excursion
13734 (save-restriction
13735 (widen)
13736 (and (goto-char (point-min))
13737 (not (re-search-forward "^\\* " nil t))
13738 (insert "\n* " (or heading "Notes") "\n"))
13739 (setq reversed (org-notes-order-reversed-p))
13741 ;; Find the default location
13742 (when (and heading (stringp heading) (string-match "\\S-" heading))
13743 (goto-char (point-min))
13744 (if (re-search-forward
13745 (concat "^\\*+[ \t]+" (regexp-quote heading)
13746 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13747 nil t)
13748 (setq org-goto-start-pos (match-beginning 0))
13749 (when fastp
13750 (goto-char (point-max))
13751 (unless (bolp) (newline))
13752 (insert "* " heading "\n")
13753 (setq org-goto-start-pos (point-at-bol 0)))))
13755 ;; Ask the User for a location, using the appropriate interface
13756 (cond
13757 (fastp (setq spos org-goto-start-pos
13758 exitcmd 'return))
13759 ((eq org-remember-interactive-interface 'outline)
13760 (setq spos (org-get-location (current-buffer)
13761 org-remember-help)
13762 exitcmd (cdr spos)
13763 spos (car spos)))
13764 ((eq org-remember-interactive-interface 'outline-path-completion)
13765 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
13766 (org-refile-use-outline-path t))
13767 (setq spos (org-refile-get-location "Heading: ")
13768 exitcmd 'return
13769 spos (nth 3 spos))))
13770 (t (error "this should not hapen")))
13771 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13772 ; not handle this note
13773 (goto-char spos)
13774 (cond ((org-on-heading-p t)
13775 (org-back-to-heading t)
13776 (setq level (funcall outline-level))
13777 (cond
13778 ((eq exitcmd 'return)
13779 ;; sublevel of current
13780 (setq org-remember-previous-location
13781 (cons (abbreviate-file-name file)
13782 (org-get-heading 'notags)))
13783 (if reversed
13784 (outline-next-heading)
13785 (org-end-of-subtree t)
13786 (if (not (bolp))
13787 (if (looking-at "[ \t]*\n")
13788 (beginning-of-line 2)
13789 (end-of-line 1)
13790 (insert "\n"))))
13791 (bookmark-set "org-remember-last-stored")
13792 (org-paste-subtree (org-get-valid-level level 1) txt))
13793 ((eq exitcmd 'left)
13794 ;; before current
13795 (bookmark-set "org-remember-last-stored")
13796 (org-paste-subtree level txt))
13797 ((eq exitcmd 'right)
13798 ;; after current
13799 (org-end-of-subtree t)
13800 (bookmark-set "org-remember-last-stored")
13801 (org-paste-subtree level txt))
13802 (t (error "This should not happen"))))
13804 ((and (bobp) (not reversed))
13805 ;; Put it at the end, one level below level 1
13806 (save-restriction
13807 (widen)
13808 (goto-char (point-max))
13809 (if (not (bolp)) (newline))
13810 (bookmark-set "org-remember-last-stored")
13811 (org-paste-subtree (org-get-valid-level 1 1) txt)))
13813 ((and (bobp) reversed)
13814 ;; Put it at the start, as level 1
13815 (save-restriction
13816 (widen)
13817 (goto-char (point-min))
13818 (re-search-forward "^\\*+ " nil t)
13819 (beginning-of-line 1)
13820 (bookmark-set "org-remember-last-stored")
13821 (org-paste-subtree 1 txt)))
13823 ;; Put it right there, with automatic level determined by
13824 ;; org-paste-subtree or from prefix arg
13825 (bookmark-set "org-remember-last-stored")
13826 (org-paste-subtree
13827 (if (numberp current-prefix-arg) current-prefix-arg)
13828 txt)))
13829 (when remember-save-after-remembering
13830 (save-buffer)
13831 (if (not visiting) (kill-buffer (current-buffer)))))))))
13833 t) ;; return t to indicate that we took care of this note.
13835 (defun org-get-org-file ()
13836 "Read a filename, with default directory `org-directory'."
13837 (let ((default (or org-default-notes-file remember-data-file)))
13838 (read-file-name (format "File name [%s]: " default)
13839 (file-name-as-directory org-directory)
13840 default)))
13842 (defun org-notes-order-reversed-p ()
13843 "Check if the current file should receive notes in reversed order."
13844 (cond
13845 ((not org-reverse-note-order) nil)
13846 ((eq t org-reverse-note-order) t)
13847 ((not (listp org-reverse-note-order)) nil)
13848 (t (catch 'exit
13849 (let ((all org-reverse-note-order)
13850 entry)
13851 (while (setq entry (pop all))
13852 (if (string-match (car entry) buffer-file-name)
13853 (throw 'exit (cdr entry))))
13854 nil)))))
13856 ;;; Refiling
13858 (defvar org-refile-target-table nil
13859 "The list of refile targets, created by `org-refile'.")
13861 (defvar org-agenda-new-buffers nil
13862 "Buffers created to visit agenda files.")
13864 (defun org-get-refile-targets (&optional default-buffer)
13865 "Produce a table with refile targets."
13866 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
13867 targets txt re files f desc descre)
13868 (with-current-buffer (or default-buffer (current-buffer))
13869 (while (setq entry (pop entries))
13870 (setq files (car entry) desc (cdr entry))
13871 (cond
13872 ((null files) (setq files (list (current-buffer))))
13873 ((eq files 'org-agenda-files)
13874 (setq files (org-agenda-files 'unrestricted)))
13875 ((and (symbolp files) (fboundp files))
13876 (setq files (funcall files)))
13877 ((and (symbolp files) (boundp files))
13878 (setq files (symbol-value files))))
13879 (if (stringp files) (setq files (list files)))
13880 (cond
13881 ((eq (car desc) :tag)
13882 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
13883 ((eq (car desc) :todo)
13884 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
13885 ((eq (car desc) :regexp)
13886 (setq descre (cdr desc)))
13887 ((eq (car desc) :level)
13888 (setq descre (concat "^\\*\\{" (number-to-string
13889 (if org-odd-levels-only
13890 (1- (* 2 (cdr desc)))
13891 (cdr desc)))
13892 "\\}[ \t]")))
13893 ((eq (car desc) :maxlevel)
13894 (setq descre (concat "^\\*\\{1," (number-to-string
13895 (if org-odd-levels-only
13896 (1- (* 2 (cdr desc)))
13897 (cdr desc)))
13898 "\\}[ \t]")))
13899 (t (error "Bad refiling target description %s" desc)))
13900 (while (setq f (pop files))
13901 (save-excursion
13902 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
13903 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
13904 (save-excursion
13905 (save-restriction
13906 (widen)
13907 (goto-char (point-min))
13908 (while (re-search-forward descre nil t)
13909 (goto-char (point-at-bol))
13910 (when (looking-at org-complex-heading-regexp)
13911 (setq txt (match-string 4)
13912 re (concat "^" (regexp-quote
13913 (buffer-substring (match-beginning 1)
13914 (match-end 4)))))
13915 (if (match-end 5) (setq re (concat re "[ \t]+"
13916 (regexp-quote
13917 (match-string 5)))))
13918 (setq re (concat re "[ \t]*$"))
13919 (when org-refile-use-outline-path
13920 (setq txt (mapconcat 'identity
13921 (append
13922 (if (eq org-refile-use-outline-path 'file)
13923 (list (file-name-nondirectory
13924 (buffer-file-name (buffer-base-buffer))))
13925 (if (eq org-refile-use-outline-path 'full-file-path)
13926 (list (buffer-file-name (buffer-base-buffer)))))
13927 (org-get-outline-path)
13928 (list txt))
13929 "/")))
13930 (push (list txt f re (point)) targets))
13931 (goto-char (point-at-eol))))))))
13932 (nreverse targets))))
13934 (defun org-get-outline-path ()
13935 "Return the outline path to the current entry, as a list."
13936 (let (rtn)
13937 (save-excursion
13938 (while (org-up-heading-safe)
13939 (when (looking-at org-complex-heading-regexp)
13940 (push (org-match-string-no-properties 4) rtn)))
13941 rtn)))
13943 (defvar org-refile-history nil
13944 "History for refiling operations.")
13946 (defun org-refile (&optional goto default-buffer)
13947 "Move the entry at point to another heading.
13948 The list of target headings is compiled using the information in
13949 `org-refile-targets', which see. This list is created upon first use, and
13950 you can update it by calling this command with a double prefix (`C-u C-u').
13951 FIXME: Can we find a better way of updating?
13953 At the target location, the entry is filed as a subitem of the target heading.
13954 Depending on `org-reverse-note-order', the new subitem will either be the
13955 first of the last subitem.
13957 With prefix arg GOTO, the command will only visit the target location,
13958 not actually move anything.
13959 With a double prefix `C-c C-c', go to the location where the last refiling
13960 operation has put the subtree.
13962 With a double prefix argument, the command can be used to jump to any
13963 heading in the current buffer."
13964 (interactive "P")
13965 (let* ((cbuf (current-buffer))
13966 (filename (buffer-file-name (buffer-base-buffer cbuf)))
13967 pos it nbuf file re level reversed)
13968 (if (equal goto '(16))
13969 (org-refile-goto-last-stored)
13970 (when (setq it (org-refile-get-location
13971 (if goto "Goto: " "Refile to: ") default-buffer))
13972 (setq file (nth 1 it)
13973 re (nth 2 it)
13974 pos (nth 3 it))
13975 (setq nbuf (or (find-buffer-visiting file)
13976 (find-file-noselect file)))
13977 (if goto
13978 (progn
13979 (switch-to-buffer nbuf)
13980 (goto-char pos)
13981 (org-show-context 'org-goto))
13982 (org-copy-special)
13983 (save-excursion
13984 (set-buffer (setq nbuf (or (find-buffer-visiting file)
13985 (find-file-noselect file))))
13986 (setq reversed (org-notes-order-reversed-p))
13987 (save-excursion
13988 (save-restriction
13989 (widen)
13990 (goto-char pos)
13991 (looking-at outline-regexp)
13992 (setq level (org-get-valid-level (funcall outline-level) 1))
13993 (goto-char
13994 (if reversed
13995 (outline-next-heading)
13996 (or (save-excursion (outline-get-next-sibling))
13997 (org-end-of-subtree t t)
13998 (point-max))))
13999 (bookmark-set "org-refile-last-stored")
14000 (org-paste-subtree level))))
14001 (org-cut-special)
14002 (message "Entry refiled to \"%s\"" (car it)))))))
14004 (defun org-refile-goto-last-stored ()
14005 "Go to the location where the last refile was stored."
14006 (interactive)
14007 (bookmark-jump "org-refile-last-stored")
14008 (message "This is the location of the last refile"))
14010 (defun org-refile-get-location (&optional prompt default-buffer)
14011 "Prompt the user for a refile location, using PROMPT."
14012 (let ((org-refile-targets org-refile-targets)
14013 (org-refile-use-outline-path org-refile-use-outline-path))
14014 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14015 (unless org-refile-target-table
14016 (error "No refile targets"))
14017 (let* ((cbuf (current-buffer))
14018 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14019 (fname (and filename (file-truename filename)))
14020 (tbl (mapcar
14021 (lambda (x)
14022 (if (not (equal fname (file-truename (nth 1 x))))
14023 (cons (concat (car x) " (" (file-name-nondirectory
14024 (nth 1 x)) ")")
14025 (cdr x))
14027 org-refile-target-table))
14028 (completion-ignore-case t))
14029 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14030 tbl)))
14032 ;;;; Dynamic blocks
14034 (defun org-find-dblock (name)
14035 "Find the first dynamic block with name NAME in the buffer.
14036 If not found, stay at current position and return nil."
14037 (let (pos)
14038 (save-excursion
14039 (goto-char (point-min))
14040 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14041 nil t)
14042 (match-beginning 0))))
14043 (if pos (goto-char pos))
14044 pos))
14046 (defconst org-dblock-start-re
14047 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14048 "Matches the startline of a dynamic block, with parameters.")
14050 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14051 "Matches the end of a dyhamic block.")
14053 (defun org-create-dblock (plist)
14054 "Create a dynamic block section, with parameters taken from PLIST.
14055 PLIST must containe a :name entry which is used as name of the block."
14056 (unless (bolp) (newline))
14057 (let ((name (plist-get plist :name)))
14058 (insert "#+BEGIN: " name)
14059 (while plist
14060 (if (eq (car plist) :name)
14061 (setq plist (cddr plist))
14062 (insert " " (prin1-to-string (pop plist)))))
14063 (insert "\n\n#+END:\n")
14064 (beginning-of-line -2)))
14066 (defun org-prepare-dblock ()
14067 "Prepare dynamic block for refresh.
14068 This empties the block, puts the cursor at the insert position and returns
14069 the property list including an extra property :name with the block name."
14070 (unless (looking-at org-dblock-start-re)
14071 (error "Not at a dynamic block"))
14072 (let* ((begdel (1+ (match-end 0)))
14073 (name (org-no-properties (match-string 1)))
14074 (params (append (list :name name)
14075 (read (concat "(" (match-string 3) ")")))))
14076 (unless (re-search-forward org-dblock-end-re nil t)
14077 (error "Dynamic block not terminated"))
14078 (setq params
14079 (append params
14080 (list :content (buffer-substring
14081 begdel (match-beginning 0)))))
14082 (delete-region begdel (match-beginning 0))
14083 (goto-char begdel)
14084 (open-line 1)
14085 params))
14087 (defun org-map-dblocks (&optional command)
14088 "Apply COMMAND to all dynamic blocks in the current buffer.
14089 If COMMAND is not given, use `org-update-dblock'."
14090 (let ((cmd (or command 'org-update-dblock))
14091 pos)
14092 (save-excursion
14093 (goto-char (point-min))
14094 (while (re-search-forward org-dblock-start-re nil t)
14095 (goto-char (setq pos (match-beginning 0)))
14096 (condition-case nil
14097 (funcall cmd)
14098 (error (message "Error during update of dynamic block")))
14099 (goto-char pos)
14100 (unless (re-search-forward org-dblock-end-re nil t)
14101 (error "Dynamic block not terminated"))))))
14103 (defun org-dblock-update (&optional arg)
14104 "User command for updating dynamic blocks.
14105 Update the dynamic block at point. With prefix ARG, update all dynamic
14106 blocks in the buffer."
14107 (interactive "P")
14108 (if arg
14109 (org-update-all-dblocks)
14110 (or (looking-at org-dblock-start-re)
14111 (org-beginning-of-dblock))
14112 (org-update-dblock)))
14114 (defun org-update-dblock ()
14115 "Update the dynamic block at point
14116 This means to empty the block, parse for parameters and then call
14117 the correct writing function."
14118 (save-window-excursion
14119 (let* ((pos (point))
14120 (line (org-current-line))
14121 (params (org-prepare-dblock))
14122 (name (plist-get params :name))
14123 (cmd (intern (concat "org-dblock-write:" name))))
14124 (message "Updating dynamic block `%s' at line %d..." name line)
14125 (funcall cmd params)
14126 (message "Updating dynamic block `%s' at line %d...done" name line)
14127 (goto-char pos))))
14129 (defun org-beginning-of-dblock ()
14130 "Find the beginning of the dynamic block at point.
14131 Error if there is no scuh block at point."
14132 (let ((pos (point))
14133 beg)
14134 (end-of-line 1)
14135 (if (and (re-search-backward org-dblock-start-re nil t)
14136 (setq beg (match-beginning 0))
14137 (re-search-forward org-dblock-end-re nil t)
14138 (> (match-end 0) pos))
14139 (goto-char beg)
14140 (goto-char pos)
14141 (error "Not in a dynamic block"))))
14143 (defun org-update-all-dblocks ()
14144 "Update all dynamic blocks in the buffer.
14145 This function can be used in a hook."
14146 (when (org-mode-p)
14147 (org-map-dblocks 'org-update-dblock)))
14150 ;;;; Completion
14152 (defconst org-additional-option-like-keywords
14153 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14154 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
14155 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14157 (defun org-complete (&optional arg)
14158 "Perform completion on word at point.
14159 At the beginning of a headline, this completes TODO keywords as given in
14160 `org-todo-keywords'.
14161 If the current word is preceded by a backslash, completes the TeX symbols
14162 that are supported for HTML support.
14163 If the current word is preceded by \"#+\", completes special words for
14164 setting file options.
14165 In the line after \"#+STARTUP:, complete valid keywords.\"
14166 At all other locations, this simply calls the value of
14167 `org-completion-fallback-command'."
14168 (interactive "P")
14169 (org-without-partial-completion
14170 (catch 'exit
14171 (let* ((end (point))
14172 (beg1 (save-excursion
14173 (skip-chars-backward (org-re "[:alnum:]_@"))
14174 (point)))
14175 (beg (save-excursion
14176 (skip-chars-backward "a-zA-Z0-9_:$")
14177 (point)))
14178 (confirm (lambda (x) (stringp (car x))))
14179 (searchhead (equal (char-before beg) ?*))
14180 (tag (and (equal (char-before beg1) ?:)
14181 (equal (char-after (point-at-bol)) ?*)))
14182 (prop (and (equal (char-before beg1) ?:)
14183 (not (equal (char-after (point-at-bol)) ?*))))
14184 (texp (equal (char-before beg) ?\\))
14185 (link (equal (char-before beg) ?\[))
14186 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14187 beg)
14188 "#+"))
14189 (startup (string-match "^#\\+STARTUP:.*"
14190 (buffer-substring (point-at-bol) (point))))
14191 (completion-ignore-case opt)
14192 (type nil)
14193 (tbl nil)
14194 (table (cond
14195 (opt
14196 (setq type :opt)
14197 (append
14198 (mapcar
14199 (lambda (x)
14200 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14201 (cons (match-string 2 x) (match-string 1 x)))
14202 (org-split-string (org-get-current-options) "\n"))
14203 (mapcar 'list org-additional-option-like-keywords)))
14204 (startup
14205 (setq type :startup)
14206 org-startup-options)
14207 (link (append org-link-abbrev-alist-local
14208 org-link-abbrev-alist))
14209 (texp
14210 (setq type :tex)
14211 org-html-entities)
14212 ((string-match "\\`\\*+[ \t]+\\'"
14213 (buffer-substring (point-at-bol) beg))
14214 (setq type :todo)
14215 (mapcar 'list org-todo-keywords-1))
14216 (searchhead
14217 (setq type :searchhead)
14218 (save-excursion
14219 (goto-char (point-min))
14220 (while (re-search-forward org-todo-line-regexp nil t)
14221 (push (list
14222 (org-make-org-heading-search-string
14223 (match-string 3) t))
14224 tbl)))
14225 tbl)
14226 (tag (setq type :tag beg beg1)
14227 (or org-tag-alist (org-get-buffer-tags)))
14228 (prop (setq type :prop beg beg1)
14229 (mapcar 'list (org-buffer-property-keys nil t t)))
14230 (t (progn
14231 (call-interactively org-completion-fallback-command)
14232 (throw 'exit nil)))))
14233 (pattern (buffer-substring-no-properties beg end))
14234 (completion (try-completion pattern table confirm)))
14235 (cond ((eq completion t)
14236 (if (not (assoc (upcase pattern) table))
14237 (message "Already complete")
14238 (if (and (equal type :opt)
14239 (not (member (car (assoc (upcase pattern) table))
14240 org-additional-option-like-keywords)))
14241 (insert (substring (cdr (assoc (upcase pattern) table))
14242 (length pattern)))
14243 (if (memq type '(:tag :prop)) (insert ":")))))
14244 ((null completion)
14245 (message "Can't find completion for \"%s\"" pattern)
14246 (ding))
14247 ((not (string= pattern completion))
14248 (delete-region beg end)
14249 (if (string-match " +$" completion)
14250 (setq completion (replace-match "" t t completion)))
14251 (insert completion)
14252 (if (get-buffer-window "*Completions*")
14253 (delete-window (get-buffer-window "*Completions*")))
14254 (if (assoc completion table)
14255 (if (eq type :todo) (insert " ")
14256 (if (memq type '(:tag :prop)) (insert ":"))))
14257 (if (and (equal type :opt) (assoc completion table))
14258 (message "%s" (substitute-command-keys
14259 "Press \\[org-complete] again to insert example settings"))))
14261 (message "Making completion list...")
14262 (let ((list (sort (all-completions pattern table confirm)
14263 'string<)))
14264 (with-output-to-temp-buffer "*Completions*"
14265 (condition-case nil
14266 ;; Protection needed for XEmacs and emacs 21
14267 (display-completion-list list pattern)
14268 (error (display-completion-list list)))))
14269 (message "Making completion list...%s" "done")))))))
14271 ;;;; TODO, DEADLINE, Comments
14273 (defun org-toggle-comment ()
14274 "Change the COMMENT state of an entry."
14275 (interactive)
14276 (save-excursion
14277 (org-back-to-heading)
14278 (let (case-fold-search)
14279 (if (looking-at (concat outline-regexp
14280 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14281 (replace-match "" t t nil 1)
14282 (if (looking-at outline-regexp)
14283 (progn
14284 (goto-char (match-end 0))
14285 (insert org-comment-string " ")))))))
14287 (defvar org-last-todo-state-is-todo nil
14288 "This is non-nil when the last TODO state change led to a TODO state.
14289 If the last change removed the TODO tag or switched to DONE, then
14290 this is nil.")
14292 (defvar org-setting-tags nil) ; dynamically skiped
14294 ;; FIXME: better place
14295 (defun org-property-or-variable-value (var &optional inherit)
14296 "Check if there is a property fixing the value of VAR.
14297 If yes, return this value. If not, return the current value of the variable."
14298 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14299 (if (and prop (stringp prop) (string-match "\\S-" prop))
14300 (read prop)
14301 (symbol-value var))))
14303 (defun org-parse-local-options (string var)
14304 "Parse STRING for startup setting relevant for variable VAR."
14305 (let ((rtn (symbol-value var))
14306 e opts)
14307 (save-match-data
14308 (if (or (not string) (not (string-match "\\S-" string)))
14310 (setq opts (delq nil (mapcar (lambda (x)
14311 (setq e (assoc x org-startup-options))
14312 (if (eq (nth 1 e) var) e nil))
14313 (org-split-string string "[ \t]+"))))
14314 (if (not opts)
14316 (setq rtn nil)
14317 (while (setq e (pop opts))
14318 (if (not (nth 3 e))
14319 (setq rtn (nth 2 e))
14320 (if (not (listp rtn)) (setq rtn nil))
14321 (push (nth 2 e) rtn)))
14322 rtn)))))
14324 (defvar org-blocker-hook nil
14325 "Hook for functions that are allowed to block a state change.
14327 Each function gets as its single argument a property list, see
14328 `org-trigger-hook' for more information about this list.
14330 If any of the functions in this hook returns nil, the state change
14331 is blocked.")
14333 (defvar org-trigger-hook nil
14334 "Hook for functions that are triggered by a state change.
14336 Each function gets as its single argument a property list with at least
14337 the following elements:
14339 (:type type-of-change :position pos-at-entry-start
14340 :from old-state :to new-state)
14342 Depending on the type, more properties may be present.
14344 This mechanism is currently implemented for:
14346 TODO state changes
14347 ------------------
14348 :type todo-state-change
14349 :from previous state (keyword as a string), or nil
14350 :to new state (keyword as a string), or nil")
14353 (defun org-todo (&optional arg)
14354 "Change the TODO state of an item.
14355 The state of an item is given by a keyword at the start of the heading,
14356 like
14357 *** TODO Write paper
14358 *** DONE Call mom
14360 The different keywords are specified in the variable `org-todo-keywords'.
14361 By default the available states are \"TODO\" and \"DONE\".
14362 So for this example: when the item starts with TODO, it is changed to DONE.
14363 When it starts with DONE, the DONE is removed. And when neither TODO nor
14364 DONE are present, add TODO at the beginning of the heading.
14366 With C-u prefix arg, use completion to determine the new state.
14367 With numeric prefix arg, switch to that state.
14369 For calling through lisp, arg is also interpreted in the following way:
14370 'none -> empty state
14371 \"\"(empty string) -> switch to empty state
14372 'done -> switch to DONE
14373 'nextset -> switch to the next set of keywords
14374 'previousset -> switch to the previous set of keywords
14375 \"WAITING\" -> switch to the specified keyword, but only if it
14376 really is a member of `org-todo-keywords'."
14377 (interactive "P")
14378 (save-excursion
14379 (catch 'exit
14380 (org-back-to-heading)
14381 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14382 (or (looking-at (concat " +" org-todo-regexp " *"))
14383 (looking-at " *"))
14384 (let* ((match-data (match-data))
14385 (startpos (point-at-bol))
14386 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14387 (org-log-done org-log-done)
14388 (org-log-repeat org-log-repeat)
14389 (org-todo-log-states org-todo-log-states)
14390 (this (match-string 1))
14391 (hl-pos (match-beginning 0))
14392 (head (org-get-todo-sequence-head this))
14393 (ass (assoc head org-todo-kwd-alist))
14394 (interpret (nth 1 ass))
14395 (done-word (nth 3 ass))
14396 (final-done-word (nth 4 ass))
14397 (last-state (or this ""))
14398 (completion-ignore-case t)
14399 (member (member this org-todo-keywords-1))
14400 (tail (cdr member))
14401 (state (cond
14402 ((and org-todo-key-trigger
14403 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14404 (and (not arg) org-use-fast-todo-selection
14405 (not (eq org-use-fast-todo-selection 'prefix)))))
14406 ;; Use fast selection
14407 (org-fast-todo-selection))
14408 ((and (equal arg '(4))
14409 (or (not org-use-fast-todo-selection)
14410 (not org-todo-key-trigger)))
14411 ;; Read a state with completion
14412 (completing-read "State: " (mapcar (lambda(x) (list x))
14413 org-todo-keywords-1)
14414 nil t))
14415 ((eq arg 'right)
14416 (if this
14417 (if tail (car tail) nil)
14418 (car org-todo-keywords-1)))
14419 ((eq arg 'left)
14420 (if (equal member org-todo-keywords-1)
14422 (if this
14423 (nth (- (length org-todo-keywords-1) (length tail) 2)
14424 org-todo-keywords-1)
14425 (org-last org-todo-keywords-1))))
14426 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14427 (setq arg nil))) ; hack to fall back to cycling
14428 (arg
14429 ;; user or caller requests a specific state
14430 (cond
14431 ((equal arg "") nil)
14432 ((eq arg 'none) nil)
14433 ((eq arg 'done) (or done-word (car org-done-keywords)))
14434 ((eq arg 'nextset)
14435 (or (car (cdr (member head org-todo-heads)))
14436 (car org-todo-heads)))
14437 ((eq arg 'previousset)
14438 (let ((org-todo-heads (reverse org-todo-heads)))
14439 (or (car (cdr (member head org-todo-heads)))
14440 (car org-todo-heads))))
14441 ((car (member arg org-todo-keywords-1)))
14442 ((nth (1- (prefix-numeric-value arg))
14443 org-todo-keywords-1))))
14444 ((null member) (or head (car org-todo-keywords-1)))
14445 ((equal this final-done-word) nil) ;; -> make empty
14446 ((null tail) nil) ;; -> first entry
14447 ((eq interpret 'sequence)
14448 (car tail))
14449 ((memq interpret '(type priority))
14450 (if (eq this-command last-command)
14451 (car tail)
14452 (if (> (length tail) 0)
14453 (or done-word (car org-done-keywords))
14454 nil)))
14455 (t nil)))
14456 (next (if state (concat " " state " ") " "))
14457 (change-plist (list :type 'todo-state-change :from this :to state
14458 :position startpos))
14459 dolog now-done-p)
14460 (when org-blocker-hook
14461 (unless (save-excursion
14462 (save-match-data
14463 (run-hook-with-args-until-failure
14464 'org-blocker-hook change-plist)))
14465 (if (interactive-p)
14466 (error "TODO state change from %s to %s blocked" this state)
14467 ;; fail silently
14468 (message "TODO state change from %s to %s blocked" this state)
14469 (throw 'exit nil))))
14470 (store-match-data match-data)
14471 (replace-match next t t)
14472 (unless (pos-visible-in-window-p hl-pos)
14473 (message "TODO state changed to %s" (org-trim next)))
14474 (unless head
14475 (setq head (org-get-todo-sequence-head state)
14476 ass (assoc head org-todo-kwd-alist)
14477 interpret (nth 1 ass)
14478 done-word (nth 3 ass)
14479 final-done-word (nth 4 ass)))
14480 (when (memq arg '(nextset previousset))
14481 (message "Keyword-Set %d/%d: %s"
14482 (- (length org-todo-sets) -1
14483 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14484 (length org-todo-sets)
14485 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14486 (setq org-last-todo-state-is-todo
14487 (not (member state org-done-keywords)))
14488 (setq now-done-p (and (member state org-done-keywords)
14489 (not (member this org-done-keywords))))
14490 (and logging (org-local-logging logging))
14491 (when (and (or org-todo-log-states org-log-done)
14492 (not (memq arg '(nextset previousset))))
14493 ;; we need to look at recording a time and note
14494 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
14495 (nth 2 (assoc this org-todo-log-states))))
14496 (when (and state
14497 (member state org-not-done-keywords)
14498 (not (member this org-not-done-keywords)))
14499 ;; This is now a todo state and was not one before
14500 ;; If there was a CLOSED time stamp, get rid of it.
14501 (org-add-planning-info nil nil 'closed))
14502 (when (and now-done-p org-log-done)
14503 ;; It is now done, and it was not done before
14504 (org-add-planning-info 'closed (org-current-time))
14505 (if (and (not dolog) (eq 'note org-log-done))
14506 (org-add-log-maybe 'done state 'findpos 'note)))
14507 (when (and state dolog)
14508 ;; This is a non-nil state, and we need to log it
14509 (org-add-log-maybe 'state state 'findpos dolog)))
14510 ;; Fixup tag positioning
14511 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14512 (run-hooks 'org-after-todo-state-change-hook)
14513 (if (and arg (not (member state org-done-keywords)))
14514 (setq head (org-get-todo-sequence-head state)))
14515 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14516 ;; Do we need to trigger a repeat?
14517 (when now-done-p (org-auto-repeat-maybe state))
14518 ;; Fixup cursor location if close to the keyword
14519 (if (and (outline-on-heading-p)
14520 (not (bolp))
14521 (save-excursion (beginning-of-line 1)
14522 (looking-at org-todo-line-regexp))
14523 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14524 (progn
14525 (goto-char (or (match-end 2) (match-end 1)))
14526 (just-one-space)))
14527 (when org-trigger-hook
14528 (save-excursion
14529 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14531 (defun org-local-logging (value)
14532 "Get logging settings from a property VALUE."
14533 (let* (words w a)
14534 ;; directly set the variables, they are already local.
14535 (setq org-log-done nil
14536 org-log-repeat nil
14537 org-todo-log-states nil)
14538 (setq words (org-split-string value))
14539 (while (setq w (pop words))
14540 (cond
14541 ((setq a (assoc w org-startup-options))
14542 (and (member (nth 1 a) '(org-log-done org-log-repeat))
14543 (set (nth 1 a) (nth 2 a))))
14544 ((setq a (org-extract-log-state-settings w))
14545 (and (member (car a) org-todo-keywords-1)
14546 (push a org-todo-log-states)))))))
14548 (defun org-get-todo-sequence-head (kwd)
14549 "Return the head of the TODO sequence to which KWD belongs.
14550 If KWD is not set, check if there is a text property remembering the
14551 right sequence."
14552 (let (p)
14553 (cond
14554 ((not kwd)
14555 (or (get-text-property (point-at-bol) 'org-todo-head)
14556 (progn
14557 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14558 nil (point-at-eol)))
14559 (get-text-property p 'org-todo-head))))
14560 ((not (member kwd org-todo-keywords-1))
14561 (car org-todo-keywords-1))
14562 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14564 (defun org-fast-todo-selection ()
14565 "Fast TODO keyword selection with single keys.
14566 Returns the new TODO keyword, or nil if no state change should occur."
14567 (let* ((fulltable org-todo-key-alist)
14568 (done-keywords org-done-keywords) ;; needed for the faces.
14569 (maxlen (apply 'max (mapcar
14570 (lambda (x)
14571 (if (stringp (car x)) (string-width (car x)) 0))
14572 fulltable)))
14573 (expert nil)
14574 (fwidth (+ maxlen 3 1 3))
14575 (ncol (/ (- (window-width) 4) fwidth))
14576 tg cnt e c tbl
14577 groups ingroup)
14578 (save-window-excursion
14579 (if expert
14580 (set-buffer (get-buffer-create " *Org todo*"))
14581 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14582 (erase-buffer)
14583 (org-set-local 'org-done-keywords done-keywords)
14584 (setq tbl fulltable cnt 0)
14585 (while (setq e (pop tbl))
14586 (cond
14587 ((equal e '(:startgroup))
14588 (push '() groups) (setq ingroup t)
14589 (when (not (= cnt 0))
14590 (setq cnt 0)
14591 (insert "\n"))
14592 (insert "{ "))
14593 ((equal e '(:endgroup))
14594 (setq ingroup nil cnt 0)
14595 (insert "}\n"))
14597 (setq tg (car e) c (cdr e))
14598 (if ingroup (push tg (car groups)))
14599 (setq tg (org-add-props tg nil 'face
14600 (org-get-todo-face tg)))
14601 (if (and (= cnt 0) (not ingroup)) (insert " "))
14602 (insert "[" c "] " tg (make-string
14603 (- fwidth 4 (length tg)) ?\ ))
14604 (when (= (setq cnt (1+ cnt)) ncol)
14605 (insert "\n")
14606 (if ingroup (insert " "))
14607 (setq cnt 0)))))
14608 (insert "\n")
14609 (goto-char (point-min))
14610 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14611 (fit-window-to-buffer))
14612 (message "[a-z..]:Set [SPC]:clear")
14613 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14614 (cond
14615 ((or (= c ?\C-g)
14616 (and (= c ?q) (not (rassoc c fulltable))))
14617 (setq quit-flag t))
14618 ((= c ?\ ) nil)
14619 ((setq e (rassoc c fulltable) tg (car e))
14621 (t (setq quit-flag t))))))
14623 (defun org-get-repeat ()
14624 "Check if tere is a deadline/schedule with repeater in this entry."
14625 (save-match-data
14626 (save-excursion
14627 (org-back-to-heading t)
14628 (if (re-search-forward
14629 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14630 (match-string 1)))))
14632 (defvar org-last-changed-timestamp)
14633 (defvar org-log-post-message)
14634 (defvar org-log-note-purpose)
14635 (defun org-auto-repeat-maybe (done-word)
14636 "Check if the current headline contains a repeated deadline/schedule.
14637 If yes, set TODO state back to what it was and change the base date
14638 of repeating deadline/scheduled time stamps to new date.
14639 This function is run automatically after each state change to a DONE state."
14640 ;; last-state is dynamically scoped into this function
14641 (let* ((repeat (org-get-repeat))
14642 (aa (assoc last-state org-todo-kwd-alist))
14643 (interpret (nth 1 aa))
14644 (head (nth 2 aa))
14645 (whata '(("d" . day) ("m" . month) ("y" . year)))
14646 (msg "Entry repeats: ")
14647 (org-log-done nil)
14648 (org-todo-log-states nil)
14649 (nshiftmax 10) (nshift 0)
14650 re type n what ts mb0 time)
14651 (when repeat
14652 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
14653 (org-todo (if (eq interpret 'type) last-state head))
14654 (when (and org-log-repeat
14655 (or (not (memq 'org-add-log-note
14656 (default-value 'post-command-hook)))
14657 (eq org-log-note-purpose 'done)))
14658 ;; Make sure a note is taken;
14659 (org-add-log-maybe 'state (or done-word (car org-done-keywords))
14660 'findpos org-log-repeat))
14661 (org-back-to-heading t)
14662 (org-add-planning-info nil nil 'closed)
14663 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14664 org-deadline-time-regexp "\\)\\|\\("
14665 org-ts-regexp "\\)"))
14666 (while (re-search-forward
14667 re (save-excursion (outline-next-heading) (point)) t)
14668 (setq type (if (match-end 1) org-scheduled-string
14669 (if (match-end 3) org-deadline-string "Plain:"))
14670 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
14671 mb0 (match-beginning 0))
14672 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
14673 (setq n (string-to-number (match-string 2 ts))
14674 what (match-string 3 ts))
14675 (if (equal what "w") (setq n (* n 7) what "d"))
14676 ;; Preparation, see if we need to modify the start date for the change
14677 (when (match-end 1)
14678 (setq time (save-match-data (org-time-string-to-time ts)))
14679 (cond
14680 ((equal (match-string 1 ts) ".")
14681 ;; Shift starting date to today
14682 (org-timestamp-change
14683 (- (time-to-days (current-time)) (time-to-days time))
14684 'day))
14685 ((equal (match-string 1 ts) "+")
14686 (while (< (time-to-days time) (time-to-days (current-time)))
14687 (when (= (incf nshift) nshiftmax)
14688 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
14689 (error "Abort")))
14690 (org-timestamp-change n (cdr (assoc what whata)))
14691 (sit-for .0001) ;; so we can watch the date shifting
14692 (org-at-timestamp-p t)
14693 (setq ts (match-string 1))
14694 (setq time (save-match-data (org-time-string-to-time ts))))
14695 (org-timestamp-change (- n) (cdr (assoc what whata)))
14696 ;; rematch, so that we have everything in place for the real shift
14697 (org-at-timestamp-p t)
14698 (setq ts (match-string 1))
14699 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
14700 (org-timestamp-change n (cdr (assoc what whata)))
14701 (setq msg (concat msg type org-last-changed-timestamp " "))))
14702 (setq org-log-post-message msg)
14703 (message "%s" msg))))
14705 (defun org-show-todo-tree (arg)
14706 "Make a compact tree which shows all headlines marked with TODO.
14707 The tree will show the lines where the regexp matches, and all higher
14708 headlines above the match.
14709 With a \\[universal-argument] prefix, also show the DONE entries.
14710 With a numeric prefix N, construct a sparse tree for the Nth element
14711 of `org-todo-keywords-1'."
14712 (interactive "P")
14713 (let ((case-fold-search nil)
14714 (kwd-re
14715 (cond ((null arg) org-not-done-regexp)
14716 ((equal arg '(4))
14717 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14718 (mapcar 'list org-todo-keywords-1))))
14719 (concat "\\("
14720 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14721 "\\)\\>")))
14722 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14723 (regexp-quote (nth (1- (prefix-numeric-value arg))
14724 org-todo-keywords-1)))
14725 (t (error "Invalid prefix argument: %s" arg)))))
14726 (message "%d TODO entries found"
14727 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14729 (defun org-deadline (&optional remove)
14730 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14731 With argument REMOVE, remove any deadline from the item."
14732 (interactive "P")
14733 (if remove
14734 (progn
14735 (org-remove-timestamp-with-keyword org-deadline-string)
14736 (message "Item no longer has a deadline."))
14737 (org-add-planning-info 'deadline nil 'closed)))
14739 (defun org-schedule (&optional remove)
14740 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14741 With argument REMOVE, remove any scheduling date from the item."
14742 (interactive "P")
14743 (if remove
14744 (progn
14745 (org-remove-timestamp-with-keyword org-scheduled-string)
14746 (message "Item is no longer scheduled."))
14747 (org-add-planning-info 'scheduled nil 'closed)))
14749 (defun org-remove-timestamp-with-keyword (keyword)
14750 "Remove all time stamps with KEYWORD in the current entry."
14751 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
14752 beg)
14753 (save-excursion
14754 (org-back-to-heading t)
14755 (setq beg (point))
14756 (org-end-of-subtree t t)
14757 (while (re-search-backward re beg t)
14758 (replace-match "")
14759 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
14760 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
14762 (defun org-add-planning-info (what &optional time &rest remove)
14763 "Insert new timestamp with keyword in the line directly after the headline.
14764 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14765 If non is given, the user is prompted for a date.
14766 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14767 be removed."
14768 (interactive)
14769 (let (org-time-was-given org-end-time-was-given ts
14770 end default-time default-input)
14772 (when (and (not time) (memq what '(scheduled deadline)))
14773 ;; Try to get a default date/time from existing timestamp
14774 (save-excursion
14775 (org-back-to-heading t)
14776 (setq end (save-excursion (outline-next-heading) (point)))
14777 (when (re-search-forward (if (eq what 'scheduled)
14778 org-scheduled-time-regexp
14779 org-deadline-time-regexp)
14780 end t)
14781 (setq ts (match-string 1)
14782 default-time
14783 (apply 'encode-time (org-parse-time-string ts))
14784 default-input (and ts (org-get-compact-tod ts))))))
14785 (when what
14786 ;; If necessary, get the time from the user
14787 (setq time (or time (org-read-date nil 'to-time nil nil
14788 default-time default-input))))
14790 (when (and org-insert-labeled-timestamps-at-point
14791 (member what '(scheduled deadline)))
14792 (insert
14793 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14794 (org-insert-time-stamp time org-time-was-given
14795 nil nil nil (list org-end-time-was-given))
14796 (setq what nil))
14797 (save-excursion
14798 (save-restriction
14799 (let (col list elt ts buffer-invisibility-spec)
14800 (org-back-to-heading t)
14801 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14802 (goto-char (match-end 1))
14803 (setq col (current-column))
14804 (goto-char (match-end 0))
14805 (if (eobp) (insert "\n") (forward-char 1))
14806 (if (and (not (looking-at outline-regexp))
14807 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14808 "[^\r\n]*"))
14809 (not (equal (match-string 1) org-clock-string)))
14810 (narrow-to-region (match-beginning 0) (match-end 0))
14811 (insert-before-markers "\n")
14812 (backward-char 1)
14813 (narrow-to-region (point) (point))
14814 (indent-to-column col))
14815 ;; Check if we have to remove something.
14816 (setq list (cons what remove))
14817 (while list
14818 (setq elt (pop list))
14819 (goto-char (point-min))
14820 (when (or (and (eq elt 'scheduled)
14821 (re-search-forward org-scheduled-time-regexp nil t))
14822 (and (eq elt 'deadline)
14823 (re-search-forward org-deadline-time-regexp nil t))
14824 (and (eq elt 'closed)
14825 (re-search-forward org-closed-time-regexp nil t)))
14826 (replace-match "")
14827 (if (looking-at "--+<[^>]+>") (replace-match ""))
14828 (if (looking-at " +") (replace-match ""))))
14829 (goto-char (point-max))
14830 (when what
14831 (insert
14832 (if (not (equal (char-before) ?\ )) " " "")
14833 (cond ((eq what 'scheduled) org-scheduled-string)
14834 ((eq what 'deadline) org-deadline-string)
14835 ((eq what 'closed) org-closed-string))
14836 " ")
14837 (setq ts (org-insert-time-stamp
14838 time
14839 (or org-time-was-given
14840 (and (eq what 'closed) org-log-done-with-time))
14841 (eq what 'closed)
14842 nil nil (list org-end-time-was-given)))
14843 (end-of-line 1))
14844 (goto-char (point-min))
14845 (widen)
14846 (if (looking-at "[ \t]+\r?\n")
14847 (replace-match ""))
14848 ts)))))
14850 (defvar org-log-note-marker (make-marker))
14851 (defvar org-log-note-purpose nil)
14852 (defvar org-log-note-state nil)
14853 (defvar org-log-note-how nil)
14854 (defvar org-log-note-window-configuration nil)
14855 (defvar org-log-note-return-to (make-marker))
14856 (defvar org-log-post-message nil
14857 "Message to be displayed after a log note has been stored.
14858 The auto-repeater uses this.")
14860 (defun org-add-log-maybe (&optional purpose state findpos how)
14861 "Set up the post command hook to take a note.
14862 If this is about to TODO state change, the new state is expected in STATE.
14863 When FINDPOS is non-nil, find the correct position for the note in
14864 the current entry. If not, assume that it can be inserted at point."
14865 (save-excursion
14866 (when findpos
14867 (org-back-to-heading t)
14868 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
14869 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
14870 "[^\r\n]*\\)?"))
14871 (goto-char (match-end 0))
14872 (unless org-log-states-order-reversed
14873 (and (= (char-after) ?\n) (forward-char 1))
14874 (org-skip-over-state-notes)
14875 (skip-chars-backward " \t\n\r")))
14876 (move-marker org-log-note-marker (point))
14877 (setq org-log-note-purpose purpose
14878 org-log-note-state state
14879 org-log-note-how how)
14880 (add-hook 'post-command-hook 'org-add-log-note 'append)))
14882 (defun org-skip-over-state-notes ()
14883 "Skip past the list of State notes in an entry."
14884 (if (looking-at "\n[ \t]*- State") (forward-char 1))
14885 (while (looking-at "[ \t]*- State")
14886 (condition-case nil
14887 (org-next-item)
14888 (error (org-end-of-item)))))
14890 (defun org-add-log-note (&optional purpose)
14891 "Pop up a window for taking a note, and add this note later at point."
14892 (remove-hook 'post-command-hook 'org-add-log-note)
14893 (setq org-log-note-window-configuration (current-window-configuration))
14894 (delete-other-windows)
14895 (move-marker org-log-note-return-to (point))
14896 (switch-to-buffer (marker-buffer org-log-note-marker))
14897 (goto-char org-log-note-marker)
14898 (org-switch-to-buffer-other-window "*Org Note*")
14899 (erase-buffer)
14900 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
14901 (org-store-log-note)
14902 (let ((org-inhibit-startup t)) (org-mode))
14903 (insert (format "# Insert note for %s.
14904 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
14905 (cond
14906 ((eq org-log-note-purpose 'clock-out) "stopped clock")
14907 ((eq org-log-note-purpose 'done) "closed todo item")
14908 ((eq org-log-note-purpose 'state)
14909 (format "state change to \"%s\"" org-log-note-state))
14910 (t (error "This should not happen")))))
14911 (org-set-local 'org-finish-function 'org-store-log-note)))
14913 (defun org-store-log-note ()
14914 "Finish taking a log note, and insert it to where it belongs."
14915 (let ((txt (buffer-string))
14916 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
14917 lines ind)
14918 (kill-buffer (current-buffer))
14919 (while (string-match "\\`#.*\n[ \t\n]*" txt)
14920 (setq txt (replace-match "" t t txt)))
14921 (if (string-match "\\s-+\\'" txt)
14922 (setq txt (replace-match "" t t txt)))
14923 (setq lines (org-split-string txt "\n"))
14924 (when (and note (string-match "\\S-" note))
14925 (setq note
14926 (org-replace-escapes
14927 note
14928 (list (cons "%u" (user-login-name))
14929 (cons "%U" user-full-name)
14930 (cons "%t" (format-time-string
14931 (org-time-stamp-format 'long 'inactive)
14932 (current-time)))
14933 (cons "%s" (if org-log-note-state
14934 (concat "\"" org-log-note-state "\"")
14935 "")))))
14936 (if lines (setq note (concat note " \\\\")))
14937 (push note lines))
14938 (when (or current-prefix-arg org-note-abort) (setq lines nil))
14939 (when lines
14940 (save-excursion
14941 (set-buffer (marker-buffer org-log-note-marker))
14942 (save-excursion
14943 (goto-char org-log-note-marker)
14944 (move-marker org-log-note-marker nil)
14945 (end-of-line 1)
14946 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
14947 (indent-relative nil)
14948 (insert "- " (pop lines))
14949 (org-indent-line-function)
14950 (beginning-of-line 1)
14951 (looking-at "[ \t]*")
14952 (setq ind (concat (match-string 0) " "))
14953 (end-of-line 1)
14954 (while lines (insert "\n" ind (pop lines)))))))
14955 (set-window-configuration org-log-note-window-configuration)
14956 (with-current-buffer (marker-buffer org-log-note-return-to)
14957 (goto-char org-log-note-return-to))
14958 (move-marker org-log-note-return-to nil)
14959 (and org-log-post-message (message "%s" org-log-post-message)))
14961 ;; FIXME: what else would be useful?
14962 ;; - priority
14963 ;; - date
14965 (defun org-sparse-tree (&optional arg)
14966 "Create a sparse tree, prompt for the details.
14967 This command can create sparse trees. You first need to select the type
14968 of match used to create the tree:
14970 t Show entries with a specific TODO keyword.
14971 T Show entries selected by a tags match.
14972 p Enter a property name and its value (both with completion on existing
14973 names/values) and show entries with that property.
14974 r Show entries matching a regular expression
14975 d Show deadlines due within `org-deadline-warning-days'."
14976 (interactive "P")
14977 (let (ans kwd value)
14978 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
14979 (setq ans (read-char-exclusive))
14980 (cond
14981 ((equal ans ?d)
14982 (call-interactively 'org-check-deadlines))
14983 ((equal ans ?b)
14984 (call-interactively 'org-check-before-date))
14985 ((equal ans ?t)
14986 (org-show-todo-tree '(4)))
14987 ((equal ans ?T)
14988 (call-interactively 'org-tags-sparse-tree))
14989 ((member ans '(?p ?P))
14990 (setq kwd (completing-read "Property: "
14991 (mapcar 'list (org-buffer-property-keys))))
14992 (setq value (completing-read "Value: "
14993 (mapcar 'list (org-property-values kwd))))
14994 (unless (string-match "\\`{.*}\\'" value)
14995 (setq value (concat "\"" value "\"")))
14996 (org-tags-sparse-tree arg (concat kwd "=" value)))
14997 ((member ans '(?r ?R ?/))
14998 (call-interactively 'org-occur))
14999 (t (error "No such sparse tree command \"%c\"" ans)))))
15001 (defvar org-occur-highlights nil
15002 "List of overlays used for occur matches.")
15003 (make-variable-buffer-local 'org-occur-highlights)
15004 (defvar org-occur-parameters nil
15005 "Parameters of the active org-occur calls.
15006 This is a list, each call to org-occur pushes as cons cell,
15007 containing the regular expression and the callback, onto the list.
15008 The list can contain several entries if `org-occur' has been called
15009 several time with the KEEP-PREVIOUS argument. Otherwise, this list
15010 will only contain one set of parameters. When the highlights are
15011 removed (for example with `C-c C-c', or with the next edit (depending
15012 on `org-remove-highlights-with-change'), this variable is emptied
15013 as well.")
15014 (make-variable-buffer-local 'org-occur-parameters)
15016 (defun org-occur (regexp &optional keep-previous callback)
15017 "Make a compact tree which shows all matches of REGEXP.
15018 The tree will show the lines where the regexp matches, and all higher
15019 headlines above the match. It will also show the heading after the match,
15020 to make sure editing the matching entry is easy.
15021 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15022 call to `org-occur' will be kept, to allow stacking of calls to this
15023 command.
15024 If CALLBACK is non-nil, it is a function which is called to confirm
15025 that the match should indeed be shown."
15026 (interactive "sRegexp: \nP")
15027 (unless keep-previous
15028 (org-remove-occur-highlights nil nil t))
15029 (push (cons regexp callback) org-occur-parameters)
15030 (let ((cnt 0))
15031 (save-excursion
15032 (goto-char (point-min))
15033 (if (or (not keep-previous) ; do not want to keep
15034 (not org-occur-highlights)) ; no previous matches
15035 ;; hide everything
15036 (org-overview))
15037 (while (re-search-forward regexp nil t)
15038 (when (or (not callback)
15039 (save-match-data (funcall callback)))
15040 (setq cnt (1+ cnt))
15041 (when org-highlight-sparse-tree-matches
15042 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15043 (org-show-context 'occur-tree))))
15044 (when org-remove-highlights-with-change
15045 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15046 nil 'local))
15047 (unless org-sparse-tree-open-archived-trees
15048 (org-hide-archived-subtrees (point-min) (point-max)))
15049 (run-hooks 'org-occur-hook)
15050 (if (interactive-p)
15051 (message "%d match(es) for regexp %s" cnt regexp))
15052 cnt))
15054 (defun org-show-context (&optional key)
15055 "Make sure point and context and visible.
15056 How much context is shown depends upon the variables
15057 `org-show-hierarchy-above', `org-show-following-heading'. and
15058 `org-show-siblings'."
15059 (let ((heading-p (org-on-heading-p t))
15060 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15061 (following-p (org-get-alist-option org-show-following-heading key))
15062 (entry-p (org-get-alist-option org-show-entry-below key))
15063 (siblings-p (org-get-alist-option org-show-siblings key)))
15064 (catch 'exit
15065 ;; Show heading or entry text
15066 (if (and heading-p (not entry-p))
15067 (org-flag-heading nil) ; only show the heading
15068 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15069 (org-show-hidden-entry))) ; show entire entry
15070 (when following-p
15071 ;; Show next sibling, or heading below text
15072 (save-excursion
15073 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15074 (org-flag-heading nil))))
15075 (when siblings-p (org-show-siblings))
15076 (when hierarchy-p
15077 ;; show all higher headings, possibly with siblings
15078 (save-excursion
15079 (while (and (condition-case nil
15080 (progn (org-up-heading-all 1) t)
15081 (error nil))
15082 (not (bobp)))
15083 (org-flag-heading nil)
15084 (when siblings-p (org-show-siblings))))))))
15086 (defun org-reveal (&optional siblings)
15087 "Show current entry, hierarchy above it, and the following headline.
15088 This can be used to show a consistent set of context around locations
15089 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15090 not t for the search context.
15092 With optional argument SIBLINGS, on each level of the hierarchy all
15093 siblings are shown. This repairs the tree structure to what it would
15094 look like when opened with hierarchical calls to `org-cycle'."
15095 (interactive "P")
15096 (let ((org-show-hierarchy-above t)
15097 (org-show-following-heading t)
15098 (org-show-siblings (if siblings t org-show-siblings)))
15099 (org-show-context nil)))
15101 (defun org-highlight-new-match (beg end)
15102 "Highlight from BEG to END and mark the highlight is an occur headline."
15103 (let ((ov (org-make-overlay beg end)))
15104 (org-overlay-put ov 'face 'secondary-selection)
15105 (push ov org-occur-highlights)))
15107 (defun org-remove-occur-highlights (&optional beg end noremove)
15108 "Remove the occur highlights from the buffer.
15109 BEG and END are ignored. If NOREMOVE is nil, remove this function
15110 from the `before-change-functions' in the current buffer."
15111 (interactive)
15112 (unless org-inhibit-highlight-removal
15113 (mapc 'org-delete-overlay org-occur-highlights)
15114 (setq org-occur-highlights nil)
15115 (setq org-occur-parameters nil)
15116 (unless noremove
15117 (remove-hook 'before-change-functions
15118 'org-remove-occur-highlights 'local))))
15120 ;;;; Priorities
15122 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15123 "Regular expression matching the priority indicator.")
15125 (defvar org-remove-priority-next-time nil)
15127 (defun org-priority-up ()
15128 "Increase the priority of the current item."
15129 (interactive)
15130 (org-priority 'up))
15132 (defun org-priority-down ()
15133 "Decrease the priority of the current item."
15134 (interactive)
15135 (org-priority 'down))
15137 (defun org-priority (&optional action)
15138 "Change the priority of an item by ARG.
15139 ACTION can be `set', `up', `down', or a character."
15140 (interactive)
15141 (setq action (or action 'set))
15142 (let (current new news have remove)
15143 (save-excursion
15144 (org-back-to-heading)
15145 (if (looking-at org-priority-regexp)
15146 (setq current (string-to-char (match-string 2))
15147 have t)
15148 (setq current org-default-priority))
15149 (cond
15150 ((or (eq action 'set) (integerp action))
15151 (if (integerp action)
15152 (setq new action)
15153 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15154 (setq new (read-char-exclusive)))
15155 (if (and (= (upcase org-highest-priority) org-highest-priority)
15156 (= (upcase org-lowest-priority) org-lowest-priority))
15157 (setq new (upcase new)))
15158 (cond ((equal new ?\ ) (setq remove t))
15159 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15160 (error "Priority must be between `%c' and `%c'"
15161 org-highest-priority org-lowest-priority))))
15162 ((eq action 'up)
15163 (if (and (not have) (eq last-command this-command))
15164 (setq new org-lowest-priority)
15165 (setq new (if (and org-priority-start-cycle-with-default (not have))
15166 org-default-priority (1- current)))))
15167 ((eq action 'down)
15168 (if (and (not have) (eq last-command this-command))
15169 (setq new org-highest-priority)
15170 (setq new (if (and org-priority-start-cycle-with-default (not have))
15171 org-default-priority (1+ current)))))
15172 (t (error "Invalid action")))
15173 (if (or (< (upcase new) org-highest-priority)
15174 (> (upcase new) org-lowest-priority))
15175 (setq remove t))
15176 (setq news (format "%c" new))
15177 (if have
15178 (if remove
15179 (replace-match "" t t nil 1)
15180 (replace-match news t t nil 2))
15181 (if remove
15182 (error "No priority cookie found in line")
15183 (looking-at org-todo-line-regexp)
15184 (if (match-end 2)
15185 (progn
15186 (goto-char (match-end 2))
15187 (insert " [#" news "]"))
15188 (goto-char (match-beginning 3))
15189 (insert "[#" news "] ")))))
15190 (org-preserve-lc (org-set-tags nil 'align))
15191 (if remove
15192 (message "Priority removed")
15193 (message "Priority of current item set to %s" news))))
15196 (defun org-get-priority (s)
15197 "Find priority cookie and return priority."
15198 (save-match-data
15199 (if (not (string-match org-priority-regexp s))
15200 (* 1000 (- org-lowest-priority org-default-priority))
15201 (* 1000 (- org-lowest-priority
15202 (string-to-char (match-string 2 s)))))))
15204 ;;;; Tags
15206 (defun org-scan-tags (action matcher &optional todo-only)
15207 "Scan headline tags with inheritance and produce output ACTION.
15208 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15209 evaluated, testing if a given set of tags qualifies a headline for
15210 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15211 are included in the output."
15212 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15213 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15214 (org-re
15215 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15216 (props (list 'face nil
15217 'done-face 'org-done
15218 'undone-face nil
15219 'mouse-face 'highlight
15220 'org-not-done-regexp org-not-done-regexp
15221 'org-todo-regexp org-todo-regexp
15222 'keymap org-agenda-keymap
15223 'help-echo
15224 (format "mouse-2 or RET jump to org file %s"
15225 (abbreviate-file-name
15226 (or (buffer-file-name (buffer-base-buffer))
15227 (buffer-name (buffer-base-buffer)))))))
15228 (case-fold-search nil)
15229 lspos
15230 tags tags-list tags-alist (llast 0) rtn level category i txt
15231 todo marker entry priority)
15232 (save-excursion
15233 (goto-char (point-min))
15234 (when (eq action 'sparse-tree)
15235 (org-overview)
15236 (org-remove-occur-highlights))
15237 (while (re-search-forward re nil t)
15238 (catch :skip
15239 (setq todo (if (match-end 1) (match-string 2))
15240 tags (if (match-end 4) (match-string 4)))
15241 (goto-char (setq lspos (1+ (match-beginning 0))))
15242 (setq level (org-reduced-level (funcall outline-level))
15243 category (org-get-category))
15244 (setq i llast llast level)
15245 ;; remove tag lists from same and sublevels
15246 (while (>= i level)
15247 (when (setq entry (assoc i tags-alist))
15248 (setq tags-alist (delete entry tags-alist)))
15249 (setq i (1- i)))
15250 ;; add the nex tags
15251 (when tags
15252 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15253 tags-alist
15254 (cons (cons level tags) tags-alist)))
15255 ;; compile tags for current headline
15256 (setq tags-list
15257 (if org-use-tag-inheritance
15258 (apply 'append (mapcar 'cdr tags-alist))
15259 tags))
15260 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15261 (eval matcher)
15262 (or (not org-agenda-skip-archived-trees)
15263 (not (member org-archive-tag tags-list))))
15264 (and (eq action 'agenda) (org-agenda-skip))
15265 ;; list this headline
15267 (if (eq action 'sparse-tree)
15268 (progn
15269 (and org-highlight-sparse-tree-matches
15270 (org-get-heading) (match-end 0)
15271 (org-highlight-new-match
15272 (match-beginning 0) (match-beginning 1)))
15273 (org-show-context 'tags-tree))
15274 (setq txt (org-format-agenda-item
15276 (concat
15277 (if org-tags-match-list-sublevels
15278 (make-string (1- level) ?.) "")
15279 (org-get-heading))
15280 category tags-list)
15281 priority (org-get-priority txt))
15282 (goto-char lspos)
15283 (setq marker (org-agenda-new-marker))
15284 (org-add-props txt props
15285 'org-marker marker 'org-hd-marker marker 'org-category category
15286 'priority priority 'type "tagsmatch")
15287 (push txt rtn))
15288 ;; if we are to skip sublevels, jump to end of subtree
15289 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15290 (when (and (eq action 'sparse-tree)
15291 (not org-sparse-tree-open-archived-trees))
15292 (org-hide-archived-subtrees (point-min) (point-max)))
15293 (nreverse rtn)))
15295 (defvar todo-only) ;; dynamically scoped
15297 (defun org-tags-sparse-tree (&optional todo-only match)
15298 "Create a sparse tree according to tags string MATCH.
15299 MATCH can contain positive and negative selection of tags, like
15300 \"+WORK+URGENT-WITHBOSS\".
15301 If optional argument TODO_ONLY is non-nil, only select lines that are
15302 also TODO lines."
15303 (interactive "P")
15304 (org-prepare-agenda-buffers (list (current-buffer)))
15305 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15307 (defvar org-cached-props nil)
15308 (defun org-cached-entry-get (pom property)
15309 (if (or (eq t org-use-property-inheritance)
15310 (member property org-use-property-inheritance))
15311 ;; Caching is not possible, check it directly
15312 (org-entry-get pom property 'inherit)
15313 ;; Get all properties, so that we can do complicated checks easily
15314 (cdr (assoc property (or org-cached-props
15315 (setq org-cached-props
15316 (org-entry-properties pom)))))))
15318 (defun org-global-tags-completion-table (&optional files)
15319 "Return the list of all tags in all agenda buffer/files."
15320 (save-excursion
15321 (org-uniquify
15322 (delq nil
15323 (apply 'append
15324 (mapcar
15325 (lambda (file)
15326 (set-buffer (find-file-noselect file))
15327 (append (org-get-buffer-tags)
15328 (mapcar (lambda (x) (if (stringp (car-safe x))
15329 (list (car-safe x)) nil))
15330 org-tag-alist)))
15331 (if (and files (car files))
15332 files
15333 (org-agenda-files))))))))
15335 (defun org-make-tags-matcher (match)
15336 "Create the TAGS//TODO matcher form for the selection string MATCH."
15337 ;; todo-only is scoped dynamically into this function, and the function
15338 ;; may change it it the matcher asksk for it.
15339 (unless match
15340 ;; Get a new match request, with completion
15341 (let ((org-last-tags-completion-table
15342 (org-global-tags-completion-table)))
15343 (setq match (completing-read
15344 "Match: " 'org-tags-completion-function nil nil nil
15345 'org-tags-history))))
15347 ;; Parse the string and create a lisp form
15348 (let ((match0 match)
15349 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15350 minus tag mm
15351 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15352 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15353 (if (string-match "/+" match)
15354 ;; match contains also a todo-matching request
15355 (progn
15356 (setq tagsmatch (substring match 0 (match-beginning 0))
15357 todomatch (substring match (match-end 0)))
15358 (if (string-match "^!" todomatch)
15359 (setq todo-only t todomatch (substring todomatch 1)))
15360 (if (string-match "^\\s-*$" todomatch)
15361 (setq todomatch nil)))
15362 ;; only matching tags
15363 (setq tagsmatch match todomatch nil))
15365 ;; Make the tags matcher
15366 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15367 (setq tagsmatcher t)
15368 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15369 (while (setq term (pop orterms))
15370 (while (and (equal (substring term -1) "\\") orterms)
15371 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15372 (while (string-match re term)
15373 (setq minus (and (match-end 1)
15374 (equal (match-string 1 term) "-"))
15375 tag (match-string 2 term)
15376 re-p (equal (string-to-char tag) ?{)
15377 level-p (match-end 3)
15378 prop-p (match-end 4)
15379 mm (cond
15380 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15381 (level-p `(= level ,(string-to-number
15382 (match-string 3 term))))
15383 (prop-p
15384 (setq pn (match-string 4 term)
15385 pv (match-string 5 term)
15386 cat-p (equal pn "CATEGORY")
15387 re-p (equal (string-to-char pv) ?{)
15388 pv (substring pv 1 -1))
15389 (if (equal pn "CATEGORY")
15390 (setq gv '(get-text-property (point) 'org-category))
15391 (setq gv `(org-cached-entry-get nil ,pn)))
15392 (if re-p
15393 `(string-match ,pv (or ,gv ""))
15394 `(equal ,pv (or ,gv ""))))
15395 (t `(member ,(downcase tag) tags-list)))
15396 mm (if minus (list 'not mm) mm)
15397 term (substring term (match-end 0)))
15398 (push mm tagsmatcher))
15399 (push (if (> (length tagsmatcher) 1)
15400 (cons 'and tagsmatcher)
15401 (car tagsmatcher))
15402 orlist)
15403 (setq tagsmatcher nil))
15404 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15405 (setq tagsmatcher
15406 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15408 ;; Make the todo matcher
15409 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15410 (setq todomatcher t)
15411 (setq orterms (org-split-string todomatch "|") orlist nil)
15412 (while (setq term (pop orterms))
15413 (while (string-match re term)
15414 (setq minus (and (match-end 1)
15415 (equal (match-string 1 term) "-"))
15416 kwd (match-string 2 term)
15417 re-p (equal (string-to-char kwd) ?{)
15418 term (substring term (match-end 0))
15419 mm (if re-p
15420 `(string-match ,(substring kwd 1 -1) todo)
15421 (list 'equal 'todo kwd))
15422 mm (if minus (list 'not mm) mm))
15423 (push mm todomatcher))
15424 (push (if (> (length todomatcher) 1)
15425 (cons 'and todomatcher)
15426 (car todomatcher))
15427 orlist)
15428 (setq todomatcher nil))
15429 (setq todomatcher (if (> (length orlist) 1)
15430 (cons 'or orlist) (car orlist))))
15432 ;; Return the string and lisp forms of the matcher
15433 (setq matcher (if todomatcher
15434 (list 'and tagsmatcher todomatcher)
15435 tagsmatcher))
15436 (cons match0 matcher)))
15438 (defun org-match-any-p (re list)
15439 "Does re match any element of list?"
15440 (setq list (mapcar (lambda (x) (string-match re x)) list))
15441 (delq nil list))
15443 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15444 (defvar org-tags-overlay (org-make-overlay 1 1))
15445 (org-detach-overlay org-tags-overlay)
15447 (defun org-align-tags-here (to-col)
15448 ;; Assumes that this is a headline
15449 (let ((pos (point)) (col (current-column)) tags)
15450 (beginning-of-line 1)
15451 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15452 (< pos (match-beginning 2)))
15453 (progn
15454 (setq tags (match-string 2))
15455 (goto-char (match-beginning 1))
15456 (insert " ")
15457 (delete-region (point) (1+ (match-end 0)))
15458 (backward-char 1)
15459 (move-to-column
15460 (max (1+ (current-column))
15461 (1+ col)
15462 (if (> to-col 0)
15463 to-col
15464 (- (abs to-col) (length tags))))
15466 (insert tags)
15467 (move-to-column (min (current-column) col) t))
15468 (goto-char pos))))
15470 (defun org-set-tags (&optional arg just-align)
15471 "Set the tags for the current headline.
15472 With prefix ARG, realign all tags in headings in the current buffer."
15473 (interactive "P")
15474 (let* ((re (concat "^" outline-regexp))
15475 (current (org-get-tags-string))
15476 (col (current-column))
15477 (org-setting-tags t)
15478 table current-tags inherited-tags ; computed below when needed
15479 tags p0 c0 c1 rpl)
15480 (if arg
15481 (save-excursion
15482 (goto-char (point-min))
15483 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15484 (while (re-search-forward re nil t)
15485 (org-set-tags nil t)
15486 (end-of-line 1)))
15487 (message "All tags realigned to column %d" org-tags-column))
15488 (if just-align
15489 (setq tags current)
15490 ;; Get a new set of tags from the user
15491 (save-excursion
15492 (setq table (or org-tag-alist (org-get-buffer-tags))
15493 org-last-tags-completion-table table
15494 current-tags (org-split-string current ":")
15495 inherited-tags (nreverse
15496 (nthcdr (length current-tags)
15497 (nreverse (org-get-tags-at))))
15498 tags
15499 (if (or (eq t org-use-fast-tag-selection)
15500 (and org-use-fast-tag-selection
15501 (delq nil (mapcar 'cdr table))))
15502 (org-fast-tag-selection
15503 current-tags inherited-tags table
15504 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15505 (let ((org-add-colon-after-tag-completion t))
15506 (org-trim
15507 (org-without-partial-completion
15508 (completing-read "Tags: " 'org-tags-completion-function
15509 nil nil current 'org-tags-history)))))))
15510 (while (string-match "[-+&]+" tags)
15511 ;; No boolean logic, just a list
15512 (setq tags (replace-match ":" t t tags))))
15514 (if (string-match "\\`[\t ]*\\'" tags)
15515 (setq tags "")
15516 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15517 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15519 ;; Insert new tags at the correct column
15520 (beginning-of-line 1)
15521 (cond
15522 ((and (equal current "") (equal tags "")))
15523 ((re-search-forward
15524 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15525 (point-at-eol) t)
15526 (if (equal tags "")
15527 (setq rpl "")
15528 (goto-char (match-beginning 0))
15529 (setq c0 (current-column) p0 (point)
15530 c1 (max (1+ c0) (if (> org-tags-column 0)
15531 org-tags-column
15532 (- (- org-tags-column) (length tags))))
15533 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15534 (replace-match rpl t t)
15535 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15536 tags)
15537 (t (error "Tags alignment failed")))
15538 (move-to-column col)
15539 (unless just-align
15540 (run-hooks 'org-after-tags-change-hook)))))
15542 (defun org-change-tag-in-region (beg end tag off)
15543 "Add or remove TAG for each entry in the region.
15544 This works in the agenda, and also in an org-mode buffer."
15545 (interactive
15546 (list (region-beginning) (region-end)
15547 (let ((org-last-tags-completion-table
15548 (if (org-mode-p)
15549 (org-get-buffer-tags)
15550 (org-global-tags-completion-table))))
15551 (completing-read
15552 "Tag: " 'org-tags-completion-function nil nil nil
15553 'org-tags-history))
15554 (progn
15555 (message "[s]et or [r]emove? ")
15556 (equal (read-char-exclusive) ?r))))
15557 (if (fboundp 'deactivate-mark) (deactivate-mark))
15558 (let ((agendap (equal major-mode 'org-agenda-mode))
15559 l1 l2 m buf pos newhead (cnt 0))
15560 (goto-char end)
15561 (setq l2 (1- (org-current-line)))
15562 (goto-char beg)
15563 (setq l1 (org-current-line))
15564 (loop for l from l1 to l2 do
15565 (goto-line l)
15566 (setq m (get-text-property (point) 'org-hd-marker))
15567 (when (or (and (org-mode-p) (org-on-heading-p))
15568 (and agendap m))
15569 (setq buf (if agendap (marker-buffer m) (current-buffer))
15570 pos (if agendap m (point)))
15571 (with-current-buffer buf
15572 (save-excursion
15573 (save-restriction
15574 (goto-char pos)
15575 (setq cnt (1+ cnt))
15576 (org-toggle-tag tag (if off 'off 'on))
15577 (setq newhead (org-get-heading)))))
15578 (and agendap (org-agenda-change-all-lines newhead m))))
15579 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15581 (defun org-tags-completion-function (string predicate &optional flag)
15582 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15583 (confirm (lambda (x) (stringp (car x)))))
15584 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15585 (setq s1 (match-string 1 string)
15586 s2 (match-string 2 string))
15587 (setq s1 "" s2 string))
15588 (cond
15589 ((eq flag nil)
15590 ;; try completion
15591 (setq rtn (try-completion s2 ctable confirm))
15592 (if (stringp rtn)
15593 (setq rtn
15594 (concat s1 s2 (substring rtn (length s2))
15595 (if (and org-add-colon-after-tag-completion
15596 (assoc rtn ctable))
15597 ":" ""))))
15598 rtn)
15599 ((eq flag t)
15600 ;; all-completions
15601 (all-completions s2 ctable confirm)
15603 ((eq flag 'lambda)
15604 ;; exact match?
15605 (assoc s2 ctable)))
15608 (defun org-fast-tag-insert (kwd tags face &optional end)
15609 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15610 (insert (format "%-12s" (concat kwd ":"))
15611 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15612 (or end "")))
15614 (defun org-fast-tag-show-exit (flag)
15615 (save-excursion
15616 (goto-line 3)
15617 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15618 (replace-match ""))
15619 (when flag
15620 (end-of-line 1)
15621 (move-to-column (- (window-width) 19) t)
15622 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15624 (defun org-set-current-tags-overlay (current prefix)
15625 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15626 (if (featurep 'xemacs)
15627 (org-overlay-display org-tags-overlay (concat prefix s)
15628 'secondary-selection)
15629 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15630 (org-overlay-display org-tags-overlay (concat prefix s)))))
15632 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15633 "Fast tag selection with single keys.
15634 CURRENT is the current list of tags in the headline, INHERITED is the
15635 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15636 possibly with grouping information. TODO-TABLE is a similar table with
15637 TODO keywords, should these have keys assigned to them.
15638 If the keys are nil, a-z are automatically assigned.
15639 Returns the new tags string, or nil to not change the current settings."
15640 (let* ((fulltable (append table todo-table))
15641 (maxlen (apply 'max (mapcar
15642 (lambda (x)
15643 (if (stringp (car x)) (string-width (car x)) 0))
15644 fulltable)))
15645 (buf (current-buffer))
15646 (expert (eq org-fast-tag-selection-single-key 'expert))
15647 (buffer-tags nil)
15648 (fwidth (+ maxlen 3 1 3))
15649 (ncol (/ (- (window-width) 4) fwidth))
15650 (i-face 'org-done)
15651 (c-face 'org-todo)
15652 tg cnt e c char c1 c2 ntable tbl rtn
15653 ov-start ov-end ov-prefix
15654 (exit-after-next org-fast-tag-selection-single-key)
15655 (done-keywords org-done-keywords)
15656 groups ingroup)
15657 (save-excursion
15658 (beginning-of-line 1)
15659 (if (looking-at
15660 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15661 (setq ov-start (match-beginning 1)
15662 ov-end (match-end 1)
15663 ov-prefix "")
15664 (setq ov-start (1- (point-at-eol))
15665 ov-end (1+ ov-start))
15666 (skip-chars-forward "^\n\r")
15667 (setq ov-prefix
15668 (concat
15669 (buffer-substring (1- (point)) (point))
15670 (if (> (current-column) org-tags-column)
15672 (make-string (- org-tags-column (current-column)) ?\ ))))))
15673 (org-move-overlay org-tags-overlay ov-start ov-end)
15674 (save-window-excursion
15675 (if expert
15676 (set-buffer (get-buffer-create " *Org tags*"))
15677 (delete-other-windows)
15678 (split-window-vertically)
15679 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15680 (erase-buffer)
15681 (org-set-local 'org-done-keywords done-keywords)
15682 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15683 (org-fast-tag-insert "Current" current c-face "\n\n")
15684 (org-fast-tag-show-exit exit-after-next)
15685 (org-set-current-tags-overlay current ov-prefix)
15686 (setq tbl fulltable char ?a cnt 0)
15687 (while (setq e (pop tbl))
15688 (cond
15689 ((equal e '(:startgroup))
15690 (push '() groups) (setq ingroup t)
15691 (when (not (= cnt 0))
15692 (setq cnt 0)
15693 (insert "\n"))
15694 (insert "{ "))
15695 ((equal e '(:endgroup))
15696 (setq ingroup nil cnt 0)
15697 (insert "}\n"))
15699 (setq tg (car e) c2 nil)
15700 (if (cdr e)
15701 (setq c (cdr e))
15702 ;; automatically assign a character.
15703 (setq c1 (string-to-char
15704 (downcase (substring
15705 tg (if (= (string-to-char tg) ?@) 1 0)))))
15706 (if (or (rassoc c1 ntable) (rassoc c1 table))
15707 (while (or (rassoc char ntable) (rassoc char table))
15708 (setq char (1+ char)))
15709 (setq c2 c1))
15710 (setq c (or c2 char)))
15711 (if ingroup (push tg (car groups)))
15712 (setq tg (org-add-props tg nil 'face
15713 (cond
15714 ((not (assoc tg table))
15715 (org-get-todo-face tg))
15716 ((member tg current) c-face)
15717 ((member tg inherited) i-face)
15718 (t nil))))
15719 (if (and (= cnt 0) (not ingroup)) (insert " "))
15720 (insert "[" c "] " tg (make-string
15721 (- fwidth 4 (length tg)) ?\ ))
15722 (push (cons tg c) ntable)
15723 (when (= (setq cnt (1+ cnt)) ncol)
15724 (insert "\n")
15725 (if ingroup (insert " "))
15726 (setq cnt 0)))))
15727 (setq ntable (nreverse ntable))
15728 (insert "\n")
15729 (goto-char (point-min))
15730 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15731 (fit-window-to-buffer))
15732 (setq rtn
15733 (catch 'exit
15734 (while t
15735 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15736 (if groups " [!] no groups" " [!]groups")
15737 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15738 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15739 (cond
15740 ((= c ?\r) (throw 'exit t))
15741 ((= c ?!)
15742 (setq groups (not groups))
15743 (goto-char (point-min))
15744 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15745 ((= c ?\C-c)
15746 (if (not expert)
15747 (org-fast-tag-show-exit
15748 (setq exit-after-next (not exit-after-next)))
15749 (setq expert nil)
15750 (delete-other-windows)
15751 (split-window-vertically)
15752 (org-switch-to-buffer-other-window " *Org tags*")
15753 (and (fboundp 'fit-window-to-buffer)
15754 (fit-window-to-buffer))))
15755 ((or (= c ?\C-g)
15756 (and (= c ?q) (not (rassoc c ntable))))
15757 (org-detach-overlay org-tags-overlay)
15758 (setq quit-flag t))
15759 ((= c ?\ )
15760 (setq current nil)
15761 (if exit-after-next (setq exit-after-next 'now)))
15762 ((= c ?\t)
15763 (condition-case nil
15764 (setq tg (completing-read
15765 "Tag: "
15766 (or buffer-tags
15767 (with-current-buffer buf
15768 (org-get-buffer-tags)))))
15769 (quit (setq tg "")))
15770 (when (string-match "\\S-" tg)
15771 (add-to-list 'buffer-tags (list tg))
15772 (if (member tg current)
15773 (setq current (delete tg current))
15774 (push tg current)))
15775 (if exit-after-next (setq exit-after-next 'now)))
15776 ((setq e (rassoc c todo-table) tg (car e))
15777 (with-current-buffer buf
15778 (save-excursion (org-todo tg)))
15779 (if exit-after-next (setq exit-after-next 'now)))
15780 ((setq e (rassoc c ntable) tg (car e))
15781 (if (member tg current)
15782 (setq current (delete tg current))
15783 (loop for g in groups do
15784 (if (member tg g)
15785 (mapc (lambda (x)
15786 (setq current (delete x current)))
15787 g)))
15788 (push tg current))
15789 (if exit-after-next (setq exit-after-next 'now))))
15791 ;; Create a sorted list
15792 (setq current
15793 (sort current
15794 (lambda (a b)
15795 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15796 (if (eq exit-after-next 'now) (throw 'exit t))
15797 (goto-char (point-min))
15798 (beginning-of-line 2)
15799 (delete-region (point) (point-at-eol))
15800 (org-fast-tag-insert "Current" current c-face)
15801 (org-set-current-tags-overlay current ov-prefix)
15802 (while (re-search-forward
15803 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15804 (setq tg (match-string 1))
15805 (add-text-properties
15806 (match-beginning 1) (match-end 1)
15807 (list 'face
15808 (cond
15809 ((member tg current) c-face)
15810 ((member tg inherited) i-face)
15811 (t (get-text-property (match-beginning 1) 'face))))))
15812 (goto-char (point-min)))))
15813 (org-detach-overlay org-tags-overlay)
15814 (if rtn
15815 (mapconcat 'identity current ":")
15816 nil))))
15818 (defun org-get-tags-string ()
15819 "Get the TAGS string in the current headline."
15820 (unless (org-on-heading-p t)
15821 (error "Not on a heading"))
15822 (save-excursion
15823 (beginning-of-line 1)
15824 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15825 (org-match-string-no-properties 1)
15826 "")))
15828 (defun org-get-tags ()
15829 "Get the list of tags specified in the current headline."
15830 (org-split-string (org-get-tags-string) ":"))
15832 (defun org-get-buffer-tags ()
15833 "Get a table of all tags used in the buffer, for completion."
15834 (let (tags)
15835 (save-excursion
15836 (goto-char (point-min))
15837 (while (re-search-forward
15838 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15839 (when (equal (char-after (point-at-bol 0)) ?*)
15840 (mapc (lambda (x) (add-to-list 'tags x))
15841 (org-split-string (org-match-string-no-properties 1) ":")))))
15842 (mapcar 'list tags)))
15845 ;;;; Properties
15847 ;;; Setting and retrieving properties
15849 (defconst org-special-properties
15850 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15851 "TIMESTAMP" "TIMESTAMP_IA")
15852 "The special properties valid in Org-mode.
15854 These are properties that are not defined in the property drawer,
15855 but in some other way.")
15857 (defconst org-default-properties
15858 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15859 "LOCATION" "LOGGING" "COLUMNS")
15860 "Some properties that are used by Org-mode for various purposes.
15861 Being in this list makes sure that they are offered for completion.")
15863 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15864 "Regular expression matching the first line of a property drawer.")
15866 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15867 "Regular expression matching the first line of a property drawer.")
15869 (defun org-property-action ()
15870 "Do an action on properties."
15871 (interactive)
15872 (let (c)
15873 (org-at-property-p)
15874 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15875 (setq c (read-char-exclusive))
15876 (cond
15877 ((equal c ?s)
15878 (call-interactively 'org-set-property))
15879 ((equal c ?d)
15880 (call-interactively 'org-delete-property))
15881 ((equal c ?D)
15882 (call-interactively 'org-delete-property-globally))
15883 ((equal c ?c)
15884 (call-interactively 'org-compute-property-at-point))
15885 (t (error "No such property action %c" c)))))
15887 (defun org-at-property-p ()
15888 "Is the cursor in a property line?"
15889 ;; FIXME: Does not check if we are actually in the drawer.
15890 ;; FIXME: also returns true on any drawers.....
15891 ;; This is used by C-c C-c for property action.
15892 (save-excursion
15893 (beginning-of-line 1)
15894 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
15896 (defmacro org-with-point-at (pom &rest body)
15897 "Move to buffer and point of point-or-marker POM for the duration of BODY."
15898 (declare (indent 1) (debug t))
15899 `(save-excursion
15900 (if (markerp pom) (set-buffer (marker-buffer pom)))
15901 (save-excursion
15902 (goto-char (or pom (point)))
15903 ,@body)))
15905 (defun org-get-property-block (&optional beg end force)
15906 "Return the (beg . end) range of the body of the property drawer.
15907 BEG and END can be beginning and end of subtree, if not given
15908 they will be found.
15909 If the drawer does not exist and FORCE is non-nil, create the drawer."
15910 (catch 'exit
15911 (save-excursion
15912 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
15913 (end (or end (progn (outline-next-heading) (point)))))
15914 (goto-char beg)
15915 (if (re-search-forward org-property-start-re end t)
15916 (setq beg (1+ (match-end 0)))
15917 (if force
15918 (save-excursion
15919 (org-insert-property-drawer)
15920 (setq end (progn (outline-next-heading) (point))))
15921 (throw 'exit nil))
15922 (goto-char beg)
15923 (if (re-search-forward org-property-start-re end t)
15924 (setq beg (1+ (match-end 0)))))
15925 (if (re-search-forward org-property-end-re end t)
15926 (setq end (match-beginning 0))
15927 (or force (throw 'exit nil))
15928 (goto-char beg)
15929 (setq end beg)
15930 (org-indent-line-function)
15931 (insert ":END:\n"))
15932 (cons beg end)))))
15934 (defun org-entry-properties (&optional pom which)
15935 "Get all properties of the entry at point-or-marker POM.
15936 This includes the TODO keyword, the tags, time strings for deadline,
15937 scheduled, and clocking, and any additional properties defined in the
15938 entry. The return value is an alist, keys may occur multiple times
15939 if the property key was used several times.
15940 POM may also be nil, in which case the current entry is used.
15941 If WHICH is nil or `all', get all properties. If WHICH is
15942 `special' or `standard', only get that subclass."
15943 (setq which (or which 'all))
15944 (org-with-point-at pom
15945 (let ((clockstr (substring org-clock-string 0 -1))
15946 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
15947 beg end range props sum-props key value string clocksum)
15948 (save-excursion
15949 (when (condition-case nil (org-back-to-heading t) (error nil))
15950 (setq beg (point))
15951 (setq sum-props (get-text-property (point) 'org-summaries))
15952 (setq clocksum (get-text-property (point) :org-clock-minutes))
15953 (outline-next-heading)
15954 (setq end (point))
15955 (when (memq which '(all special))
15956 ;; Get the special properties, like TODO and tags
15957 (goto-char beg)
15958 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15959 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15960 (when (looking-at org-priority-regexp)
15961 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15962 (when (and (setq value (org-get-tags-string))
15963 (string-match "\\S-" value))
15964 (push (cons "TAGS" value) props))
15965 (when (setq value (org-get-tags-at))
15966 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
15967 props))
15968 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15969 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
15970 string (if (equal key clockstr)
15971 (org-no-properties
15972 (org-trim
15973 (buffer-substring
15974 (match-beginning 3) (goto-char (point-at-eol)))))
15975 (substring (org-match-string-no-properties 3) 1 -1)))
15976 (unless key
15977 (if (= (char-after (match-beginning 3)) ?\[)
15978 (setq key "TIMESTAMP_IA")
15979 (setq key "TIMESTAMP")))
15980 (when (or (equal key clockstr) (not (assoc key props)))
15981 (push (cons key string) props)))
15985 (when (memq which '(all standard))
15986 ;; Get the standard properties, like :PORP: ...
15987 (setq range (org-get-property-block beg end))
15988 (when range
15989 (goto-char (car range))
15990 (while (re-search-forward
15991 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15992 (cdr range) t)
15993 (setq key (org-match-string-no-properties 1)
15994 value (org-trim (or (org-match-string-no-properties 2) "")))
15995 (unless (member key excluded)
15996 (push (cons key (or value "")) props)))))
15997 (if clocksum
15998 (push (cons "CLOCKSUM"
15999 (org-column-number-to-string (/ (float clocksum) 60.)
16000 'add_times))
16001 props))
16002 (append sum-props (nreverse props)))))))
16004 (defun org-entry-get (pom property &optional inherit)
16005 "Get value of PROPERTY for entry at point-or-marker POM.
16006 If INHERIT is non-nil and the entry does not have the property,
16007 then also check higher levels of the hierarchy.
16008 If the property is present but empty, the return value is the empty string.
16009 If the property is not present at all, nil is returned."
16010 (org-with-point-at pom
16011 (if inherit
16012 (org-entry-get-with-inheritance property)
16013 (if (member property org-special-properties)
16014 ;; We need a special property. Use brute force, get all properties.
16015 (cdr (assoc property (org-entry-properties nil 'special)))
16016 (let ((range (org-get-property-block)))
16017 (if (and range
16018 (goto-char (car range))
16019 (re-search-forward
16020 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16021 (cdr range) t))
16022 ;; Found the property, return it.
16023 (if (match-end 1)
16024 (org-match-string-no-properties 1)
16025 "")))))))
16027 (defun org-entry-delete (pom property)
16028 "Delete the property PROPERTY from entry at point-or-marker POM."
16029 (org-with-point-at pom
16030 (if (member property org-special-properties)
16031 nil ; cannot delete these properties.
16032 (let ((range (org-get-property-block)))
16033 (if (and range
16034 (goto-char (car range))
16035 (re-search-forward
16036 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16037 (cdr range) t))
16038 (progn
16039 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16041 nil)))))
16043 ;; Multi-values properties are properties that contain multiple values
16044 ;; These values are assumed to be single words, separated by whitespace.
16045 (defun org-entry-add-to-multivalued-property (pom property value)
16046 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16047 (let* ((old (org-entry-get pom property))
16048 (values (and old (org-split-string old "[ \t]"))))
16049 (unless (member value values)
16050 (setq values (cons value values))
16051 (org-entry-put pom property
16052 (mapconcat 'identity values " ")))))
16054 (defun org-entry-remove-from-multivalued-property (pom property value)
16055 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16056 (let* ((old (org-entry-get pom property))
16057 (values (and old (org-split-string old "[ \t]"))))
16058 (when (member value values)
16059 (setq values (delete value values))
16060 (org-entry-put pom property
16061 (mapconcat 'identity values " ")))))
16063 (defun org-entry-member-in-multivalued-property (pom property value)
16064 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16065 (let* ((old (org-entry-get pom property))
16066 (values (and old (org-split-string old "[ \t]"))))
16067 (member value values)))
16069 (defvar org-entry-property-inherited-from (make-marker))
16071 (defun org-entry-get-with-inheritance (property)
16072 "Get entry property, and search higher levels if not present."
16073 (let (tmp)
16074 (save-excursion
16075 (save-restriction
16076 (widen)
16077 (catch 'ex
16078 (while t
16079 (when (setq tmp (org-entry-get nil property))
16080 (org-back-to-heading t)
16081 (move-marker org-entry-property-inherited-from (point))
16082 (throw 'ex tmp))
16083 (or (org-up-heading-safe) (throw 'ex nil)))))
16084 (or tmp (cdr (assoc property org-local-properties))
16085 (cdr (assoc property org-global-properties))))))
16087 (defun org-entry-put (pom property value)
16088 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16089 (org-with-point-at pom
16090 (org-back-to-heading t)
16091 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16092 range)
16093 (cond
16094 ((equal property "TODO")
16095 (when (and (stringp value) (string-match "\\S-" value)
16096 (not (member value org-todo-keywords-1)))
16097 (error "\"%s\" is not a valid TODO state" value))
16098 (if (or (not value)
16099 (not (string-match "\\S-" value)))
16100 (setq value 'none))
16101 (org-todo value)
16102 (org-set-tags nil 'align))
16103 ((equal property "PRIORITY")
16104 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16105 (string-to-char value) ?\ ))
16106 (org-set-tags nil 'align))
16107 ((equal property "SCHEDULED")
16108 (if (re-search-forward org-scheduled-time-regexp end t)
16109 (cond
16110 ((eq value 'earlier) (org-timestamp-change -1 'day))
16111 ((eq value 'later) (org-timestamp-change 1 'day))
16112 (t (call-interactively 'org-schedule)))
16113 (call-interactively 'org-schedule)))
16114 ((equal property "DEADLINE")
16115 (if (re-search-forward org-deadline-time-regexp end t)
16116 (cond
16117 ((eq value 'earlier) (org-timestamp-change -1 'day))
16118 ((eq value 'later) (org-timestamp-change 1 'day))
16119 (t (call-interactively 'org-deadline)))
16120 (call-interactively 'org-deadline)))
16121 ((member property org-special-properties)
16122 (error "The %s property can not yet be set with `org-entry-put'"
16123 property))
16124 (t ; a non-special property
16125 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16126 (setq range (org-get-property-block beg end 'force))
16127 (goto-char (car range))
16128 (if (re-search-forward
16129 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16130 (progn
16131 (delete-region (match-beginning 1) (match-end 1))
16132 (goto-char (match-beginning 1)))
16133 (goto-char (cdr range))
16134 (insert "\n")
16135 (backward-char 1)
16136 (org-indent-line-function)
16137 (insert ":" property ":"))
16138 (and value (insert " " value))
16139 (org-indent-line-function)))))))
16141 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16142 "Get all property keys in the current buffer.
16143 With INCLUDE-SPECIALS, also list the special properties that relect things
16144 like tags and TODO state.
16145 With INCLUDE-DEFAULTS, also include properties that has special meaning
16146 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16147 With INCLUDE-COLUMNS, also include property names given in COLUMN
16148 formats in the current buffer."
16149 (let (rtn range cfmt cols s p)
16150 (save-excursion
16151 (save-restriction
16152 (widen)
16153 (goto-char (point-min))
16154 (while (re-search-forward org-property-start-re nil t)
16155 (setq range (org-get-property-block))
16156 (goto-char (car range))
16157 (while (re-search-forward
16158 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16159 (cdr range) t)
16160 (add-to-list 'rtn (org-match-string-no-properties 1)))
16161 (outline-next-heading))))
16163 (when include-specials
16164 (setq rtn (append org-special-properties rtn)))
16166 (when include-defaults
16167 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16169 (when include-columns
16170 (save-excursion
16171 (save-restriction
16172 (widen)
16173 (goto-char (point-min))
16174 (while (re-search-forward
16175 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16176 nil t)
16177 (setq cfmt (match-string 2) s 0)
16178 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16179 cfmt s)
16180 (setq s (match-end 0)
16181 p (match-string 1 cfmt))
16182 (unless (or (equal p "ITEM")
16183 (member p org-special-properties))
16184 (add-to-list 'rtn (match-string 1 cfmt))))))))
16186 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16188 (defun org-property-values (key)
16189 "Return a list of all values of property KEY."
16190 (save-excursion
16191 (save-restriction
16192 (widen)
16193 (goto-char (point-min))
16194 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16195 values)
16196 (while (re-search-forward re nil t)
16197 (add-to-list 'values (org-trim (match-string 1))))
16198 (delete "" values)))))
16200 (defun org-insert-property-drawer ()
16201 "Insert a property drawer into the current entry."
16202 (interactive)
16203 (org-back-to-heading t)
16204 (looking-at outline-regexp)
16205 (let ((indent (- (match-end 0)(match-beginning 0)))
16206 (beg (point))
16207 (re (concat "^[ \t]*" org-keyword-time-regexp))
16208 end hiddenp)
16209 (outline-next-heading)
16210 (setq end (point))
16211 (goto-char beg)
16212 (while (re-search-forward re end t))
16213 (setq hiddenp (org-invisible-p))
16214 (end-of-line 1)
16215 (and (equal (char-after) ?\n) (forward-char 1))
16216 (org-skip-over-state-notes)
16217 (skip-chars-backward " \t\n\r")
16218 (if (eq (char-before) ?*) (forward-char 1))
16219 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16220 (beginning-of-line 0)
16221 (indent-to-column indent)
16222 (beginning-of-line 2)
16223 (indent-to-column indent)
16224 (beginning-of-line 0)
16225 (if hiddenp
16226 (save-excursion
16227 (org-back-to-heading t)
16228 (hide-entry))
16229 (org-flag-drawer t))))
16231 (defun org-set-property (property value)
16232 "In the current entry, set PROPERTY to VALUE.
16233 When called interactively, this will prompt for a property name, offering
16234 completion on existing and default properties. And then it will prompt
16235 for a value, offering competion either on allowed values (via an inherited
16236 xxx_ALL property) or on existing values in other instances of this property
16237 in the current file."
16238 (interactive
16239 (let* ((prop (completing-read
16240 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16241 (cur (org-entry-get nil prop))
16242 (allowed (org-property-get-allowed-values nil prop 'table))
16243 (existing (mapcar 'list (org-property-values prop)))
16244 (val (if allowed
16245 (completing-read "Value: " allowed nil 'req-match)
16246 (completing-read
16247 (concat "Value" (if (and cur (string-match "\\S-" cur))
16248 (concat "[" cur "]") "")
16249 ": ")
16250 existing nil nil "" nil cur))))
16251 (list prop (if (equal val "") cur val))))
16252 (unless (equal (org-entry-get nil property) value)
16253 (org-entry-put nil property value)))
16255 (defun org-delete-property (property)
16256 "In the current entry, delete PROPERTY."
16257 (interactive
16258 (let* ((prop (completing-read
16259 "Property: " (org-entry-properties nil 'standard))))
16260 (list prop)))
16261 (message "Property %s %s" property
16262 (if (org-entry-delete nil property)
16263 "deleted"
16264 "was not present in the entry")))
16266 (defun org-delete-property-globally (property)
16267 "Remove PROPERTY globally, from all entries."
16268 (interactive
16269 (let* ((prop (completing-read
16270 "Globally remove property: "
16271 (mapcar 'list (org-buffer-property-keys)))))
16272 (list prop)))
16273 (save-excursion
16274 (save-restriction
16275 (widen)
16276 (goto-char (point-min))
16277 (let ((cnt 0))
16278 (while (re-search-forward
16279 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16280 nil t)
16281 (setq cnt (1+ cnt))
16282 (replace-match ""))
16283 (message "Property \"%s\" removed from %d entries" property cnt)))))
16285 (defvar org-columns-current-fmt-compiled) ; defined below
16287 (defun org-compute-property-at-point ()
16288 "Compute the property at point.
16289 This looks for an enclosing column format, extracts the operator and
16290 then applies it to the proerty in the column format's scope."
16291 (interactive)
16292 (unless (org-at-property-p)
16293 (error "Not at a property"))
16294 (let ((prop (org-match-string-no-properties 2)))
16295 (org-columns-get-format-and-top-level)
16296 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16297 (error "No operator defined for property %s" prop))
16298 (org-columns-compute prop)))
16300 (defun org-property-get-allowed-values (pom property &optional table)
16301 "Get allowed values for the property PROPERTY.
16302 When TABLE is non-nil, return an alist that can directly be used for
16303 completion."
16304 (let (vals)
16305 (cond
16306 ((equal property "TODO")
16307 (setq vals (org-with-point-at pom
16308 (append org-todo-keywords-1 '("")))))
16309 ((equal property "PRIORITY")
16310 (let ((n org-lowest-priority))
16311 (while (>= n org-highest-priority)
16312 (push (char-to-string n) vals)
16313 (setq n (1- n)))))
16314 ((member property org-special-properties))
16316 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16318 (when (and vals (string-match "\\S-" vals))
16319 (setq vals (car (read-from-string (concat "(" vals ")"))))
16320 (setq vals (mapcar (lambda (x)
16321 (cond ((stringp x) x)
16322 ((numberp x) (number-to-string x))
16323 ((symbolp x) (symbol-name x))
16324 (t "???")))
16325 vals)))))
16326 (if table (mapcar 'list vals) vals)))
16328 (defun org-property-previous-allowed-value (&optional previous)
16329 "Switch to the next allowed value for this property."
16330 (interactive)
16331 (org-property-next-allowed-value t))
16333 (defun org-property-next-allowed-value (&optional previous)
16334 "Switch to the next allowed value for this property."
16335 (interactive)
16336 (unless (org-at-property-p)
16337 (error "Not at a property"))
16338 (let* ((key (match-string 2))
16339 (value (match-string 3))
16340 (allowed (or (org-property-get-allowed-values (point) key)
16341 (and (member value '("[ ]" "[-]" "[X]"))
16342 '("[ ]" "[X]"))))
16343 nval)
16344 (unless allowed
16345 (error "Allowed values for this property have not been defined"))
16346 (if previous (setq allowed (reverse allowed)))
16347 (if (member value allowed)
16348 (setq nval (car (cdr (member value allowed)))))
16349 (setq nval (or nval (car allowed)))
16350 (if (equal nval value)
16351 (error "Only one allowed value for this property"))
16352 (org-at-property-p)
16353 (replace-match (concat " :" key ": " nval) t t)
16354 (org-indent-line-function)
16355 (beginning-of-line 1)
16356 (skip-chars-forward " \t")))
16358 (defun org-find-entry-with-id (ident)
16359 "Locate the entry that contains the ID property with exact value IDENT.
16360 IDENT can be a string, a symbol or a number, this function will search for
16361 the string representation of it.
16362 Return the position where this entry starts, or nil if there is no such entry."
16363 (let ((id (cond
16364 ((stringp ident) ident)
16365 ((symbol-name ident) (symbol-name ident))
16366 ((numberp ident) (number-to-string ident))
16367 (t (error "IDENT %s must be a string, symbol or number" ident))))
16368 (case-fold-search nil))
16369 (save-excursion
16370 (save-restriction
16371 (widen)
16372 (goto-char (point-min))
16373 (when (re-search-forward
16374 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16375 nil t)
16376 (org-back-to-heading)
16377 (point))))))
16379 ;;; Column View
16381 (defvar org-columns-overlays nil
16382 "Holds the list of current column overlays.")
16384 (defvar org-columns-current-fmt nil
16385 "Local variable, holds the currently active column format.")
16386 (defvar org-columns-current-fmt-compiled nil
16387 "Local variable, holds the currently active column format.
16388 This is the compiled version of the format.")
16389 (defvar org-columns-current-widths nil
16390 "Loval variable, holds the currently widths of fields.")
16391 (defvar org-columns-current-maxwidths nil
16392 "Loval variable, holds the currently active maximum column widths.")
16393 (defvar org-columns-begin-marker (make-marker)
16394 "Points to the position where last a column creation command was called.")
16395 (defvar org-columns-top-level-marker (make-marker)
16396 "Points to the position where current columns region starts.")
16398 (defvar org-columns-map (make-sparse-keymap)
16399 "The keymap valid in column display.")
16401 (defun org-columns-content ()
16402 "Switch to contents view while in columns view."
16403 (interactive)
16404 (org-overview)
16405 (org-content))
16407 (org-defkey org-columns-map "c" 'org-columns-content)
16408 (org-defkey org-columns-map "o" 'org-overview)
16409 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16410 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16411 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16412 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16413 (org-defkey org-columns-map "v" 'org-columns-show-value)
16414 (org-defkey org-columns-map "q" 'org-columns-quit)
16415 (org-defkey org-columns-map "r" 'org-columns-redo)
16416 (org-defkey org-columns-map "g" 'org-columns-redo)
16417 (org-defkey org-columns-map [left] 'backward-char)
16418 (org-defkey org-columns-map "\M-b" 'backward-char)
16419 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16420 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16421 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16422 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16423 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16424 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16425 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16426 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16427 (org-defkey org-columns-map "<" 'org-columns-narrow)
16428 (org-defkey org-columns-map ">" 'org-columns-widen)
16429 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16430 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16431 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16432 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16434 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16435 '("Column"
16436 ["Edit property" org-columns-edit-value t]
16437 ["Next allowed value" org-columns-next-allowed-value t]
16438 ["Previous allowed value" org-columns-previous-allowed-value t]
16439 ["Show full value" org-columns-show-value t]
16440 ["Edit allowed values" org-columns-edit-allowed t]
16441 "--"
16442 ["Edit column attributes" org-columns-edit-attributes t]
16443 ["Increase column width" org-columns-widen t]
16444 ["Decrease column width" org-columns-narrow t]
16445 "--"
16446 ["Move column right" org-columns-move-right t]
16447 ["Move column left" org-columns-move-left t]
16448 ["Add column" org-columns-new t]
16449 ["Delete column" org-columns-delete t]
16450 "--"
16451 ["CONTENTS" org-columns-content t]
16452 ["OVERVIEW" org-overview t]
16453 ["Refresh columns display" org-columns-redo t]
16454 "--"
16455 ["Open link" org-columns-open-link t]
16456 "--"
16457 ["Quit" org-columns-quit t]))
16459 (defun org-columns-new-overlay (beg end &optional string face)
16460 "Create a new column overlay and add it to the list."
16461 (let ((ov (org-make-overlay beg end)))
16462 (org-overlay-put ov 'face (or face 'secondary-selection))
16463 (org-overlay-display ov string face)
16464 (push ov org-columns-overlays)
16465 ov))
16467 (defun org-columns-display-here (&optional props)
16468 "Overlay the current line with column display."
16469 (interactive)
16470 (let* ((fmt org-columns-current-fmt-compiled)
16471 (beg (point-at-bol))
16472 (level-face (save-excursion
16473 (beginning-of-line 1)
16474 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16475 (org-get-level-face 2))))
16476 (color (list :foreground
16477 (face-attribute (or level-face 'default) :foreground)))
16478 props pom property ass width f string ov column val modval)
16479 ;; Check if the entry is in another buffer.
16480 (unless props
16481 (if (eq major-mode 'org-agenda-mode)
16482 (setq pom (or (get-text-property (point) 'org-hd-marker)
16483 (get-text-property (point) 'org-marker))
16484 props (if pom (org-entry-properties pom) nil))
16485 (setq props (org-entry-properties nil))))
16486 ;; Walk the format
16487 (while (setq column (pop fmt))
16488 (setq property (car column)
16489 ass (if (equal property "ITEM")
16490 (cons "ITEM"
16491 (save-match-data
16492 (org-no-properties
16493 (org-remove-tabs
16494 (buffer-substring-no-properties
16495 (point-at-bol) (point-at-eol))))))
16496 (assoc property props))
16497 width (or (cdr (assoc property org-columns-current-maxwidths))
16498 (nth 2 column)
16499 (length property))
16500 f (format "%%-%d.%ds | " width width)
16501 val (or (cdr ass) "")
16502 modval (if (equal property "ITEM")
16503 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16504 string (format f (or modval val)))
16505 ;; Create the overlay
16506 (org-unmodified
16507 (setq ov (org-columns-new-overlay
16508 beg (setq beg (1+ beg)) string
16509 (list color 'org-column)))
16510 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16511 (org-overlay-put ov 'keymap org-columns-map)
16512 (org-overlay-put ov 'org-columns-key property)
16513 (org-overlay-put ov 'org-columns-value (cdr ass))
16514 (org-overlay-put ov 'org-columns-value-modified modval)
16515 (org-overlay-put ov 'org-columns-pom pom)
16516 (org-overlay-put ov 'org-columns-format f))
16517 (if (or (not (char-after beg))
16518 (equal (char-after beg) ?\n))
16519 (let ((inhibit-read-only t))
16520 (save-excursion
16521 (goto-char beg)
16522 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16523 ;; Make the rest of the line disappear.
16524 (org-unmodified
16525 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16526 (org-overlay-put ov 'invisible t)
16527 (org-overlay-put ov 'keymap org-columns-map)
16528 (org-overlay-put ov 'intangible t)
16529 (push ov org-columns-overlays)
16530 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16531 (org-overlay-put ov 'keymap org-columns-map)
16532 (push ov org-columns-overlays)
16533 (let ((inhibit-read-only t))
16534 (put-text-property (max (point-min) (1- (point-at-bol)))
16535 (min (point-max) (1+ (point-at-eol)))
16536 'read-only "Type `e' to edit property")))))
16538 (defvar org-previous-header-line-format nil
16539 "The header line format before column view was turned on.")
16540 (defvar org-columns-inhibit-recalculation nil
16541 "Inhibit recomputing of columns on column view startup.")
16544 (defvar header-line-format)
16545 (defun org-columns-display-here-title ()
16546 "Overlay the newline before the current line with the table title."
16547 (interactive)
16548 (let ((fmt org-columns-current-fmt-compiled)
16549 string (title "")
16550 property width f column str widths)
16551 (while (setq column (pop fmt))
16552 (setq property (car column)
16553 str (or (nth 1 column) property)
16554 width (or (cdr (assoc property org-columns-current-maxwidths))
16555 (nth 2 column)
16556 (length str))
16557 widths (push width widths)
16558 f (format "%%-%d.%ds | " width width)
16559 string (format f str)
16560 title (concat title string)))
16561 (setq title (concat
16562 (org-add-props " " nil 'display '(space :align-to 0))
16563 (org-add-props title nil 'face '(:weight bold :underline t))))
16564 (org-set-local 'org-previous-header-line-format header-line-format)
16565 (org-set-local 'org-columns-current-widths (nreverse widths))
16566 (setq header-line-format title)))
16568 (defun org-columns-remove-overlays ()
16569 "Remove all currently active column overlays."
16570 (interactive)
16571 (when (marker-buffer org-columns-begin-marker)
16572 (with-current-buffer (marker-buffer org-columns-begin-marker)
16573 (when (local-variable-p 'org-previous-header-line-format)
16574 (setq header-line-format org-previous-header-line-format)
16575 (kill-local-variable 'org-previous-header-line-format))
16576 (move-marker org-columns-begin-marker nil)
16577 (move-marker org-columns-top-level-marker nil)
16578 (org-unmodified
16579 (mapc 'org-delete-overlay org-columns-overlays)
16580 (setq org-columns-overlays nil)
16581 (let ((inhibit-read-only t))
16582 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16584 (defun org-columns-cleanup-item (item fmt)
16585 "Remove from ITEM what is a column in the format FMT."
16586 (if (not org-complex-heading-regexp)
16587 item
16588 (when (string-match org-complex-heading-regexp item)
16589 (concat
16590 (org-add-props (concat (match-string 1 item) " ") nil
16591 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16592 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16593 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16594 " " (match-string 4 item)
16595 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16597 (defun org-columns-show-value ()
16598 "Show the full value of the property."
16599 (interactive)
16600 (let ((value (get-char-property (point) 'org-columns-value)))
16601 (message "Value is: %s" (or value ""))))
16603 (defun org-columns-quit ()
16604 "Remove the column overlays and in this way exit column editing."
16605 (interactive)
16606 (org-unmodified
16607 (org-columns-remove-overlays)
16608 (let ((inhibit-read-only t))
16609 (remove-text-properties (point-min) (point-max) '(read-only t))))
16610 (when (eq major-mode 'org-agenda-mode)
16611 (message
16612 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16614 (defun org-columns-check-computed ()
16615 "Check if this column value is computed.
16616 If yes, throw an error indicating that changing it does not make sense."
16617 (let ((val (get-char-property (point) 'org-columns-value)))
16618 (when (and (stringp val)
16619 (get-char-property 0 'org-computed val))
16620 (error "This value is computed from the entry's children"))))
16622 (defun org-columns-todo (&optional arg)
16623 "Change the TODO state during column view."
16624 (interactive "P")
16625 (org-columns-edit-value "TODO"))
16627 (defun org-columns-set-tags-or-toggle (&optional arg)
16628 "Toggle checkbox at point, or set tags for current headline."
16629 (interactive "P")
16630 (if (string-match "\\`\\[[ xX-]\\]\\'"
16631 (get-char-property (point) 'org-columns-value))
16632 (org-columns-next-allowed-value)
16633 (org-columns-edit-value "TAGS")))
16635 (defun org-columns-edit-value (&optional key)
16636 "Edit the value of the property at point in column view.
16637 Where possible, use the standard interface for changing this line."
16638 (interactive)
16639 (org-columns-check-computed)
16640 (let* ((external-key key)
16641 (col (current-column))
16642 (key (or key (get-char-property (point) 'org-columns-key)))
16643 (value (get-char-property (point) 'org-columns-value))
16644 (bol (point-at-bol)) (eol (point-at-eol))
16645 (pom (or (get-text-property bol 'org-hd-marker)
16646 (point))) ; keep despite of compiler waring
16647 (line-overlays
16648 (delq nil (mapcar (lambda (x)
16649 (and (eq (overlay-buffer x) (current-buffer))
16650 (>= (overlay-start x) bol)
16651 (<= (overlay-start x) eol)
16653 org-columns-overlays)))
16654 nval eval allowed)
16655 (cond
16656 ((equal key "CLOCKSUM")
16657 (error "This special column cannot be edited"))
16658 ((equal key "ITEM")
16659 (setq eval '(org-with-point-at pom
16660 (org-edit-headline))))
16661 ((equal key "TODO")
16662 (setq eval '(org-with-point-at pom
16663 (let ((current-prefix-arg
16664 (if external-key current-prefix-arg '(4))))
16665 (call-interactively 'org-todo)))))
16666 ((equal key "PRIORITY")
16667 (setq eval '(org-with-point-at pom
16668 (call-interactively 'org-priority))))
16669 ((equal key "TAGS")
16670 (setq eval '(org-with-point-at pom
16671 (let ((org-fast-tag-selection-single-key
16672 (if (eq org-fast-tag-selection-single-key 'expert)
16673 t org-fast-tag-selection-single-key)))
16674 (call-interactively 'org-set-tags)))))
16675 ((equal key "DEADLINE")
16676 (setq eval '(org-with-point-at pom
16677 (call-interactively 'org-deadline))))
16678 ((equal key "SCHEDULED")
16679 (setq eval '(org-with-point-at pom
16680 (call-interactively 'org-schedule))))
16682 (setq allowed (org-property-get-allowed-values pom key 'table))
16683 (if allowed
16684 (setq nval (completing-read "Value: " allowed nil t))
16685 (setq nval (read-string "Edit: " value)))
16686 (setq nval (org-trim nval))
16687 (when (not (equal nval value))
16688 (setq eval '(org-entry-put pom key nval)))))
16689 (when eval
16690 (let ((inhibit-read-only t))
16691 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16692 (unwind-protect
16693 (progn
16694 (setq org-columns-overlays
16695 (org-delete-all line-overlays org-columns-overlays))
16696 (mapc 'org-delete-overlay line-overlays)
16697 (org-columns-eval eval))
16698 (org-columns-display-here))))
16699 (move-to-column col)
16700 (if (and (org-mode-p)
16701 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16702 (org-columns-update key))))
16704 (defun org-edit-headline () ; FIXME: this is not columns specific
16705 "Edit the current headline, the part without TODO keyword, TAGS."
16706 (org-back-to-heading)
16707 (when (looking-at org-todo-line-regexp)
16708 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16709 (txt (match-string 3))
16710 (post "")
16711 txt2)
16712 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16713 (setq post (match-string 0 txt)
16714 txt (substring txt 0 (match-beginning 0))))
16715 (setq txt2 (read-string "Edit: " txt))
16716 (when (not (equal txt txt2))
16717 (beginning-of-line 1)
16718 (insert pre txt2 post)
16719 (delete-region (point) (point-at-eol))
16720 (org-set-tags nil t)))))
16722 (defun org-columns-edit-allowed ()
16723 "Edit the list of allowed values for the current property."
16724 (interactive)
16725 (let* ((key (get-char-property (point) 'org-columns-key))
16726 (key1 (concat key "_ALL"))
16727 (allowed (org-entry-get (point) key1 t))
16728 nval)
16729 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16730 (setq nval (read-string "Allowed: " allowed))
16731 (org-entry-put
16732 (cond ((marker-position org-entry-property-inherited-from)
16733 org-entry-property-inherited-from)
16734 ((marker-position org-columns-top-level-marker)
16735 org-columns-top-level-marker))
16736 key1 nval)))
16738 (defmacro org-no-warnings (&rest body)
16739 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16741 (defun org-columns-eval (form)
16742 (let (hidep)
16743 (save-excursion
16744 (beginning-of-line 1)
16745 ;; `next-line' is needed here, because it skips invisible line.
16746 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16747 (setq hidep (org-on-heading-p 1)))
16748 (eval form)
16749 (and hidep (hide-entry))))
16751 (defun org-columns-previous-allowed-value ()
16752 "Switch to the previous allowed value for this column."
16753 (interactive)
16754 (org-columns-next-allowed-value t))
16756 (defun org-columns-next-allowed-value (&optional previous)
16757 "Switch to the next allowed value for this column."
16758 (interactive)
16759 (org-columns-check-computed)
16760 (let* ((col (current-column))
16761 (key (get-char-property (point) 'org-columns-key))
16762 (value (get-char-property (point) 'org-columns-value))
16763 (bol (point-at-bol)) (eol (point-at-eol))
16764 (pom (or (get-text-property bol 'org-hd-marker)
16765 (point))) ; keep despite of compiler waring
16766 (line-overlays
16767 (delq nil (mapcar (lambda (x)
16768 (and (eq (overlay-buffer x) (current-buffer))
16769 (>= (overlay-start x) bol)
16770 (<= (overlay-start x) eol)
16772 org-columns-overlays)))
16773 (allowed (or (org-property-get-allowed-values pom key)
16774 (and (memq
16775 (nth 4 (assoc key org-columns-current-fmt-compiled))
16776 '(checkbox checkbox-n-of-m checkbox-percent))
16777 '("[ ]" "[X]"))))
16778 nval)
16779 (when (equal key "ITEM")
16780 (error "Cannot edit item headline from here"))
16781 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16782 (error "Allowed values for this property have not been defined"))
16783 (if (member key '("SCHEDULED" "DEADLINE"))
16784 (setq nval (if previous 'earlier 'later))
16785 (if previous (setq allowed (reverse allowed)))
16786 (if (member value allowed)
16787 (setq nval (car (cdr (member value allowed)))))
16788 (setq nval (or nval (car allowed)))
16789 (if (equal nval value)
16790 (error "Only one allowed value for this property")))
16791 (let ((inhibit-read-only t))
16792 (remove-text-properties (1- bol) eol '(read-only t))
16793 (unwind-protect
16794 (progn
16795 (setq org-columns-overlays
16796 (org-delete-all line-overlays org-columns-overlays))
16797 (mapc 'org-delete-overlay line-overlays)
16798 (org-columns-eval '(org-entry-put pom key nval)))
16799 (org-columns-display-here)))
16800 (move-to-column col)
16801 (if (and (org-mode-p)
16802 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16803 (org-columns-update key))))
16805 (defun org-verify-version (task)
16806 (cond
16807 ((eq task 'columns)
16808 (if (or (featurep 'xemacs)
16809 (< emacs-major-version 22))
16810 (error "Emacs 22 is required for the columns feature")))))
16812 (defun org-columns-open-link (&optional arg)
16813 (interactive "P")
16814 (let ((value (get-char-property (point) 'org-columns-value)))
16815 (org-open-link-from-string value arg)))
16817 (defun org-open-link-from-string (s &optional arg)
16818 "Open a link in the string S, as if it was in Org-mode."
16819 (interactive)
16820 (with-temp-buffer
16821 (let ((org-inhibit-startup t))
16822 (org-mode)
16823 (insert s)
16824 (goto-char (point-min))
16825 (org-open-at-point arg))))
16827 (defun org-columns-get-format-and-top-level ()
16828 (let (fmt)
16829 (when (condition-case nil (org-back-to-heading) (error nil))
16830 (move-marker org-entry-property-inherited-from nil)
16831 (setq fmt (org-entry-get nil "COLUMNS" t)))
16832 (setq fmt (or fmt org-columns-default-format))
16833 (org-set-local 'org-columns-current-fmt fmt)
16834 (org-columns-compile-format fmt)
16835 (if (marker-position org-entry-property-inherited-from)
16836 (move-marker org-columns-top-level-marker
16837 org-entry-property-inherited-from)
16838 (move-marker org-columns-top-level-marker (point)))
16839 fmt))
16841 (defun org-columns ()
16842 "Turn on column view on an org-mode file."
16843 (interactive)
16844 (org-verify-version 'columns)
16845 (org-columns-remove-overlays)
16846 (move-marker org-columns-begin-marker (point))
16847 (let (beg end fmt cache maxwidths)
16848 (setq fmt (org-columns-get-format-and-top-level))
16849 (save-excursion
16850 (goto-char org-columns-top-level-marker)
16851 (setq beg (point))
16852 (unless org-columns-inhibit-recalculation
16853 (org-columns-compute-all))
16854 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16855 (point-max)))
16856 ;; Get and cache the properties
16857 (goto-char beg)
16858 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
16859 (save-excursion
16860 (save-restriction
16861 (narrow-to-region beg end)
16862 (org-clock-sum))))
16863 (while (re-search-forward (concat "^" outline-regexp) end t)
16864 (push (cons (org-current-line) (org-entry-properties)) cache))
16865 (when cache
16866 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16867 (org-set-local 'org-columns-current-maxwidths maxwidths)
16868 (org-columns-display-here-title)
16869 (mapc (lambda (x)
16870 (goto-line (car x))
16871 (org-columns-display-here (cdr x)))
16872 cache)))))
16874 (defun org-columns-new (&optional prop title width op fmt &rest rest)
16875 "Insert a new column, to the left of the current column."
16876 (interactive)
16877 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
16878 cell)
16879 (setq prop (completing-read
16880 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
16881 nil nil prop))
16882 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
16883 (setq width (read-string "Column width: " (if width (number-to-string width))))
16884 (if (string-match "\\S-" width)
16885 (setq width (string-to-number width))
16886 (setq width nil))
16887 (setq fmt (completing-read "Summary [none]: "
16888 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
16889 nil t))
16890 (if (string-match "\\S-" fmt)
16891 (setq fmt (intern fmt))
16892 (setq fmt nil))
16893 (if (eq fmt 'none) (setq fmt nil))
16894 (if editp
16895 (progn
16896 (setcar editp prop)
16897 (setcdr editp (list title width nil fmt)))
16898 (setq cell (nthcdr (1- (current-column))
16899 org-columns-current-fmt-compiled))
16900 (setcdr cell (cons (list prop title width nil fmt)
16901 (cdr cell))))
16902 (org-columns-store-format)
16903 (org-columns-redo)))
16905 (defun org-columns-delete ()
16906 "Delete the column at point from columns view."
16907 (interactive)
16908 (let* ((n (current-column))
16909 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
16910 (when (y-or-n-p
16911 (format "Are you sure you want to remove column \"%s\"? " title))
16912 (setq org-columns-current-fmt-compiled
16913 (delq (nth n org-columns-current-fmt-compiled)
16914 org-columns-current-fmt-compiled))
16915 (org-columns-store-format)
16916 (org-columns-redo)
16917 (if (>= (current-column) (length org-columns-current-fmt-compiled))
16918 (backward-char 1)))))
16920 (defun org-columns-edit-attributes ()
16921 "Edit the attributes of the current column."
16922 (interactive)
16923 (let* ((n (current-column))
16924 (info (nth n org-columns-current-fmt-compiled)))
16925 (apply 'org-columns-new info)))
16927 (defun org-columns-widen (arg)
16928 "Make the column wider by ARG characters."
16929 (interactive "p")
16930 (let* ((n (current-column))
16931 (entry (nth n org-columns-current-fmt-compiled))
16932 (width (or (nth 2 entry)
16933 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
16934 (setq width (max 1 (+ width arg)))
16935 (setcar (nthcdr 2 entry) width)
16936 (org-columns-store-format)
16937 (org-columns-redo)))
16939 (defun org-columns-narrow (arg)
16940 "Make the column nrrower by ARG characters."
16941 (interactive "p")
16942 (org-columns-widen (- arg)))
16944 (defun org-columns-move-right ()
16945 "Swap this column with the one to the right."
16946 (interactive)
16947 (let* ((n (current-column))
16948 (cell (nthcdr n org-columns-current-fmt-compiled))
16950 (when (>= n (1- (length org-columns-current-fmt-compiled)))
16951 (error "Cannot shift this column further to the right"))
16952 (setq e (car cell))
16953 (setcar cell (car (cdr cell)))
16954 (setcdr cell (cons e (cdr (cdr cell))))
16955 (org-columns-store-format)
16956 (org-columns-redo)
16957 (forward-char 1)))
16959 (defun org-columns-move-left ()
16960 "Swap this column with the one to the left."
16961 (interactive)
16962 (let* ((n (current-column)))
16963 (when (= n 0)
16964 (error "Cannot shift this column further to the left"))
16965 (backward-char 1)
16966 (org-columns-move-right)
16967 (backward-char 1)))
16969 (defun org-columns-store-format ()
16970 "Store the text version of the current columns format in appropriate place.
16971 This is either in the COLUMNS property of the node starting the current column
16972 display, or in the #+COLUMNS line of the current buffer."
16973 (let (fmt (cnt 0))
16974 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
16975 (org-set-local 'org-columns-current-fmt fmt)
16976 (if (marker-position org-columns-top-level-marker)
16977 (save-excursion
16978 (goto-char org-columns-top-level-marker)
16979 (if (and (org-at-heading-p)
16980 (org-entry-get nil "COLUMNS"))
16981 (org-entry-put nil "COLUMNS" fmt)
16982 (goto-char (point-min))
16983 ;; Overwrite all #+COLUMNS lines....
16984 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
16985 (setq cnt (1+ cnt))
16986 (replace-match (concat "#+COLUMNS: " fmt) t t))
16987 (unless (> cnt 0)
16988 (goto-char (point-min))
16989 (or (org-on-heading-p t) (outline-next-heading))
16990 (let ((inhibit-read-only t))
16991 (insert-before-markers "#+COLUMNS: " fmt "\n")))
16992 (org-set-local 'org-columns-default-format fmt))))))
16994 (defvar org-overriding-columns-format nil
16995 "When set, overrides any other definition.")
16996 (defvar org-agenda-view-columns-initially nil
16997 "When set, switch to columns view immediately after creating the agenda.")
16999 (defun org-agenda-columns ()
17000 "Turn on column view in the agenda."
17001 (interactive)
17002 (org-verify-version 'columns)
17003 (org-columns-remove-overlays)
17004 (move-marker org-columns-begin-marker (point))
17005 (let (fmt cache maxwidths m)
17006 (cond
17007 ((and (local-variable-p 'org-overriding-columns-format)
17008 org-overriding-columns-format)
17009 (setq fmt org-overriding-columns-format))
17010 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
17011 (setq fmt (org-entry-get m "COLUMNS" t)))
17012 ((and (boundp 'org-columns-current-fmt)
17013 (local-variable-p 'org-columns-current-fmt)
17014 org-columns-current-fmt)
17015 (setq fmt org-columns-current-fmt))
17016 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
17017 (setq m (get-text-property m 'org-hd-marker))
17018 (setq fmt (org-entry-get m "COLUMNS" t))))
17019 (setq fmt (or fmt org-columns-default-format))
17020 (org-set-local 'org-columns-current-fmt fmt)
17021 (org-columns-compile-format fmt)
17022 (save-excursion
17023 ;; Get and cache the properties
17024 (goto-char (point-min))
17025 (while (not (eobp))
17026 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17027 (get-text-property (point) 'org-marker)))
17028 (push (cons (org-current-line) (org-entry-properties m)) cache))
17029 (beginning-of-line 2))
17030 (when cache
17031 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17032 (org-set-local 'org-columns-current-maxwidths maxwidths)
17033 (org-columns-display-here-title)
17034 (mapc (lambda (x)
17035 (goto-line (car x))
17036 (org-columns-display-here (cdr x)))
17037 cache)))))
17039 (defun org-columns-get-autowidth-alist (s cache)
17040 "Derive the maximum column widths from the format and the cache."
17041 (let ((start 0) rtn)
17042 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
17043 (push (cons (match-string 1 s) 1) rtn)
17044 (setq start (match-end 0)))
17045 (mapc (lambda (x)
17046 (setcdr x (apply 'max
17047 (mapcar
17048 (lambda (y)
17049 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17050 cache))))
17051 rtn)
17052 rtn))
17054 (defun org-columns-compute-all ()
17055 "Compute all columns that have operators defined."
17056 (org-unmodified
17057 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17058 (let ((columns org-columns-current-fmt-compiled) col)
17059 (while (setq col (pop columns))
17060 (when (nth 3 col)
17061 (save-excursion
17062 (org-columns-compute (car col)))))))
17064 (defun org-columns-update (property)
17065 "Recompute PROPERTY, and update the columns display for it."
17066 (org-columns-compute property)
17067 (let (fmt val pos)
17068 (save-excursion
17069 (mapc (lambda (ov)
17070 (when (equal (org-overlay-get ov 'org-columns-key) property)
17071 (setq pos (org-overlay-start ov))
17072 (goto-char pos)
17073 (when (setq val (cdr (assoc property
17074 (get-text-property
17075 (point-at-bol) 'org-summaries))))
17076 (setq fmt (org-overlay-get ov 'org-columns-format))
17077 (org-overlay-put ov 'org-columns-value val)
17078 (org-overlay-put ov 'display (format fmt val)))))
17079 org-columns-overlays))))
17081 (defun org-columns-compute (property)
17082 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17083 (interactive)
17084 (let* ((re (concat "^" outline-regexp))
17085 (lmax 30) ; Does anyone use deeper levels???
17086 (lsum (make-vector lmax 0))
17087 (lflag (make-vector lmax nil))
17088 (level 0)
17089 (ass (assoc property org-columns-current-fmt-compiled))
17090 (format (nth 4 ass))
17091 (printf (nth 5 ass))
17092 (beg org-columns-top-level-marker)
17093 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17094 (save-excursion
17095 ;; Find the region to compute
17096 (goto-char beg)
17097 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17098 (goto-char end)
17099 ;; Walk the tree from the back and do the computations
17100 (while (re-search-backward re beg t)
17101 (setq sumpos (match-beginning 0)
17102 last-level level
17103 level (org-outline-level)
17104 val (org-entry-get nil property)
17105 valflag (and val (string-match "\\S-" val)))
17106 (cond
17107 ((< level last-level)
17108 ;; put the sum of lower levels here as a property
17109 (setq sum (aref lsum last-level) ; current sum
17110 flag (aref lflag last-level) ; any valid entries from children?
17111 str (org-column-number-to-string sum format printf)
17112 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17113 useval (if flag str1 (if valflag val ""))
17114 sum-alist (get-text-property sumpos 'org-summaries))
17115 (if (assoc property sum-alist)
17116 (setcdr (assoc property sum-alist) useval)
17117 (push (cons property useval) sum-alist)
17118 (org-unmodified
17119 (add-text-properties sumpos (1+ sumpos)
17120 (list 'org-summaries sum-alist))))
17121 (when val
17122 (org-entry-put nil property (if flag str val)))
17123 ;; add current to current level accumulator
17124 (when (or flag valflag)
17125 (aset lsum level (+ (aref lsum level)
17126 (if flag sum (org-column-string-to-number
17127 (if flag str val) format))))
17128 (aset lflag level t))
17129 ;; clear accumulators for deeper levels
17130 (loop for l from (1+ level) to (1- lmax) do
17131 (aset lsum l 0)
17132 (aset lflag l nil)))
17133 ((>= level last-level)
17134 ;; add what we have here to the accumulator for this level
17135 (aset lsum level (+ (aref lsum level)
17136 (org-column-string-to-number (or val "0") format)))
17137 (and valflag (aset lflag level t)))
17138 (t (error "This should not happen")))))))
17140 (defun org-columns-redo ()
17141 "Construct the column display again."
17142 (interactive)
17143 (message "Recomputing columns...")
17144 (save-excursion
17145 (if (marker-position org-columns-begin-marker)
17146 (goto-char org-columns-begin-marker))
17147 (org-columns-remove-overlays)
17148 (if (org-mode-p)
17149 (call-interactively 'org-columns)
17150 (call-interactively 'org-agenda-columns)))
17151 (message "Recomputing columns...done"))
17153 (defun org-columns-not-in-agenda ()
17154 (if (eq major-mode 'org-agenda-mode)
17155 (error "This command is only allowed in Org-mode buffers")))
17158 (defun org-string-to-number (s)
17159 "Convert string to number, and interpret hh:mm:ss."
17160 (if (not (string-match ":" s))
17161 (string-to-number s)
17162 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17163 (while l
17164 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17165 sum)))
17167 (defun org-column-number-to-string (n fmt &optional printf)
17168 "Convert a computed column number to a string value, according to FMT."
17169 (cond
17170 ((eq fmt 'add_times)
17171 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17172 (format "%d:%02d" h m)))
17173 ((eq fmt 'checkbox)
17174 (cond ((= n (floor n)) "[X]")
17175 ((> n 1.) "[-]")
17176 (t "[ ]")))
17177 ((memq fmt '(checkbox-n-of-m checkbox-percent))
17178 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
17179 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
17180 (printf (format printf n))
17181 ((eq fmt 'currency)
17182 (format "%.2f" n))
17183 (t (number-to-string n))))
17185 (defun org-nofm-to-completion (n m &optional percent)
17186 (if (not percent)
17187 (format "[%d/%d]" n m)
17188 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
17190 (defun org-column-string-to-number (s fmt)
17191 "Convert a column value to a number that can be used for column computing."
17192 (cond
17193 ((string-match ":" s)
17194 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17195 (while l
17196 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17197 sum))
17198 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
17199 (if (equal s "[X]") 1. 0.000001))
17200 (t (string-to-number s))))
17202 (defun org-columns-uncompile-format (cfmt)
17203 "Turn the compiled columns format back into a string representation."
17204 (let ((rtn "") e s prop title op width fmt printf)
17205 (while (setq e (pop cfmt))
17206 (setq prop (car e)
17207 title (nth 1 e)
17208 width (nth 2 e)
17209 op (nth 3 e)
17210 fmt (nth 4 e)
17211 printf (nth 5 e))
17212 (cond
17213 ((eq fmt 'add_times) (setq op ":"))
17214 ((eq fmt 'checkbox) (setq op "X"))
17215 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
17216 ((eq fmt 'checkbox-percent) (setq op "X%"))
17217 ((eq fmt 'add_numbers) (setq op "+"))
17218 ((eq fmt 'currency) (setq op "$")))
17219 (if (and op printf) (setq op (concat op ";" printf)))
17220 (if (equal title prop) (setq title nil))
17221 (setq s (concat "%" (if width (number-to-string width))
17222 prop
17223 (if title (concat "(" title ")"))
17224 (if op (concat "{" op "}"))))
17225 (setq rtn (concat rtn " " s)))
17226 (org-trim rtn)))
17228 (defun org-columns-compile-format (fmt)
17229 "Turn a column format string into an alist of specifications.
17230 The alist has one entry for each column in the format. The elements of
17231 that list are:
17232 property the property
17233 title the title field for the columns
17234 width the column width in characters, can be nil for automatic
17235 operator the operator if any
17236 format the output format for computed results, derived from operator
17237 printf a printf format for computed values"
17238 (let ((start 0) width prop title op f printf)
17239 (setq org-columns-current-fmt-compiled nil)
17240 (while (string-match
17241 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17242 fmt start)
17243 (setq start (match-end 0)
17244 width (match-string 1 fmt)
17245 prop (match-string 2 fmt)
17246 title (or (match-string 3 fmt) prop)
17247 op (match-string 4 fmt)
17248 f nil
17249 printf nil)
17250 (if width (setq width (string-to-number width)))
17251 (when (and op (string-match ";" op))
17252 (setq printf (substring op (match-end 0))
17253 op (substring op 0 (match-beginning 0))))
17254 (cond
17255 ((equal op "+") (setq f 'add_numbers))
17256 ((equal op "$") (setq f 'currency))
17257 ((equal op ":") (setq f 'add_times))
17258 ((equal op "X") (setq f 'checkbox))
17259 ((equal op "X/") (setq f 'checkbox-n-of-m))
17260 ((equal op "X%") (setq f 'checkbox-percent))
17262 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17263 (setq org-columns-current-fmt-compiled
17264 (nreverse org-columns-current-fmt-compiled))))
17267 ;;; Dynamic block for Column view
17269 (defun org-columns-capture-view (&optional maxlevel skip-empty-rows)
17270 "Get the column view of the current buffer or subtree.
17271 The first optional argument MAXLEVEL sets the level limit. A
17272 second optional argument SKIP-EMPTY-ROWS tells whether to skip
17273 empty rows, an empty row being one where all the column view
17274 specifiers except ITEM are empty. This function returns a list
17275 containing the title row and all other rows. Each row is a list
17276 of fields."
17277 (save-excursion
17278 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17279 (n (length title)) row tbl)
17280 (goto-char (point-min))
17281 (while (and (re-search-forward "^\\(\\*+\\) " nil t)
17282 (or (null maxlevel)
17283 (>= maxlevel
17284 (if org-odd-levels-only
17285 (/ (1+ (length (match-string 1))) 2)
17286 (length (match-string 1))))))
17287 (when (get-char-property (match-beginning 0) 'org-columns-key)
17288 (setq row nil)
17289 (loop for i from 0 to (1- n) do
17290 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17291 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17293 row))
17294 (setq row (nreverse row))
17295 (unless (and skip-empty-rows
17296 (eq 1 (length (delete "" (delete-dups row)))))
17297 (push row tbl))))
17298 (append (list title 'hline) (nreverse tbl)))))
17300 (defun org-dblock-write:columnview (params)
17301 "Write the column view table.
17302 PARAMS is a property list of parameters:
17304 :width enforce same column widths with <N> specifiers.
17305 :id the :ID: property of the entry where the columns view
17306 should be built, as a string. When `local', call locally.
17307 When `global' call column view with the cursor at the beginning
17308 of the buffer (usually this means that the whole buffer switches
17309 to column view).
17310 :hlines When t, insert a hline before each item. When a number, insert
17311 a hline before each level <= that number.
17312 :vlines When t, make each column a colgroup to enforce vertical lines.
17313 :maxlevel When set to a number, don't capture headlines below this level.
17314 :skip-empty-rows
17315 When t, skip rows where all specifiers other than ITEM are empty."
17316 (let ((pos (move-marker (make-marker) (point)))
17317 (hlines (plist-get params :hlines))
17318 (vlines (plist-get params :vlines))
17319 (maxlevel (plist-get params :maxlevel))
17320 (skip-empty-rows (plist-get params :skip-empty-rows))
17321 tbl id idpos nfields tmp)
17322 (save-excursion
17323 (save-restriction
17324 (when (setq id (plist-get params :id))
17325 (cond ((not id) nil)
17326 ((eq id 'global) (goto-char (point-min)))
17327 ((eq id 'local) nil)
17328 ((setq idpos (org-find-entry-with-id id))
17329 (goto-char idpos))
17330 (t (error "Cannot find entry with :ID: %s" id))))
17331 (org-columns)
17332 (setq tbl (org-columns-capture-view maxlevel skip-empty-rows))
17333 (setq nfields (length (car tbl)))
17334 (org-columns-quit)))
17335 (goto-char pos)
17336 (move-marker pos nil)
17337 (when tbl
17338 (when (plist-get params :hlines)
17339 (setq tmp nil)
17340 (while tbl
17341 (if (eq (car tbl) 'hline)
17342 (push (pop tbl) tmp)
17343 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17344 (if (and (not (eq (car tmp) 'hline))
17345 (or (eq hlines t)
17346 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17347 (push 'hline tmp)))
17348 (push (pop tbl) tmp)))
17349 (setq tbl (nreverse tmp)))
17350 (when vlines
17351 (setq tbl (mapcar (lambda (x)
17352 (if (eq 'hline x) x (cons "" x)))
17353 tbl))
17354 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17355 (setq pos (point))
17356 (insert (org-listtable-to-string tbl))
17357 (when (plist-get params :width)
17358 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17359 org-columns-current-widths "|")))
17360 (goto-char pos)
17361 (org-table-align))))
17363 (defun org-listtable-to-string (tbl)
17364 "Convert a listtable TBL to a string that contains the Org-mode table.
17365 The table still need to be alligned. The resulting string has no leading
17366 and tailing newline characters."
17367 (mapconcat
17368 (lambda (x)
17369 (cond
17370 ((listp x)
17371 (concat "|" (mapconcat 'identity x "|") "|"))
17372 ((eq x 'hline) "|-|")
17373 (t (error "Garbage in listtable: %s" x))))
17374 tbl "\n"))
17376 (defun org-insert-columns-dblock ()
17377 "Create a dynamic block capturing a column view table."
17378 (interactive)
17379 (let ((defaults '(:name "columnview" :hlines 1))
17380 (id (completing-read
17381 "Capture columns (local, global, entry with :ID: property) [local]: "
17382 (append '(("global") ("local"))
17383 (mapcar 'list (org-property-values "ID"))))))
17384 (if (equal id "") (setq id 'local))
17385 (if (equal id "global") (setq id 'global))
17386 (setq defaults (append defaults (list :id id)))
17387 (org-create-dblock defaults)
17388 (org-update-dblock)))
17390 ;;;; Timestamps
17392 (defvar org-last-changed-timestamp nil)
17393 (defvar org-time-was-given) ; dynamically scoped parameter
17394 (defvar org-end-time-was-given) ; dynamically scoped parameter
17395 (defvar org-ts-what) ; dynamically scoped parameter
17397 (defun org-time-stamp (arg)
17398 "Prompt for a date/time and insert a time stamp.
17399 If the user specifies a time like HH:MM, or if this command is called
17400 with a prefix argument, the time stamp will contain date and time.
17401 Otherwise, only the date will be included. All parts of a date not
17402 specified by the user will be filled in from the current date/time.
17403 So if you press just return without typing anything, the time stamp
17404 will represent the current date/time. If there is already a timestamp
17405 at the cursor, it will be modified."
17406 (interactive "P")
17407 (let* ((ts nil)
17408 (default-time
17409 ;; Default time is either today, or, when entering a range,
17410 ;; the range start.
17411 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17412 (save-excursion
17413 (re-search-backward
17414 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17415 (- (point) 20) t)))
17416 (apply 'encode-time (org-parse-time-string (match-string 1)))
17417 (current-time)))
17418 (default-input (and ts (org-get-compact-tod ts)))
17419 org-time-was-given org-end-time-was-given time)
17420 (cond
17421 ((and (org-at-timestamp-p)
17422 (eq last-command 'org-time-stamp)
17423 (eq this-command 'org-time-stamp))
17424 (insert "--")
17425 (setq time (let ((this-command this-command))
17426 (org-read-date arg 'totime nil nil default-time default-input)))
17427 (org-insert-time-stamp time (or org-time-was-given arg)))
17428 ((org-at-timestamp-p)
17429 (setq time (let ((this-command this-command))
17430 (org-read-date arg 'totime nil nil default-time default-input)))
17431 (when (org-at-timestamp-p) ; just to get the match data
17432 (replace-match "")
17433 (setq org-last-changed-timestamp
17434 (org-insert-time-stamp
17435 time (or org-time-was-given arg)
17436 nil nil nil (list org-end-time-was-given))))
17437 (message "Timestamp updated"))
17439 (setq time (let ((this-command this-command))
17440 (org-read-date arg 'totime nil nil default-time default-input)))
17441 (org-insert-time-stamp time (or org-time-was-given arg)
17442 nil nil nil (list org-end-time-was-given))))))
17444 ;; FIXME: can we use this for something else????
17445 ;; like computing time differences?????
17446 (defun org-get-compact-tod (s)
17447 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17448 (let* ((t1 (match-string 1 s))
17449 (h1 (string-to-number (match-string 2 s)))
17450 (m1 (string-to-number (match-string 3 s)))
17451 (t2 (and (match-end 4) (match-string 5 s)))
17452 (h2 (and t2 (string-to-number (match-string 6 s))))
17453 (m2 (and t2 (string-to-number (match-string 7 s))))
17454 dh dm)
17455 (if (not t2)
17457 (setq dh (- h2 h1) dm (- m2 m1))
17458 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17459 (concat t1 "+" (number-to-string dh)
17460 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17462 (defun org-time-stamp-inactive (&optional arg)
17463 "Insert an inactive time stamp.
17464 An inactive time stamp is enclosed in square brackets instead of angle
17465 brackets. It is inactive in the sense that it does not trigger agenda entries,
17466 does not link to the calendar and cannot be changed with the S-cursor keys.
17467 So these are more for recording a certain time/date."
17468 (interactive "P")
17469 (let (org-time-was-given org-end-time-was-given time)
17470 (setq time (org-read-date arg 'totime))
17471 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17472 nil nil (list org-end-time-was-given))))
17474 (defvar org-date-ovl (org-make-overlay 1 1))
17475 (org-overlay-put org-date-ovl 'face 'org-warning)
17476 (org-detach-overlay org-date-ovl)
17478 (defvar org-ans1) ; dynamically scoped parameter
17479 (defvar org-ans2) ; dynamically scoped parameter
17481 (defvar org-plain-time-of-day-regexp) ; defined below
17483 (defvar org-read-date-overlay nil)
17484 (defvar org-dcst nil) ; dynamically scoped
17486 (defun org-read-date (&optional with-time to-time from-string prompt
17487 default-time default-input)
17488 "Read a date, possibly a time, and make things smooth for the user.
17489 The prompt will suggest to enter an ISO date, but you can also enter anything
17490 which will at least partially be understood by `parse-time-string'.
17491 Unrecognized parts of the date will default to the current day, month, year,
17492 hour and minute. If this command is called to replace a timestamp at point,
17493 of to enter the second timestamp of a range, the default time is taken from the
17494 existing stamp. For example,
17495 3-2-5 --> 2003-02-05
17496 feb 15 --> currentyear-02-15
17497 sep 12 9 --> 2009-09-12
17498 12:45 --> today 12:45
17499 22 sept 0:34 --> currentyear-09-22 0:34
17500 12 --> currentyear-currentmonth-12
17501 Fri --> nearest Friday (today or later)
17502 etc.
17504 Furthermore you can specify a relative date by giving, as the *first* thing
17505 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17506 change in days weeks, months, years.
17507 With a single plus or minus, the date is relative to today. With a double
17508 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17509 +4d --> four days from today
17510 +4 --> same as above
17511 +2w --> two weeks from today
17512 ++5 --> five days from default date
17514 The function understands only English month and weekday abbreviations,
17515 but this can be configured with the variables `parse-time-months' and
17516 `parse-time-weekdays'.
17518 While prompting, a calendar is popped up - you can also select the
17519 date with the mouse (button 1). The calendar shows a period of three
17520 months. To scroll it to other months, use the keys `>' and `<'.
17521 If you don't like the calendar, turn it off with
17522 \(setq org-read-date-popup-calendar nil)
17524 With optional argument TO-TIME, the date will immediately be converted
17525 to an internal time.
17526 With an optional argument WITH-TIME, the prompt will suggest to also
17527 insert a time. Note that when WITH-TIME is not set, you can still
17528 enter a time, and this function will inform the calling routine about
17529 this change. The calling routine may then choose to change the format
17530 used to insert the time stamp into the buffer to include the time.
17531 With optional argument FROM-STRING, read from this string instead from
17532 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17533 the time/date that is used for everything that is not specified by the
17534 user."
17535 (require 'parse-time)
17536 (let* ((org-time-stamp-rounding-minutes
17537 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
17538 (org-dcst org-display-custom-times)
17539 (ct (org-current-time))
17540 (def (or default-time ct))
17541 (defdecode (decode-time def))
17542 (dummy (progn
17543 (when (< (nth 2 defdecode) org-extend-today-until)
17544 (setcar (nthcdr 2 defdecode) -1)
17545 (setcar (nthcdr 1 defdecode) 59)
17546 (setq def (apply 'encode-time defdecode)
17547 defdecode (decode-time def)))))
17548 (calendar-move-hook nil)
17549 (view-diary-entries-initially nil)
17550 (view-calendar-holidays-initially nil)
17551 (timestr (format-time-string
17552 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17553 (prompt (concat (if prompt (concat prompt " ") "")
17554 (format "Date+time [%s]: " timestr)))
17555 ans (org-ans0 "") org-ans1 org-ans2 final)
17557 (cond
17558 (from-string (setq ans from-string))
17559 (org-read-date-popup-calendar
17560 (save-excursion
17561 (save-window-excursion
17562 (calendar)
17563 (calendar-forward-day (- (time-to-days def)
17564 (calendar-absolute-from-gregorian
17565 (calendar-current-date))))
17566 (org-eval-in-calendar nil t)
17567 (let* ((old-map (current-local-map))
17568 (map (copy-keymap calendar-mode-map))
17569 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17570 (org-defkey map (kbd "RET") 'org-calendar-select)
17571 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17572 'org-calendar-select-mouse)
17573 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17574 'org-calendar-select-mouse)
17575 (org-defkey minibuffer-local-map [(meta shift left)]
17576 (lambda () (interactive)
17577 (org-eval-in-calendar '(calendar-backward-month 1))))
17578 (org-defkey minibuffer-local-map [(meta shift right)]
17579 (lambda () (interactive)
17580 (org-eval-in-calendar '(calendar-forward-month 1))))
17581 (org-defkey minibuffer-local-map [(meta shift up)]
17582 (lambda () (interactive)
17583 (org-eval-in-calendar '(calendar-backward-year 1))))
17584 (org-defkey minibuffer-local-map [(meta shift down)]
17585 (lambda () (interactive)
17586 (org-eval-in-calendar '(calendar-forward-year 1))))
17587 (org-defkey minibuffer-local-map [(shift up)]
17588 (lambda () (interactive)
17589 (org-eval-in-calendar '(calendar-backward-week 1))))
17590 (org-defkey minibuffer-local-map [(shift down)]
17591 (lambda () (interactive)
17592 (org-eval-in-calendar '(calendar-forward-week 1))))
17593 (org-defkey minibuffer-local-map [(shift left)]
17594 (lambda () (interactive)
17595 (org-eval-in-calendar '(calendar-backward-day 1))))
17596 (org-defkey minibuffer-local-map [(shift right)]
17597 (lambda () (interactive)
17598 (org-eval-in-calendar '(calendar-forward-day 1))))
17599 (org-defkey minibuffer-local-map ">"
17600 (lambda () (interactive)
17601 (org-eval-in-calendar '(scroll-calendar-left 1))))
17602 (org-defkey minibuffer-local-map "<"
17603 (lambda () (interactive)
17604 (org-eval-in-calendar '(scroll-calendar-right 1))))
17605 (unwind-protect
17606 (progn
17607 (use-local-map map)
17608 (add-hook 'post-command-hook 'org-read-date-display)
17609 (setq org-ans0 (read-string prompt default-input nil nil))
17610 ;; org-ans0: from prompt
17611 ;; org-ans1: from mouse click
17612 ;; org-ans2: from calendar motion
17613 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17614 (remove-hook 'post-command-hook 'org-read-date-display)
17615 (use-local-map old-map)
17616 (when org-read-date-overlay
17617 (org-delete-overlay org-read-date-overlay)
17618 (setq org-read-date-overlay nil)))))))
17620 (t ; Naked prompt only
17621 (unwind-protect
17622 (setq ans (read-string prompt default-input nil timestr))
17623 (when org-read-date-overlay
17624 (org-delete-overlay org-read-date-overlay)
17625 (setq org-read-date-overlay nil)))))
17627 (setq final (org-read-date-analyze ans def defdecode))
17629 (if to-time
17630 (apply 'encode-time final)
17631 (if (and (boundp 'org-time-was-given) org-time-was-given)
17632 (format "%04d-%02d-%02d %02d:%02d"
17633 (nth 5 final) (nth 4 final) (nth 3 final)
17634 (nth 2 final) (nth 1 final))
17635 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17636 (defvar def)
17637 (defvar defdecode)
17638 (defvar with-time)
17639 (defun org-read-date-display ()
17640 "Display the currrent date prompt interpretation in the minibuffer."
17641 (when org-read-date-display-live
17642 (when org-read-date-overlay
17643 (org-delete-overlay org-read-date-overlay))
17644 (let ((p (point)))
17645 (end-of-line 1)
17646 (while (not (equal (buffer-substring
17647 (max (point-min) (- (point) 4)) (point))
17648 " "))
17649 (insert " "))
17650 (goto-char p))
17651 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17652 " " (or org-ans1 org-ans2)))
17653 (org-end-time-was-given nil)
17654 (f (org-read-date-analyze ans def defdecode))
17655 (fmts (if org-dcst
17656 org-time-stamp-custom-formats
17657 org-time-stamp-formats))
17658 (fmt (if (or with-time
17659 (and (boundp 'org-time-was-given) org-time-was-given))
17660 (cdr fmts)
17661 (car fmts)))
17662 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17663 (when (and org-end-time-was-given
17664 (string-match org-plain-time-of-day-regexp txt))
17665 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17666 org-end-time-was-given
17667 (substring txt (match-end 0)))))
17668 (setq org-read-date-overlay
17669 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17670 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17672 (defun org-read-date-analyze (ans def defdecode)
17673 "Analyze the combined answer of the date prompt."
17674 ;; FIXME: cleanup and comment
17675 (let (delta deltan deltaw deltadef year month day
17676 hour minute second wday pm h2 m2 tl wday1
17677 iso-year iso-weekday iso-week iso-year)
17679 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17680 (setq ans (replace-match "" t t ans)
17681 deltan (car delta)
17682 deltaw (nth 1 delta)
17683 deltadef (nth 2 delta)))
17685 ;; Check if there is an iso week date in there
17686 ;; If yes, sore the info and ostpone interpreting it until the rest
17687 ;; of the parsing is done
17688 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17689 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
17690 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
17691 iso-week (string-to-number (match-string 2 ans)))
17692 (setq ans (replace-match "" t t ans)))
17694 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17695 (when (string-match
17696 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17697 (setq year (if (match-end 2)
17698 (string-to-number (match-string 2 ans))
17699 (string-to-number (format-time-string "%Y")))
17700 month (string-to-number (match-string 3 ans))
17701 day (string-to-number (match-string 4 ans)))
17702 (if (< year 100) (setq year (+ 2000 year)))
17703 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17704 t nil ans)))
17705 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17706 ;; If there is a time with am/pm, and *no* time without it, we convert
17707 ;; so that matching will be successful.
17708 (loop for i from 1 to 2 do ; twice, for end time as well
17709 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17710 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17711 (setq hour (string-to-number (match-string 1 ans))
17712 minute (if (match-end 3)
17713 (string-to-number (match-string 3 ans))
17715 pm (equal ?p
17716 (string-to-char (downcase (match-string 4 ans)))))
17717 (if (and (= hour 12) (not pm))
17718 (setq hour 0)
17719 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17720 (setq ans (replace-match (format "%02d:%02d" hour minute)
17721 t t ans))))
17723 ;; Check if a time range is given as a duration
17724 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17725 (setq hour (string-to-number (match-string 1 ans))
17726 h2 (+ hour (string-to-number (match-string 3 ans)))
17727 minute (string-to-number (match-string 2 ans))
17728 m2 (+ minute (if (match-end 5) (string-to-number
17729 (match-string 5 ans))0)))
17730 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17731 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17732 t t ans)))
17734 ;; Check if there is a time range
17735 (when (boundp 'org-end-time-was-given)
17736 (setq org-time-was-given nil)
17737 (when (and (string-match org-plain-time-of-day-regexp ans)
17738 (match-end 8))
17739 (setq org-end-time-was-given (match-string 8 ans))
17740 (setq ans (concat (substring ans 0 (match-beginning 7))
17741 (substring ans (match-end 7))))))
17743 (setq tl (parse-time-string ans)
17744 day (or (nth 3 tl) (nth 3 defdecode))
17745 month (or (nth 4 tl)
17746 (if (and org-read-date-prefer-future
17747 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17748 (1+ (nth 4 defdecode))
17749 (nth 4 defdecode)))
17750 year (or (nth 5 tl)
17751 (if (and org-read-date-prefer-future
17752 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17753 (1+ (nth 5 defdecode))
17754 (nth 5 defdecode)))
17755 hour (or (nth 2 tl) (nth 2 defdecode))
17756 minute (or (nth 1 tl) (nth 1 defdecode))
17757 second (or (nth 0 tl) 0)
17758 wday (nth 6 tl))
17760 ;; Special date definitions below
17761 (cond
17762 (iso-week
17763 ;; There was an iso week
17764 (setq year (or iso-year year)
17765 day (or iso-weekday wday 1)
17766 wday nil ; to make sure that the trigger below does not match
17767 iso-date (calendar-gregorian-from-absolute
17768 (calendar-absolute-from-iso
17769 (list iso-week day year))))
17770 ; FIXME: Should we also push ISO weeks into the future?
17771 ; (when (and org-read-date-prefer-future
17772 ; (not iso-year)
17773 ; (< (calendar-absolute-from-gregorian iso-date)
17774 ; (time-to-days (current-time))))
17775 ; (setq year (1+ year)
17776 ; iso-date (calendar-gregorian-from-absolute
17777 ; (calendar-absolute-from-iso
17778 ; (list iso-week day year)))))
17779 (setq month (car iso-date)
17780 year (nth 2 iso-date)
17781 day (nth 1 iso-date)))
17782 (deltan
17783 (unless deltadef
17784 (let ((now (decode-time (current-time))))
17785 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17786 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17787 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17788 ((equal deltaw "m") (setq month (+ month deltan)))
17789 ((equal deltaw "y") (setq year (+ year deltan)))))
17790 ((and wday (not (nth 3 tl)))
17791 ;; Weekday was given, but no day, so pick that day in the week
17792 ;; on or after the derived date.
17793 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17794 (unless (equal wday wday1)
17795 (setq day (+ day (% (- wday wday1 -7) 7))))))
17796 (if (and (boundp 'org-time-was-given)
17797 (nth 2 tl))
17798 (setq org-time-was-given t))
17799 (if (< year 100) (setq year (+ 2000 year)))
17800 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17801 (list second minute hour day month year)))
17803 (defvar parse-time-weekdays)
17805 (defun org-read-date-get-relative (s today default)
17806 "Check string S for special relative date string.
17807 TODAY and DEFAULT are internal times, for today and for a default.
17808 Return shift list (N what def-flag)
17809 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17810 N is the number of WHATs to shift.
17811 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17812 the DEFAULT date rather than TODAY."
17813 (when (string-match
17814 (concat
17815 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17816 "\\([0-9]+\\)?"
17817 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17818 "\\([ \t]\\|$\\)") s)
17819 (let* ((dir (if (match-end 1)
17820 (string-to-char (substring (match-string 1 s) -1))
17821 ?+))
17822 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17823 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17824 (what (if (match-end 3) (match-string 3 s) "d"))
17825 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17826 (date (if rel default today))
17827 (wday (nth 6 (decode-time date)))
17828 delta)
17829 (if wday1
17830 (progn
17831 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17832 (if (= dir ?-) (setq delta (- delta 7)))
17833 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17834 (list delta "d" rel))
17835 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17837 (defun org-eval-in-calendar (form &optional keepdate)
17838 "Eval FORM in the calendar window and return to current window.
17839 Also, store the cursor date in variable org-ans2."
17840 (let ((sw (selected-window)))
17841 (select-window (get-buffer-window "*Calendar*"))
17842 (eval form)
17843 (when (and (not keepdate) (calendar-cursor-to-date))
17844 (let* ((date (calendar-cursor-to-date))
17845 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17846 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17847 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17848 (select-window sw)))
17850 ; ;; Update the prompt to show new default date
17851 ; (save-excursion
17852 ; (goto-char (point-min))
17853 ; (when (and org-ans2
17854 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17855 ; (get-text-property (match-end 0) 'field))
17856 ; (let ((inhibit-read-only t))
17857 ; (replace-match (concat "[" org-ans2 "]") t t)
17858 ; (add-text-properties (point-min) (1+ (match-end 0))
17859 ; (text-properties-at (1+ (point-min)))))))))
17861 (defun org-calendar-select ()
17862 "Return to `org-read-date' with the date currently selected.
17863 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17864 (interactive)
17865 (when (calendar-cursor-to-date)
17866 (let* ((date (calendar-cursor-to-date))
17867 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17868 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17869 (if (active-minibuffer-window) (exit-minibuffer))))
17871 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17872 "Insert a date stamp for the date given by the internal TIME.
17873 WITH-HM means, use the stamp format that includes the time of the day.
17874 INACTIVE means use square brackets instead of angular ones, so that the
17875 stamp will not contribute to the agenda.
17876 PRE and POST are optional strings to be inserted before and after the
17877 stamp.
17878 The command returns the inserted time stamp."
17879 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17880 stamp)
17881 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17882 (insert-before-markers (or pre ""))
17883 (insert-before-markers (setq stamp (format-time-string fmt time)))
17884 (when (listp extra)
17885 (setq extra (car extra))
17886 (if (and (stringp extra)
17887 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17888 (setq extra (format "-%02d:%02d"
17889 (string-to-number (match-string 1 extra))
17890 (string-to-number (match-string 2 extra))))
17891 (setq extra nil)))
17892 (when extra
17893 (backward-char 1)
17894 (insert-before-markers extra)
17895 (forward-char 1))
17896 (insert-before-markers (or post ""))
17897 stamp))
17899 (defun org-toggle-time-stamp-overlays ()
17900 "Toggle the use of custom time stamp formats."
17901 (interactive)
17902 (setq org-display-custom-times (not org-display-custom-times))
17903 (unless org-display-custom-times
17904 (let ((p (point-min)) (bmp (buffer-modified-p)))
17905 (while (setq p (next-single-property-change p 'display))
17906 (if (and (get-text-property p 'display)
17907 (eq (get-text-property p 'face) 'org-date))
17908 (remove-text-properties
17909 p (setq p (next-single-property-change p 'display))
17910 '(display t))))
17911 (set-buffer-modified-p bmp)))
17912 (if (featurep 'xemacs)
17913 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17914 (org-restart-font-lock)
17915 (setq org-table-may-need-update t)
17916 (if org-display-custom-times
17917 (message "Time stamps are overlayed with custom format")
17918 (message "Time stamp overlays removed")))
17920 (defun org-display-custom-time (beg end)
17921 "Overlay modified time stamp format over timestamp between BED and END."
17922 (let* ((ts (buffer-substring beg end))
17923 t1 w1 with-hm tf time str w2 (off 0))
17924 (save-match-data
17925 (setq t1 (org-parse-time-string ts t))
17926 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
17927 (setq off (- (match-end 0) (match-beginning 0)))))
17928 (setq end (- end off))
17929 (setq w1 (- end beg)
17930 with-hm (and (nth 1 t1) (nth 2 t1))
17931 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17932 time (org-fix-decoded-time t1)
17933 str (org-add-props
17934 (format-time-string
17935 (substring tf 1 -1) (apply 'encode-time time))
17936 nil 'mouse-face 'highlight)
17937 w2 (length str))
17938 (if (not (= w2 w1))
17939 (add-text-properties (1+ beg) (+ 2 beg)
17940 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17941 (if (featurep 'xemacs)
17942 (progn
17943 (put-text-property beg end 'invisible t)
17944 (put-text-property beg end 'end-glyph (make-glyph str)))
17945 (put-text-property beg end 'display str))))
17947 (defun org-translate-time (string)
17948 "Translate all timestamps in STRING to custom format.
17949 But do this only if the variable `org-display-custom-times' is set."
17950 (when org-display-custom-times
17951 (save-match-data
17952 (let* ((start 0)
17953 (re org-ts-regexp-both)
17954 t1 with-hm inactive tf time str beg end)
17955 (while (setq start (string-match re string start))
17956 (setq beg (match-beginning 0)
17957 end (match-end 0)
17958 t1 (save-match-data
17959 (org-parse-time-string (substring string beg end) t))
17960 with-hm (and (nth 1 t1) (nth 2 t1))
17961 inactive (equal (substring string beg (1+ beg)) "[")
17962 tf (funcall (if with-hm 'cdr 'car)
17963 org-time-stamp-custom-formats)
17964 time (org-fix-decoded-time t1)
17965 str (format-time-string
17966 (concat
17967 (if inactive "[" "<") (substring tf 1 -1)
17968 (if inactive "]" ">"))
17969 (apply 'encode-time time))
17970 string (replace-match str t t string)
17971 start (+ start (length str)))))))
17972 string)
17974 (defun org-fix-decoded-time (time)
17975 "Set 0 instead of nil for the first 6 elements of time.
17976 Don't touch the rest."
17977 (let ((n 0))
17978 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17980 (defun org-days-to-time (timestamp-string)
17981 "Difference between TIMESTAMP-STRING and now in days."
17982 (- (time-to-days (org-time-string-to-time timestamp-string))
17983 (time-to-days (current-time))))
17985 (defun org-deadline-close (timestamp-string &optional ndays)
17986 "Is the time in TIMESTAMP-STRING close to the current date?"
17987 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17988 (and (< (org-days-to-time timestamp-string) ndays)
17989 (not (org-entry-is-done-p))))
17991 (defun org-get-wdays (ts)
17992 "Get the deadline lead time appropriate for timestring TS."
17993 (cond
17994 ((<= org-deadline-warning-days 0)
17995 ;; 0 or negative, enforce this value no matter what
17996 (- org-deadline-warning-days))
17997 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
17998 ;; lead time is specified.
17999 (floor (* (string-to-number (match-string 1 ts))
18000 (cdr (assoc (match-string 2 ts)
18001 '(("d" . 1) ("w" . 7)
18002 ("m" . 30.4) ("y" . 365.25)))))))
18003 ;; go for the default.
18004 (t org-deadline-warning-days)))
18006 (defun org-calendar-select-mouse (ev)
18007 "Return to `org-read-date' with the date currently selected.
18008 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18009 (interactive "e")
18010 (mouse-set-point ev)
18011 (when (calendar-cursor-to-date)
18012 (let* ((date (calendar-cursor-to-date))
18013 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18014 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18015 (if (active-minibuffer-window) (exit-minibuffer))))
18017 (defun org-check-deadlines (ndays)
18018 "Check if there are any deadlines due or past due.
18019 A deadline is considered due if it happens within `org-deadline-warning-days'
18020 days from today's date. If the deadline appears in an entry marked DONE,
18021 it is not shown. The prefix arg NDAYS can be used to test that many
18022 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
18023 (interactive "P")
18024 (let* ((org-warn-days
18025 (cond
18026 ((equal ndays '(4)) 100000)
18027 (ndays (prefix-numeric-value ndays))
18028 (t (abs org-deadline-warning-days))))
18029 (case-fold-search nil)
18030 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
18031 (callback
18032 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
18034 (message "%d deadlines past-due or due within %d days"
18035 (org-occur regexp nil callback)
18036 org-warn-days)))
18038 (defun org-check-before-date (date)
18039 "Check if there are deadlines or scheduled entries before DATE."
18040 (interactive (list (org-read-date)))
18041 (let ((case-fold-search nil)
18042 (regexp (concat "\\<\\(" org-deadline-string
18043 "\\|" org-scheduled-string
18044 "\\) *<\\([^>]+\\)>"))
18045 (callback
18046 (lambda () (time-less-p
18047 (org-time-string-to-time (match-string 2))
18048 (org-time-string-to-time date)))))
18049 (message "%d entries before %s"
18050 (org-occur regexp nil callback) date)))
18052 (defun org-evaluate-time-range (&optional to-buffer)
18053 "Evaluate a time range by computing the difference between start and end.
18054 Normally the result is just printed in the echo area, but with prefix arg
18055 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
18056 If the time range is actually in a table, the result is inserted into the
18057 next column.
18058 For time difference computation, a year is assumed to be exactly 365
18059 days in order to avoid rounding problems."
18060 (interactive "P")
18062 (org-clock-update-time-maybe)
18063 (save-excursion
18064 (unless (org-at-date-range-p t)
18065 (goto-char (point-at-bol))
18066 (re-search-forward org-tr-regexp-both (point-at-eol) t))
18067 (if (not (org-at-date-range-p t))
18068 (error "Not at a time-stamp range, and none found in current line")))
18069 (let* ((ts1 (match-string 1))
18070 (ts2 (match-string 2))
18071 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
18072 (match-end (match-end 0))
18073 (time1 (org-time-string-to-time ts1))
18074 (time2 (org-time-string-to-time ts2))
18075 (t1 (time-to-seconds time1))
18076 (t2 (time-to-seconds time2))
18077 (diff (abs (- t2 t1)))
18078 (negative (< (- t2 t1) 0))
18079 ;; (ys (floor (* 365 24 60 60)))
18080 (ds (* 24 60 60))
18081 (hs (* 60 60))
18082 (fy "%dy %dd %02d:%02d")
18083 (fy1 "%dy %dd")
18084 (fd "%dd %02d:%02d")
18085 (fd1 "%dd")
18086 (fh "%02d:%02d")
18087 y d h m align)
18088 (if havetime
18089 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18091 d (floor (/ diff ds)) diff (mod diff ds)
18092 h (floor (/ diff hs)) diff (mod diff hs)
18093 m (floor (/ diff 60)))
18094 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18096 d (floor (+ (/ diff ds) 0.5))
18097 h 0 m 0))
18098 (if (not to-buffer)
18099 (message "%s" (org-make-tdiff-string y d h m))
18100 (if (org-at-table-p)
18101 (progn
18102 (goto-char match-end)
18103 (setq align t)
18104 (and (looking-at " *|") (goto-char (match-end 0))))
18105 (goto-char match-end))
18106 (if (looking-at
18107 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18108 (replace-match ""))
18109 (if negative (insert " -"))
18110 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18111 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18112 (insert " " (format fh h m))))
18113 (if align (org-table-align))
18114 (message "Time difference inserted")))))
18116 (defun org-make-tdiff-string (y d h m)
18117 (let ((fmt "")
18118 (l nil))
18119 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18120 l (push y l)))
18121 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18122 l (push d l)))
18123 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18124 l (push h l)))
18125 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18126 l (push m l)))
18127 (apply 'format fmt (nreverse l))))
18129 (defun org-time-string-to-time (s)
18130 (apply 'encode-time (org-parse-time-string s)))
18132 (defun org-time-string-to-absolute (s &optional daynr prefer)
18133 "Convert a time stamp to an absolute day number.
18134 If there is a specifyer for a cyclic time stamp, get the closest date to
18135 DAYNR."
18136 (cond
18137 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18138 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18139 daynr
18140 (+ daynr 1000)))
18141 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18142 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18143 (time-to-days (current-time))) (match-string 0 s)
18144 prefer))
18145 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18147 (defun org-time-from-absolute (d)
18148 "Return the time corresponding to date D.
18149 D may be an absolute day number, or a calendar-type list (month day year)."
18150 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18151 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18153 (defun org-calendar-holiday ()
18154 "List of holidays, for Diary display in Org-mode."
18155 (require 'holidays)
18156 (let ((hl (funcall
18157 (if (fboundp 'calendar-check-holidays)
18158 'calendar-check-holidays 'check-calendar-holidays) date)))
18159 (if hl (mapconcat 'identity hl "; "))))
18161 (defun org-diary-sexp-entry (sexp entry date)
18162 "Process a SEXP diary ENTRY for DATE."
18163 (require 'diary-lib)
18164 (let ((result (if calendar-debug-sexp
18165 (let ((stack-trace-on-error t))
18166 (eval (car (read-from-string sexp))))
18167 (condition-case nil
18168 (eval (car (read-from-string sexp)))
18169 (error
18170 (beep)
18171 (message "Bad sexp at line %d in %s: %s"
18172 (org-current-line)
18173 (buffer-file-name) sexp)
18174 (sleep-for 2))))))
18175 (cond ((stringp result) result)
18176 ((and (consp result)
18177 (stringp (cdr result))) (cdr result))
18178 (result entry)
18179 (t nil))))
18181 (defun org-diary-to-ical-string (frombuf)
18182 "Get iCalendar entries from diary entries in buffer FROMBUF.
18183 This uses the icalendar.el library."
18184 (let* ((tmpdir (if (featurep 'xemacs)
18185 (temp-directory)
18186 temporary-file-directory))
18187 (tmpfile (make-temp-name
18188 (expand-file-name "orgics" tmpdir)))
18189 buf rtn b e)
18190 (save-excursion
18191 (set-buffer frombuf)
18192 (icalendar-export-region (point-min) (point-max) tmpfile)
18193 (setq buf (find-buffer-visiting tmpfile))
18194 (set-buffer buf)
18195 (goto-char (point-min))
18196 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18197 (setq b (match-beginning 0)))
18198 (goto-char (point-max))
18199 (if (re-search-backward "^END:VEVENT" nil t)
18200 (setq e (match-end 0)))
18201 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18202 (kill-buffer buf)
18203 (kill-buffer frombuf)
18204 (delete-file tmpfile)
18205 rtn))
18207 (defun org-closest-date (start current change prefer)
18208 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18209 When PREFER is `past' return a date that is either CURRENT or past.
18210 When PREFER is `future', return a date that is either CURRENT or future."
18211 ;; Make the proper lists from the dates
18212 (catch 'exit
18213 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18214 dn dw sday cday n1 n2
18215 d m y y1 y2 date1 date2 nmonths nm ny m2)
18217 (setq start (org-date-to-gregorian start)
18218 current (org-date-to-gregorian
18219 (if org-agenda-repeating-timestamp-show-all
18220 current
18221 (time-to-days (current-time))))
18222 sday (calendar-absolute-from-gregorian start)
18223 cday (calendar-absolute-from-gregorian current))
18225 (if (<= cday sday) (throw 'exit sday))
18227 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18228 (setq dn (string-to-number (match-string 1 change))
18229 dw (cdr (assoc (match-string 2 change) a1)))
18230 (error "Invalid change specifyer: %s" change))
18231 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18232 (cond
18233 ((eq dw 'day)
18234 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18235 n2 (+ n1 dn)))
18236 ((eq dw 'year)
18237 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18238 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18239 (setq date1 (list m d y1)
18240 n1 (calendar-absolute-from-gregorian date1)
18241 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18242 n2 (calendar-absolute-from-gregorian date2)))
18243 ((eq dw 'month)
18244 ;; approx number of month between the tow dates
18245 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18246 ;; How often does dn fit in there?
18247 (setq d (nth 1 start) m (car start) y (nth 2 start)
18248 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18249 m (+ m nm)
18250 ny (floor (/ m 12))
18251 y (+ y ny)
18252 m (- m (* ny 12)))
18253 (while (> m 12) (setq m (- m 12) y (1+ y)))
18254 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18255 (setq m2 (+ m dn) y2 y)
18256 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18257 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18258 (while (< n2 cday)
18259 (setq n1 n2 m m2 y y2)
18260 (setq m2 (+ m dn) y2 y)
18261 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18262 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18264 (if org-agenda-repeating-timestamp-show-all
18265 (cond
18266 ((eq prefer 'past) n1)
18267 ((eq prefer 'future) (if (= cday n1) n1 n2))
18268 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18269 (cond
18270 ((eq prefer 'past) n1)
18271 ((eq prefer 'future) (if (= cday n1) n1 n2))
18272 (t (if (= cday n1) n1 n2)))))))
18274 (defun org-date-to-gregorian (date)
18275 "Turn any specification of DATE into a gregorian date for the calendar."
18276 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18277 ((and (listp date) (= (length date) 3)) date)
18278 ((stringp date)
18279 (setq date (org-parse-time-string date))
18280 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18281 ((listp date)
18282 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18284 (defun org-parse-time-string (s &optional nodefault)
18285 "Parse the standard Org-mode time string.
18286 This should be a lot faster than the normal `parse-time-string'.
18287 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18288 hour and minute fields will be nil if not given."
18289 (if (string-match org-ts-regexp0 s)
18290 (list 0
18291 (if (or (match-beginning 8) (not nodefault))
18292 (string-to-number (or (match-string 8 s) "0")))
18293 (if (or (match-beginning 7) (not nodefault))
18294 (string-to-number (or (match-string 7 s) "0")))
18295 (string-to-number (match-string 4 s))
18296 (string-to-number (match-string 3 s))
18297 (string-to-number (match-string 2 s))
18298 nil nil nil)
18299 (make-list 9 0)))
18301 (defun org-timestamp-up (&optional arg)
18302 "Increase the date item at the cursor by one.
18303 If the cursor is on the year, change the year. If it is on the month or
18304 the day, change that.
18305 With prefix ARG, change by that many units."
18306 (interactive "p")
18307 (org-timestamp-change (prefix-numeric-value arg)))
18309 (defun org-timestamp-down (&optional arg)
18310 "Decrease the date item at the cursor by one.
18311 If the cursor is on the year, change the year. If it is on the month or
18312 the day, change that.
18313 With prefix ARG, change by that many units."
18314 (interactive "p")
18315 (org-timestamp-change (- (prefix-numeric-value arg))))
18317 (defun org-timestamp-up-day (&optional arg)
18318 "Increase the date in the time stamp by one day.
18319 With prefix ARG, change that many days."
18320 (interactive "p")
18321 (if (and (not (org-at-timestamp-p t))
18322 (org-on-heading-p))
18323 (org-todo 'up)
18324 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18326 (defun org-timestamp-down-day (&optional arg)
18327 "Decrease the date in the time stamp by one day.
18328 With prefix ARG, change that many days."
18329 (interactive "p")
18330 (if (and (not (org-at-timestamp-p t))
18331 (org-on-heading-p))
18332 (org-todo 'down)
18333 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18335 (defsubst org-pos-in-match-range (pos n)
18336 (and (match-beginning n)
18337 (<= (match-beginning n) pos)
18338 (>= (match-end n) pos)))
18340 (defun org-at-timestamp-p (&optional inactive-ok)
18341 "Determine if the cursor is in or at a timestamp."
18342 (interactive)
18343 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18344 (pos (point))
18345 (ans (or (looking-at tsr)
18346 (save-excursion
18347 (skip-chars-backward "^[<\n\r\t")
18348 (if (> (point) (point-min)) (backward-char 1))
18349 (and (looking-at tsr)
18350 (> (- (match-end 0) pos) -1))))))
18351 (and ans
18352 (boundp 'org-ts-what)
18353 (setq org-ts-what
18354 (cond
18355 ((= pos (match-beginning 0)) 'bracket)
18356 ((= pos (1- (match-end 0))) 'bracket)
18357 ((org-pos-in-match-range pos 2) 'year)
18358 ((org-pos-in-match-range pos 3) 'month)
18359 ((org-pos-in-match-range pos 7) 'hour)
18360 ((org-pos-in-match-range pos 8) 'minute)
18361 ((or (org-pos-in-match-range pos 4)
18362 (org-pos-in-match-range pos 5)) 'day)
18363 ((and (> pos (or (match-end 8) (match-end 5)))
18364 (< pos (match-end 0)))
18365 (- pos (or (match-end 8) (match-end 5))))
18366 (t 'day))))
18367 ans))
18369 (defun org-toggle-timestamp-type ()
18370 "Toggle the type (<active> or [inactive]) of a time stamp."
18371 (interactive)
18372 (when (org-at-timestamp-p t)
18373 (save-excursion
18374 (goto-char (match-beginning 0))
18375 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18376 (goto-char (1- (match-end 0)))
18377 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18378 (message "Timestamp is now %sactive"
18379 (if (equal (char-before) ?>) "in" ""))))
18381 (defun org-timestamp-change (n &optional what)
18382 "Change the date in the time stamp at point.
18383 The date will be changed by N times WHAT. WHAT can be `day', `month',
18384 `year', `minute', `second'. If WHAT is not given, the cursor position
18385 in the timestamp determines what will be changed."
18386 (let ((pos (point))
18387 with-hm inactive
18388 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18389 org-ts-what
18390 extra rem
18391 ts time time0)
18392 (if (not (org-at-timestamp-p t))
18393 (error "Not at a timestamp"))
18394 (if (and (not what) (eq org-ts-what 'bracket))
18395 (org-toggle-timestamp-type)
18396 (if (and (not what) (not (eq org-ts-what 'day))
18397 org-display-custom-times
18398 (get-text-property (point) 'display)
18399 (not (get-text-property (1- (point)) 'display)))
18400 (setq org-ts-what 'day))
18401 (setq org-ts-what (or what org-ts-what)
18402 inactive (= (char-after (match-beginning 0)) ?\[)
18403 ts (match-string 0))
18404 (replace-match "")
18405 (if (string-match
18406 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
18408 (setq extra (match-string 1 ts)))
18409 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18410 (setq with-hm t))
18411 (setq time0 (org-parse-time-string ts))
18412 (when (and (eq org-ts-what 'minute)
18413 (eq current-prefix-arg nil))
18414 (setq n (* dm (org-no-warnings (signum n))))
18415 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
18416 (setcar (cdr time0) (+ (nth 1 time0)
18417 (if (> n 0) (- rem) (- dm rem))))))
18418 (setq time
18419 (encode-time (or (car time0) 0)
18420 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18421 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18422 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18423 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18424 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18425 (nthcdr 6 time0)))
18426 (when (integerp org-ts-what)
18427 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18428 (if (eq what 'calendar)
18429 (let ((cal-date (org-get-date-from-calendar)))
18430 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18431 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18432 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18433 (setcar time0 (or (car time0) 0))
18434 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18435 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18436 (setq time (apply 'encode-time time0))))
18437 (setq org-last-changed-timestamp
18438 (org-insert-time-stamp time with-hm inactive nil nil extra))
18439 (org-clock-update-time-maybe)
18440 (goto-char pos)
18441 ;; Try to recenter the calendar window, if any
18442 (if (and org-calendar-follow-timestamp-change
18443 (get-buffer-window "*Calendar*" t)
18444 (memq org-ts-what '(day month year)))
18445 (org-recenter-calendar (time-to-days time))))))
18447 ;; FIXME: does not yet work for lead times
18448 (defun org-modify-ts-extra (s pos n dm)
18449 "Change the different parts of the lead-time and repeat fields in timestamp."
18450 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18451 ng h m new rem)
18452 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18453 (cond
18454 ((or (org-pos-in-match-range pos 2)
18455 (org-pos-in-match-range pos 3))
18456 (setq m (string-to-number (match-string 3 s))
18457 h (string-to-number (match-string 2 s)))
18458 (if (org-pos-in-match-range pos 2)
18459 (setq h (+ h n))
18460 (setq n (* dm (org-no-warnings (signum n))))
18461 (when (not (= 0 (setq rem (% m dm))))
18462 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18463 (setq m (+ m n)))
18464 (if (< m 0) (setq m (+ m 60) h (1- h)))
18465 (if (> m 59) (setq m (- m 60) h (1+ h)))
18466 (setq h (min 24 (max 0 h)))
18467 (setq ng 1 new (format "-%02d:%02d" h m)))
18468 ((org-pos-in-match-range pos 6)
18469 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18470 ((org-pos-in-match-range pos 5)
18471 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18473 ((org-pos-in-match-range pos 9)
18474 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18475 ((org-pos-in-match-range pos 8)
18476 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18478 (when ng
18479 (setq s (concat
18480 (substring s 0 (match-beginning ng))
18482 (substring s (match-end ng))))))
18485 (defun org-recenter-calendar (date)
18486 "If the calendar is visible, recenter it to DATE."
18487 (let* ((win (selected-window))
18488 (cwin (get-buffer-window "*Calendar*" t))
18489 (calendar-move-hook nil))
18490 (when cwin
18491 (select-window cwin)
18492 (calendar-goto-date (if (listp date) date
18493 (calendar-gregorian-from-absolute date)))
18494 (select-window win))))
18496 (defun org-goto-calendar (&optional arg)
18497 "Go to the Emacs calendar at the current date.
18498 If there is a time stamp in the current line, go to that date.
18499 A prefix ARG can be used to force the current date."
18500 (interactive "P")
18501 (let ((tsr org-ts-regexp) diff
18502 (calendar-move-hook nil)
18503 (view-calendar-holidays-initially nil)
18504 (view-diary-entries-initially nil))
18505 (if (or (org-at-timestamp-p)
18506 (save-excursion
18507 (beginning-of-line 1)
18508 (looking-at (concat ".*" tsr))))
18509 (let ((d1 (time-to-days (current-time)))
18510 (d2 (time-to-days
18511 (org-time-string-to-time (match-string 1)))))
18512 (setq diff (- d2 d1))))
18513 (calendar)
18514 (calendar-goto-today)
18515 (if (and diff (not arg)) (calendar-forward-day diff))))
18517 (defun org-get-date-from-calendar ()
18518 "Return a list (month day year) of date at point in calendar."
18519 (with-current-buffer "*Calendar*"
18520 (save-match-data
18521 (calendar-cursor-to-date))))
18523 (defun org-date-from-calendar ()
18524 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18525 If there is already a time stamp at the cursor position, update it."
18526 (interactive)
18527 (if (org-at-timestamp-p t)
18528 (org-timestamp-change 0 'calendar)
18529 (let ((cal-date (org-get-date-from-calendar)))
18530 (org-insert-time-stamp
18531 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18533 (defvar appt-time-msg-list)
18535 ;;;###autoload
18536 (defun org-agenda-to-appt (&optional refresh filter)
18537 "Activate appointments found in `org-agenda-files'.
18538 With a \\[universal-argument] prefix, refresh the list of
18539 appointements.
18541 If FILTER is t, interactively prompt the user for a regular
18542 expression, and filter out entries that don't match it.
18544 If FILTER is a string, use this string as a regular expression
18545 for filtering entries out.
18547 FILTER can also be an alist with the car of each cell being
18548 either 'headline or 'category. For example:
18550 '((headline \"IMPORTANT\")
18551 (category \"Work\"))
18553 will only add headlines containing IMPORTANT or headlines
18554 belonging to the \"Work\" category."
18555 (interactive "P")
18556 (require 'calendar)
18557 (if refresh (setq appt-time-msg-list nil))
18558 (if (eq filter t)
18559 (setq filter (read-from-minibuffer "Regexp filter: ")))
18560 (let* ((cnt 0) ; count added events
18561 (org-agenda-new-buffers nil)
18562 (org-deadline-warning-days 0)
18563 (today (org-date-to-gregorian
18564 (time-to-days (current-time))))
18565 (files (org-agenda-files)) entries file)
18566 ;; Get all entries which may contain an appt
18567 (while (setq file (pop files))
18568 (setq entries
18569 (append entries
18570 (org-agenda-get-day-entries
18571 file today :timestamp :scheduled :deadline))))
18572 (setq entries (delq nil entries))
18573 ;; Map thru entries and find if we should filter them out
18574 (mapc
18575 (lambda(x)
18576 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18577 (cat (get-text-property 1 'org-category x))
18578 (tod (get-text-property 1 'time-of-day x))
18579 (ok (or (null filter)
18580 (and (stringp filter) (string-match filter evt))
18581 (and (listp filter)
18582 (or (string-match
18583 (cadr (assoc 'category filter)) cat)
18584 (string-match
18585 (cadr (assoc 'headline filter)) evt))))))
18586 ;; FIXME: Shall we remove text-properties for the appt text?
18587 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18588 (when (and ok tod)
18589 (setq tod (number-to-string tod)
18590 tod (when (string-match
18591 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18592 (concat (match-string 1 tod) ":"
18593 (match-string 2 tod))))
18594 (appt-add tod evt)
18595 (setq cnt (1+ cnt))))) entries)
18596 (org-release-buffers org-agenda-new-buffers)
18597 (if (eq cnt 0)
18598 (message "No event to add")
18599 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" "")))))
18601 ;;; The clock for measuring work time.
18603 (defvar org-mode-line-string "")
18604 (put 'org-mode-line-string 'risky-local-variable t)
18606 (defvar org-mode-line-timer nil)
18607 (defvar org-clock-heading "")
18608 (defvar org-clock-start-time "")
18610 (defun org-update-mode-line ()
18611 (let* ((delta (- (time-to-seconds (current-time))
18612 (time-to-seconds org-clock-start-time)))
18613 (h (floor delta 3600))
18614 (m (floor (- delta (* 3600 h)) 60)))
18615 (setq org-mode-line-string
18616 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18617 'help-echo "Org-mode clock is running"))
18618 (force-mode-line-update)))
18620 (defvar org-clock-marker (make-marker)
18621 "Marker recording the last clock-in.")
18622 (defvar org-clock-mode-line-entry nil
18623 "Information for the modeline about the running clock.")
18625 (defun org-clock-in ()
18626 "Start the clock on the current item.
18627 If necessary, clock-out of the currently active clock."
18628 (interactive)
18629 (org-clock-out t)
18630 (let (ts)
18631 (save-excursion
18632 (org-back-to-heading t)
18633 (when (and org-clock-in-switch-to-state
18634 (not (looking-at (concat outline-regexp "[ \t]*"
18635 org-clock-in-switch-to-state
18636 "\\>"))))
18637 (org-todo org-clock-in-switch-to-state))
18638 (if (and org-clock-heading-function
18639 (functionp org-clock-heading-function))
18640 (setq org-clock-heading (funcall org-clock-heading-function))
18641 (if (looking-at org-complex-heading-regexp)
18642 (setq org-clock-heading (match-string 4))
18643 (setq org-clock-heading "???")))
18644 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18645 (org-clock-find-position)
18647 (insert "\n") (backward-char 1)
18648 (indent-relative)
18649 (insert org-clock-string " ")
18650 (setq org-clock-start-time (current-time))
18651 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18652 (move-marker org-clock-marker (point) (buffer-base-buffer))
18653 (or global-mode-string (setq global-mode-string '("")))
18654 (or (memq 'org-mode-line-string global-mode-string)
18655 (setq global-mode-string
18656 (append global-mode-string '(org-mode-line-string))))
18657 (org-update-mode-line)
18658 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18659 (message "Clock started at %s" ts))))
18661 (defun org-clock-find-position ()
18662 "Find the location where the next clock line should be inserted."
18663 (org-back-to-heading t)
18664 (catch 'exit
18665 (let ((beg (save-excursion
18666 (beginning-of-line 2)
18667 (or (bolp) (newline))
18668 (point)))
18669 (end (progn (outline-next-heading) (point)))
18670 (re (concat "^[ \t]*" org-clock-string))
18671 (cnt 0)
18672 first last)
18673 (goto-char beg)
18674 (when (eobp) (newline) (setq end (max (point) end)))
18675 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18676 ;; we seem to have a CLOCK drawer, so go there.
18677 (beginning-of-line 2)
18678 (throw 'exit t))
18679 ;; Lets count the CLOCK lines
18680 (goto-char beg)
18681 (while (re-search-forward re end t)
18682 (setq first (or first (match-beginning 0))
18683 last (match-beginning 0)
18684 cnt (1+ cnt)))
18685 (when (and (integerp org-clock-into-drawer)
18686 (>= (1+ cnt) org-clock-into-drawer))
18687 ;; Wrap current entries into a new drawer
18688 (goto-char last)
18689 (beginning-of-line 2)
18690 (if (org-at-item-p) (org-end-of-item))
18691 (insert ":END:\n")
18692 (beginning-of-line 0)
18693 (org-indent-line-function)
18694 (goto-char first)
18695 (insert ":CLOCK:\n")
18696 (beginning-of-line 0)
18697 (org-indent-line-function)
18698 (org-flag-drawer t)
18699 (beginning-of-line 2)
18700 (throw 'exit nil))
18702 (goto-char beg)
18703 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18704 (not (equal (match-string 1) org-clock-string)))
18705 ;; Planning info, skip to after it
18706 (beginning-of-line 2)
18707 (or (bolp) (newline)))
18708 (when (eq t org-clock-into-drawer)
18709 (insert ":CLOCK:\n:END:\n")
18710 (beginning-of-line -1)
18711 (org-indent-line-function)
18712 (org-flag-drawer t)
18713 (beginning-of-line 2)
18714 (org-indent-line-function)))))
18716 (defun org-clock-out (&optional fail-quietly)
18717 "Stop the currently running clock.
18718 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18719 (interactive)
18720 (catch 'exit
18721 (if (not (marker-buffer org-clock-marker))
18722 (if fail-quietly (throw 'exit t) (error "No active clock")))
18723 (let (ts te s h m)
18724 (save-excursion
18725 (set-buffer (marker-buffer org-clock-marker))
18726 (goto-char org-clock-marker)
18727 (beginning-of-line 1)
18728 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18729 (equal (match-string 1) org-clock-string))
18730 (setq ts (match-string 2))
18731 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18732 (goto-char (match-end 0))
18733 (delete-region (point) (point-at-eol))
18734 (insert "--")
18735 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18736 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18737 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18738 h (floor (/ s 3600))
18739 s (- s (* 3600 h))
18740 m (floor (/ s 60))
18741 s (- s (* 60 s)))
18742 (insert " => " (format "%2d:%02d" h m))
18743 (move-marker org-clock-marker nil)
18744 (when org-log-note-clock-out
18745 (org-add-log-maybe 'clock-out))
18746 (when org-mode-line-timer
18747 (cancel-timer org-mode-line-timer)
18748 (setq org-mode-line-timer nil))
18749 (setq global-mode-string
18750 (delq 'org-mode-line-string global-mode-string))
18751 (force-mode-line-update)
18752 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18754 (defun org-clock-cancel ()
18755 "Cancel the running clock be removing the start timestamp."
18756 (interactive)
18757 (if (not (marker-buffer org-clock-marker))
18758 (error "No active clock"))
18759 (save-excursion
18760 (set-buffer (marker-buffer org-clock-marker))
18761 (goto-char org-clock-marker)
18762 (delete-region (1- (point-at-bol)) (point-at-eol)))
18763 (setq global-mode-string
18764 (delq 'org-mode-line-string global-mode-string))
18765 (force-mode-line-update)
18766 (message "Clock canceled"))
18768 (defun org-clock-goto (&optional delete-windows)
18769 "Go to the currently clocked-in entry."
18770 (interactive "P")
18771 (if (not (marker-buffer org-clock-marker))
18772 (error "No active clock"))
18773 (switch-to-buffer-other-window
18774 (marker-buffer org-clock-marker))
18775 (if delete-windows (delete-other-windows))
18776 (goto-char org-clock-marker)
18777 (org-show-entry)
18778 (org-back-to-heading)
18779 (recenter))
18781 (defvar org-clock-file-total-minutes nil
18782 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18783 (make-variable-buffer-local 'org-clock-file-total-minutes)
18785 (defun org-clock-sum (&optional tstart tend)
18786 "Sum the times for each subtree.
18787 Puts the resulting times in minutes as a text property on each headline."
18788 (interactive)
18789 (let* ((bmp (buffer-modified-p))
18790 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18791 org-clock-string
18792 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18793 (lmax 30)
18794 (ltimes (make-vector lmax 0))
18795 (t1 0)
18796 (level 0)
18797 ts te dt
18798 time)
18799 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18800 (save-excursion
18801 (goto-char (point-max))
18802 (while (re-search-backward re nil t)
18803 (cond
18804 ((match-end 2)
18805 ;; Two time stamps
18806 (setq ts (match-string 2)
18807 te (match-string 3)
18808 ts (time-to-seconds
18809 (apply 'encode-time (org-parse-time-string ts)))
18810 te (time-to-seconds
18811 (apply 'encode-time (org-parse-time-string te)))
18812 ts (if tstart (max ts tstart) ts)
18813 te (if tend (min te tend) te)
18814 dt (- te ts)
18815 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18816 ((match-end 4)
18817 ;; A naket time
18818 (setq t1 (+ t1 (string-to-number (match-string 5))
18819 (* 60 (string-to-number (match-string 4))))))
18820 (t ;; A headline
18821 (setq level (- (match-end 1) (match-beginning 1)))
18822 (when (or (> t1 0) (> (aref ltimes level) 0))
18823 (loop for l from 0 to level do
18824 (aset ltimes l (+ (aref ltimes l) t1)))
18825 (setq t1 0 time (aref ltimes level))
18826 (loop for l from level to (1- lmax) do
18827 (aset ltimes l 0))
18828 (goto-char (match-beginning 0))
18829 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18830 (setq org-clock-file-total-minutes (aref ltimes 0)))
18831 (set-buffer-modified-p bmp)))
18833 (defun org-clock-display (&optional total-only)
18834 "Show subtree times in the entire buffer.
18835 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18836 in the echo area."
18837 (interactive)
18838 (org-remove-clock-overlays)
18839 (let (time h m p)
18840 (org-clock-sum)
18841 (unless total-only
18842 (save-excursion
18843 (goto-char (point-min))
18844 (while (or (and (equal (setq p (point)) (point-min))
18845 (get-text-property p :org-clock-minutes))
18846 (setq p (next-single-property-change
18847 (point) :org-clock-minutes)))
18848 (goto-char p)
18849 (when (setq time (get-text-property p :org-clock-minutes))
18850 (org-put-clock-overlay time (funcall outline-level))))
18851 (setq h (/ org-clock-file-total-minutes 60)
18852 m (- org-clock-file-total-minutes (* 60 h)))
18853 ;; Arrange to remove the overlays upon next change.
18854 (when org-remove-highlights-with-change
18855 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18856 nil 'local))))
18857 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18859 (defvar org-clock-overlays nil)
18860 (make-variable-buffer-local 'org-clock-overlays)
18862 (defun org-put-clock-overlay (time &optional level)
18863 "Put an overlays on the current line, displaying TIME.
18864 If LEVEL is given, prefix time with a corresponding number of stars.
18865 This creates a new overlay and stores it in `org-clock-overlays', so that it
18866 will be easy to remove."
18867 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18868 (l (if level (org-get-valid-level level 0) 0))
18869 (off 0)
18870 ov tx)
18871 (move-to-column c)
18872 (unless (eolp) (skip-chars-backward "^ \t"))
18873 (skip-chars-backward " \t")
18874 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18875 tx (concat (buffer-substring (1- (point)) (point))
18876 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18877 (org-add-props (format "%s %2d:%02d%s"
18878 (make-string l ?*) h m
18879 (make-string (- 16 l) ?\ ))
18880 '(face secondary-selection))
18881 ""))
18882 (if (not (featurep 'xemacs))
18883 (org-overlay-put ov 'display tx)
18884 (org-overlay-put ov 'invisible t)
18885 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18886 (push ov org-clock-overlays)))
18888 (defun org-remove-clock-overlays (&optional beg end noremove)
18889 "Remove the occur highlights from the buffer.
18890 BEG and END are ignored. If NOREMOVE is nil, remove this function
18891 from the `before-change-functions' in the current buffer."
18892 (interactive)
18893 (unless org-inhibit-highlight-removal
18894 (mapc 'org-delete-overlay org-clock-overlays)
18895 (setq org-clock-overlays nil)
18896 (unless noremove
18897 (remove-hook 'before-change-functions
18898 'org-remove-clock-overlays 'local))))
18900 (defun org-clock-out-if-current ()
18901 "Clock out if the current entry contains the running clock.
18902 This is used to stop the clock after a TODO entry is marked DONE,
18903 and is only done if the variable `org-clock-out-when-done' is not nil."
18904 (when (and org-clock-out-when-done
18905 (member state org-done-keywords)
18906 (equal (marker-buffer org-clock-marker) (current-buffer))
18907 (< (point) org-clock-marker)
18908 (> (save-excursion (outline-next-heading) (point))
18909 org-clock-marker))
18910 ;; Clock out, but don't accept a logging message for this.
18911 (let ((org-log-note-clock-out nil))
18912 (org-clock-out))))
18914 (add-hook 'org-after-todo-state-change-hook
18915 'org-clock-out-if-current)
18917 (defun org-check-running-clock ()
18918 "Check if the current buffer contains the running clock.
18919 If yes, offer to stop it and to save the buffer with the changes."
18920 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
18921 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
18922 (buffer-name))))
18923 (org-clock-out)
18924 (when (y-or-n-p "Save changed buffer?")
18925 (save-buffer))))
18927 (defun org-clock-report (&optional arg)
18928 "Create a table containing a report about clocked time.
18929 If the cursor is inside an existing clocktable block, then the table
18930 will be updated. If not, a new clocktable will be inserted.
18931 When called with a prefix argument, move to the first clock table in the
18932 buffer and update it."
18933 (interactive "P")
18934 (org-remove-clock-overlays)
18935 (when arg
18936 (org-find-dblock "clocktable")
18937 (org-show-entry))
18938 (if (org-in-clocktable-p)
18939 (goto-char (org-in-clocktable-p))
18940 (org-create-dblock (list :name "clocktable"
18941 :maxlevel 2 :scope 'file)))
18942 (org-update-dblock))
18944 (defun org-in-clocktable-p ()
18945 "Check if the cursor is in a clocktable."
18946 (let ((pos (point)) start)
18947 (save-excursion
18948 (end-of-line 1)
18949 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
18950 (setq start (match-beginning 0))
18951 (re-search-forward "^#\\+END:.*" nil t)
18952 (>= (match-end 0) pos)
18953 start))))
18955 (defun org-clock-update-time-maybe ()
18956 "If this is a CLOCK line, update it and return t.
18957 Otherwise, return nil."
18958 (interactive)
18959 (save-excursion
18960 (beginning-of-line 1)
18961 (skip-chars-forward " \t")
18962 (when (looking-at org-clock-string)
18963 (let ((re (concat "[ \t]*" org-clock-string
18964 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
18965 "\\([ \t]*=>.*\\)?"))
18966 ts te h m s)
18967 (if (not (looking-at re))
18969 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
18970 (end-of-line 1)
18971 (setq ts (match-string 1)
18972 te (match-string 2))
18973 (setq s (- (time-to-seconds
18974 (apply 'encode-time (org-parse-time-string te)))
18975 (time-to-seconds
18976 (apply 'encode-time (org-parse-time-string ts))))
18977 h (floor (/ s 3600))
18978 s (- s (* 3600 h))
18979 m (floor (/ s 60))
18980 s (- s (* 60 s)))
18981 (insert " => " (format "%2d:%02d" h m))
18982 t)))))
18984 (defun org-clock-special-range (key &optional time as-strings)
18985 "Return two times bordering a special time range.
18986 Key is a symbol specifying the range and can be one of `today', `yesterday',
18987 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
18988 A week starts Monday 0:00 and ends Sunday 24:00.
18989 The range is determined relative to TIME. TIME defaults to the current time.
18990 The return value is a cons cell with two internal times like the ones
18991 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
18992 the returned times will be formatted strings."
18993 (let* ((tm (decode-time (or time (current-time))))
18994 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
18995 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
18996 (dow (nth 6 tm))
18997 s1 m1 h1 d1 month1 y1 diff ts te fm)
18998 (cond
18999 ((eq key 'today)
19000 (setq h 0 m 0 h1 24 m1 0))
19001 ((eq key 'yesterday)
19002 (setq d (1- d) h 0 m 0 h1 24 m1 0))
19003 ((eq key 'thisweek)
19004 (setq diff (if (= dow 0) 6 (1- dow))
19005 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19006 ((eq key 'lastweek)
19007 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
19008 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19009 ((eq key 'thismonth)
19010 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
19011 ((eq key 'lastmonth)
19012 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
19013 ((eq key 'thisyear)
19014 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
19015 ((eq key 'lastyear)
19016 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
19017 (t (error "No such time block %s" key)))
19018 (setq ts (encode-time s m h d month y)
19019 te (encode-time (or s1 s) (or m1 m) (or h1 h)
19020 (or d1 d) (or month1 month) (or y1 y)))
19021 (setq fm (cdr org-time-stamp-formats))
19022 (if as-strings
19023 (cons (format-time-string fm ts) (format-time-string fm te))
19024 (cons ts te))))
19026 (defun org-dblock-write:clocktable (params)
19027 "Write the standard clocktable."
19028 (catch 'exit
19029 (let* ((hlchars '((1 . "*") (2 . "/")))
19030 (ins (make-marker))
19031 (total-time nil)
19032 (scope (plist-get params :scope))
19033 (tostring (plist-get params :tostring))
19034 (multifile (plist-get params :multifile))
19035 (header (plist-get params :header))
19036 (maxlevel (or (plist-get params :maxlevel) 3))
19037 (step (plist-get params :step))
19038 (emph (plist-get params :emphasize))
19039 (ts (plist-get params :tstart))
19040 (te (plist-get params :tend))
19041 (block (plist-get params :block))
19042 (link (plist-get params :link))
19043 ipos time h m p level hlc hdl
19044 cc beg end pos tbl)
19045 (when step
19046 (org-clocktable-steps params)
19047 (throw 'exit nil))
19048 (when block
19049 (setq cc (org-clock-special-range block nil t)
19050 ts (car cc) te (cdr cc)))
19051 (if ts (setq ts (time-to-seconds
19052 (apply 'encode-time (org-parse-time-string ts)))))
19053 (if te (setq te (time-to-seconds
19054 (apply 'encode-time (org-parse-time-string te)))))
19055 (move-marker ins (point))
19056 (setq ipos (point))
19058 ;; Get the right scope
19059 (setq pos (point))
19060 (save-restriction
19061 (cond
19062 ((not scope))
19063 ((eq scope 'file) (widen))
19064 ((eq scope 'subtree) (org-narrow-to-subtree))
19065 ((eq scope 'tree)
19066 (while (org-up-heading-safe))
19067 (org-narrow-to-subtree))
19068 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
19069 (symbol-name scope)))
19070 (setq level (string-to-number (match-string 1 (symbol-name scope))))
19071 (catch 'exit
19072 (while (org-up-heading-safe)
19073 (looking-at outline-regexp)
19074 (if (<= (org-reduced-level (funcall outline-level)) level)
19075 (throw 'exit nil))))
19076 (org-narrow-to-subtree))
19077 ((or (listp scope) (eq scope 'agenda))
19078 (let* ((files (if (listp scope) scope (org-agenda-files)))
19079 (scope 'agenda)
19080 (p1 (copy-sequence params))
19081 file)
19082 (plist-put p1 :tostring t)
19083 (plist-put p1 :multifile t)
19084 (plist-put p1 :scope 'file)
19085 (org-prepare-agenda-buffers files)
19086 (while (setq file (pop files))
19087 (with-current-buffer (find-buffer-visiting file)
19088 (push (org-clocktable-add-file
19089 file (org-dblock-write:clocktable p1)) tbl)
19090 (setq total-time (+ (or total-time 0)
19091 org-clock-file-total-minutes)))))))
19092 (goto-char pos)
19094 (unless (eq scope 'agenda)
19095 (org-clock-sum ts te)
19096 (goto-char (point-min))
19097 (while (setq p (next-single-property-change (point) :org-clock-minutes))
19098 (goto-char p)
19099 (when (setq time (get-text-property p :org-clock-minutes))
19100 (save-excursion
19101 (beginning-of-line 1)
19102 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19103 (setq level (org-reduced-level
19104 (- (match-end 1) (match-beginning 1))))
19105 (<= level maxlevel))
19106 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19107 hdl (if (not link)
19108 (match-string 2)
19109 (org-make-link-string
19110 (format "file:%s::%s"
19111 (buffer-file-name)
19112 (save-match-data
19113 (org-make-org-heading-search-string
19114 (match-string 2))))
19115 (match-string 2)))
19116 h (/ time 60)
19117 m (- time (* 60 h)))
19118 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19119 (push (concat
19120 "| " (int-to-string level) "|" hlc hdl hlc " |"
19121 (make-string (1- level) ?|)
19122 hlc (format "%d:%02d" h m) hlc
19123 " |") tbl))))))
19124 (setq tbl (nreverse tbl))
19125 (if tostring
19126 (if tbl (mapconcat 'identity tbl "\n") nil)
19127 (goto-char ins)
19128 (insert-before-markers
19129 (or header
19130 (concat
19131 "Clock summary at ["
19132 (substring
19133 (format-time-string (cdr org-time-stamp-formats))
19134 1 -1)
19135 "]."
19136 (if block
19137 (format " Considered range is /%s/." block)
19139 "\n\n"))
19140 (if (eq scope 'agenda) "|File" "")
19141 "|L|Headline|Time|\n")
19142 (setq total-time (or total-time org-clock-file-total-minutes)
19143 h (/ total-time 60)
19144 m (- total-time (* 60 h)))
19145 (insert-before-markers
19146 "|-\n|"
19147 (if (eq scope 'agenda) "|" "")
19149 "*Total time*| "
19150 (format "*%d:%02d*" h m)
19151 "|\n|-\n")
19152 (setq tbl (delq nil tbl))
19153 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19154 (equal (substring (car tbl) 0 2) "|-"))
19155 (pop tbl))
19156 (insert-before-markers (mapconcat
19157 'identity (delq nil tbl)
19158 (if (eq scope 'agenda) "\n|-\n" "\n")))
19159 (backward-delete-char 1)
19160 (goto-char ipos)
19161 (skip-chars-forward "^|")
19162 (org-table-align))))))
19164 (defun org-clocktable-steps (params)
19165 (let* ((p1 (copy-sequence params))
19166 (ts (plist-get p1 :tstart))
19167 (te (plist-get p1 :tend))
19168 (step0 (plist-get p1 :step))
19169 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19170 (block (plist-get p1 :block))
19172 (when block
19173 (setq cc (org-clock-special-range block nil t)
19174 ts (car cc) te (cdr cc)))
19175 (if ts (setq ts (time-to-seconds
19176 (apply 'encode-time (org-parse-time-string ts)))))
19177 (if te (setq te (time-to-seconds
19178 (apply 'encode-time (org-parse-time-string te)))))
19179 (plist-put p1 :header "")
19180 (plist-put p1 :step nil)
19181 (plist-put p1 :block nil)
19182 (while (< ts te)
19183 (or (bolp) (insert "\n"))
19184 (plist-put p1 :tstart (format-time-string
19185 (car org-time-stamp-formats)
19186 (seconds-to-time ts)))
19187 (plist-put p1 :tend (format-time-string
19188 (car org-time-stamp-formats)
19189 (seconds-to-time (setq ts (+ ts step)))))
19190 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19191 (plist-get p1 :tstart) "\n")
19192 (org-dblock-write:clocktable p1)
19193 (re-search-forward "#\\+END:")
19194 (end-of-line 0))))
19197 (defun org-clocktable-add-file (file table)
19198 (if table
19199 (let ((lines (org-split-string table "\n"))
19200 (ff (file-name-nondirectory file)))
19201 (mapconcat 'identity
19202 (mapcar (lambda (x)
19203 (if (string-match org-table-dataline-regexp x)
19204 (concat "|" ff x)
19206 lines)
19207 "\n"))))
19209 ;; FIXME: I don't think anybody uses this, ask David
19210 (defun org-collect-clock-time-entries ()
19211 "Return an internal list with clocking information.
19212 This list has one entry for each CLOCK interval.
19213 FIXME: describe the elements."
19214 (interactive)
19215 (let ((re (concat "^[ \t]*" org-clock-string
19216 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19217 rtn beg end next cont level title total closedp leafp
19218 clockpos titlepos h m donep)
19219 (save-excursion
19220 (org-clock-sum)
19221 (goto-char (point-min))
19222 (while (re-search-forward re nil t)
19223 (setq clockpos (match-beginning 0)
19224 beg (match-string 1) end (match-string 2)
19225 cont (match-end 0))
19226 (setq beg (apply 'encode-time (org-parse-time-string beg))
19227 end (apply 'encode-time (org-parse-time-string end)))
19228 (org-back-to-heading t)
19229 (setq donep (org-entry-is-done-p))
19230 (setq titlepos (point)
19231 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19232 h (/ total 60) m (- total (* 60 h))
19233 total (cons h m))
19234 (looking-at "\\(\\*+\\) +\\(.*\\)")
19235 (setq level (- (match-end 1) (match-beginning 1))
19236 title (org-match-string-no-properties 2))
19237 (save-excursion (outline-next-heading) (setq next (point)))
19238 (setq closedp (re-search-forward org-closed-time-regexp next t))
19239 (goto-char next)
19240 (setq leafp (and (looking-at "^\\*+ ")
19241 (<= (- (match-end 0) (point)) level)))
19242 (push (list beg end clockpos closedp donep
19243 total title titlepos level leafp)
19244 rtn)
19245 (goto-char cont)))
19246 (nreverse rtn)))
19248 ;;;; Agenda, and Diary Integration
19250 ;;; Define the Org-agenda-mode
19252 (defvar org-agenda-mode-map (make-sparse-keymap)
19253 "Keymap for `org-agenda-mode'.")
19255 (defvar org-agenda-menu) ; defined later in this file.
19256 (defvar org-agenda-follow-mode nil)
19257 (defvar org-agenda-show-log nil)
19258 (defvar org-agenda-redo-command nil)
19259 (defvar org-agenda-query-string nil)
19260 (defvar org-agenda-mode-hook nil)
19261 (defvar org-agenda-type nil)
19262 (defvar org-agenda-force-single-file nil)
19264 (defun org-agenda-mode ()
19265 "Mode for time-sorted view on action items in Org-mode files.
19267 The following commands are available:
19269 \\{org-agenda-mode-map}"
19270 (interactive)
19271 (kill-all-local-variables)
19272 (setq org-agenda-undo-list nil
19273 org-agenda-pending-undo-list nil)
19274 (setq major-mode 'org-agenda-mode)
19275 ;; Keep global-font-lock-mode from turning on font-lock-mode
19276 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19277 (setq mode-name "Org-Agenda")
19278 (use-local-map org-agenda-mode-map)
19279 (easy-menu-add org-agenda-menu)
19280 (if org-startup-truncated (setq truncate-lines t))
19281 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19282 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19283 ;; Make sure properties are removed when copying text
19284 (when (boundp 'buffer-substring-filters)
19285 (org-set-local 'buffer-substring-filters
19286 (cons (lambda (x)
19287 (set-text-properties 0 (length x) nil x) x)
19288 buffer-substring-filters)))
19289 (unless org-agenda-keep-modes
19290 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19291 org-agenda-show-log nil))
19292 (easy-menu-change
19293 '("Agenda") "Agenda Files"
19294 (append
19295 (list
19296 (vector
19297 (if (get 'org-agenda-files 'org-restrict)
19298 "Restricted to single file"
19299 "Edit File List")
19300 '(org-edit-agenda-file-list)
19301 (not (get 'org-agenda-files 'org-restrict)))
19302 "--")
19303 (mapcar 'org-file-menu-entry (org-agenda-files))))
19304 (org-agenda-set-mode-name)
19305 (apply
19306 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19307 (list 'org-agenda-mode-hook)))
19309 (substitute-key-definition 'undo 'org-agenda-undo
19310 org-agenda-mode-map global-map)
19311 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19312 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19313 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19314 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19315 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19316 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19317 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19318 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19319 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19320 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19321 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19322 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19323 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19324 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19325 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19326 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19327 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19328 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19329 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19330 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19331 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19332 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19333 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19334 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19335 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19336 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19337 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19338 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19339 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19341 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19342 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19343 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19344 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19345 (while l (org-defkey org-agenda-mode-map
19346 (int-to-string (pop l)) 'digit-argument)))
19348 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19349 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19350 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19351 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19352 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19353 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19354 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19355 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19356 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19357 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19358 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19359 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19360 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19361 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19362 (org-defkey org-agenda-mode-map "n" 'next-line)
19363 (org-defkey org-agenda-mode-map "p" 'previous-line)
19364 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19365 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19366 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19367 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19368 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19369 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19370 (eval-after-load "calendar"
19371 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19372 'org-calendar-goto-agenda))
19373 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19374 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19375 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19376 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19377 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19378 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19379 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19380 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19381 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19382 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19383 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19384 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19385 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19386 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19387 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19388 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19389 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19390 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19391 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19392 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19393 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19394 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19396 (org-defkey org-agenda-mode-map "[" 'org-agenda-manipulate-query-add)
19397 (org-defkey org-agenda-mode-map "]" 'org-agenda-manipulate-query-subtract)
19398 (org-defkey org-agenda-mode-map "{" 'org-agenda-manipulate-query-add-re)
19399 (org-defkey org-agenda-mode-map "}" 'org-agenda-manipulate-query-subtract-re)
19401 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19402 "Local keymap for agenda entries from Org-mode.")
19404 (org-defkey org-agenda-keymap
19405 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19406 (org-defkey org-agenda-keymap
19407 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19408 (when org-agenda-mouse-1-follows-link
19409 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19410 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19411 '("Agenda"
19412 ("Agenda Files")
19413 "--"
19414 ["Show" org-agenda-show t]
19415 ["Go To (other window)" org-agenda-goto t]
19416 ["Go To (this window)" org-agenda-switch-to t]
19417 ["Follow Mode" org-agenda-follow-mode
19418 :style toggle :selected org-agenda-follow-mode :active t]
19419 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19420 "--"
19421 ["Cycle TODO" org-agenda-todo t]
19422 ["Archive subtree" org-agenda-archive t]
19423 ["Delete subtree" org-agenda-kill t]
19424 "--"
19425 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19426 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19427 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19428 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19429 "--"
19430 ("Tags and Properties"
19431 ["Show all Tags" org-agenda-show-tags t]
19432 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19433 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19434 "--"
19435 ["Column View" org-columns t])
19436 ("Date/Schedule"
19437 ["Schedule" org-agenda-schedule t]
19438 ["Set Deadline" org-agenda-deadline t]
19439 "--"
19440 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19441 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19442 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19443 ("Clock"
19444 ["Clock in" org-agenda-clock-in t]
19445 ["Clock out" org-agenda-clock-out t]
19446 ["Clock cancel" org-agenda-clock-cancel t]
19447 ["Goto running clock" org-clock-goto t])
19448 ("Priority"
19449 ["Set Priority" org-agenda-priority t]
19450 ["Increase Priority" org-agenda-priority-up t]
19451 ["Decrease Priority" org-agenda-priority-down t]
19452 ["Show Priority" org-agenda-show-priority t])
19453 ("Calendar/Diary"
19454 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19455 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19456 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19457 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19458 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19459 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19460 "--"
19461 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19462 "--"
19463 ("View"
19464 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19465 :style radio :selected (equal org-agenda-ndays 1)]
19466 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19467 :style radio :selected (equal org-agenda-ndays 7)]
19468 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19469 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19470 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19471 :style radio :selected (member org-agenda-ndays '(365 366))]
19472 "--"
19473 ["Show Logbook entries" org-agenda-log-mode
19474 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19475 ["Include Diary" org-agenda-toggle-diary
19476 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19477 ["Use Time Grid" org-agenda-toggle-time-grid
19478 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19479 ["Write view to file" org-write-agenda t]
19480 ["Rebuild buffer" org-agenda-redo t]
19481 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19482 "--"
19483 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19484 "--"
19485 ["Quit" org-agenda-quit t]
19486 ["Exit and Release Buffers" org-agenda-exit t]
19489 ;;; Agenda undo
19491 (defvar org-agenda-allow-remote-undo t
19492 "Non-nil means, allow remote undo from the agenda buffer.")
19493 (defvar org-agenda-undo-list nil
19494 "List of undoable operations in the agenda since last refresh.")
19495 (defvar org-agenda-undo-has-started-in nil
19496 "Buffers that have already seen `undo-start' in the current undo sequence.")
19497 (defvar org-agenda-pending-undo-list nil
19498 "In a series of undo commands, this is the list of remaning undo items.")
19500 (defmacro org-if-unprotected (&rest body)
19501 "Execute BODY if there is no `org-protected' text property at point."
19502 (declare (debug t))
19503 `(unless (get-text-property (point) 'org-protected)
19504 ,@body))
19506 (defmacro org-with-remote-undo (_buffer &rest _body)
19507 "Execute BODY while recording undo information in two buffers."
19508 (declare (indent 1) (debug t))
19509 `(let ((_cline (org-current-line))
19510 (_cmd this-command)
19511 (_buf1 (current-buffer))
19512 (_buf2 ,_buffer)
19513 (_undo1 buffer-undo-list)
19514 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19515 _c1 _c2)
19516 ,@_body
19517 (when org-agenda-allow-remote-undo
19518 (setq _c1 (org-verify-change-for-undo
19519 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19520 _c2 (org-verify-change-for-undo
19521 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19522 (when (or _c1 _c2)
19523 ;; make sure there are undo boundaries
19524 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19525 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19526 ;; remember which buffer to undo
19527 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19528 org-agenda-undo-list)))))
19530 (defun org-agenda-undo ()
19531 "Undo a remote editing step in the agenda.
19532 This undoes changes both in the agenda buffer and in the remote buffer
19533 that have been changed along."
19534 (interactive)
19535 (or org-agenda-allow-remote-undo
19536 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19537 (if (not (eq this-command last-command))
19538 (setq org-agenda-undo-has-started-in nil
19539 org-agenda-pending-undo-list org-agenda-undo-list))
19540 (if (not org-agenda-pending-undo-list)
19541 (error "No further undo information"))
19542 (let* ((entry (pop org-agenda-pending-undo-list))
19543 buf line cmd rembuf)
19544 (setq cmd (pop entry) line (pop entry))
19545 (setq rembuf (nth 2 entry))
19546 (org-with-remote-undo rembuf
19547 (while (bufferp (setq buf (pop entry)))
19548 (if (pop entry)
19549 (with-current-buffer buf
19550 (let ((last-undo-buffer buf)
19551 (inhibit-read-only t))
19552 (unless (memq buf org-agenda-undo-has-started-in)
19553 (push buf org-agenda-undo-has-started-in)
19554 (make-local-variable 'pending-undo-list)
19555 (undo-start))
19556 (while (and pending-undo-list
19557 (listp pending-undo-list)
19558 (not (car pending-undo-list)))
19559 (pop pending-undo-list))
19560 (undo-more 1))))))
19561 (goto-line line)
19562 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19564 (defun org-verify-change-for-undo (l1 l2)
19565 "Verify that a real change occurred between the undo lists L1 and L2."
19566 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19567 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19568 (not (eq l1 l2)))
19570 ;;; Agenda dispatch
19572 (defvar org-agenda-restrict nil)
19573 (defvar org-agenda-restrict-begin (make-marker))
19574 (defvar org-agenda-restrict-end (make-marker))
19575 (defvar org-agenda-last-dispatch-buffer nil)
19576 (defvar org-agenda-overriding-restriction nil)
19578 ;;;###autoload
19579 (defun org-agenda (arg &optional keys restriction)
19580 "Dispatch agenda commands to collect entries to the agenda buffer.
19581 Prompts for a command to execute. Any prefix arg will be passed
19582 on to the selected command. The default selections are:
19584 a Call `org-agenda-list' to display the agenda for current day or week.
19585 t Call `org-todo-list' to display the global todo list.
19586 T Call `org-todo-list' to display the global todo list, select only
19587 entries with a specific TODO keyword (the user gets a prompt).
19588 m Call `org-tags-view' to display headlines with tags matching
19589 a condition (the user is prompted for the condition).
19590 M Like `m', but select only TODO entries, no ordinary headlines.
19591 L Create a timeline for the current buffer.
19592 e Export views to associated files.
19594 More commands can be added by configuring the variable
19595 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19596 searches can be pre-defined in this way.
19598 If the current buffer is in Org-mode and visiting a file, you can also
19599 first press `<' once to indicate that the agenda should be temporarily
19600 \(until the next use of \\[org-agenda]) restricted to the current file.
19601 Pressing `<' twice means to restrict to the current subtree or region
19602 \(if active)."
19603 (interactive "P")
19604 (catch 'exit
19605 (let* ((prefix-descriptions nil)
19606 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19607 (org-agenda-custom-commands
19608 ;; normalize different versions
19609 (delq nil
19610 (mapcar
19611 (lambda (x)
19612 (cond ((stringp (cdr x))
19613 (push x prefix-descriptions)
19614 nil)
19615 ((stringp (nth 1 x)) x)
19616 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19617 (t (cons (car x) (cons "" (cdr x))))))
19618 org-agenda-custom-commands)))
19619 (buf (current-buffer))
19620 (bfn (buffer-file-name (buffer-base-buffer)))
19621 entry key type match lprops ans)
19622 ;; Turn off restriction unless there is an overriding one
19623 (unless org-agenda-overriding-restriction
19624 (put 'org-agenda-files 'org-restrict nil)
19625 (setq org-agenda-restrict nil)
19626 (move-marker org-agenda-restrict-begin nil)
19627 (move-marker org-agenda-restrict-end nil))
19628 ;; Delete old local properties
19629 (put 'org-agenda-redo-command 'org-lprops nil)
19630 ;; Remember where this call originated
19631 (setq org-agenda-last-dispatch-buffer (current-buffer))
19632 (unless keys
19633 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19634 keys (car ans)
19635 restriction (cdr ans)))
19636 ;; Estabish the restriction, if any
19637 (when (and (not org-agenda-overriding-restriction) restriction)
19638 (put 'org-agenda-files 'org-restrict (list bfn))
19639 (cond
19640 ((eq restriction 'region)
19641 (setq org-agenda-restrict t)
19642 (move-marker org-agenda-restrict-begin (region-beginning))
19643 (move-marker org-agenda-restrict-end (region-end)))
19644 ((eq restriction 'subtree)
19645 (save-excursion
19646 (setq org-agenda-restrict t)
19647 (org-back-to-heading t)
19648 (move-marker org-agenda-restrict-begin (point))
19649 (move-marker org-agenda-restrict-end
19650 (progn (org-end-of-subtree t)))))))
19652 (require 'calendar) ; FIXME: can we avoid this for some commands?
19653 ;; For example the todo list should not need it (but does...)
19654 (cond
19655 ((setq entry (assoc keys org-agenda-custom-commands))
19656 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19657 (progn
19658 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19659 (put 'org-agenda-redo-command 'org-lprops lprops)
19660 (cond
19661 ((eq type 'agenda)
19662 (org-let lprops '(org-agenda-list current-prefix-arg)))
19663 ((eq type 'alltodo)
19664 (org-let lprops '(org-todo-list current-prefix-arg)))
19665 ((eq type 'search)
19666 (org-let lprops '(org-search-view current-prefix-arg match nil)))
19667 ((eq type 'stuck)
19668 (org-let lprops '(org-agenda-list-stuck-projects
19669 current-prefix-arg)))
19670 ((eq type 'tags)
19671 (org-let lprops '(org-tags-view current-prefix-arg match)))
19672 ((eq type 'tags-todo)
19673 (org-let lprops '(org-tags-view '(4) match)))
19674 ((eq type 'todo)
19675 (org-let lprops '(org-todo-list match)))
19676 ((eq type 'tags-tree)
19677 (org-check-for-org-mode)
19678 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19679 ((eq type 'todo-tree)
19680 (org-check-for-org-mode)
19681 (org-let lprops
19682 '(org-occur (concat "^" outline-regexp "[ \t]*"
19683 (regexp-quote match) "\\>"))))
19684 ((eq type 'occur-tree)
19685 (org-check-for-org-mode)
19686 (org-let lprops '(org-occur match)))
19687 ((functionp type)
19688 (org-let lprops '(funcall type match)))
19689 ((fboundp type)
19690 (org-let lprops '(funcall type match)))
19691 (t (error "Invalid custom agenda command type %s" type))))
19692 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19693 ((equal keys "C")
19694 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19695 (customize-variable 'org-agenda-custom-commands))
19696 ((equal keys "a") (call-interactively 'org-agenda-list))
19697 ((equal keys "s") (call-interactively 'org-search-view))
19698 ((equal keys "t") (call-interactively 'org-todo-list))
19699 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19700 ((equal keys "m") (call-interactively 'org-tags-view))
19701 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19702 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19703 ((equal keys "L")
19704 (unless (org-mode-p)
19705 (error "This is not an Org-mode file"))
19706 (unless restriction
19707 (put 'org-agenda-files 'org-restrict (list bfn))
19708 (org-call-with-arg 'org-timeline arg)))
19709 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19710 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19711 ((equal keys "!") (customize-variable 'org-stuck-projects))
19712 (t (error "Invalid agenda key"))))))
19714 (defun org-agenda-normalize-custom-commands (cmds)
19715 (delq nil
19716 (mapcar
19717 (lambda (x)
19718 (cond ((stringp (cdr x)) nil)
19719 ((stringp (nth 1 x)) x)
19720 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19721 (t (cons (car x) (cons "" (cdr x))))))
19722 cmds)))
19724 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19725 "The user interface for selecting an agenda command."
19726 (catch 'exit
19727 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19728 (restrict-ok (and bfn (org-mode-p)))
19729 (region-p (org-region-active-p))
19730 (custom org-agenda-custom-commands)
19731 (selstring "")
19732 restriction second-time
19733 c entry key type match prefixes rmheader header-end custom1 desc)
19734 (save-window-excursion
19735 (delete-other-windows)
19736 (org-switch-to-buffer-other-window " *Agenda Commands*")
19737 (erase-buffer)
19738 (insert (eval-when-compile
19739 (let ((header
19741 Press key for an agenda command: < Buffer,subtree/region restriction
19742 -------------------------------- > Remove restriction
19743 a Agenda for current week or day e Export agenda views
19744 t List of all TODO entries T Entries with special TODO kwd
19745 m Match a TAGS query M Like m, but only TODO entries
19746 L Timeline for current buffer # List stuck projects (!=configure)
19747 s Search for keywords C Configure custom agenda commands
19748 / Multi-occur
19750 (start 0))
19751 (while (string-match
19752 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19753 header start)
19754 (setq start (match-end 0))
19755 (add-text-properties (match-beginning 2) (match-end 2)
19756 '(face bold) header))
19757 header)))
19758 (setq header-end (move-marker (make-marker) (point)))
19759 (while t
19760 (setq custom1 custom)
19761 (when (eq rmheader t)
19762 (goto-line 1)
19763 (re-search-forward ":" nil t)
19764 (delete-region (match-end 0) (point-at-eol))
19765 (forward-char 1)
19766 (looking-at "-+")
19767 (delete-region (match-end 0) (point-at-eol))
19768 (move-marker header-end (match-end 0)))
19769 (goto-char header-end)
19770 (delete-region (point) (point-max))
19771 (while (setq entry (pop custom1))
19772 (setq key (car entry) desc (nth 1 entry)
19773 type (nth 2 entry) match (nth 3 entry))
19774 (if (> (length key) 1)
19775 (add-to-list 'prefixes (string-to-char key))
19776 (insert
19777 (format
19778 "\n%-4s%-14s: %s"
19779 (org-add-props (copy-sequence key)
19780 '(face bold))
19781 (cond
19782 ((string-match "\\S-" desc) desc)
19783 ((eq type 'agenda) "Agenda for current week or day")
19784 ((eq type 'alltodo) "List of all TODO entries")
19785 ((eq type 'search) "Word search")
19786 ((eq type 'stuck) "List of stuck projects")
19787 ((eq type 'todo) "TODO keyword")
19788 ((eq type 'tags) "Tags query")
19789 ((eq type 'tags-todo) "Tags (TODO)")
19790 ((eq type 'tags-tree) "Tags tree")
19791 ((eq type 'todo-tree) "TODO kwd tree")
19792 ((eq type 'occur-tree) "Occur tree")
19793 ((functionp type) (if (symbolp type)
19794 (symbol-name type)
19795 "Lambda expression"))
19796 (t "???"))
19797 (cond
19798 ((stringp match)
19799 (org-add-props match nil 'face 'org-warning))
19800 (match
19801 (format "set of %d commands" (length match)))
19802 (t ""))))))
19803 (when prefixes
19804 (mapc (lambda (x)
19805 (insert
19806 (format "\n%s %s"
19807 (org-add-props (char-to-string x)
19808 nil 'face 'bold)
19809 (or (cdr (assoc (concat selstring (char-to-string x))
19810 prefix-descriptions))
19811 "Prefix key"))))
19812 prefixes))
19813 (goto-char (point-min))
19814 (when (fboundp 'fit-window-to-buffer)
19815 (if second-time
19816 (if (not (pos-visible-in-window-p (point-max)))
19817 (fit-window-to-buffer))
19818 (setq second-time t)
19819 (fit-window-to-buffer)))
19820 (message "Press key for agenda command%s:"
19821 (if (or restrict-ok org-agenda-overriding-restriction)
19822 (if org-agenda-overriding-restriction
19823 " (restriction lock active)"
19824 (if restriction
19825 (format " (restricted to %s)" restriction)
19826 " (unrestricted)"))
19827 ""))
19828 (setq c (read-char-exclusive))
19829 (message "")
19830 (cond
19831 ((assoc (char-to-string c) custom)
19832 (setq selstring (concat selstring (char-to-string c)))
19833 (throw 'exit (cons selstring restriction)))
19834 ((memq c prefixes)
19835 (setq selstring (concat selstring (char-to-string c))
19836 prefixes nil
19837 rmheader (or rmheader t)
19838 custom (delq nil (mapcar
19839 (lambda (x)
19840 (if (or (= (length (car x)) 1)
19841 (/= (string-to-char (car x)) c))
19843 (cons (substring (car x) 1) (cdr x))))
19844 custom))))
19845 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19846 (message "Restriction is only possible in Org-mode buffers")
19847 (ding) (sit-for 1))
19848 ((eq c ?1)
19849 (org-agenda-remove-restriction-lock 'noupdate)
19850 (setq restriction 'buffer))
19851 ((eq c ?0)
19852 (org-agenda-remove-restriction-lock 'noupdate)
19853 (setq restriction (if region-p 'region 'subtree)))
19854 ((eq c ?<)
19855 (org-agenda-remove-restriction-lock 'noupdate)
19856 (setq restriction
19857 (cond
19858 ((eq restriction 'buffer)
19859 (if region-p 'region 'subtree))
19860 ((memq restriction '(subtree region))
19861 nil)
19862 (t 'buffer))))
19863 ((eq c ?>)
19864 (org-agenda-remove-restriction-lock 'noupdate)
19865 (setq restriction nil))
19866 ((and (equal selstring "") (memq c '(?s ?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19867 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19868 ((and (> (length selstring) 0) (eq c ?\d))
19869 (delete-window)
19870 (org-agenda-get-restriction-and-command prefix-descriptions))
19872 ((equal c ?q) (error "Abort"))
19873 (t (error "Invalid key %c" c))))))))
19875 (defun org-run-agenda-series (name series)
19876 (org-prepare-agenda name)
19877 (let* ((org-agenda-multi t)
19878 (redo (list 'org-run-agenda-series name (list 'quote series)))
19879 (cmds (car series))
19880 (gprops (nth 1 series))
19881 match ;; The byte compiler incorrectly complains about this. Keep it!
19882 cmd type lprops)
19883 (while (setq cmd (pop cmds))
19884 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19885 (cond
19886 ((eq type 'agenda)
19887 (org-let2 gprops lprops
19888 '(call-interactively 'org-agenda-list)))
19889 ((eq type 'alltodo)
19890 (org-let2 gprops lprops
19891 '(call-interactively 'org-todo-list)))
19892 ((eq type 'search)
19893 (org-let2 gprops lprops
19894 '(org-search-view current-prefix-arg match nil)))
19895 ((eq type 'stuck)
19896 (org-let2 gprops lprops
19897 '(call-interactively 'org-agenda-list-stuck-projects)))
19898 ((eq type 'tags)
19899 (org-let2 gprops lprops
19900 '(org-tags-view current-prefix-arg match)))
19901 ((eq type 'tags-todo)
19902 (org-let2 gprops lprops
19903 '(org-tags-view '(4) match)))
19904 ((eq type 'todo)
19905 (org-let2 gprops lprops
19906 '(org-todo-list match)))
19907 ((fboundp type)
19908 (org-let2 gprops lprops
19909 '(funcall type match)))
19910 (t (error "Invalid type in command series"))))
19911 (widen)
19912 (setq org-agenda-redo-command redo)
19913 (goto-char (point-min)))
19914 (org-finalize-agenda))
19916 ;;;###autoload
19917 (defmacro org-batch-agenda (cmd-key &rest parameters)
19918 "Run an agenda command in batch mode and send the result to STDOUT.
19919 If CMD-KEY is a string of length 1, it is used as a key in
19920 `org-agenda-custom-commands' and triggers this command. If it is a
19921 longer string it is used as a tags/todo match string.
19922 Paramters are alternating variable names and values that will be bound
19923 before running the agenda command."
19924 (let (pars)
19925 (while parameters
19926 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19927 (if (> (length cmd-key) 2)
19928 (eval (list 'let (nreverse pars)
19929 (list 'org-tags-view nil cmd-key)))
19930 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19931 (set-buffer org-agenda-buffer-name)
19932 (princ (org-encode-for-stdout (buffer-string)))))
19934 (defun org-encode-for-stdout (string)
19935 (if (fboundp 'encode-coding-string)
19936 (encode-coding-string string buffer-file-coding-system)
19937 string))
19939 (defvar org-agenda-info nil)
19941 ;;;###autoload
19942 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
19943 "Run an agenda command in batch mode and send the result to STDOUT.
19944 If CMD-KEY is a string of length 1, it is used as a key in
19945 `org-agenda-custom-commands' and triggers this command. If it is a
19946 longer string it is used as a tags/todo match string.
19947 Paramters are alternating variable names and values that will be bound
19948 before running the agenda command.
19950 The output gives a line for each selected agenda item. Each
19951 item is a list of comma-separated values, like this:
19953 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
19955 category The category of the item
19956 head The headline, without TODO kwd, TAGS and PRIORITY
19957 type The type of the agenda entry, can be
19958 todo selected in TODO match
19959 tagsmatch selected in tags match
19960 diary imported from diary
19961 deadline a deadline on given date
19962 scheduled scheduled on given date
19963 timestamp entry has timestamp on given date
19964 closed entry was closed on given date
19965 upcoming-deadline warning about deadline
19966 past-scheduled forwarded scheduled item
19967 block entry has date block including g. date
19968 todo The todo keyword, if any
19969 tags All tags including inherited ones, separated by colons
19970 date The relevant date, like 2007-2-14
19971 time The time, like 15:00-16:50
19972 extra Sting with extra planning info
19973 priority-l The priority letter if any was given
19974 priority-n The computed numerical priority
19975 agenda-day The day in the agenda where this is listed"
19977 (let (pars)
19978 (while parameters
19979 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19980 (push (list 'org-agenda-remove-tags t) pars)
19981 (if (> (length cmd-key) 2)
19982 (eval (list 'let (nreverse pars)
19983 (list 'org-tags-view nil cmd-key)))
19984 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19985 (set-buffer org-agenda-buffer-name)
19986 (let* ((lines (org-split-string (buffer-string) "\n"))
19987 line)
19988 (while (setq line (pop lines))
19989 (catch 'next
19990 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
19991 (setq org-agenda-info
19992 (org-fix-agenda-info (text-properties-at 0 line)))
19993 (princ
19994 (org-encode-for-stdout
19995 (mapconcat 'org-agenda-export-csv-mapper
19996 '(org-category txt type todo tags date time-of-day extra
19997 priority-letter priority agenda-day)
19998 ",")))
19999 (princ "\n"))))))
20001 (defun org-fix-agenda-info (props)
20002 "Make sure all properties on an agenda item have a canonical form,
20003 so the export commands can easily use it."
20004 (let (tmp re)
20005 (when (setq tmp (plist-get props 'tags))
20006 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
20007 (when (setq tmp (plist-get props 'date))
20008 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20009 (let ((calendar-date-display-form '(year "-" month "-" day)))
20010 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
20012 (setq tmp (calendar-date-string tmp)))
20013 (setq props (plist-put props 'date tmp)))
20014 (when (setq tmp (plist-get props 'day))
20015 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20016 (let ((calendar-date-display-form '(year "-" month "-" day)))
20017 (setq tmp (calendar-date-string tmp)))
20018 (setq props (plist-put props 'day tmp))
20019 (setq props (plist-put props 'agenda-day tmp)))
20020 (when (setq tmp (plist-get props 'txt))
20021 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
20022 (plist-put props 'priority-letter (match-string 1 tmp))
20023 (setq tmp (replace-match "" t t tmp)))
20024 (when (and (setq re (plist-get props 'org-todo-regexp))
20025 (setq re (concat "\\`\\.*" re " ?"))
20026 (string-match re tmp))
20027 (plist-put props 'todo (match-string 1 tmp))
20028 (setq tmp (replace-match "" t t tmp)))
20029 (plist-put props 'txt tmp)))
20030 props)
20032 (defun org-agenda-export-csv-mapper (prop)
20033 (let ((res (plist-get org-agenda-info prop)))
20034 (setq res
20035 (cond
20036 ((not res) "")
20037 ((stringp res) res)
20038 (t (prin1-to-string res))))
20039 (while (string-match "," res)
20040 (setq res (replace-match ";" t t res)))
20041 (org-trim res)))
20044 ;;;###autoload
20045 (defun org-store-agenda-views (&rest parameters)
20046 (interactive)
20047 (eval (list 'org-batch-store-agenda-views)))
20049 ;; FIXME, why is this a macro?????
20050 ;;;###autoload
20051 (defmacro org-batch-store-agenda-views (&rest parameters)
20052 "Run all custom agenda commands that have a file argument."
20053 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
20054 (pop-up-frames nil)
20055 (dir default-directory)
20056 pars cmd thiscmdkey files opts)
20057 (while parameters
20058 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20059 (setq pars (reverse pars))
20060 (save-window-excursion
20061 (while cmds
20062 (setq cmd (pop cmds)
20063 thiscmdkey (car cmd)
20064 opts (nth 4 cmd)
20065 files (nth 5 cmd))
20066 (if (stringp files) (setq files (list files)))
20067 (when files
20068 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20069 (list 'org-agenda nil thiscmdkey)))
20070 (set-buffer org-agenda-buffer-name)
20071 (while files
20072 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20073 (list 'org-write-agenda
20074 (expand-file-name (pop files) dir) t))))
20075 (and (get-buffer org-agenda-buffer-name)
20076 (kill-buffer org-agenda-buffer-name)))))))
20078 (defun org-write-agenda (file &optional nosettings)
20079 "Write the current buffer (an agenda view) as a file.
20080 Depending on the extension of the file name, plain text (.txt),
20081 HTML (.html or .htm) or Postscript (.ps) is produced.
20082 If the extension is .ics, run icalendar export over all files used
20083 to construct the agenda and limit the export to entries listed in the
20084 agenda now.
20085 If NOSETTINGS is given, do not scope the settings of
20086 `org-agenda-exporter-settings' into the export commands. This is used when
20087 the settings have already been scoped and we do not wish to overrule other,
20088 higher priority settings."
20089 (interactive "FWrite agenda to file: ")
20090 (if (not (file-writable-p file))
20091 (error "Cannot write agenda to file %s" file))
20092 (cond
20093 ((string-match "\\.html?\\'" file) (require 'htmlize))
20094 ((string-match "\\.ps\\'" file) (require 'ps-print)))
20095 (org-let (if nosettings nil org-agenda-exporter-settings)
20096 '(save-excursion
20097 (save-window-excursion
20098 (cond
20099 ((string-match "\\.html?\\'" file)
20100 (set-buffer (htmlize-buffer (current-buffer)))
20102 (when (and org-agenda-export-html-style
20103 (string-match "<style>" org-agenda-export-html-style))
20104 ;; replace <style> section with org-agenda-export-html-style
20105 (goto-char (point-min))
20106 (kill-region (- (search-forward "<style") 6)
20107 (search-forward "</style>"))
20108 (insert org-agenda-export-html-style))
20109 (write-file file)
20110 (kill-buffer (current-buffer))
20111 (message "HTML written to %s" file))
20112 ((string-match "\\.ps\\'" file)
20113 (ps-print-buffer-with-faces file)
20114 (message "Postscript written to %s" file))
20115 ((string-match "\\.ics\\'" file)
20116 (let ((org-agenda-marker-table
20117 (org-create-marker-find-array
20118 (org-agenda-collect-markers)))
20119 (org-icalendar-verify-function 'org-check-agenda-marker-table)
20120 (org-combined-agenda-icalendar-file file))
20121 (apply 'org-export-icalendar 'combine (org-agenda-files))))
20123 (let ((bs (buffer-string)))
20124 (find-file file)
20125 (insert bs)
20126 (save-buffer 0)
20127 (kill-buffer (current-buffer))
20128 (message "Plain text written to %s" file))))))
20129 (set-buffer org-agenda-buffer-name)))
20131 (defun org-agenda-collect-markers ()
20132 "Collect the markers pointing to entries in the agenda buffer."
20133 (let (m markers)
20134 (save-excursion
20135 (goto-char (point-min))
20136 (while (not (eobp))
20137 (when (setq m (or (get-text-property (point) 'org-hd-marker)
20138 (get-text-property (point) 'org-marker)))
20139 (push m markers))
20140 (beginning-of-line 2)))
20141 (nreverse markers)))
20143 (defun org-create-marker-find-array (marker-list)
20144 "Create a alist of files names with all marker positions in that file."
20145 (let (f tbl m a p)
20146 (while (setq m (pop marker-list))
20147 (setq p (marker-position m)
20148 f (buffer-file-name (or (buffer-base-buffer
20149 (marker-buffer m))
20150 (marker-buffer m))))
20151 (if (setq a (assoc f tbl))
20152 (push (marker-position m) (cdr a))
20153 (push (list f p) tbl)))
20154 (mapcar (lambda (x) (setcdr x (sort (copy-sequence (cdr x)) '<)) x)
20155 tbl)))
20157 (defvar org-agenda-marker-table nil) ; dyamically scoped parameter
20158 (defun org-check-agenda-marker-table ()
20159 "Check of the current entry is on the marker list."
20160 (let ((file (buffer-file-name (or (buffer-base-buffer) (current-buffer))))
20162 (and (setq a (assoc file org-agenda-marker-table))
20163 (save-match-data
20164 (save-excursion
20165 (org-back-to-heading t)
20166 (member (point) (cdr a)))))))
20168 (defmacro org-no-read-only (&rest body)
20169 "Inhibit read-only for BODY."
20170 `(let ((inhibit-read-only t)) ,@body))
20172 (defun org-check-for-org-mode ()
20173 "Make sure current buffer is in org-mode. Error if not."
20174 (or (org-mode-p)
20175 (error "Cannot execute org-mode agenda command on buffer in %s."
20176 major-mode)))
20178 (defun org-fit-agenda-window ()
20179 "Fit the window to the buffer size."
20180 (and (memq org-agenda-window-setup '(reorganize-frame))
20181 (fboundp 'fit-window-to-buffer)
20182 (fit-window-to-buffer
20184 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20185 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20187 ;;; Agenda file list
20189 (defun org-agenda-files (&optional unrestricted)
20190 "Get the list of agenda files.
20191 Optional UNRESTRICTED means return the full list even if a restriction
20192 is currently in place."
20193 (let ((files
20194 (cond
20195 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20196 ((stringp org-agenda-files) (org-read-agenda-file-list))
20197 ((listp org-agenda-files) org-agenda-files)
20198 (t (error "Invalid value of `org-agenda-files'")))))
20199 (setq files (apply 'append
20200 (mapcar (lambda (f)
20201 (if (file-directory-p f)
20202 (directory-files f t
20203 org-agenda-file-regexp)
20204 (list f)))
20205 files)))
20206 (if org-agenda-skip-unavailable-files
20207 (delq nil
20208 (mapcar (function
20209 (lambda (file)
20210 (and (file-readable-p file) file)))
20211 files))
20212 files))) ; `org-check-agenda-file' will remove them from the list
20214 (defun org-edit-agenda-file-list ()
20215 "Edit the list of agenda files.
20216 Depending on setup, this either uses customize to edit the variable
20217 `org-agenda-files', or it visits the file that is holding the list. In the
20218 latter case, the buffer is set up in a way that saving it automatically kills
20219 the buffer and restores the previous window configuration."
20220 (interactive)
20221 (if (stringp org-agenda-files)
20222 (let ((cw (current-window-configuration)))
20223 (find-file org-agenda-files)
20224 (org-set-local 'org-window-configuration cw)
20225 (org-add-hook 'after-save-hook
20226 (lambda ()
20227 (set-window-configuration
20228 (prog1 org-window-configuration
20229 (kill-buffer (current-buffer))))
20230 (org-install-agenda-files-menu)
20231 (message "New agenda file list installed"))
20232 nil 'local)
20233 (message "%s" (substitute-command-keys
20234 "Edit list and finish with \\[save-buffer]")))
20235 (customize-variable 'org-agenda-files)))
20237 (defun org-store-new-agenda-file-list (list)
20238 "Set new value for the agenda file list and save it correcly."
20239 (if (stringp org-agenda-files)
20240 (let ((f org-agenda-files) b)
20241 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20242 (with-temp-file f
20243 (insert (mapconcat 'identity list "\n") "\n")))
20244 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20245 (setq org-agenda-files list)
20246 (customize-save-variable 'org-agenda-files org-agenda-files))))
20248 (defun org-read-agenda-file-list ()
20249 "Read the list of agenda files from a file."
20250 (when (stringp org-agenda-files)
20251 (with-temp-buffer
20252 (insert-file-contents org-agenda-files)
20253 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20256 ;;;###autoload
20257 (defun org-cycle-agenda-files ()
20258 "Cycle through the files in `org-agenda-files'.
20259 If the current buffer visits an agenda file, find the next one in the list.
20260 If the current buffer does not, find the first agenda file."
20261 (interactive)
20262 (let* ((fs (org-agenda-files t))
20263 (files (append fs (list (car fs))))
20264 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20265 file)
20266 (unless files (error "No agenda files"))
20267 (catch 'exit
20268 (while (setq file (pop files))
20269 (if (equal (file-truename file) tcf)
20270 (when (car files)
20271 (find-file (car files))
20272 (throw 'exit t))))
20273 (find-file (car fs)))
20274 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20276 (defun org-agenda-file-to-front (&optional to-end)
20277 "Move/add the current file to the top of the agenda file list.
20278 If the file is not present in the list, it is added to the front. If it is
20279 present, it is moved there. With optional argument TO-END, add/move to the
20280 end of the list."
20281 (interactive "P")
20282 (let ((org-agenda-skip-unavailable-files nil)
20283 (file-alist (mapcar (lambda (x)
20284 (cons (file-truename x) x))
20285 (org-agenda-files t)))
20286 (ctf (file-truename buffer-file-name))
20287 x had)
20288 (setq x (assoc ctf file-alist) had x)
20290 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20291 (if to-end
20292 (setq file-alist (append (delq x file-alist) (list x)))
20293 (setq file-alist (cons x (delq x file-alist))))
20294 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20295 (org-install-agenda-files-menu)
20296 (message "File %s to %s of agenda file list"
20297 (if had "moved" "added") (if to-end "end" "front"))))
20299 (defun org-remove-file (&optional file)
20300 "Remove current file from the list of files in variable `org-agenda-files'.
20301 These are the files which are being checked for agenda entries.
20302 Optional argument FILE means, use this file instead of the current."
20303 (interactive)
20304 (let* ((org-agenda-skip-unavailable-files nil)
20305 (file (or file buffer-file-name))
20306 (true-file (file-truename file))
20307 (afile (abbreviate-file-name file))
20308 (files (delq nil (mapcar
20309 (lambda (x)
20310 (if (equal true-file
20311 (file-truename x))
20312 nil x))
20313 (org-agenda-files t)))))
20314 (if (not (= (length files) (length (org-agenda-files t))))
20315 (progn
20316 (org-store-new-agenda-file-list files)
20317 (org-install-agenda-files-menu)
20318 (message "Removed file: %s" afile))
20319 (message "File was not in list: %s (not removed)" afile))))
20321 (defun org-file-menu-entry (file)
20322 (vector file (list 'find-file file) t))
20324 (defun org-check-agenda-file (file)
20325 "Make sure FILE exists. If not, ask user what to do."
20326 (when (not (file-exists-p file))
20327 (message "non-existent file %s. [R]emove from list or [A]bort?"
20328 (abbreviate-file-name file))
20329 (let ((r (downcase (read-char-exclusive))))
20330 (cond
20331 ((equal r ?r)
20332 (org-remove-file file)
20333 (throw 'nextfile t))
20334 (t (error "Abort"))))))
20336 ;;; Agenda prepare and finalize
20338 (defvar org-agenda-multi nil) ; dynammically scoped
20339 (defvar org-agenda-buffer-name "*Org Agenda*")
20340 (defvar org-pre-agenda-window-conf nil)
20341 (defvar org-agenda-name nil)
20342 (defun org-prepare-agenda (&optional name)
20343 (setq org-todo-keywords-for-agenda nil)
20344 (setq org-done-keywords-for-agenda nil)
20345 (if org-agenda-multi
20346 (progn
20347 (setq buffer-read-only nil)
20348 (goto-char (point-max))
20349 (unless (or (bobp) org-agenda-compact-blocks)
20350 (insert "\n" (make-string (window-width) ?=) "\n"))
20351 (narrow-to-region (point) (point-max)))
20352 (org-agenda-reset-markers)
20353 (org-prepare-agenda-buffers (org-agenda-files))
20354 (setq org-todo-keywords-for-agenda
20355 (org-uniquify org-todo-keywords-for-agenda))
20356 (setq org-done-keywords-for-agenda
20357 (org-uniquify org-done-keywords-for-agenda))
20358 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20359 (awin (get-buffer-window abuf)))
20360 (cond
20361 ((equal (current-buffer) abuf) nil)
20362 (awin (select-window awin))
20363 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20364 ((equal org-agenda-window-setup 'current-window)
20365 (switch-to-buffer abuf))
20366 ((equal org-agenda-window-setup 'other-window)
20367 (org-switch-to-buffer-other-window abuf))
20368 ((equal org-agenda-window-setup 'other-frame)
20369 (switch-to-buffer-other-frame abuf))
20370 ((equal org-agenda-window-setup 'reorganize-frame)
20371 (delete-other-windows)
20372 (org-switch-to-buffer-other-window abuf))))
20373 (setq buffer-read-only nil)
20374 (erase-buffer)
20375 (org-agenda-mode)
20376 (and name (not org-agenda-name)
20377 (org-set-local 'org-agenda-name name)))
20378 (setq buffer-read-only nil))
20380 (defun org-finalize-agenda ()
20381 "Finishing touch for the agenda buffer, called just before displaying it."
20382 (unless org-agenda-multi
20383 (save-excursion
20384 (let ((inhibit-read-only t))
20385 (goto-char (point-min))
20386 (while (org-activate-bracket-links (point-max))
20387 (add-text-properties (match-beginning 0) (match-end 0)
20388 '(face org-link)))
20389 (org-agenda-align-tags)
20390 (unless org-agenda-with-colors
20391 (remove-text-properties (point-min) (point-max) '(face nil))))
20392 (if (and (boundp 'org-overriding-columns-format)
20393 org-overriding-columns-format)
20394 (org-set-local 'org-overriding-columns-format
20395 org-overriding-columns-format))
20396 (if (and (boundp 'org-agenda-view-columns-initially)
20397 org-agenda-view-columns-initially)
20398 (org-agenda-columns))
20399 (when org-agenda-fontify-priorities
20400 (org-fontify-priorities))
20401 (run-hooks 'org-finalize-agenda-hook)
20402 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20405 (defun org-fontify-priorities ()
20406 "Make highest priority lines bold, and lowest italic."
20407 (interactive)
20408 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20409 (org-delete-overlay o)))
20410 (org-overlays-in (point-min) (point-max)))
20411 (save-excursion
20412 (let ((inhibit-read-only t)
20413 b e p ov h l)
20414 (goto-char (point-min))
20415 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20416 (setq h (or (get-char-property (point) 'org-highest-priority)
20417 org-highest-priority)
20418 l (or (get-char-property (point) 'org-lowest-priority)
20419 org-lowest-priority)
20420 p (string-to-char (match-string 1))
20421 b (match-beginning 0) e (point-at-eol)
20422 ov (org-make-overlay b e))
20423 (org-overlay-put
20424 ov 'face
20425 (cond ((listp org-agenda-fontify-priorities)
20426 (cdr (assoc p org-agenda-fontify-priorities)))
20427 ((equal p l) 'italic)
20428 ((equal p h) 'bold)))
20429 (org-overlay-put ov 'org-type 'org-priority)))))
20431 (defun org-prepare-agenda-buffers (files)
20432 "Create buffers for all agenda files, protect archived trees and comments."
20433 (interactive)
20434 (let ((pa '(:org-archived t))
20435 (pc '(:org-comment t))
20436 (pall '(:org-archived t :org-comment t))
20437 (inhibit-read-only t)
20438 (rea (concat ":" org-archive-tag ":"))
20439 bmp file re)
20440 (save-excursion
20441 (save-restriction
20442 (while (setq file (pop files))
20443 (if (bufferp file)
20444 (set-buffer file)
20445 (org-check-agenda-file file)
20446 (set-buffer (org-get-agenda-file-buffer file)))
20447 (widen)
20448 (setq bmp (buffer-modified-p))
20449 (org-refresh-category-properties)
20450 (setq org-todo-keywords-for-agenda
20451 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20452 (setq org-done-keywords-for-agenda
20453 (append org-done-keywords-for-agenda org-done-keywords))
20454 (save-excursion
20455 (remove-text-properties (point-min) (point-max) pall)
20456 (when org-agenda-skip-archived-trees
20457 (goto-char (point-min))
20458 (while (re-search-forward rea nil t)
20459 (if (org-on-heading-p t)
20460 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20461 (goto-char (point-min))
20462 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20463 (while (re-search-forward re nil t)
20464 (add-text-properties
20465 (match-beginning 0) (org-end-of-subtree t) pc)))
20466 (set-buffer-modified-p bmp))))))
20468 (defvar org-agenda-skip-function nil
20469 "Function to be called at each match during agenda construction.
20470 If this function returns nil, the current match should not be skipped.
20471 Otherwise, the function must return a position from where the search
20472 should be continued.
20473 This may also be a Lisp form, it will be evaluated.
20474 Never set this variable using `setq' or so, because then it will apply
20475 to all future agenda commands. Instead, bind it with `let' to scope
20476 it dynamically into the agenda-constructing command. A good way to set
20477 it is through options in org-agenda-custom-commands.")
20479 (defun org-agenda-skip ()
20480 "Throw to `:skip' in places that should be skipped.
20481 Also moves point to the end of the skipped region, so that search can
20482 continue from there."
20483 (let ((p (point-at-bol)) to fp)
20484 (and org-agenda-skip-archived-trees
20485 (get-text-property p :org-archived)
20486 (org-end-of-subtree t)
20487 (throw :skip t))
20488 (and (get-text-property p :org-comment)
20489 (org-end-of-subtree t)
20490 (throw :skip t))
20491 (if (equal (char-after p) ?#) (throw :skip t))
20492 (when (and (or (setq fp (functionp org-agenda-skip-function))
20493 (consp org-agenda-skip-function))
20494 (setq to (save-excursion
20495 (save-match-data
20496 (if fp
20497 (funcall org-agenda-skip-function)
20498 (eval org-agenda-skip-function))))))
20499 (goto-char to)
20500 (throw :skip t))))
20502 (defvar org-agenda-markers nil
20503 "List of all currently active markers created by `org-agenda'.")
20504 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20505 "Creation time of the last agenda marker.")
20507 (defun org-agenda-new-marker (&optional pos)
20508 "Return a new agenda marker.
20509 Org-mode keeps a list of these markers and resets them when they are
20510 no longer in use."
20511 (let ((m (copy-marker (or pos (point)))))
20512 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20513 (push m org-agenda-markers)
20516 (defun org-agenda-reset-markers ()
20517 "Reset markers created by `org-agenda'."
20518 (while org-agenda-markers
20519 (move-marker (pop org-agenda-markers) nil)))
20521 (defun org-get-agenda-file-buffer (file)
20522 "Get a buffer visiting FILE. If the buffer needs to be created, add
20523 it to the list of buffers which might be released later."
20524 (let ((buf (org-find-base-buffer-visiting file)))
20525 (if buf
20526 buf ; just return it
20527 ;; Make a new buffer and remember it
20528 (setq buf (find-file-noselect file))
20529 (if buf (push buf org-agenda-new-buffers))
20530 buf)))
20532 (defun org-release-buffers (blist)
20533 "Release all buffers in list, asking the user for confirmation when needed.
20534 When a buffer is unmodified, it is just killed. When modified, it is saved
20535 \(if the user agrees) and then killed."
20536 (let (buf file)
20537 (while (setq buf (pop blist))
20538 (setq file (buffer-file-name buf))
20539 (when (and (buffer-modified-p buf)
20540 file
20541 (y-or-n-p (format "Save file %s? " file)))
20542 (with-current-buffer buf (save-buffer)))
20543 (kill-buffer buf))))
20545 (defun org-get-category (&optional pos)
20546 "Get the category applying to position POS."
20547 (get-text-property (or pos (point)) 'org-category))
20549 ;;; Agenda timeline
20551 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20553 (defun org-timeline (&optional include-all)
20554 "Show a time-sorted view of the entries in the current org file.
20555 Only entries with a time stamp of today or later will be listed. With
20556 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20557 under the current date.
20558 If the buffer contains an active region, only check the region for
20559 dates."
20560 (interactive "P")
20561 (require 'calendar)
20562 (org-compile-prefix-format 'timeline)
20563 (org-set-sorting-strategy 'timeline)
20564 (let* ((dopast t)
20565 (dotodo include-all)
20566 (doclosed org-agenda-show-log)
20567 (entry buffer-file-name)
20568 (date (calendar-current-date))
20569 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20570 (end (if (org-region-active-p) (region-end) (point-max)))
20571 (day-numbers (org-get-all-dates beg end 'no-ranges
20572 t doclosed ; always include today
20573 org-timeline-show-empty-dates))
20574 (org-deadline-warning-days 0)
20575 (org-agenda-only-exact-dates t)
20576 (today (time-to-days (current-time)))
20577 (past t)
20578 args
20579 s e rtn d emptyp)
20580 (setq org-agenda-redo-command
20581 (list 'progn
20582 (list 'org-switch-to-buffer-other-window (current-buffer))
20583 (list 'org-timeline (list 'quote include-all))))
20584 (if (not dopast)
20585 ;; Remove past dates from the list of dates.
20586 (setq day-numbers (delq nil (mapcar (lambda(x)
20587 (if (>= x today) x nil))
20588 day-numbers))))
20589 (org-prepare-agenda (concat "Timeline "
20590 (file-name-nondirectory buffer-file-name)))
20591 (if doclosed (push :closed args))
20592 (push :timestamp args)
20593 (push :deadline args)
20594 (push :scheduled args)
20595 (push :sexp args)
20596 (if dotodo (push :todo args))
20597 (while (setq d (pop day-numbers))
20598 (if (and (listp d) (eq (car d) :omitted))
20599 (progn
20600 (setq s (point))
20601 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20602 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20603 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20604 (if (and (>= d today)
20605 dopast
20606 past)
20607 (progn
20608 (setq past nil)
20609 (insert (make-string 79 ?-) "\n")))
20610 (setq date (calendar-gregorian-from-absolute d))
20611 (setq s (point))
20612 (setq rtn (and (not emptyp)
20613 (apply 'org-agenda-get-day-entries entry
20614 date args)))
20615 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20616 (progn
20617 (insert
20618 (if (stringp org-agenda-format-date)
20619 (format-time-string org-agenda-format-date
20620 (org-time-from-absolute date))
20621 (funcall org-agenda-format-date date))
20622 "\n")
20623 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20624 (put-text-property s (1- (point)) 'org-date-line t)
20625 (if (equal d today)
20626 (put-text-property s (1- (point)) 'org-today t))
20627 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20628 (put-text-property s (1- (point)) 'day d)))))
20629 (goto-char (point-min))
20630 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20631 (point-min)))
20632 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20633 (org-finalize-agenda)
20634 (setq buffer-read-only t)))
20636 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20637 "Return a list of all relevant day numbers from BEG to END buffer positions.
20638 If NO-RANGES is non-nil, include only the start and end dates of a range,
20639 not every single day in the range. If FORCE-TODAY is non-nil, make
20640 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20641 inactive time stamps (those in square brackets) are included.
20642 When EMPTY is non-nil, also include days without any entries."
20643 (let ((re (concat
20644 (if pre-re pre-re "")
20645 (if inactive org-ts-regexp-both org-ts-regexp)))
20646 dates dates1 date day day1 day2 ts1 ts2)
20647 (if force-today
20648 (setq dates (list (time-to-days (current-time)))))
20649 (save-excursion
20650 (goto-char beg)
20651 (while (re-search-forward re end t)
20652 (setq day (time-to-days (org-time-string-to-time
20653 (substring (match-string 1) 0 10))))
20654 (or (memq day dates) (push day dates)))
20655 (unless no-ranges
20656 (goto-char beg)
20657 (while (re-search-forward org-tr-regexp end t)
20658 (setq ts1 (substring (match-string 1) 0 10)
20659 ts2 (substring (match-string 2) 0 10)
20660 day1 (time-to-days (org-time-string-to-time ts1))
20661 day2 (time-to-days (org-time-string-to-time ts2)))
20662 (while (< (setq day1 (1+ day1)) day2)
20663 (or (memq day1 dates) (push day1 dates)))))
20664 (setq dates (sort dates '<))
20665 (when empty
20666 (while (setq day (pop dates))
20667 (setq day2 (car dates))
20668 (push day dates1)
20669 (when (and day2 empty)
20670 (if (or (eq empty t)
20671 (and (numberp empty) (<= (- day2 day) empty)))
20672 (while (< (setq day (1+ day)) day2)
20673 (push (list day) dates1))
20674 (push (cons :omitted (- day2 day)) dates1))))
20675 (setq dates (nreverse dates1)))
20676 dates)))
20678 ;;; Agenda Daily/Weekly
20680 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20681 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20682 (defvar org-agenda-last-arguments nil
20683 "The arguments of the previous call to org-agenda")
20684 (defvar org-starting-day nil) ; local variable in the agenda buffer
20685 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20686 (defvar org-include-all-loc nil) ; local variable
20687 (defvar org-agenda-remove-date nil) ; dynamically scoped FIXME: not used???
20689 ;;;###autoload
20690 (defun org-agenda-list (&optional include-all start-day ndays)
20691 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20692 The view will be for the current day or week, but from the overview buffer
20693 you will be able to go to other days/weeks.
20695 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20696 all unfinished TODO items will also be shown, before the agenda.
20697 This feature is considered obsolete, please use the TODO list or a block
20698 agenda instead.
20700 With a numeric prefix argument in an interactive call, the agenda will
20701 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20702 the number of days. NDAYS defaults to `org-agenda-ndays'.
20704 START-DAY defaults to TODAY, or to the most recent match for the weekday
20705 given in `org-agenda-start-on-weekday'."
20706 (interactive "P")
20707 (if (and (integerp include-all) (> include-all 0))
20708 (setq ndays include-all include-all nil))
20709 (setq ndays (or ndays org-agenda-ndays)
20710 start-day (or start-day org-agenda-start-day))
20711 (if org-agenda-overriding-arguments
20712 (setq include-all (car org-agenda-overriding-arguments)
20713 start-day (nth 1 org-agenda-overriding-arguments)
20714 ndays (nth 2 org-agenda-overriding-arguments)))
20715 (if (stringp start-day)
20716 ;; Convert to an absolute day number
20717 (setq start-day (time-to-days (org-read-date nil t start-day))))
20718 (setq org-agenda-last-arguments (list include-all start-day ndays))
20719 (org-compile-prefix-format 'agenda)
20720 (org-set-sorting-strategy 'agenda)
20721 (require 'calendar)
20722 (let* ((org-agenda-start-on-weekday
20723 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20724 org-agenda-start-on-weekday nil))
20725 (thefiles (org-agenda-files))
20726 (files thefiles)
20727 (today (time-to-days
20728 (time-subtract (current-time)
20729 (list 0 (* 3600 org-extend-today-until) 0))))
20730 (sd (or start-day today))
20731 (start (if (or (null org-agenda-start-on-weekday)
20732 (< org-agenda-ndays 7))
20734 (let* ((nt (calendar-day-of-week
20735 (calendar-gregorian-from-absolute sd)))
20736 (n1 org-agenda-start-on-weekday)
20737 (d (- nt n1)))
20738 (- sd (+ (if (< d 0) 7 0) d)))))
20739 (day-numbers (list start))
20740 (day-cnt 0)
20741 (inhibit-redisplay (not debug-on-error))
20742 s e rtn rtnall file date d start-pos end-pos todayp nd)
20743 (setq org-agenda-redo-command
20744 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20745 ;; Make the list of days
20746 (setq ndays (or ndays org-agenda-ndays)
20747 nd ndays)
20748 (while (> ndays 1)
20749 (push (1+ (car day-numbers)) day-numbers)
20750 (setq ndays (1- ndays)))
20751 (setq day-numbers (nreverse day-numbers))
20752 (org-prepare-agenda "Day/Week")
20753 (org-set-local 'org-starting-day (car day-numbers))
20754 (org-set-local 'org-include-all-loc include-all)
20755 (org-set-local 'org-agenda-span
20756 (org-agenda-ndays-to-span nd))
20757 (when (and (or include-all org-agenda-include-all-todo)
20758 (member today day-numbers))
20759 (setq files thefiles
20760 rtnall nil)
20761 (while (setq file (pop files))
20762 (catch 'nextfile
20763 (org-check-agenda-file file)
20764 (setq date (calendar-gregorian-from-absolute today)
20765 rtn (org-agenda-get-day-entries
20766 file date :todo))
20767 (setq rtnall (append rtnall rtn))))
20768 (when rtnall
20769 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20770 (add-text-properties (point-min) (1- (point))
20771 (list 'face 'org-agenda-structure))
20772 (insert (org-finalize-agenda-entries rtnall) "\n")))
20773 (unless org-agenda-compact-blocks
20774 (let* ((d1 (car day-numbers))
20775 (d2 (org-last day-numbers))
20776 (w1 (org-days-to-iso-week d1))
20777 (w2 (org-days-to-iso-week d2)))
20778 (setq s (point))
20779 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20780 "-agenda"
20781 (if (< (- d2 d1) 350)
20782 (if (= w1 w2)
20783 (format " (W%02d)" w1)
20784 (format " (W%02d-W%02d)" w1 w2))
20786 ":\n"))
20787 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20788 'org-date-line t)))
20789 (while (setq d (pop day-numbers))
20790 (setq date (calendar-gregorian-from-absolute d)
20791 s (point))
20792 (if (or (setq todayp (= d today))
20793 (and (not start-pos) (= d sd)))
20794 (setq start-pos (point))
20795 (if (and start-pos (not end-pos))
20796 (setq end-pos (point))))
20797 (setq files thefiles
20798 rtnall nil)
20799 (while (setq file (pop files))
20800 (catch 'nextfile
20801 (org-check-agenda-file file)
20802 (if org-agenda-show-log
20803 (setq rtn (org-agenda-get-day-entries
20804 file date
20805 :deadline :scheduled :timestamp :sexp :closed))
20806 (setq rtn (org-agenda-get-day-entries
20807 file date
20808 :deadline :scheduled :sexp :timestamp)))
20809 (setq rtnall (append rtnall rtn))))
20810 (if org-agenda-include-diary
20811 (progn
20812 (require 'diary-lib)
20813 (setq rtn (org-get-entries-from-diary date))
20814 (setq rtnall (append rtnall rtn))))
20815 (if (or rtnall org-agenda-show-all-dates)
20816 (progn
20817 (setq day-cnt (1+ day-cnt))
20818 (insert
20819 (if (stringp org-agenda-format-date)
20820 (format-time-string org-agenda-format-date
20821 (org-time-from-absolute date))
20822 (funcall org-agenda-format-date date))
20823 "\n")
20824 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20825 (put-text-property s (1- (point)) 'org-date-line t)
20826 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20827 (if todayp (put-text-property s (1- (point)) 'org-today t))
20828 (if rtnall (insert
20829 (org-finalize-agenda-entries
20830 (org-agenda-add-time-grid-maybe
20831 rtnall nd todayp))
20832 "\n"))
20833 (put-text-property s (1- (point)) 'day d)
20834 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20835 (goto-char (point-min))
20836 (org-fit-agenda-window)
20837 (unless (and (pos-visible-in-window-p (point-min))
20838 (pos-visible-in-window-p (point-max)))
20839 (goto-char (1- (point-max)))
20840 (recenter -1)
20841 (if (not (pos-visible-in-window-p (or start-pos 1)))
20842 (progn
20843 (goto-char (or start-pos 1))
20844 (recenter 1))))
20845 (goto-char (or start-pos 1))
20846 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20847 (org-finalize-agenda)
20848 (setq buffer-read-only t)
20849 (message "")))
20851 (defun org-agenda-ndays-to-span (n)
20852 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20854 ;;; Agenda word search
20856 (defvar org-agenda-search-history nil)
20857 (defvar org-todo-only nil)
20859 (defvar org-search-syntax-table nil
20860 "Special syntax table for org-mode search.
20861 In this table, we have single quotes not as word constituents, to
20862 that when \"+Ameli\" is searchd as a work, it will also match \"Ameli's\"")
20864 (defun org-search-syntax-table ()
20865 (unless org-search-syntax-table
20866 (setq org-search-syntax-table (copy-syntax-table org-mode-syntax-table))
20867 (modify-syntax-entry ?' "." org-search-syntax-table)
20868 (modify-syntax-entry ?` "." org-search-syntax-table))
20869 org-search-syntax-table)
20871 ;;;###autoload
20872 (defun org-search-view (&optional todo-only string edit-at)
20873 "Show all entries that contain words or regular expressions.
20874 If the first character of the search string is an asterisks,
20875 search only the headlines.
20877 With optional prefix argument TODO-ONLY, only consider entries that are
20878 TODO entries. The argument STRING can be used to pass a default search
20879 string into this function. If EDIT-AT is non-nil, it means that the
20880 user should get a chance to edit this string, with cursor at position
20881 EDIT-AT.
20883 The search string is broken into \"words\" by splitting at whitespace.
20884 The individual words are then interpreted as a boolean expression with
20885 logical AND. Words prefixed with a minus must not occur in the entry.
20886 Words without a prefix or prefixed with a plus must occur in the entry.
20887 Matching is case-insensitive and the words are enclosed by word delimiters.
20889 Words enclosed by curly braces are interpreted as regular expressions
20890 that must or must not match in the entry.
20892 If the search string starts with an asterisk, search only in headlines.
20893 If (possibly after the leading star) the search string starts with an
20894 exclamation mark, this also means to look at TODO entries only, an effect
20895 that can also be achieved with a prefix argument.
20897 This command searches the agenda files, and in addition the files listed
20898 in `org-agenda-text-search-extra-files'."
20899 (interactive "P")
20900 (org-compile-prefix-format 'search)
20901 (org-set-sorting-strategy 'search)
20902 (org-prepare-agenda "SEARCH")
20903 (let* ((props (list 'face nil
20904 'done-face 'org-done
20905 'org-not-done-regexp org-not-done-regexp
20906 'org-todo-regexp org-todo-regexp
20907 'mouse-face 'highlight
20908 'keymap org-agenda-keymap
20909 'help-echo (format "mouse-2 or RET jump to location")))
20910 regexp rtn rtnall files file pos
20911 marker priority category tags c neg re
20912 ee txt beg end words regexps+ regexps- hdl-only buffer beg1 str)
20913 (unless (and (not edit-at)
20914 (stringp string)
20915 (string-match "\\S-" string))
20916 (setq string (read-string "[+-]Word/{Regexp} ...: "
20917 (cond
20918 ((integerp edit-at) (cons string edit-at))
20919 (edit-at string))
20920 'org-agenda-search-history)))
20921 (org-set-local 'org-todo-only todo-only)
20922 (setq org-agenda-redo-command
20923 (list 'org-search-view (if todo-only t nil) string
20924 '(if current-prefix-arg 1 nil)))
20925 (setq org-agenda-query-string string)
20927 (if (equal (string-to-char string) ?*)
20928 (setq hdl-only t
20929 words (substring string 1))
20930 (setq words string))
20931 (when (equal (string-to-char words) ?!)
20932 (setq todo-only t
20933 words (substring words 1)))
20934 (setq words (org-split-string words))
20935 (mapc (lambda (w)
20936 (setq c (string-to-char w))
20937 (if (equal c ?-)
20938 (setq neg t w (substring w 1))
20939 (if (equal c ?+)
20940 (setq neg nil w (substring w 1))
20941 (setq neg nil)))
20942 (if (string-match "\\`{.*}\\'" w)
20943 (setq re (substring w 1 -1))
20944 (setq re (concat "\\<" (regexp-quote (downcase w)) "\\>")))
20945 (if neg (push re regexps-) (push re regexps+)))
20946 words)
20947 (setq regexps+ (sort regexps+ (lambda (a b) (> (length a) (length b)))))
20948 (if (not regexps+)
20949 (setq regexp (concat "^" org-outline-regexp))
20950 (setq regexp (pop regexps+))
20951 (if hdl-only (setq regexp (concat "^" org-outline-regexp ".*?"
20952 regexp))))
20953 (setq files (append (org-agenda-files) org-agenda-text-search-extra-files)
20954 rtnall nil)
20955 (while (setq file (pop files))
20956 (setq ee nil)
20957 (catch 'nextfile
20958 (org-check-agenda-file file)
20959 (setq buffer (if (file-exists-p file)
20960 (org-get-agenda-file-buffer file)
20961 (error "No such file %s" file)))
20962 (if (not buffer)
20963 ;; If file does not exist, make sure an error message is sent
20964 (setq rtn (list (format "ORG-AGENDA-ERROR: No such org-file %s"
20965 file))))
20966 (with-current-buffer buffer
20967 (with-syntax-table (org-search-syntax-table)
20968 (unless (org-mode-p)
20969 (error "Agenda file %s is not in `org-mode'" file))
20970 (let ((case-fold-search t))
20971 (save-excursion
20972 (save-restriction
20973 (if org-agenda-restrict
20974 (narrow-to-region org-agenda-restrict-begin
20975 org-agenda-restrict-end)
20976 (widen))
20977 (goto-char (point-min))
20978 (unless (or (org-on-heading-p)
20979 (outline-next-heading))
20980 (throw 'nextfile t))
20981 (goto-char (max (point-min) (1- (point))))
20982 (while (re-search-forward regexp nil t)
20983 (org-back-to-heading t)
20984 (skip-chars-forward "* ")
20985 (setq beg (point-at-bol)
20986 beg1 (point)
20987 end (progn (outline-next-heading) (point)))
20988 (catch :skip
20989 (goto-char beg)
20990 (org-agenda-skip)
20991 (setq str (buffer-substring-no-properties
20992 (point-at-bol)
20993 (if hdl-only (point-at-eol) end)))
20994 (mapc (lambda (wr) (when (string-match wr str)
20995 (goto-char (1- end))
20996 (throw :skip t)))
20997 regexps-)
20998 (mapc (lambda (wr) (unless (string-match wr str)
20999 (goto-char (1- end))
21000 (throw :skip t)))
21001 (if todo-only
21002 (cons (concat "^\*+[ \t]+" org-not-done-regexp)
21003 regexps+)
21004 regexps+))
21005 (goto-char beg)
21006 (setq marker (org-agenda-new-marker (point))
21007 category (org-get-category)
21008 tags (org-get-tags-at (point))
21009 txt (org-format-agenda-item
21011 (buffer-substring-no-properties
21012 beg1 (point-at-eol))
21013 category tags))
21014 (org-add-props txt props
21015 'org-marker marker 'org-hd-marker marker
21016 'org-todo-regexp org-todo-regexp
21017 'priority 1000 'org-category category
21018 'type "search")
21019 (push txt ee)
21020 (goto-char (1- end))))))))))
21021 (setq rtn (nreverse ee))
21022 (setq rtnall (append rtnall rtn)))
21023 (if org-agenda-overriding-header
21024 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21025 nil 'face 'org-agenda-structure) "\n")
21026 (insert "Search words: ")
21027 (add-text-properties (point-min) (1- (point))
21028 (list 'face 'org-agenda-structure))
21029 (setq pos (point))
21030 (insert string "\n")
21031 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21032 (setq pos (point))
21033 (unless org-agenda-multi
21034 (insert "Press `[', `]' to add/sub word, `{', `}' to add/sub regexp, `C-u r' to edit\n")
21035 (add-text-properties pos (1- (point))
21036 (list 'face 'org-agenda-structure))))
21037 (when rtnall
21038 (insert (org-finalize-agenda-entries rtnall) "\n"))
21039 (goto-char (point-min))
21040 (org-fit-agenda-window)
21041 (add-text-properties (point-min) (point-max) '(org-agenda-type search))
21042 (org-finalize-agenda)
21043 (setq buffer-read-only t)))
21045 ;;; Agenda TODO list
21047 (defvar org-select-this-todo-keyword nil)
21048 (defvar org-last-arg nil)
21050 ;;;###autoload
21051 (defun org-todo-list (arg)
21052 "Show all TODO entries from all agenda file in a single list.
21053 The prefix arg can be used to select a specific TODO keyword and limit
21054 the list to these. When using \\[universal-argument], you will be prompted
21055 for a keyword. A numeric prefix directly selects the Nth keyword in
21056 `org-todo-keywords-1'."
21057 (interactive "P")
21058 (require 'calendar)
21059 (org-compile-prefix-format 'todo)
21060 (org-set-sorting-strategy 'todo)
21061 (org-prepare-agenda "TODO")
21062 (let* ((today (time-to-days (current-time)))
21063 (date (calendar-gregorian-from-absolute today))
21064 (kwds org-todo-keywords-for-agenda)
21065 (completion-ignore-case t)
21066 (org-select-this-todo-keyword
21067 (if (stringp arg) arg
21068 (and arg (integerp arg) (> arg 0)
21069 (nth (1- arg) kwds))))
21070 rtn rtnall files file pos)
21071 (when (equal arg '(4))
21072 (setq org-select-this-todo-keyword
21073 (completing-read "Keyword (or KWD1|K2D2|...): "
21074 (mapcar 'list kwds) nil nil)))
21075 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
21076 (org-set-local 'org-last-arg arg)
21077 (setq org-agenda-redo-command
21078 '(org-todo-list (or current-prefix-arg org-last-arg)))
21079 (setq files (org-agenda-files)
21080 rtnall nil)
21081 (while (setq file (pop files))
21082 (catch 'nextfile
21083 (org-check-agenda-file file)
21084 (setq rtn (org-agenda-get-day-entries file date :todo))
21085 (setq rtnall (append rtnall rtn))))
21086 (if org-agenda-overriding-header
21087 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21088 nil 'face 'org-agenda-structure) "\n")
21089 (insert "Global list of TODO items of type: ")
21090 (add-text-properties (point-min) (1- (point))
21091 (list 'face 'org-agenda-structure))
21092 (setq pos (point))
21093 (insert (or org-select-this-todo-keyword "ALL") "\n")
21094 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21095 (setq pos (point))
21096 (unless org-agenda-multi
21097 (insert "Available with `N r': (0)ALL")
21098 (let ((n 0) s)
21099 (mapc (lambda (x)
21100 (setq s (format "(%d)%s" (setq n (1+ n)) x))
21101 (if (> (+ (current-column) (string-width s) 1) (frame-width))
21102 (insert "\n "))
21103 (insert " " s))
21104 kwds))
21105 (insert "\n"))
21106 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21107 (when rtnall
21108 (insert (org-finalize-agenda-entries rtnall) "\n"))
21109 (goto-char (point-min))
21110 (org-fit-agenda-window)
21111 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
21112 (org-finalize-agenda)
21113 (setq buffer-read-only t)))
21115 ;;; Agenda tags match
21117 ;;;###autoload
21118 (defun org-tags-view (&optional todo-only match)
21119 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
21120 The prefix arg TODO-ONLY limits the search to TODO entries."
21121 (interactive "P")
21122 (org-compile-prefix-format 'tags)
21123 (org-set-sorting-strategy 'tags)
21124 (let* ((org-tags-match-list-sublevels
21125 (if todo-only t org-tags-match-list-sublevels))
21126 (completion-ignore-case t)
21127 rtn rtnall files file pos matcher
21128 buffer)
21129 (setq matcher (org-make-tags-matcher match)
21130 match (car matcher) matcher (cdr matcher))
21131 (org-prepare-agenda (concat "TAGS " match))
21132 (setq org-agenda-query-string match)
21133 (setq org-agenda-redo-command
21134 (list 'org-tags-view (list 'quote todo-only)
21135 (list 'if 'current-prefix-arg nil 'org-agenda-query-string)))
21136 (setq files (org-agenda-files)
21137 rtnall nil)
21138 (while (setq file (pop files))
21139 (catch 'nextfile
21140 (org-check-agenda-file file)
21141 (setq buffer (if (file-exists-p file)
21142 (org-get-agenda-file-buffer file)
21143 (error "No such file %s" file)))
21144 (if (not buffer)
21145 ;; If file does not exist, merror message to agenda
21146 (setq rtn (list
21147 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21148 rtnall (append rtnall rtn))
21149 (with-current-buffer buffer
21150 (unless (org-mode-p)
21151 (error "Agenda file %s is not in `org-mode'" file))
21152 (save-excursion
21153 (save-restriction
21154 (if org-agenda-restrict
21155 (narrow-to-region org-agenda-restrict-begin
21156 org-agenda-restrict-end)
21157 (widen))
21158 (setq rtn (org-scan-tags 'agenda matcher todo-only))
21159 (setq rtnall (append rtnall rtn))))))))
21160 (if org-agenda-overriding-header
21161 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21162 nil 'face 'org-agenda-structure) "\n")
21163 (insert "Headlines with TAGS match: ")
21164 (add-text-properties (point-min) (1- (point))
21165 (list 'face 'org-agenda-structure))
21166 (setq pos (point))
21167 (insert match "\n")
21168 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21169 (setq pos (point))
21170 (unless org-agenda-multi
21171 (insert "Press `C-u r' to search again with new search string\n"))
21172 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21173 (when rtnall
21174 (insert (org-finalize-agenda-entries rtnall) "\n"))
21175 (goto-char (point-min))
21176 (org-fit-agenda-window)
21177 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
21178 (org-finalize-agenda)
21179 (setq buffer-read-only t)))
21181 ;;; Agenda Finding stuck projects
21183 (defvar org-agenda-skip-regexp nil
21184 "Regular expression used in skipping subtrees for the agenda.
21185 This is basically a temporary global variable that can be set and then
21186 used by user-defined selections using `org-agenda-skip-function'.")
21188 (defvar org-agenda-overriding-header nil
21189 "When this is set during todo and tags searches, will replace header.")
21191 (defun org-agenda-skip-subtree-when-regexp-matches ()
21192 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
21193 If yes, it returns the end position of this tree, causing agenda commands
21194 to skip this subtree. This is a function that can be put into
21195 `org-agenda-skip-function' for the duration of a command."
21196 (let ((end (save-excursion (org-end-of-subtree t)))
21197 skip)
21198 (save-excursion
21199 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
21200 (and skip end)))
21202 (defun org-agenda-skip-entry-if (&rest conditions)
21203 "Skip entry if any of CONDITIONS is true.
21204 See `org-agenda-skip-if' for details."
21205 (org-agenda-skip-if nil conditions))
21207 (defun org-agenda-skip-subtree-if (&rest conditions)
21208 "Skip entry if any of CONDITIONS is true.
21209 See `org-agenda-skip-if' for details."
21210 (org-agenda-skip-if t conditions))
21212 (defun org-agenda-skip-if (subtree conditions)
21213 "Checks current entity for CONDITIONS.
21214 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
21215 the entry, i.e. the text before the next heading is checked.
21217 CONDITIONS is a list of symbols, boolean OR is used to combine the results
21218 from different tests. Valid conditions are:
21220 scheduled Check if there is a scheduled cookie
21221 notscheduled Check if there is no scheduled cookie
21222 deadline Check if there is a deadline
21223 notdeadline Check if there is no deadline
21224 regexp Check if regexp matches
21225 notregexp Check if regexp does not match.
21227 The regexp is taken from the conditions list, it must come right after
21228 the `regexp' or `notregexp' element.
21230 If any of these conditions is met, this function returns the end point of
21231 the entity, causing the search to continue from there. This is a function
21232 that can be put into `org-agenda-skip-function' for the duration of a command."
21233 (let (beg end m)
21234 (org-back-to-heading t)
21235 (setq beg (point)
21236 end (if subtree
21237 (progn (org-end-of-subtree t) (point))
21238 (progn (outline-next-heading) (1- (point)))))
21239 (goto-char beg)
21240 (and
21242 (and (memq 'scheduled conditions)
21243 (re-search-forward org-scheduled-time-regexp end t))
21244 (and (memq 'notscheduled conditions)
21245 (not (re-search-forward org-scheduled-time-regexp end t)))
21246 (and (memq 'deadline conditions)
21247 (re-search-forward org-deadline-time-regexp end t))
21248 (and (memq 'notdeadline conditions)
21249 (not (re-search-forward org-deadline-time-regexp end t)))
21250 (and (setq m (memq 'regexp conditions))
21251 (stringp (nth 1 m))
21252 (re-search-forward (nth 1 m) end t))
21253 (and (setq m (memq 'notregexp conditions))
21254 (stringp (nth 1 m))
21255 (not (re-search-forward (nth 1 m) end t))))
21256 end)))
21258 ;;;###autoload
21259 (defun org-agenda-list-stuck-projects (&rest ignore)
21260 "Create agenda view for projects that are stuck.
21261 Stuck projects are project that have no next actions. For the definitions
21262 of what a project is and how to check if it stuck, customize the variable
21263 `org-stuck-projects'.
21264 MATCH is being ignored."
21265 (interactive)
21266 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
21267 ;; FIXME: we could have used org-agenda-skip-if here.
21268 (org-agenda-overriding-header "List of stuck projects: ")
21269 (matcher (nth 0 org-stuck-projects))
21270 (todo (nth 1 org-stuck-projects))
21271 (todo-wds (if (member "*" todo)
21272 (progn
21273 (org-prepare-agenda-buffers (org-agenda-files))
21274 (org-delete-all
21275 org-done-keywords-for-agenda
21276 (copy-sequence org-todo-keywords-for-agenda)))
21277 todo))
21278 (todo-re (concat "^\\*+[ \t]+\\("
21279 (mapconcat 'identity todo-wds "\\|")
21280 "\\)\\>"))
21281 (tags (nth 2 org-stuck-projects))
21282 (tags-re (if (member "*" tags)
21283 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
21284 (concat "^\\*+ .*:\\("
21285 (mapconcat 'identity tags "\\|")
21286 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
21287 (gen-re (nth 3 org-stuck-projects))
21288 (re-list
21289 (delq nil
21290 (list
21291 (if todo todo-re)
21292 (if tags tags-re)
21293 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
21294 gen-re)))))
21295 (setq org-agenda-skip-regexp
21296 (if re-list
21297 (mapconcat 'identity re-list "\\|")
21298 (error "No information how to identify unstuck projects")))
21299 (org-tags-view nil matcher)
21300 (with-current-buffer org-agenda-buffer-name
21301 (setq org-agenda-redo-command
21302 '(org-agenda-list-stuck-projects
21303 (or current-prefix-arg org-last-arg))))))
21305 ;;; Diary integration
21307 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
21308 (defvar list-diary-entries-hook)
21310 (defun org-get-entries-from-diary (date)
21311 "Get the (Emacs Calendar) diary entries for DATE."
21312 (require 'diary-lib)
21313 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
21314 (diary-display-hook '(fancy-diary-display))
21315 (pop-up-frames nil)
21316 (list-diary-entries-hook
21317 (cons 'org-diary-default-entry list-diary-entries-hook))
21318 (diary-file-name-prefix-function nil) ; turn this feature off
21319 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
21320 entries
21321 (org-disable-agenda-to-diary t))
21322 (save-excursion
21323 (save-window-excursion
21324 (funcall (if (fboundp 'diary-list-entries)
21325 'diary-list-entries 'list-diary-entries)
21326 date 1)))
21327 (if (not (get-buffer fancy-diary-buffer))
21328 (setq entries nil)
21329 (with-current-buffer fancy-diary-buffer
21330 (setq buffer-read-only nil)
21331 (if (zerop (buffer-size))
21332 ;; No entries
21333 (setq entries nil)
21334 ;; Omit the date and other unnecessary stuff
21335 (org-agenda-cleanup-fancy-diary)
21336 ;; Add prefix to each line and extend the text properties
21337 (if (zerop (buffer-size))
21338 (setq entries nil)
21339 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
21340 (set-buffer-modified-p nil)
21341 (kill-buffer fancy-diary-buffer)))
21342 (when entries
21343 (setq entries (org-split-string entries "\n"))
21344 (setq entries
21345 (mapcar
21346 (lambda (x)
21347 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
21348 ;; Extend the text properties to the beginning of the line
21349 (org-add-props x (text-properties-at (1- (length x)) x)
21350 'type "diary" 'date date))
21351 entries)))))
21353 (defun org-agenda-cleanup-fancy-diary ()
21354 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
21355 This gets rid of the date, the underline under the date, and
21356 the dummy entry installed by `org-mode' to ensure non-empty diary for each
21357 date. It also removes lines that contain only whitespace."
21358 (goto-char (point-min))
21359 (if (looking-at ".*?:[ \t]*")
21360 (progn
21361 (replace-match "")
21362 (re-search-forward "\n=+$" nil t)
21363 (replace-match "")
21364 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
21365 (re-search-forward "\n=+$" nil t)
21366 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
21367 (goto-char (point-min))
21368 (while (re-search-forward "^ +\n" nil t)
21369 (replace-match ""))
21370 (goto-char (point-min))
21371 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21372 (replace-match "")))
21374 ;; Make sure entries from the diary have the right text properties.
21375 (eval-after-load "diary-lib"
21376 '(if (boundp 'diary-modify-entry-list-string-function)
21377 ;; We can rely on the hook, nothing to do
21379 ;; Hook not avaiable, must use advice to make this work
21380 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21381 "Make the position visible."
21382 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21383 (stringp string)
21384 buffer-file-name)
21385 (setq string (org-modify-diary-entry-string string))))))
21387 (defun org-modify-diary-entry-string (string)
21388 "Add text properties to string, allowing org-mode to act on it."
21389 (org-add-props string nil
21390 'mouse-face 'highlight
21391 'keymap org-agenda-keymap
21392 'help-echo (if buffer-file-name
21393 (format "mouse-2 or RET jump to diary file %s"
21394 (abbreviate-file-name buffer-file-name))
21396 'org-agenda-diary-link t
21397 'org-marker (org-agenda-new-marker (point-at-bol))))
21399 (defun org-diary-default-entry ()
21400 "Add a dummy entry to the diary.
21401 Needed to avoid empty dates which mess up holiday display."
21402 ;; Catch the error if dealing with the new add-to-diary-alist
21403 (when org-disable-agenda-to-diary
21404 (condition-case nil
21405 (add-to-diary-list original-date "Org-mode dummy" "")
21406 (error
21407 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21409 ;;;###autoload
21410 (defun org-diary (&rest args)
21411 "Return diary information from org-files.
21412 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21413 It accesses org files and extracts information from those files to be
21414 listed in the diary. The function accepts arguments specifying what
21415 items should be listed. The following arguments are allowed:
21417 :timestamp List the headlines of items containing a date stamp or
21418 date range matching the selected date. Deadlines will
21419 also be listed, on the expiration day.
21421 :sexp List entries resulting from diary-like sexps.
21423 :deadline List any deadlines past due, or due within
21424 `org-deadline-warning-days'. The listing occurs only
21425 in the diary for *today*, not at any other date. If
21426 an entry is marked DONE, it is no longer listed.
21428 :scheduled List all items which are scheduled for the given date.
21429 The diary for *today* also contains items which were
21430 scheduled earlier and are not yet marked DONE.
21432 :todo List all TODO items from the org-file. This may be a
21433 long list - so this is not turned on by default.
21434 Like deadlines, these entries only show up in the
21435 diary for *today*, not at any other date.
21437 The call in the diary file should look like this:
21439 &%%(org-diary) ~/path/to/some/orgfile.org
21441 Use a separate line for each org file to check. Or, if you omit the file name,
21442 all files listed in `org-agenda-files' will be checked automatically:
21444 &%%(org-diary)
21446 If you don't give any arguments (as in the example above), the default
21447 arguments (:deadline :scheduled :timestamp :sexp) are used.
21448 So the example above may also be written as
21450 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21452 The function expects the lisp variables `entry' and `date' to be provided
21453 by the caller, because this is how the calendar works. Don't use this
21454 function from a program - use `org-agenda-get-day-entries' instead."
21455 (when (> (- (time-to-seconds (current-time))
21456 org-agenda-last-marker-time)
21458 (org-agenda-reset-markers))
21459 (org-compile-prefix-format 'agenda)
21460 (org-set-sorting-strategy 'agenda)
21461 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21462 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21463 (list entry)
21464 (org-agenda-files t)))
21465 file rtn results)
21466 (org-prepare-agenda-buffers files)
21467 ;; If this is called during org-agenda, don't return any entries to
21468 ;; the calendar. Org Agenda will list these entries itself.
21469 (if org-disable-agenda-to-diary (setq files nil))
21470 (while (setq file (pop files))
21471 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21472 (setq results (append results rtn)))
21473 (if results
21474 (concat (org-finalize-agenda-entries results) "\n"))))
21476 ;;; Agenda entry finders
21478 (defun org-agenda-get-day-entries (file date &rest args)
21479 "Does the work for `org-diary' and `org-agenda'.
21480 FILE is the path to a file to be checked for entries. DATE is date like
21481 the one returned by `calendar-current-date'. ARGS are symbols indicating
21482 which kind of entries should be extracted. For details about these, see
21483 the documentation of `org-diary'."
21484 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21485 (let* ((org-startup-folded nil)
21486 (org-startup-align-all-tables nil)
21487 (buffer (if (file-exists-p file)
21488 (org-get-agenda-file-buffer file)
21489 (error "No such file %s" file)))
21490 arg results rtn)
21491 (if (not buffer)
21492 ;; If file does not exist, make sure an error message ends up in diary
21493 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21494 (with-current-buffer buffer
21495 (unless (org-mode-p)
21496 (error "Agenda file %s is not in `org-mode'" file))
21497 (let ((case-fold-search nil))
21498 (save-excursion
21499 (save-restriction
21500 (if org-agenda-restrict
21501 (narrow-to-region org-agenda-restrict-begin
21502 org-agenda-restrict-end)
21503 (widen))
21504 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21505 (while (setq arg (pop args))
21506 (cond
21507 ((and (eq arg :todo)
21508 (equal date (calendar-current-date)))
21509 (setq rtn (org-agenda-get-todos))
21510 (setq results (append results rtn)))
21511 ((eq arg :timestamp)
21512 (setq rtn (org-agenda-get-blocks))
21513 (setq results (append results rtn))
21514 (setq rtn (org-agenda-get-timestamps))
21515 (setq results (append results rtn)))
21516 ((eq arg :sexp)
21517 (setq rtn (org-agenda-get-sexps))
21518 (setq results (append results rtn)))
21519 ((eq arg :scheduled)
21520 (setq rtn (org-agenda-get-scheduled))
21521 (setq results (append results rtn)))
21522 ((eq arg :closed)
21523 (setq rtn (org-agenda-get-closed))
21524 (setq results (append results rtn)))
21525 ((eq arg :deadline)
21526 (setq rtn (org-agenda-get-deadlines))
21527 (setq results (append results rtn))))))))
21528 results))))
21530 (defun org-entry-is-todo-p ()
21531 (member (org-get-todo-state) org-not-done-keywords))
21533 (defun org-entry-is-done-p ()
21534 (member (org-get-todo-state) org-done-keywords))
21536 (defun org-get-todo-state ()
21537 (save-excursion
21538 (org-back-to-heading t)
21539 (and (looking-at org-todo-line-regexp)
21540 (match-end 2)
21541 (match-string 2))))
21543 (defun org-at-date-range-p (&optional inactive-ok)
21544 "Is the cursor inside a date range?"
21545 (interactive)
21546 (save-excursion
21547 (catch 'exit
21548 (let ((pos (point)))
21549 (skip-chars-backward "^[<\r\n")
21550 (skip-chars-backward "<[")
21551 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21552 (>= (match-end 0) pos)
21553 (throw 'exit t))
21554 (skip-chars-backward "^<[\r\n")
21555 (skip-chars-backward "<[")
21556 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21557 (>= (match-end 0) pos)
21558 (throw 'exit t)))
21559 nil)))
21561 (defun org-agenda-get-todos ()
21562 "Return the TODO information for agenda display."
21563 (let* ((props (list 'face nil
21564 'done-face 'org-done
21565 'org-not-done-regexp org-not-done-regexp
21566 'org-todo-regexp org-todo-regexp
21567 'mouse-face 'highlight
21568 'keymap org-agenda-keymap
21569 'help-echo
21570 (format "mouse-2 or RET jump to org file %s"
21571 (abbreviate-file-name buffer-file-name))))
21572 ;; FIXME: get rid of the \n at some point but watch out
21573 (regexp (concat "^\\*+[ \t]+\\("
21574 (if org-select-this-todo-keyword
21575 (if (equal org-select-this-todo-keyword "*")
21576 org-todo-regexp
21577 (concat "\\<\\("
21578 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21579 "\\)\\>"))
21580 org-not-done-regexp)
21581 "[^\n\r]*\\)"))
21582 marker priority category tags
21583 ee txt beg end)
21584 (goto-char (point-min))
21585 (while (re-search-forward regexp nil t)
21586 (catch :skip
21587 (save-match-data
21588 (beginning-of-line)
21589 (setq beg (point) end (progn (outline-next-heading) (point)))
21590 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21591 (re-search-forward org-ts-regexp end t))
21592 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21593 (re-search-forward org-scheduled-time-regexp end t))
21594 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21595 (re-search-forward org-deadline-time-regexp end t)
21596 (org-deadline-close (match-string 1))))
21597 (goto-char (1+ beg))
21598 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21599 (throw :skip nil)))
21600 (goto-char beg)
21601 (org-agenda-skip)
21602 (goto-char (match-beginning 1))
21603 (setq marker (org-agenda-new-marker (match-beginning 0))
21604 category (org-get-category)
21605 tags (org-get-tags-at (point))
21606 txt (org-format-agenda-item "" (match-string 1) category tags)
21607 priority (1+ (org-get-priority txt)))
21608 (org-add-props txt props
21609 'org-marker marker 'org-hd-marker marker
21610 'priority priority 'org-category category
21611 'type "todo")
21612 (push txt ee)
21613 (if org-agenda-todo-list-sublevels
21614 (goto-char (match-end 1))
21615 (org-end-of-subtree 'invisible))))
21616 (nreverse ee)))
21618 (defconst org-agenda-no-heading-message
21619 "No heading for this item in buffer or region.")
21621 (defun org-agenda-get-timestamps ()
21622 "Return the date stamp information for agenda display."
21623 (let* ((props (list 'face nil
21624 'org-not-done-regexp org-not-done-regexp
21625 'org-todo-regexp org-todo-regexp
21626 'mouse-face 'highlight
21627 'keymap org-agenda-keymap
21628 'help-echo
21629 (format "mouse-2 or RET jump to org file %s"
21630 (abbreviate-file-name buffer-file-name))))
21631 (d1 (calendar-absolute-from-gregorian date))
21632 (remove-re
21633 (concat
21634 (regexp-quote
21635 (format-time-string
21636 "<%Y-%m-%d"
21637 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21638 ".*?>"))
21639 (regexp
21640 (concat
21641 (regexp-quote
21642 (substring
21643 (format-time-string
21644 (car org-time-stamp-formats)
21645 (apply 'encode-time ; DATE bound by calendar
21646 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21647 0 11))
21648 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21649 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21650 marker hdmarker deadlinep scheduledp donep tmp priority category
21651 ee txt timestr tags b0 b3 e3 head)
21652 (goto-char (point-min))
21653 (while (re-search-forward regexp nil t)
21654 (setq b0 (match-beginning 0)
21655 b3 (match-beginning 3) e3 (match-end 3))
21656 (catch :skip
21657 (and (org-at-date-range-p) (throw :skip nil))
21658 (org-agenda-skip)
21659 (if (and (match-end 1)
21660 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21661 (throw :skip nil))
21662 (if (and e3
21663 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21664 (throw :skip nil))
21665 (setq marker (org-agenda-new-marker b0)
21666 category (org-get-category b0)
21667 tmp (buffer-substring (max (point-min)
21668 (- b0 org-ds-keyword-length))
21670 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21671 deadlinep (string-match org-deadline-regexp tmp)
21672 scheduledp (string-match org-scheduled-regexp tmp)
21673 donep (org-entry-is-done-p))
21674 (if (or scheduledp deadlinep) (throw :skip t))
21675 (if (string-match ">" timestr)
21676 ;; substring should only run to end of time stamp
21677 (setq timestr (substring timestr 0 (match-end 0))))
21678 (save-excursion
21679 (if (re-search-backward "^\\*+ " nil t)
21680 (progn
21681 (goto-char (match-beginning 0))
21682 (setq hdmarker (org-agenda-new-marker)
21683 tags (org-get-tags-at))
21684 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21685 (setq head (match-string 1))
21686 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21687 (setq txt (org-format-agenda-item
21688 nil head category tags timestr nil
21689 remove-re)))
21690 (setq txt org-agenda-no-heading-message))
21691 (setq priority (org-get-priority txt))
21692 (org-add-props txt props
21693 'org-marker marker 'org-hd-marker hdmarker)
21694 (org-add-props txt nil 'priority priority
21695 'org-category category 'date date
21696 'type "timestamp")
21697 (push txt ee))
21698 (outline-next-heading)))
21699 (nreverse ee)))
21701 (defun org-agenda-get-sexps ()
21702 "Return the sexp information for agenda display."
21703 (require 'diary-lib)
21704 (let* ((props (list 'face nil
21705 'mouse-face 'highlight
21706 'keymap org-agenda-keymap
21707 'help-echo
21708 (format "mouse-2 or RET jump to org file %s"
21709 (abbreviate-file-name buffer-file-name))))
21710 (regexp "^&?%%(")
21711 marker category ee txt tags entry result beg b sexp sexp-entry)
21712 (goto-char (point-min))
21713 (while (re-search-forward regexp nil t)
21714 (catch :skip
21715 (org-agenda-skip)
21716 (setq beg (match-beginning 0))
21717 (goto-char (1- (match-end 0)))
21718 (setq b (point))
21719 (forward-sexp 1)
21720 (setq sexp (buffer-substring b (point)))
21721 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21722 (org-trim (match-string 1))
21723 ""))
21724 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21725 (when result
21726 (setq marker (org-agenda-new-marker beg)
21727 category (org-get-category beg))
21729 (if (string-match "\\S-" result)
21730 (setq txt result)
21731 (setq txt "SEXP entry returned empty string"))
21733 (setq txt (org-format-agenda-item
21734 "" txt category tags 'time))
21735 (org-add-props txt props 'org-marker marker)
21736 (org-add-props txt nil
21737 'org-category category 'date date
21738 'type "sexp")
21739 (push txt ee))))
21740 (nreverse ee)))
21742 (defun org-agenda-get-closed ()
21743 "Return the logged TODO entries for agenda display."
21744 (let* ((props (list 'mouse-face 'highlight
21745 'org-not-done-regexp org-not-done-regexp
21746 'org-todo-regexp org-todo-regexp
21747 'keymap org-agenda-keymap
21748 'help-echo
21749 (format "mouse-2 or RET jump to org file %s"
21750 (abbreviate-file-name buffer-file-name))))
21751 (regexp (concat
21752 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21753 (regexp-quote
21754 (substring
21755 (format-time-string
21756 (car org-time-stamp-formats)
21757 (apply 'encode-time ; DATE bound by calendar
21758 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21759 1 11))))
21760 marker hdmarker priority category tags closedp
21761 ee txt timestr)
21762 (goto-char (point-min))
21763 (while (re-search-forward regexp nil t)
21764 (catch :skip
21765 (org-agenda-skip)
21766 (setq marker (org-agenda-new-marker (match-beginning 0))
21767 closedp (equal (match-string 1) org-closed-string)
21768 category (org-get-category (match-beginning 0))
21769 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21770 ;; donep (org-entry-is-done-p)
21772 (if (string-match "\\]" timestr)
21773 ;; substring should only run to end of time stamp
21774 (setq timestr (substring timestr 0 (match-end 0))))
21775 (save-excursion
21776 (if (re-search-backward "^\\*+ " nil t)
21777 (progn
21778 (goto-char (match-beginning 0))
21779 (setq hdmarker (org-agenda-new-marker)
21780 tags (org-get-tags-at))
21781 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21782 (setq txt (org-format-agenda-item
21783 (if closedp "Closed: " "Clocked: ")
21784 (match-string 1) category tags timestr)))
21785 (setq txt org-agenda-no-heading-message))
21786 (setq priority 100000)
21787 (org-add-props txt props
21788 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21789 'priority priority 'org-category category
21790 'type "closed" 'date date
21791 'undone-face 'org-warning 'done-face 'org-done)
21792 (push txt ee))
21793 (goto-char (point-at-eol))))
21794 (nreverse ee)))
21796 (defun org-agenda-get-deadlines ()
21797 "Return the deadline information for agenda display."
21798 (let* ((props (list 'mouse-face 'highlight
21799 'org-not-done-regexp org-not-done-regexp
21800 'org-todo-regexp org-todo-regexp
21801 'keymap org-agenda-keymap
21802 'help-echo
21803 (format "mouse-2 or RET jump to org file %s"
21804 (abbreviate-file-name buffer-file-name))))
21805 (regexp org-deadline-time-regexp)
21806 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21807 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21808 d2 diff dfrac wdays pos pos1 category tags
21809 ee txt head face s upcomingp donep timestr)
21810 (goto-char (point-min))
21811 (while (re-search-forward regexp nil t)
21812 (catch :skip
21813 (org-agenda-skip)
21814 (setq s (match-string 1)
21815 pos (1- (match-beginning 1))
21816 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21817 diff (- d2 d1)
21818 wdays (org-get-wdays s)
21819 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
21820 upcomingp (and todayp (> diff 0)))
21821 ;; When to show a deadline in the calendar:
21822 ;; If the expiration is within wdays warning time.
21823 ;; Past-due deadlines are only shown on the current date
21824 (if (or (and (<= diff wdays)
21825 (and todayp (not org-agenda-only-exact-dates)))
21826 (= diff 0))
21827 (save-excursion
21828 (setq category (org-get-category))
21829 (if (re-search-backward "^\\*+[ \t]+" nil t)
21830 (progn
21831 (goto-char (match-end 0))
21832 (setq pos1 (match-beginning 0))
21833 (setq tags (org-get-tags-at pos1))
21834 (setq head (buffer-substring-no-properties
21835 (point)
21836 (progn (skip-chars-forward "^\r\n")
21837 (point))))
21838 (setq donep (string-match org-looking-at-done-regexp head))
21839 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21840 (setq timestr
21841 (concat (substring s (match-beginning 1)) " "))
21842 (setq timestr 'time))
21843 (if (and donep
21844 (or org-agenda-skip-deadline-if-done
21845 (not (= diff 0))))
21846 (setq txt nil)
21847 (setq txt (org-format-agenda-item
21848 (if (= diff 0)
21849 (car org-agenda-deadline-leaders)
21850 (format (nth 1 org-agenda-deadline-leaders)
21851 diff))
21852 head category tags timestr))))
21853 (setq txt org-agenda-no-heading-message))
21854 (when txt
21855 (setq face (org-agenda-deadline-face dfrac wdays))
21856 (org-add-props txt props
21857 'org-marker (org-agenda-new-marker pos)
21858 'org-hd-marker (org-agenda-new-marker pos1)
21859 'priority (+ (- diff)
21860 (org-get-priority txt))
21861 'org-category category
21862 'type (if upcomingp "upcoming-deadline" "deadline")
21863 'date (if upcomingp date d2)
21864 'face (if donep 'org-done face)
21865 'undone-face face 'done-face 'org-done)
21866 (push txt ee))))))
21867 (nreverse ee)))
21869 (defun org-agenda-deadline-face (fraction &optional wdays)
21870 "Return the face to displaying a deadline item.
21871 FRACTION is what fraction of the head-warning time has passed."
21872 (if (equal wdays 0) (setq fraction 1.))
21873 (let ((faces org-agenda-deadline-faces) f)
21874 (catch 'exit
21875 (while (setq f (pop faces))
21876 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21878 (defun org-agenda-get-scheduled ()
21879 "Return the scheduled information for agenda display."
21880 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21881 'org-todo-regexp org-todo-regexp
21882 'done-face 'org-done
21883 'mouse-face 'highlight
21884 'keymap org-agenda-keymap
21885 'help-echo
21886 (format "mouse-2 or RET jump to org file %s"
21887 (abbreviate-file-name buffer-file-name))))
21888 (regexp org-scheduled-time-regexp)
21889 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21890 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21891 d2 diff pos pos1 category tags
21892 ee txt head pastschedp donep face timestr s)
21893 (goto-char (point-min))
21894 (while (re-search-forward regexp nil t)
21895 (catch :skip
21896 (org-agenda-skip)
21897 (setq s (match-string 1)
21898 pos (1- (match-beginning 1))
21899 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21900 ;;; is this right?
21901 ;;; do we need to do this for deadleine too????
21902 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
21903 diff (- d2 d1))
21904 (setq pastschedp (and todayp (< diff 0)))
21905 ;; When to show a scheduled item in the calendar:
21906 ;; If it is on or past the date.
21907 (if (or (and (< diff 0)
21908 (< (abs diff) org-scheduled-past-days)
21909 (and todayp (not org-agenda-only-exact-dates)))
21910 (= diff 0))
21911 (save-excursion
21912 (setq category (org-get-category))
21913 (if (re-search-backward "^\\*+[ \t]+" nil t)
21914 (progn
21915 (goto-char (match-end 0))
21916 (setq pos1 (match-beginning 0))
21917 (setq tags (org-get-tags-at))
21918 (setq head (buffer-substring-no-properties
21919 (point)
21920 (progn (skip-chars-forward "^\r\n") (point))))
21921 (setq donep (string-match org-looking-at-done-regexp head))
21922 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21923 (setq timestr
21924 (concat (substring s (match-beginning 1)) " "))
21925 (setq timestr 'time))
21926 (if (and donep
21927 (or org-agenda-skip-scheduled-if-done
21928 (not (= diff 0))))
21929 (setq txt nil)
21930 (setq txt (org-format-agenda-item
21931 (if (= diff 0)
21932 (car org-agenda-scheduled-leaders)
21933 (format (nth 1 org-agenda-scheduled-leaders)
21934 (- 1 diff)))
21935 head category tags timestr))))
21936 (setq txt org-agenda-no-heading-message))
21937 (when txt
21938 (setq face (if pastschedp
21939 'org-scheduled-previously
21940 'org-scheduled-today))
21941 (org-add-props txt props
21942 'undone-face face
21943 'face (if donep 'org-done face)
21944 'org-marker (org-agenda-new-marker pos)
21945 'org-hd-marker (org-agenda-new-marker pos1)
21946 'type (if pastschedp "past-scheduled" "scheduled")
21947 'date (if pastschedp d2 date)
21948 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21949 'org-category category)
21950 (push txt ee))))))
21951 (nreverse ee)))
21953 (defun org-agenda-get-blocks ()
21954 "Return the date-range information for agenda display."
21955 (let* ((props (list 'face nil
21956 'org-not-done-regexp org-not-done-regexp
21957 'org-todo-regexp org-todo-regexp
21958 'mouse-face 'highlight
21959 'keymap org-agenda-keymap
21960 'help-echo
21961 (format "mouse-2 or RET jump to org file %s"
21962 (abbreviate-file-name buffer-file-name))))
21963 (regexp org-tr-regexp)
21964 (d0 (calendar-absolute-from-gregorian date))
21965 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21966 donep head)
21967 (goto-char (point-min))
21968 (while (re-search-forward regexp nil t)
21969 (catch :skip
21970 (org-agenda-skip)
21971 (setq pos (point))
21972 (setq timestr (match-string 0)
21973 s1 (match-string 1)
21974 s2 (match-string 2)
21975 d1 (time-to-days (org-time-string-to-time s1))
21976 d2 (time-to-days (org-time-string-to-time s2)))
21977 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21978 ;; Only allow days between the limits, because the normal
21979 ;; date stamps will catch the limits.
21980 (save-excursion
21981 (setq marker (org-agenda-new-marker (point)))
21982 (setq category (org-get-category))
21983 (if (re-search-backward "^\\*+ " nil t)
21984 (progn
21985 (goto-char (match-beginning 0))
21986 (setq hdmarker (org-agenda-new-marker (point)))
21987 (setq tags (org-get-tags-at))
21988 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21989 (setq head (match-string 1))
21990 (and org-agenda-skip-timestamp-if-done
21991 (org-entry-is-done-p)
21992 (throw :skip t))
21993 (setq txt (org-format-agenda-item
21994 (format (if (= d1 d2) "" "(%d/%d): ")
21995 (1+ (- d0 d1)) (1+ (- d2 d1)))
21996 head category tags
21997 (if (= d0 d1) timestr))))
21998 (setq txt org-agenda-no-heading-message))
21999 (org-add-props txt props
22000 'org-marker marker 'org-hd-marker hdmarker
22001 'type "block" 'date date
22002 'priority (org-get-priority txt) 'org-category category)
22003 (push txt ee)))
22004 (goto-char pos)))
22005 ;; Sort the entries by expiration date.
22006 (nreverse ee)))
22008 ;;; Agenda presentation and sorting
22010 (defconst org-plain-time-of-day-regexp
22011 (concat
22012 "\\(\\<[012]?[0-9]"
22013 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22014 "\\(--?"
22015 "\\(\\<[012]?[0-9]"
22016 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22017 "\\)?")
22018 "Regular expression to match a plain time or time range.
22019 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22020 groups carry important information:
22021 0 the full match
22022 1 the first time, range or not
22023 8 the second time, if it is a range.")
22025 (defconst org-plain-time-extension-regexp
22026 (concat
22027 "\\(\\<[012]?[0-9]"
22028 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22029 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
22030 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
22031 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22032 groups carry important information:
22033 0 the full match
22034 7 hours of duration
22035 9 minutes of duration")
22037 (defconst org-stamp-time-of-day-regexp
22038 (concat
22039 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
22040 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
22041 "\\(--?"
22042 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
22043 "Regular expression to match a timestamp time or time range.
22044 After a match, the following groups carry important information:
22045 0 the full match
22046 1 date plus weekday, for backreferencing to make sure both times on same day
22047 2 the first time, range or not
22048 4 the second time, if it is a range.")
22050 (defvar org-prefix-has-time nil
22051 "A flag, set by `org-compile-prefix-format'.
22052 The flag is set if the currently compiled format contains a `%t'.")
22053 (defvar org-prefix-has-tag nil
22054 "A flag, set by `org-compile-prefix-format'.
22055 The flag is set if the currently compiled format contains a `%T'.")
22057 (defun org-format-agenda-item (extra txt &optional category tags dotime
22058 noprefix remove-re)
22059 "Format TXT to be inserted into the agenda buffer.
22060 In particular, it adds the prefix and corresponding text properties. EXTRA
22061 must be a string and replaces the `%s' specifier in the prefix format.
22062 CATEGORY (string, symbol or nil) may be used to overrule the default
22063 category taken from local variable or file name. It will replace the `%c'
22064 specifier in the format. DOTIME, when non-nil, indicates that a
22065 time-of-day should be extracted from TXT for sorting of this entry, and for
22066 the `%t' specifier in the format. When DOTIME is a string, this string is
22067 searched for a time before TXT is. NOPREFIX is a flag and indicates that
22068 only the correctly processes TXT should be returned - this is used by
22069 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
22070 Any match of REMOVE-RE will be removed from TXT."
22071 (save-match-data
22072 ;; Diary entries sometimes have extra whitespace at the beginning
22073 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
22074 (let* ((category (or category
22075 org-category
22076 (if buffer-file-name
22077 (file-name-sans-extension
22078 (file-name-nondirectory buffer-file-name))
22079 "")))
22080 (tag (if tags (nth (1- (length tags)) tags) ""))
22081 time ; time and tag are needed for the eval of the prefix format
22082 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
22083 (time-of-day (and dotime (org-get-time-of-day ts)))
22084 stamp plain s0 s1 s2 rtn srp)
22085 (when (and dotime time-of-day org-prefix-has-time)
22086 ;; Extract starting and ending time and move them to prefix
22087 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
22088 (setq plain (string-match org-plain-time-of-day-regexp ts)))
22089 (setq s0 (match-string 0 ts)
22090 srp (and stamp (match-end 3))
22091 s1 (match-string (if plain 1 2) ts)
22092 s2 (match-string (if plain 8 (if srp 4 6)) ts))
22094 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
22095 ;; them, we might want to remove them there to avoid duplication.
22096 ;; The user can turn this off with a variable.
22097 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
22098 (string-match (concat (regexp-quote s0) " *") txt)
22099 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
22100 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
22101 (= (match-beginning 0) 0)
22103 (setq txt (replace-match "" nil nil txt))))
22104 ;; Normalize the time(s) to 24 hour
22105 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
22106 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
22108 (when (and s1 (not s2) org-agenda-default-appointment-duration
22109 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
22110 (let ((m (+ (string-to-number (match-string 2 s1))
22111 (* 60 (string-to-number (match-string 1 s1)))
22112 org-agenda-default-appointment-duration))
22114 (setq h (/ m 60) m (- m (* h 60)))
22115 (setq s2 (format "%02d:%02d" h m))))
22117 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22118 txt)
22119 ;; Tags are in the string
22120 (if (or (eq org-agenda-remove-tags t)
22121 (and org-agenda-remove-tags
22122 org-prefix-has-tag))
22123 (setq txt (replace-match "" t t txt))
22124 (setq txt (replace-match
22125 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
22126 (match-string 2 txt))
22127 t t txt))))
22129 (when remove-re
22130 (while (string-match remove-re txt)
22131 (setq txt (replace-match "" t t txt))))
22133 ;; Create the final string
22134 (if noprefix
22135 (setq rtn txt)
22136 ;; Prepare the variables needed in the eval of the compiled format
22137 (setq time (cond (s2 (concat s1 "-" s2))
22138 (s1 (concat s1 "......"))
22139 (t ""))
22140 extra (or extra "")
22141 category (if (symbolp category) (symbol-name category) category))
22142 ;; Evaluate the compiled format
22143 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
22145 ;; And finally add the text properties
22146 (org-add-props rtn nil
22147 'org-category (downcase category) 'tags tags
22148 'org-highest-priority org-highest-priority
22149 'org-lowest-priority org-lowest-priority
22150 'prefix-length (- (length rtn) (length txt))
22151 'time-of-day time-of-day
22152 'txt txt
22153 'time time
22154 'extra extra
22155 'dotime dotime))))
22157 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
22158 (defvar org-agenda-sorting-strategy-selected nil)
22160 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
22161 (catch 'exit
22162 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
22163 ((and todayp (member 'today (car org-agenda-time-grid))))
22164 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
22165 ((member 'weekly (car org-agenda-time-grid)))
22166 (t (throw 'exit list)))
22167 (let* ((have (delq nil (mapcar
22168 (lambda (x) (get-text-property 1 'time-of-day x))
22169 list)))
22170 (string (nth 1 org-agenda-time-grid))
22171 (gridtimes (nth 2 org-agenda-time-grid))
22172 (req (car org-agenda-time-grid))
22173 (remove (member 'remove-match req))
22174 new time)
22175 (if (and (member 'require-timed req) (not have))
22176 ;; don't show empty grid
22177 (throw 'exit list))
22178 (while (setq time (pop gridtimes))
22179 (unless (and remove (member time have))
22180 (setq time (int-to-string time))
22181 (push (org-format-agenda-item
22182 nil string "" nil
22183 (concat (substring time 0 -2) ":" (substring time -2)))
22184 new)
22185 (put-text-property
22186 1 (length (car new)) 'face 'org-time-grid (car new))))
22187 (if (member 'time-up org-agenda-sorting-strategy-selected)
22188 (append new list)
22189 (append list new)))))
22191 (defun org-compile-prefix-format (key)
22192 "Compile the prefix format into a Lisp form that can be evaluated.
22193 The resulting form is returned and stored in the variable
22194 `org-prefix-format-compiled'."
22195 (setq org-prefix-has-time nil org-prefix-has-tag nil)
22196 (let ((s (cond
22197 ((stringp org-agenda-prefix-format)
22198 org-agenda-prefix-format)
22199 ((assq key org-agenda-prefix-format)
22200 (cdr (assq key org-agenda-prefix-format)))
22201 (t " %-12:c%?-12t% s")))
22202 (start 0)
22203 varform vars var e c f opt)
22204 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
22205 s start)
22206 (setq var (cdr (assoc (match-string 4 s)
22207 '(("c" . category) ("t" . time) ("s" . extra)
22208 ("T" . tag))))
22209 c (or (match-string 3 s) "")
22210 opt (match-beginning 1)
22211 start (1+ (match-beginning 0)))
22212 (if (equal var 'time) (setq org-prefix-has-time t))
22213 (if (equal var 'tag) (setq org-prefix-has-tag t))
22214 (setq f (concat "%" (match-string 2 s) "s"))
22215 (if opt
22216 (setq varform
22217 `(if (equal "" ,var)
22219 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
22220 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
22221 (setq s (replace-match "%s" t nil s))
22222 (push varform vars))
22223 (setq vars (nreverse vars))
22224 (setq org-prefix-format-compiled `(format ,s ,@vars))))
22226 (defun org-set-sorting-strategy (key)
22227 (if (symbolp (car org-agenda-sorting-strategy))
22228 ;; the old format
22229 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
22230 (setq org-agenda-sorting-strategy-selected
22231 (or (cdr (assq key org-agenda-sorting-strategy))
22232 (cdr (assq 'agenda org-agenda-sorting-strategy))
22233 '(time-up category-keep priority-down)))))
22235 (defun org-get-time-of-day (s &optional string mod24)
22236 "Check string S for a time of day.
22237 If found, return it as a military time number between 0 and 2400.
22238 If not found, return nil.
22239 The optional STRING argument forces conversion into a 5 character wide string
22240 HH:MM."
22241 (save-match-data
22242 (when
22243 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
22244 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
22245 (let* ((h (string-to-number (match-string 1 s)))
22246 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
22247 (ampm (if (match-end 4) (downcase (match-string 4 s))))
22248 (am-p (equal ampm "am"))
22249 (h1 (cond ((not ampm) h)
22250 ((= h 12) (if am-p 0 12))
22251 (t (+ h (if am-p 0 12)))))
22252 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
22253 (mod h1 24) h1))
22254 (t0 (+ (* 100 h2) m))
22255 (t1 (concat (if (>= h1 24) "+" " ")
22256 (if (< t0 100) "0" "")
22257 (if (< t0 10) "0" "")
22258 (int-to-string t0))))
22259 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
22261 (defun org-finalize-agenda-entries (list &optional nosort)
22262 "Sort and concatenate the agenda items."
22263 (setq list (mapcar 'org-agenda-highlight-todo list))
22264 (if nosort
22265 list
22266 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
22268 (defun org-agenda-highlight-todo (x)
22269 (let (re pl)
22270 (if (eq x 'line)
22271 (save-excursion
22272 (beginning-of-line 1)
22273 (setq re (get-text-property (point) 'org-todo-regexp))
22274 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
22275 (when (looking-at (concat "[ \t]*\\.*" re " +"))
22276 (add-text-properties (match-beginning 0) (match-end 0)
22277 (list 'face (org-get-todo-face 0)))
22278 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
22279 (delete-region (match-beginning 1) (1- (match-end 0)))
22280 (goto-char (match-beginning 1))
22281 (insert (format org-agenda-todo-keyword-format s)))))
22282 (setq re (concat (get-text-property 0 'org-todo-regexp x))
22283 pl (get-text-property 0 'prefix-length x))
22284 (when (and re
22285 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
22286 x (or pl 0)) pl))
22287 (add-text-properties
22288 (or (match-end 1) (match-end 0)) (match-end 0)
22289 (list 'face (org-get-todo-face (match-string 2 x)))
22291 (setq x (concat (substring x 0 (match-end 1))
22292 (format org-agenda-todo-keyword-format
22293 (match-string 2 x))
22295 (substring x (match-end 3)))))
22296 x)))
22298 (defsubst org-cmp-priority (a b)
22299 "Compare the priorities of string A and B."
22300 (let ((pa (or (get-text-property 1 'priority a) 0))
22301 (pb (or (get-text-property 1 'priority b) 0)))
22302 (cond ((> pa pb) +1)
22303 ((< pa pb) -1)
22304 (t nil))))
22306 (defsubst org-cmp-category (a b)
22307 "Compare the string values of categories of strings A and B."
22308 (let ((ca (or (get-text-property 1 'org-category a) ""))
22309 (cb (or (get-text-property 1 'org-category b) "")))
22310 (cond ((string-lessp ca cb) -1)
22311 ((string-lessp cb ca) +1)
22312 (t nil))))
22314 (defsubst org-cmp-tag (a b)
22315 "Compare the string values of categories of strings A and B."
22316 (let ((ta (car (last (get-text-property 1 'tags a))))
22317 (tb (car (last (get-text-property 1 'tags b)))))
22318 (cond ((not ta) +1)
22319 ((not tb) -1)
22320 ((string-lessp ta tb) -1)
22321 ((string-lessp tb ta) +1)
22322 (t nil))))
22324 (defsubst org-cmp-time (a b)
22325 "Compare the time-of-day values of strings A and B."
22326 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
22327 (ta (or (get-text-property 1 'time-of-day a) def))
22328 (tb (or (get-text-property 1 'time-of-day b) def)))
22329 (cond ((< ta tb) -1)
22330 ((< tb ta) +1)
22331 (t nil))))
22333 (defun org-entries-lessp (a b)
22334 "Predicate for sorting agenda entries."
22335 ;; The following variables will be used when the form is evaluated.
22336 ;; So even though the compiler complains, keep them.
22337 (let* ((time-up (org-cmp-time a b))
22338 (time-down (if time-up (- time-up) nil))
22339 (priority-up (org-cmp-priority a b))
22340 (priority-down (if priority-up (- priority-up) nil))
22341 (category-up (org-cmp-category a b))
22342 (category-down (if category-up (- category-up) nil))
22343 (category-keep (if category-up +1 nil))
22344 (tag-up (org-cmp-tag a b))
22345 (tag-down (if tag-up (- tag-up) nil)))
22346 (cdr (assoc
22347 (eval (cons 'or org-agenda-sorting-strategy-selected))
22348 '((-1 . t) (1 . nil) (nil . nil))))))
22350 ;;; Agenda restriction lock
22352 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
22353 "Overlay to mark the headline to which arenda commands are restricted.")
22354 (org-overlay-put org-agenda-restriction-lock-overlay
22355 'face 'org-agenda-restriction-lock)
22356 (org-overlay-put org-agenda-restriction-lock-overlay
22357 'help-echo "Agendas are currently limited to this subtree.")
22358 (org-detach-overlay org-agenda-restriction-lock-overlay)
22359 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
22360 "Overlay marking the agenda restriction line in speedbar.")
22361 (org-overlay-put org-speedbar-restriction-lock-overlay
22362 'face 'org-agenda-restriction-lock)
22363 (org-overlay-put org-speedbar-restriction-lock-overlay
22364 'help-echo "Agendas are currently limited to this item.")
22365 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22367 (defun org-agenda-set-restriction-lock (&optional type)
22368 "Set restriction lock for agenda, to current subtree or file.
22369 Restriction will be the file if TYPE is `file', or if type is the
22370 universal prefix '(4), or if the cursor is before the first headline
22371 in the file. Otherwise, restriction will be to the current subtree."
22372 (interactive "P")
22373 (and (equal type '(4)) (setq type 'file))
22374 (setq type (cond
22375 (type type)
22376 ((org-at-heading-p) 'subtree)
22377 ((condition-case nil (org-back-to-heading t) (error nil))
22378 'subtree)
22379 (t 'file)))
22380 (if (eq type 'subtree)
22381 (progn
22382 (setq org-agenda-restrict t)
22383 (setq org-agenda-overriding-restriction 'subtree)
22384 (put 'org-agenda-files 'org-restrict
22385 (list (buffer-file-name (buffer-base-buffer))))
22386 (org-back-to-heading t)
22387 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22388 (move-marker org-agenda-restrict-begin (point))
22389 (move-marker org-agenda-restrict-end
22390 (save-excursion (org-end-of-subtree t)))
22391 (message "Locking agenda restriction to subtree"))
22392 (put 'org-agenda-files 'org-restrict
22393 (list (buffer-file-name (buffer-base-buffer))))
22394 (setq org-agenda-restrict nil)
22395 (setq org-agenda-overriding-restriction 'file)
22396 (move-marker org-agenda-restrict-begin nil)
22397 (move-marker org-agenda-restrict-end nil)
22398 (message "Locking agenda restriction to file"))
22399 (setq current-prefix-arg nil)
22400 (org-agenda-maybe-redo))
22402 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22403 "Remove the agenda restriction lock."
22404 (interactive "P")
22405 (org-detach-overlay org-agenda-restriction-lock-overlay)
22406 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22407 (setq org-agenda-overriding-restriction nil)
22408 (setq org-agenda-restrict nil)
22409 (put 'org-agenda-files 'org-restrict nil)
22410 (move-marker org-agenda-restrict-begin nil)
22411 (move-marker org-agenda-restrict-end nil)
22412 (setq current-prefix-arg nil)
22413 (message "Agenda restriction lock removed")
22414 (or noupdate (org-agenda-maybe-redo)))
22416 (defun org-agenda-maybe-redo ()
22417 "If there is any window showing the agenda view, update it."
22418 (let ((w (get-buffer-window org-agenda-buffer-name t))
22419 (w0 (selected-window)))
22420 (when w
22421 (select-window w)
22422 (org-agenda-redo)
22423 (select-window w0)
22424 (if org-agenda-overriding-restriction
22425 (message "Agenda view shifted to new %s restriction"
22426 org-agenda-overriding-restriction)
22427 (message "Agenda restriction lock removed")))))
22429 ;;; Agenda commands
22431 (defun org-agenda-check-type (error &rest types)
22432 "Check if agenda buffer is of allowed type.
22433 If ERROR is non-nil, throw an error, otherwise just return nil."
22434 (if (memq org-agenda-type types)
22436 (if error
22437 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22438 nil)))
22440 (defun org-agenda-quit ()
22441 "Exit agenda by removing the window or the buffer."
22442 (interactive)
22443 (let ((buf (current-buffer)))
22444 (if (not (one-window-p)) (delete-window))
22445 (kill-buffer buf)
22446 (org-agenda-reset-markers)
22447 (org-columns-remove-overlays))
22448 ;; Maybe restore the pre-agenda window configuration.
22449 (and org-agenda-restore-windows-after-quit
22450 (not (eq org-agenda-window-setup 'other-frame))
22451 org-pre-agenda-window-conf
22452 (set-window-configuration org-pre-agenda-window-conf)))
22454 (defun org-agenda-exit ()
22455 "Exit agenda by removing the window or the buffer.
22456 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22457 Org-mode buffers visited directly by the user will not be touched."
22458 (interactive)
22459 (org-release-buffers org-agenda-new-buffers)
22460 (setq org-agenda-new-buffers nil)
22461 (org-agenda-quit))
22463 (defun org-agenda-execute (arg)
22464 "Execute another agenda command, keeping same window.\\<global-map>
22465 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22466 (interactive "P")
22467 (let ((org-agenda-window-setup 'current-window))
22468 (org-agenda arg)))
22470 (defun org-save-all-org-buffers ()
22471 "Save all Org-mode buffers without user confirmation."
22472 (interactive)
22473 (message "Saving all Org-mode buffers...")
22474 (save-some-buffers t 'org-mode-p)
22475 (message "Saving all Org-mode buffers... done"))
22477 (defun org-agenda-redo ()
22478 "Rebuild Agenda.
22479 When this is the global TODO list, a prefix argument will be interpreted."
22480 (interactive)
22481 (let* ((org-agenda-keep-modes t)
22482 (line (org-current-line))
22483 (window-line (- line (org-current-line (window-start))))
22484 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22485 (message "Rebuilding agenda buffer...")
22486 (org-let lprops '(eval org-agenda-redo-command))
22487 (setq org-agenda-undo-list nil
22488 org-agenda-pending-undo-list nil)
22489 (message "Rebuilding agenda buffer...done")
22490 (goto-line line)
22491 (recenter window-line)))
22493 (defun org-agenda-manipulate-query-add ()
22494 "Manipulate the query by adding a search term with positive selection.
22495 Positive selection means, the term must be matched for selection of an entry."
22496 (interactive)
22497 (org-agenda-manipulate-query ?\[))
22498 (defun org-agenda-manipulate-query-subtract ()
22499 "Manipulate the query by adding a search term with negative selection.
22500 Negative selection means, term must not be matched for selection of an entry."
22501 (interactive)
22502 (org-agenda-manipulate-query ?\]))
22503 (defun org-agenda-manipulate-query-add-re ()
22504 "Manipulate the query by adding a search regexp with positive selection.
22505 Positive selection means, the regexp must match for selection of an entry."
22506 (interactive)
22507 (org-agenda-manipulate-query ?\{))
22508 (defun org-agenda-manipulate-query-subtract-re ()
22509 "Manipulate the query by adding a search regexp with negative selection.
22510 Negative selection means, regexp must not match for selection of an entry."
22511 (interactive)
22512 (org-agenda-manipulate-query ?\}))
22513 (defun org-agenda-manipulate-query (char)
22514 (cond
22515 ((eq org-agenda-type 'search)
22516 (org-add-to-string
22517 'org-agenda-query-string
22518 (cdr (assoc char '((?\[ . " +") (?\] . " -")
22519 (?\{ . " +{}") (?\} . " -{}")))))
22520 (setq org-agenda-redo-command
22521 (list 'org-search-view
22522 org-todo-only
22523 org-agenda-query-string
22524 (+ (length org-agenda-query-string)
22525 (if (member char '(?\{ ?\})) 0 1))))
22526 (set-register org-agenda-query-register org-agenda-query-string)
22527 (org-agenda-redo))
22528 (t (error "Canot manipulate query for %s-type agenda buffers"
22529 org-agenda-type))))
22531 (defun org-add-to-string (var string)
22532 (set var (concat (symbol-value var) string)))
22534 (defun org-agenda-goto-date (date)
22535 "Jump to DATE in agenda."
22536 (interactive (list (org-read-date)))
22537 (org-agenda-list nil date))
22539 (defun org-agenda-goto-today ()
22540 "Go to today."
22541 (interactive)
22542 (org-agenda-check-type t 'timeline 'agenda)
22543 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22544 (cond
22545 (tdpos (goto-char tdpos))
22546 ((eq org-agenda-type 'agenda)
22547 (let* ((sd (time-to-days
22548 (time-subtract (current-time)
22549 (list 0 (* 3600 org-extend-today-until) 0))))
22550 (comp (org-agenda-compute-time-span sd org-agenda-span))
22551 (org-agenda-overriding-arguments org-agenda-last-arguments))
22552 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22553 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22554 (org-agenda-redo)
22555 (org-agenda-find-same-or-today-or-agenda)))
22556 (t (error "Cannot find today")))))
22558 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22559 (goto-char
22560 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22561 (text-property-any (point-min) (point-max) 'org-today t)
22562 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22563 (point-min))))
22565 (defun org-agenda-later (arg)
22566 "Go forward in time by thee current span.
22567 With prefix ARG, go forward that many times the current span."
22568 (interactive "p")
22569 (org-agenda-check-type t 'agenda)
22570 (let* ((span org-agenda-span)
22571 (sd org-starting-day)
22572 (greg (calendar-gregorian-from-absolute sd))
22573 (cnt (get-text-property (point) 'org-day-cnt))
22574 greg2 nd)
22575 (cond
22576 ((eq span 'day)
22577 (setq sd (+ arg sd) nd 1))
22578 ((eq span 'week)
22579 (setq sd (+ (* 7 arg) sd) nd 7))
22580 ((eq span 'month)
22581 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22582 sd (calendar-absolute-from-gregorian greg2))
22583 (setcar greg2 (1+ (car greg2)))
22584 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22585 ((eq span 'year)
22586 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22587 sd (calendar-absolute-from-gregorian greg2))
22588 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22589 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22590 (let ((org-agenda-overriding-arguments
22591 (list (car org-agenda-last-arguments) sd nd t)))
22592 (org-agenda-redo)
22593 (org-agenda-find-same-or-today-or-agenda cnt))))
22595 (defun org-agenda-earlier (arg)
22596 "Go backward in time by the current span.
22597 With prefix ARG, go backward that many times the current span."
22598 (interactive "p")
22599 (org-agenda-later (- arg)))
22601 (defun org-agenda-day-view (&optional day-of-year)
22602 "Switch to daily view for agenda.
22603 With argument DAY-OF-YEAR, switch to that day of the year."
22604 (interactive "P")
22605 (setq org-agenda-ndays 1)
22606 (org-agenda-change-time-span 'day day-of-year))
22607 (defun org-agenda-week-view (&optional iso-week)
22608 "Switch to daily view for agenda.
22609 With argument ISO-WEEK, switch to the corresponding ISO week.
22610 If ISO-WEEK has more then 2 digits, only the last two encode the
22611 week. Any digits before this encode a year. So 200712 means
22612 week 12 of year 2007. Years in the range 1938-2037 can also be
22613 written as 2-digit years."
22614 (interactive "P")
22615 (setq org-agenda-ndays 7)
22616 (org-agenda-change-time-span 'week iso-week))
22617 (defun org-agenda-month-view (&optional month)
22618 "Switch to daily view for agenda.
22619 With argument MONTH, switch to that month."
22620 (interactive "P")
22621 ;; FIXME: allow month like 812 to mean 2008 december
22622 (org-agenda-change-time-span 'month month))
22623 (defun org-agenda-year-view (&optional year)
22624 "Switch to daily view for agenda.
22625 With argument YEAR, switch to that year.
22626 If MONTH has more then 2 digits, only the last two encode the
22627 month. Any digits before this encode a year. So 200712 means
22628 December year 2007. Years in the range 1938-2037 can also be
22629 written as 2-digit years."
22630 (interactive "P")
22631 (when year
22632 (setq year (org-small-year-to-year year)))
22633 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22634 (org-agenda-change-time-span 'year year)
22635 (error "Abort")))
22637 (defun org-agenda-change-time-span (span &optional n)
22638 "Change the agenda view to SPAN.
22639 SPAN may be `day', `week', `month', `year'."
22640 (org-agenda-check-type t 'agenda)
22641 (if (and (not n) (equal org-agenda-span span))
22642 (error "Viewing span is already \"%s\"" span))
22643 (let* ((sd (or (get-text-property (point) 'day)
22644 org-starting-day))
22645 (computed (org-agenda-compute-time-span sd span n))
22646 (org-agenda-overriding-arguments
22647 (list (car org-agenda-last-arguments)
22648 (car computed) (cdr computed) t)))
22649 (org-agenda-redo)
22650 (org-agenda-find-same-or-today-or-agenda))
22651 (org-agenda-set-mode-name)
22652 (message "Switched to %s view" span))
22654 (defun org-agenda-compute-time-span (sd span &optional n)
22655 "Compute starting date and number of days for agenda.
22656 SPAN may be `day', `week', `month', `year'. The return value
22657 is a cons cell with the starting date and the number of days,
22658 so that the date SD will be in that range."
22659 (let* ((greg (calendar-gregorian-from-absolute sd))
22660 (dg (nth 1 greg))
22661 (mg (car greg))
22662 (yg (nth 2 greg))
22663 nd w1 y1 m1 thisweek)
22664 (cond
22665 ((eq span 'day)
22666 (when n
22667 (setq sd (+ (calendar-absolute-from-gregorian
22668 (list mg 1 yg))
22669 n -1)))
22670 (setq nd 1))
22671 ((eq span 'week)
22672 (let* ((nt (calendar-day-of-week
22673 (calendar-gregorian-from-absolute sd)))
22674 (d (if org-agenda-start-on-weekday
22675 (- nt org-agenda-start-on-weekday)
22676 0)))
22677 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22678 (when n
22679 (require 'cal-iso)
22680 (setq thisweek (car (calendar-iso-from-absolute sd)))
22681 (when (> n 99)
22682 (setq y1 (org-small-year-to-year (/ n 100))
22683 n (mod n 100)))
22684 (setq sd
22685 (calendar-absolute-from-iso
22686 (list n 1
22687 (or y1 (nth 2 (calendar-iso-from-absolute sd)))))))
22688 (setq nd 7)))
22689 ((eq span 'month)
22690 (when (and n (> n 99))
22691 (setq y1 (org-small-year-to-year (/ n 100))
22692 n (mod n 100)))
22693 (setq sd (calendar-absolute-from-gregorian
22694 (list (or n mg) 1 (or y1 yg)))
22695 nd (- (calendar-absolute-from-gregorian
22696 (list (1+ (or n mg)) 1 (or y1 yg)))
22697 sd)))
22698 ((eq span 'year)
22699 (setq sd (calendar-absolute-from-gregorian
22700 (list 1 1 (or n yg)))
22701 nd (- (calendar-absolute-from-gregorian
22702 (list 1 1 (1+ (or n yg))))
22703 sd))))
22704 (cons sd nd)))
22706 (defun org-days-to-iso-week (days)
22707 "Return the iso week number."
22708 (require 'cal-iso)
22709 (car (calendar-iso-from-absolute days)))
22711 (defun org-small-year-to-year (year)
22712 "Convert 2-digit years into 4-digit years.
22713 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
22714 The year 2000 cannot be abbreviated. Any year lager than 99
22715 is retrned unchanged."
22716 (if (< year 38)
22717 (setq year (+ 2000 year))
22718 (if (< year 100)
22719 (setq year (+ 1900 year))))
22720 year)
22722 ;; FIXME: does not work if user makes date format that starts with a blank
22723 (defun org-agenda-next-date-line (&optional arg)
22724 "Jump to the next line indicating a date in agenda buffer."
22725 (interactive "p")
22726 (org-agenda-check-type t 'agenda 'timeline)
22727 (beginning-of-line 1)
22728 (if (looking-at "^\\S-") (forward-char 1))
22729 (if (not (re-search-forward "^\\S-" nil t arg))
22730 (progn
22731 (backward-char 1)
22732 (error "No next date after this line in this buffer")))
22733 (goto-char (match-beginning 0)))
22735 (defun org-agenda-previous-date-line (&optional arg)
22736 "Jump to the previous line indicating a date in agenda buffer."
22737 (interactive "p")
22738 (org-agenda-check-type t 'agenda 'timeline)
22739 (beginning-of-line 1)
22740 (if (not (re-search-backward "^\\S-" nil t arg))
22741 (error "No previous date before this line in this buffer")))
22743 ;; Initialize the highlight
22744 (defvar org-hl (org-make-overlay 1 1))
22745 (org-overlay-put org-hl 'face 'highlight)
22747 (defun org-highlight (begin end &optional buffer)
22748 "Highlight a region with overlay."
22749 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22750 org-hl begin end (or buffer (current-buffer))))
22752 (defun org-unhighlight ()
22753 "Detach overlay INDEX."
22754 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22756 ;; FIXME this is currently not used.
22757 (defun org-highlight-until-next-command (beg end &optional buffer)
22758 (org-highlight beg end buffer)
22759 (add-hook 'pre-command-hook 'org-unhighlight-once))
22760 (defun org-unhighlight-once ()
22761 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22762 (org-unhighlight))
22764 (defun org-agenda-follow-mode ()
22765 "Toggle follow mode in an agenda buffer."
22766 (interactive)
22767 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22768 (org-agenda-set-mode-name)
22769 (message "Follow mode is %s"
22770 (if org-agenda-follow-mode "on" "off")))
22772 (defun org-agenda-log-mode ()
22773 "Toggle log mode in an agenda buffer."
22774 (interactive)
22775 (org-agenda-check-type t 'agenda 'timeline)
22776 (setq org-agenda-show-log (not org-agenda-show-log))
22777 (org-agenda-set-mode-name)
22778 (org-agenda-redo)
22779 (message "Log mode is %s"
22780 (if org-agenda-show-log "on" "off")))
22782 (defun org-agenda-toggle-diary ()
22783 "Toggle diary inclusion in an agenda buffer."
22784 (interactive)
22785 (org-agenda-check-type t 'agenda)
22786 (setq org-agenda-include-diary (not org-agenda-include-diary))
22787 (org-agenda-redo)
22788 (org-agenda-set-mode-name)
22789 (message "Diary inclusion turned %s"
22790 (if org-agenda-include-diary "on" "off")))
22792 (defun org-agenda-toggle-time-grid ()
22793 "Toggle time grid in an agenda buffer."
22794 (interactive)
22795 (org-agenda-check-type t 'agenda)
22796 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22797 (org-agenda-redo)
22798 (org-agenda-set-mode-name)
22799 (message "Time-grid turned %s"
22800 (if org-agenda-use-time-grid "on" "off")))
22802 (defun org-agenda-set-mode-name ()
22803 "Set the mode name to indicate all the small mode settings."
22804 (setq mode-name
22805 (concat "Org-Agenda"
22806 (if (equal org-agenda-ndays 1) " Day" "")
22807 (if (equal org-agenda-ndays 7) " Week" "")
22808 (if org-agenda-follow-mode " Follow" "")
22809 (if org-agenda-include-diary " Diary" "")
22810 (if org-agenda-use-time-grid " Grid" "")
22811 (if org-agenda-show-log " Log" "")))
22812 (force-mode-line-update))
22814 (defun org-agenda-post-command-hook ()
22815 (and (eolp) (not (bolp)) (backward-char 1))
22816 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22817 (if (and org-agenda-follow-mode
22818 (get-text-property (point) 'org-marker))
22819 (org-agenda-show)))
22821 (defun org-agenda-show-priority ()
22822 "Show the priority of the current item.
22823 This priority is composed of the main priority given with the [#A] cookies,
22824 and by additional input from the age of a schedules or deadline entry."
22825 (interactive)
22826 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22827 (message "Priority is %d" (if pri pri -1000))))
22829 (defun org-agenda-show-tags ()
22830 "Show the tags applicable to the current item."
22831 (interactive)
22832 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22833 (if tags
22834 (message "Tags are :%s:"
22835 (org-no-properties (mapconcat 'identity tags ":")))
22836 (message "No tags associated with this line"))))
22838 (defun org-agenda-goto (&optional highlight)
22839 "Go to the Org-mode file which contains the item at point."
22840 (interactive)
22841 (let* ((marker (or (get-text-property (point) 'org-marker)
22842 (org-agenda-error)))
22843 (buffer (marker-buffer marker))
22844 (pos (marker-position marker)))
22845 (switch-to-buffer-other-window buffer)
22846 (widen)
22847 (goto-char pos)
22848 (when (org-mode-p)
22849 (org-show-context 'agenda)
22850 (save-excursion
22851 (and (outline-next-heading)
22852 (org-flag-heading nil)))) ; show the next heading
22853 (recenter (/ (window-height) 2))
22854 (run-hooks 'org-agenda-after-show-hook)
22855 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22857 (defvar org-agenda-after-show-hook nil
22858 "Normal hook run after an item has been shown from the agenda.
22859 Point is in the buffer where the item originated.")
22861 (defun org-agenda-kill ()
22862 "Kill the entry or subtree belonging to the current agenda entry."
22863 (interactive)
22864 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22865 (let* ((marker (or (get-text-property (point) 'org-marker)
22866 (org-agenda-error)))
22867 (buffer (marker-buffer marker))
22868 (pos (marker-position marker))
22869 (type (get-text-property (point) 'type))
22870 dbeg dend (n 0) conf)
22871 (org-with-remote-undo buffer
22872 (with-current-buffer buffer
22873 (save-excursion
22874 (goto-char pos)
22875 (if (and (org-mode-p) (not (member type '("sexp"))))
22876 (setq dbeg (progn (org-back-to-heading t) (point))
22877 dend (org-end-of-subtree t t))
22878 (setq dbeg (point-at-bol)
22879 dend (min (point-max) (1+ (point-at-eol)))))
22880 (goto-char dbeg)
22881 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22882 (setq conf (or (eq t org-agenda-confirm-kill)
22883 (and (numberp org-agenda-confirm-kill)
22884 (> n org-agenda-confirm-kill))))
22885 (and conf
22886 (not (y-or-n-p
22887 (format "Delete entry with %d lines in buffer \"%s\"? "
22888 n (buffer-name buffer))))
22889 (error "Abort"))
22890 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22891 (with-current-buffer buffer (delete-region dbeg dend))
22892 (message "Agenda item and source killed"))))
22894 (defun org-agenda-archive ()
22895 "Kill the entry or subtree belonging to the current agenda entry."
22896 (interactive)
22897 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22898 (let* ((marker (or (get-text-property (point) 'org-marker)
22899 (org-agenda-error)))
22900 (buffer (marker-buffer marker))
22901 (pos (marker-position marker)))
22902 (org-with-remote-undo buffer
22903 (with-current-buffer buffer
22904 (if (org-mode-p)
22905 (save-excursion
22906 (goto-char pos)
22907 (org-remove-subtree-entries-from-agenda)
22908 (org-back-to-heading t)
22909 (org-archive-subtree))
22910 (error "Archiving works only in Org-mode files"))))))
22912 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22913 "Remove all lines in the agenda that correspond to a given subtree.
22914 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22915 If this information is not given, the function uses the tree at point."
22916 (let ((buf (or buf (current-buffer))) m p)
22917 (save-excursion
22918 (unless (and beg end)
22919 (org-back-to-heading t)
22920 (setq beg (point))
22921 (org-end-of-subtree t)
22922 (setq end (point)))
22923 (set-buffer (get-buffer org-agenda-buffer-name))
22924 (save-excursion
22925 (goto-char (point-max))
22926 (beginning-of-line 1)
22927 (while (not (bobp))
22928 (when (and (setq m (get-text-property (point) 'org-marker))
22929 (equal buf (marker-buffer m))
22930 (setq p (marker-position m))
22931 (>= p beg)
22932 (<= p end))
22933 (let ((inhibit-read-only t))
22934 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22935 (beginning-of-line 0))))))
22937 (defun org-agenda-open-link ()
22938 "Follow the link in the current line, if any."
22939 (interactive)
22940 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22941 (save-excursion
22942 (save-restriction
22943 (narrow-to-region (point-at-bol) (point-at-eol))
22944 (org-open-at-point))))
22946 (defun org-agenda-copy-local-variable (var)
22947 "Get a variable from a referenced buffer and install it here."
22948 (let ((m (get-text-property (point) 'org-marker)))
22949 (when (and m (buffer-live-p (marker-buffer m)))
22950 (org-set-local var (with-current-buffer (marker-buffer m)
22951 (symbol-value var))))))
22953 (defun org-agenda-switch-to (&optional delete-other-windows)
22954 "Go to the Org-mode file which contains the item at point."
22955 (interactive)
22956 (let* ((marker (or (get-text-property (point) 'org-marker)
22957 (org-agenda-error)))
22958 (buffer (marker-buffer marker))
22959 (pos (marker-position marker)))
22960 (switch-to-buffer buffer)
22961 (and delete-other-windows (delete-other-windows))
22962 (widen)
22963 (goto-char pos)
22964 (when (org-mode-p)
22965 (org-show-context 'agenda)
22966 (save-excursion
22967 (and (outline-next-heading)
22968 (org-flag-heading nil)))))) ; show the next heading
22970 (defun org-agenda-goto-mouse (ev)
22971 "Go to the Org-mode file which contains the item at the mouse click."
22972 (interactive "e")
22973 (mouse-set-point ev)
22974 (org-agenda-goto))
22976 (defun org-agenda-show ()
22977 "Display the Org-mode file which contains the item at point."
22978 (interactive)
22979 (let ((win (selected-window)))
22980 (org-agenda-goto t)
22981 (select-window win)))
22983 (defun org-agenda-recenter (arg)
22984 "Display the Org-mode file which contains the item at point and recenter."
22985 (interactive "P")
22986 (let ((win (selected-window)))
22987 (org-agenda-goto t)
22988 (recenter arg)
22989 (select-window win)))
22991 (defun org-agenda-show-mouse (ev)
22992 "Display the Org-mode file which contains the item at the mouse click."
22993 (interactive "e")
22994 (mouse-set-point ev)
22995 (org-agenda-show))
22997 (defun org-agenda-check-no-diary ()
22998 "Check if the entry is a diary link and abort if yes."
22999 (if (get-text-property (point) 'org-agenda-diary-link)
23000 (org-agenda-error)))
23002 (defun org-agenda-error ()
23003 (error "Command not allowed in this line"))
23005 (defun org-agenda-tree-to-indirect-buffer ()
23006 "Show the subtree corresponding to the current entry in an indirect buffer.
23007 This calls the command `org-tree-to-indirect-buffer' from the original
23008 Org-mode buffer.
23009 With numerical prefix arg ARG, go up to this level and then take that tree.
23010 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
23011 dedicated frame)."
23012 (interactive)
23013 (org-agenda-check-no-diary)
23014 (let* ((marker (or (get-text-property (point) 'org-marker)
23015 (org-agenda-error)))
23016 (buffer (marker-buffer marker))
23017 (pos (marker-position marker)))
23018 (with-current-buffer buffer
23019 (save-excursion
23020 (goto-char pos)
23021 (call-interactively 'org-tree-to-indirect-buffer)))))
23023 (defvar org-last-heading-marker (make-marker)
23024 "Marker pointing to the headline that last changed its TODO state
23025 by a remote command from the agenda.")
23027 (defun org-agenda-todo-nextset ()
23028 "Switch TODO entry to next sequence."
23029 (interactive)
23030 (org-agenda-todo 'nextset))
23032 (defun org-agenda-todo-previousset ()
23033 "Switch TODO entry to previous sequence."
23034 (interactive)
23035 (org-agenda-todo 'previousset))
23037 (defun org-agenda-todo (&optional arg)
23038 "Cycle TODO state of line at point, also in Org-mode file.
23039 This changes the line at point, all other lines in the agenda referring to
23040 the same tree node, and the headline of the tree node in the Org-mode file."
23041 (interactive "P")
23042 (org-agenda-check-no-diary)
23043 (let* ((col (current-column))
23044 (marker (or (get-text-property (point) 'org-marker)
23045 (org-agenda-error)))
23046 (buffer (marker-buffer marker))
23047 (pos (marker-position marker))
23048 (hdmarker (get-text-property (point) 'org-hd-marker))
23049 (inhibit-read-only t)
23050 newhead)
23051 (org-with-remote-undo buffer
23052 (with-current-buffer buffer
23053 (widen)
23054 (goto-char pos)
23055 (org-show-context 'agenda)
23056 (save-excursion
23057 (and (outline-next-heading)
23058 (org-flag-heading nil))) ; show the next heading
23059 (org-todo arg)
23060 (and (bolp) (forward-char 1))
23061 (setq newhead (org-get-heading))
23062 (save-excursion
23063 (org-back-to-heading)
23064 (move-marker org-last-heading-marker (point))))
23065 (beginning-of-line 1)
23066 (save-excursion
23067 (org-agenda-change-all-lines newhead hdmarker 'fixface))
23068 (move-to-column col))))
23070 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
23071 "Change all lines in the agenda buffer which match HDMARKER.
23072 The new content of the line will be NEWHEAD (as modified by
23073 `org-format-agenda-item'). HDMARKER is checked with
23074 `equal' against all `org-hd-marker' text properties in the file.
23075 If FIXFACE is non-nil, the face of each item is modified acording to
23076 the new TODO state."
23077 (let* ((inhibit-read-only t)
23078 props m pl undone-face done-face finish new dotime cat tags)
23079 (save-excursion
23080 (goto-char (point-max))
23081 (beginning-of-line 1)
23082 (while (not finish)
23083 (setq finish (bobp))
23084 (when (and (setq m (get-text-property (point) 'org-hd-marker))
23085 (equal m hdmarker))
23086 (setq props (text-properties-at (point))
23087 dotime (get-text-property (point) 'dotime)
23088 cat (get-text-property (point) 'org-category)
23089 tags (get-text-property (point) 'tags)
23090 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
23091 pl (get-text-property (point) 'prefix-length)
23092 undone-face (get-text-property (point) 'undone-face)
23093 done-face (get-text-property (point) 'done-face))
23094 (move-to-column pl)
23095 (cond
23096 ((equal new "")
23097 (beginning-of-line 1)
23098 (and (looking-at ".*\n?") (replace-match "")))
23099 ((looking-at ".*")
23100 (replace-match new t t)
23101 (beginning-of-line 1)
23102 (add-text-properties (point-at-bol) (point-at-eol) props)
23103 (when fixface
23104 (add-text-properties
23105 (point-at-bol) (point-at-eol)
23106 (list 'face
23107 (if org-last-todo-state-is-todo
23108 undone-face done-face))))
23109 (org-agenda-highlight-todo 'line)
23110 (beginning-of-line 1))
23111 (t (error "Line update did not work"))))
23112 (beginning-of-line 0)))
23113 (org-finalize-agenda)))
23115 (defun org-agenda-align-tags (&optional line)
23116 "Align all tags in agenda items to `org-agenda-tags-column'."
23117 (let ((inhibit-read-only t) l c)
23118 (save-excursion
23119 (goto-char (if line (point-at-bol) (point-min)))
23120 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
23121 (if line (point-at-eol) nil) t)
23122 (add-text-properties
23123 (match-beginning 2) (match-end 2)
23124 (list 'face (delq nil (list 'org-tag (get-text-property
23125 (match-beginning 2) 'face)))))
23126 (setq l (- (match-end 2) (match-beginning 2))
23127 c (if (< org-agenda-tags-column 0)
23128 (- (abs org-agenda-tags-column) l)
23129 org-agenda-tags-column))
23130 (delete-region (match-beginning 1) (match-end 1))
23131 (goto-char (match-beginning 1))
23132 (insert (org-add-props
23133 (make-string (max 1 (- c (current-column))) ?\ )
23134 (text-properties-at (point))))))))
23136 (defun org-agenda-priority-up ()
23137 "Increase the priority of line at point, also in Org-mode file."
23138 (interactive)
23139 (org-agenda-priority 'up))
23141 (defun org-agenda-priority-down ()
23142 "Decrease the priority of line at point, also in Org-mode file."
23143 (interactive)
23144 (org-agenda-priority 'down))
23146 (defun org-agenda-priority (&optional force-direction)
23147 "Set the priority of line at point, also in Org-mode file.
23148 This changes the line at point, all other lines in the agenda referring to
23149 the same tree node, and the headline of the tree node in the Org-mode file."
23150 (interactive)
23151 (org-agenda-check-no-diary)
23152 (let* ((marker (or (get-text-property (point) 'org-marker)
23153 (org-agenda-error)))
23154 (hdmarker (get-text-property (point) 'org-hd-marker))
23155 (buffer (marker-buffer hdmarker))
23156 (pos (marker-position hdmarker))
23157 (inhibit-read-only t)
23158 newhead)
23159 (org-with-remote-undo buffer
23160 (with-current-buffer buffer
23161 (widen)
23162 (goto-char pos)
23163 (org-show-context 'agenda)
23164 (save-excursion
23165 (and (outline-next-heading)
23166 (org-flag-heading nil))) ; show the next heading
23167 (funcall 'org-priority force-direction)
23168 (end-of-line 1)
23169 (setq newhead (org-get-heading)))
23170 (org-agenda-change-all-lines newhead hdmarker)
23171 (beginning-of-line 1))))
23173 (defun org-get-tags-at (&optional pos)
23174 "Get a list of all headline tags applicable at POS.
23175 POS defaults to point. If tags are inherited, the list contains
23176 the targets in the same sequence as the headlines appear, i.e.
23177 the tags of the current headline come last."
23178 (interactive)
23179 (let (tags lastpos)
23180 (save-excursion
23181 (save-restriction
23182 (widen)
23183 (goto-char (or pos (point)))
23184 (save-match-data
23185 (condition-case nil
23186 (progn
23187 (org-back-to-heading t)
23188 (while (not (equal lastpos (point)))
23189 (setq lastpos (point))
23190 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
23191 (setq tags (append (org-split-string
23192 (org-match-string-no-properties 1) ":")
23193 tags)))
23194 (or org-use-tag-inheritance (error ""))
23195 (org-up-heading-all 1)))
23196 (error nil))))
23197 tags)))
23199 ;; FIXME: should fix the tags property of the agenda line.
23200 (defun org-agenda-set-tags ()
23201 "Set tags for the current headline."
23202 (interactive)
23203 (org-agenda-check-no-diary)
23204 (if (and (org-region-active-p) (interactive-p))
23205 (call-interactively 'org-change-tag-in-region)
23206 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23207 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23208 (org-agenda-error)))
23209 (buffer (marker-buffer hdmarker))
23210 (pos (marker-position hdmarker))
23211 (inhibit-read-only t)
23212 newhead)
23213 (org-with-remote-undo buffer
23214 (with-current-buffer buffer
23215 (widen)
23216 (goto-char pos)
23217 (save-excursion
23218 (org-show-context 'agenda))
23219 (save-excursion
23220 (and (outline-next-heading)
23221 (org-flag-heading nil))) ; show the next heading
23222 (goto-char pos)
23223 (call-interactively 'org-set-tags)
23224 (end-of-line 1)
23225 (setq newhead (org-get-heading)))
23226 (org-agenda-change-all-lines newhead hdmarker)
23227 (beginning-of-line 1)))))
23229 (defun org-agenda-toggle-archive-tag ()
23230 "Toggle the archive tag for the current entry."
23231 (interactive)
23232 (org-agenda-check-no-diary)
23233 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23234 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23235 (org-agenda-error)))
23236 (buffer (marker-buffer hdmarker))
23237 (pos (marker-position hdmarker))
23238 (inhibit-read-only t)
23239 newhead)
23240 (org-with-remote-undo buffer
23241 (with-current-buffer buffer
23242 (widen)
23243 (goto-char pos)
23244 (org-show-context 'agenda)
23245 (save-excursion
23246 (and (outline-next-heading)
23247 (org-flag-heading nil))) ; show the next heading
23248 (call-interactively 'org-toggle-archive-tag)
23249 (end-of-line 1)
23250 (setq newhead (org-get-heading)))
23251 (org-agenda-change-all-lines newhead hdmarker)
23252 (beginning-of-line 1))))
23254 (defun org-agenda-date-later (arg &optional what)
23255 "Change the date of this item to one day later."
23256 (interactive "p")
23257 (org-agenda-check-type t 'agenda 'timeline)
23258 (org-agenda-check-no-diary)
23259 (let* ((marker (or (get-text-property (point) 'org-marker)
23260 (org-agenda-error)))
23261 (buffer (marker-buffer marker))
23262 (pos (marker-position marker)))
23263 (org-with-remote-undo buffer
23264 (with-current-buffer buffer
23265 (widen)
23266 (goto-char pos)
23267 (if (not (org-at-timestamp-p))
23268 (error "Cannot find time stamp"))
23269 (org-timestamp-change arg (or what 'day)))
23270 (org-agenda-show-new-time marker org-last-changed-timestamp))
23271 (message "Time stamp changed to %s" org-last-changed-timestamp)))
23273 (defun org-agenda-date-earlier (arg &optional what)
23274 "Change the date of this item to one day earlier."
23275 (interactive "p")
23276 (org-agenda-date-later (- arg) what))
23278 (defun org-agenda-show-new-time (marker stamp &optional prefix)
23279 "Show new date stamp via text properties."
23280 ;; We use text properties to make this undoable
23281 (let ((inhibit-read-only t))
23282 (setq stamp (concat " " prefix " => " stamp))
23283 (save-excursion
23284 (goto-char (point-max))
23285 (while (not (bobp))
23286 (when (equal marker (get-text-property (point) 'org-marker))
23287 (move-to-column (- (window-width) (length stamp)) t)
23288 (if (featurep 'xemacs)
23289 ;; Use `duplicable' property to trigger undo recording
23290 (let ((ex (make-extent nil nil))
23291 (gl (make-glyph stamp)))
23292 (set-glyph-face gl 'secondary-selection)
23293 (set-extent-properties
23294 ex (list 'invisible t 'end-glyph gl 'duplicable t))
23295 (insert-extent ex (1- (point)) (point-at-eol)))
23296 (add-text-properties
23297 (1- (point)) (point-at-eol)
23298 (list 'display (org-add-props stamp nil
23299 'face 'secondary-selection))))
23300 (beginning-of-line 1))
23301 (beginning-of-line 0)))))
23303 (defun org-agenda-date-prompt (arg)
23304 "Change the date of this item. Date is prompted for, with default today.
23305 The prefix ARG is passed to the `org-time-stamp' command and can therefore
23306 be used to request time specification in the time stamp."
23307 (interactive "P")
23308 (org-agenda-check-type t 'agenda 'timeline)
23309 (org-agenda-check-no-diary)
23310 (let* ((marker (or (get-text-property (point) 'org-marker)
23311 (org-agenda-error)))
23312 (buffer (marker-buffer marker))
23313 (pos (marker-position marker)))
23314 (org-with-remote-undo buffer
23315 (with-current-buffer buffer
23316 (widen)
23317 (goto-char pos)
23318 (if (not (org-at-timestamp-p))
23319 (error "Cannot find time stamp"))
23320 (org-time-stamp arg)
23321 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
23323 (defun org-agenda-schedule (arg)
23324 "Schedule the item at point."
23325 (interactive "P")
23326 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags 'search)
23327 (org-agenda-check-no-diary)
23328 (let* ((marker (or (get-text-property (point) 'org-marker)
23329 (org-agenda-error)))
23330 (type (marker-insertion-type marker))
23331 (buffer (marker-buffer marker))
23332 (pos (marker-position marker))
23333 (org-insert-labeled-timestamps-at-point nil)
23335 (when type (message "%s" type) (sit-for 3))
23336 (set-marker-insertion-type marker t)
23337 (org-with-remote-undo buffer
23338 (with-current-buffer buffer
23339 (widen)
23340 (goto-char pos)
23341 (setq ts (org-schedule arg)))
23342 (org-agenda-show-new-time marker ts "S"))
23343 (message "Item scheduled for %s" ts)))
23345 (defun org-agenda-deadline (arg)
23346 "Schedule the item at point."
23347 (interactive "P")
23348 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags 'search)
23349 (org-agenda-check-no-diary)
23350 (let* ((marker (or (get-text-property (point) 'org-marker)
23351 (org-agenda-error)))
23352 (buffer (marker-buffer marker))
23353 (pos (marker-position marker))
23354 (org-insert-labeled-timestamps-at-point nil)
23356 (org-with-remote-undo buffer
23357 (with-current-buffer buffer
23358 (widen)
23359 (goto-char pos)
23360 (setq ts (org-deadline arg)))
23361 (org-agenda-show-new-time marker ts "S"))
23362 (message "Deadline for this item set to %s" ts)))
23364 (defun org-get-heading (&optional no-tags)
23365 "Return the heading of the current entry, without the stars."
23366 (save-excursion
23367 (org-back-to-heading t)
23368 (if (looking-at
23369 (if no-tags
23370 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
23371 "\\*+[ \t]+\\([^\r\n]*\\)"))
23372 (match-string 1) "")))
23374 (defun org-agenda-clock-in (&optional arg)
23375 "Start the clock on the currently selected item."
23376 (interactive "P")
23377 (org-agenda-check-no-diary)
23378 (let* ((marker (or (get-text-property (point) 'org-marker)
23379 (org-agenda-error)))
23380 (pos (marker-position marker)))
23381 (org-with-remote-undo (marker-buffer marker)
23382 (with-current-buffer (marker-buffer marker)
23383 (widen)
23384 (goto-char pos)
23385 (org-clock-in)))))
23387 (defun org-agenda-clock-out (&optional arg)
23388 "Stop the currently running clock."
23389 (interactive "P")
23390 (unless (marker-buffer org-clock-marker)
23391 (error "No running clock"))
23392 (org-with-remote-undo (marker-buffer org-clock-marker)
23393 (org-clock-out)))
23395 (defun org-agenda-clock-cancel (&optional arg)
23396 "Cancel the currently running clock."
23397 (interactive "P")
23398 (unless (marker-buffer org-clock-marker)
23399 (error "No running clock"))
23400 (org-with-remote-undo (marker-buffer org-clock-marker)
23401 (org-clock-cancel)))
23403 (defun org-agenda-diary-entry ()
23404 "Make a diary entry, like the `i' command from the calendar.
23405 All the standard commands work: block, weekly etc."
23406 (interactive)
23407 (org-agenda-check-type t 'agenda 'timeline)
23408 (require 'diary-lib)
23409 (let* ((char (progn
23410 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
23411 (read-char-exclusive)))
23412 (cmd (cdr (assoc char
23413 '((?d . insert-diary-entry)
23414 (?w . insert-weekly-diary-entry)
23415 (?m . insert-monthly-diary-entry)
23416 (?y . insert-yearly-diary-entry)
23417 (?a . insert-anniversary-diary-entry)
23418 (?b . insert-block-diary-entry)
23419 (?c . insert-cyclic-diary-entry)))))
23420 (oldf (symbol-function 'calendar-cursor-to-date))
23421 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
23422 (point (point))
23423 (mark (or (mark t) (point))))
23424 (unless cmd
23425 (error "No command associated with <%c>" char))
23426 (unless (and (get-text-property point 'day)
23427 (or (not (equal ?b char))
23428 (get-text-property mark 'day)))
23429 (error "Don't know which date to use for diary entry"))
23430 ;; We implement this by hacking the `calendar-cursor-to-date' function
23431 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
23432 (let ((calendar-mark-ring
23433 (list (calendar-gregorian-from-absolute
23434 (or (get-text-property mark 'day)
23435 (get-text-property point 'day))))))
23436 (unwind-protect
23437 (progn
23438 (fset 'calendar-cursor-to-date
23439 (lambda (&optional error)
23440 (calendar-gregorian-from-absolute
23441 (get-text-property point 'day))))
23442 (call-interactively cmd))
23443 (fset 'calendar-cursor-to-date oldf)))))
23446 (defun org-agenda-execute-calendar-command (cmd)
23447 "Execute a calendar command from the agenda, with the date associated to
23448 the cursor position."
23449 (org-agenda-check-type t 'agenda 'timeline)
23450 (require 'diary-lib)
23451 (unless (get-text-property (point) 'day)
23452 (error "Don't know which date to use for calendar command"))
23453 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
23454 (point (point))
23455 (date (calendar-gregorian-from-absolute
23456 (get-text-property point 'day)))
23457 ;; the following 3 vars are needed in the calendar
23458 (displayed-day (extract-calendar-day date))
23459 (displayed-month (extract-calendar-month date))
23460 (displayed-year (extract-calendar-year date)))
23461 (unwind-protect
23462 (progn
23463 (fset 'calendar-cursor-to-date
23464 (lambda (&optional error)
23465 (calendar-gregorian-from-absolute
23466 (get-text-property point 'day))))
23467 (call-interactively cmd))
23468 (fset 'calendar-cursor-to-date oldf))))
23470 (defun org-agenda-phases-of-moon ()
23471 "Display the phases of the moon for the 3 months around the cursor date."
23472 (interactive)
23473 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23475 (defun org-agenda-holidays ()
23476 "Display the holidays for the 3 months around the cursor date."
23477 (interactive)
23478 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23480 (defvar calendar-longitude)
23481 (defvar calendar-latitude)
23482 (defvar calendar-location-name)
23484 (defun org-agenda-sunrise-sunset (arg)
23485 "Display sunrise and sunset for the cursor date.
23486 Latitude and longitude can be specified with the variables
23487 `calendar-latitude' and `calendar-longitude'. When called with prefix
23488 argument, latitude and longitude will be prompted for."
23489 (interactive "P")
23490 (require 'solar)
23491 (let ((calendar-longitude (if arg nil calendar-longitude))
23492 (calendar-latitude (if arg nil calendar-latitude))
23493 (calendar-location-name
23494 (if arg "the given coordinates" calendar-location-name)))
23495 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23497 (defun org-agenda-goto-calendar ()
23498 "Open the Emacs calendar with the date at the cursor."
23499 (interactive)
23500 (org-agenda-check-type t 'agenda 'timeline)
23501 (let* ((day (or (get-text-property (point) 'day)
23502 (error "Don't know which date to open in calendar")))
23503 (date (calendar-gregorian-from-absolute day))
23504 (calendar-move-hook nil)
23505 (view-calendar-holidays-initially nil)
23506 (view-diary-entries-initially nil))
23507 (calendar)
23508 (calendar-goto-date date)))
23510 (defun org-calendar-goto-agenda ()
23511 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23512 This is a command that has to be installed in `calendar-mode-map'."
23513 (interactive)
23514 (org-agenda-list nil (calendar-absolute-from-gregorian
23515 (calendar-cursor-to-date))
23516 nil))
23518 (defun org-agenda-convert-date ()
23519 (interactive)
23520 (org-agenda-check-type t 'agenda 'timeline)
23521 (let ((day (get-text-property (point) 'day))
23522 date s)
23523 (unless day
23524 (error "Don't know which date to convert"))
23525 (setq date (calendar-gregorian-from-absolute day))
23526 (setq s (concat
23527 "Gregorian: " (calendar-date-string date) "\n"
23528 "ISO: " (calendar-iso-date-string date) "\n"
23529 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23530 "Julian: " (calendar-julian-date-string date) "\n"
23531 "Astron. JD: " (calendar-astro-date-string date)
23532 " (Julian date number at noon UTC)\n"
23533 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23534 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23535 "French: " (calendar-french-date-string date) "\n"
23536 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23537 "Mayan: " (calendar-mayan-date-string date) "\n"
23538 "Coptic: " (calendar-coptic-date-string date) "\n"
23539 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23540 "Persian: " (calendar-persian-date-string date) "\n"
23541 "Chinese: " (calendar-chinese-date-string date) "\n"))
23542 (with-output-to-temp-buffer "*Dates*"
23543 (princ s))
23544 (if (fboundp 'fit-window-to-buffer)
23545 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23548 ;;;; Embedded LaTeX
23550 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23551 "Keymap for the minor `org-cdlatex-mode'.")
23553 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23554 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23555 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23556 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23557 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23559 (defvar org-cdlatex-texmathp-advice-is-done nil
23560 "Flag remembering if we have applied the advice to texmathp already.")
23562 (define-minor-mode org-cdlatex-mode
23563 "Toggle the minor `org-cdlatex-mode'.
23564 This mode supports entering LaTeX environment and math in LaTeX fragments
23565 in Org-mode.
23566 \\{org-cdlatex-mode-map}"
23567 nil " OCDL" nil
23568 (when org-cdlatex-mode (require 'cdlatex))
23569 (unless org-cdlatex-texmathp-advice-is-done
23570 (setq org-cdlatex-texmathp-advice-is-done t)
23571 (defadvice texmathp (around org-math-always-on activate)
23572 "Always return t in org-mode buffers.
23573 This is because we want to insert math symbols without dollars even outside
23574 the LaTeX math segments. If Orgmode thinks that point is actually inside
23575 en embedded LaTeX fragement, let texmathp do its job.
23576 \\[org-cdlatex-mode-map]"
23577 (interactive)
23578 (let (p)
23579 (cond
23580 ((not (org-mode-p)) ad-do-it)
23581 ((eq this-command 'cdlatex-math-symbol)
23582 (setq ad-return-value t
23583 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23585 (let ((p (org-inside-LaTeX-fragment-p)))
23586 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23587 (setq ad-return-value t
23588 texmathp-why '("Org-mode embedded math" . 0))
23589 (if p ad-do-it)))))))))
23591 (defun turn-on-org-cdlatex ()
23592 "Unconditionally turn on `org-cdlatex-mode'."
23593 (org-cdlatex-mode 1))
23595 (defun org-inside-LaTeX-fragment-p ()
23596 "Test if point is inside a LaTeX fragment.
23597 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23598 sequence appearing also before point.
23599 Even though the matchers for math are configurable, this function assumes
23600 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23601 delimiters are skipped when they have been removed by customization.
23602 The return value is nil, or a cons cell with the delimiter and
23603 and the position of this delimiter.
23605 This function does a reasonably good job, but can locally be fooled by
23606 for example currency specifications. For example it will assume being in
23607 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23608 fragments that are properly closed, but during editing, we have to live
23609 with the uncertainty caused by missing closing delimiters. This function
23610 looks only before point, not after."
23611 (catch 'exit
23612 (let ((pos (point))
23613 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23614 (lim (progn
23615 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23616 (point)))
23617 dd-on str (start 0) m re)
23618 (goto-char pos)
23619 (when dodollar
23620 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23621 re (nth 1 (assoc "$" org-latex-regexps)))
23622 (while (string-match re str start)
23623 (cond
23624 ((= (match-end 0) (length str))
23625 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23626 ((= (match-end 0) (- (length str) 5))
23627 (throw 'exit nil))
23628 (t (setq start (match-end 0))))))
23629 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23630 (goto-char pos)
23631 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23632 (and (match-beginning 2) (throw 'exit nil))
23633 ;; count $$
23634 (while (re-search-backward "\\$\\$" lim t)
23635 (setq dd-on (not dd-on)))
23636 (goto-char pos)
23637 (if dd-on (cons "$$" m))))))
23640 (defun org-try-cdlatex-tab ()
23641 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23642 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23643 - inside a LaTeX fragment, or
23644 - after the first word in a line, where an abbreviation expansion could
23645 insert a LaTeX environment."
23646 (when org-cdlatex-mode
23647 (cond
23648 ((save-excursion
23649 (skip-chars-backward "a-zA-Z0-9*")
23650 (skip-chars-backward " \t")
23651 (bolp))
23652 (cdlatex-tab) t)
23653 ((org-inside-LaTeX-fragment-p)
23654 (cdlatex-tab) t)
23655 (t nil))))
23657 (defun org-cdlatex-underscore-caret (&optional arg)
23658 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23659 Revert to the normal definition outside of these fragments."
23660 (interactive "P")
23661 (if (org-inside-LaTeX-fragment-p)
23662 (call-interactively 'cdlatex-sub-superscript)
23663 (let (org-cdlatex-mode)
23664 (call-interactively (key-binding (vector last-input-event))))))
23666 (defun org-cdlatex-math-modify (&optional arg)
23667 "Execute `cdlatex-math-modify' in LaTeX fragments.
23668 Revert to the normal definition outside of these fragments."
23669 (interactive "P")
23670 (if (org-inside-LaTeX-fragment-p)
23671 (call-interactively 'cdlatex-math-modify)
23672 (let (org-cdlatex-mode)
23673 (call-interactively (key-binding (vector last-input-event))))))
23675 (defvar org-latex-fragment-image-overlays nil
23676 "List of overlays carrying the images of latex fragments.")
23677 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23679 (defun org-remove-latex-fragment-image-overlays ()
23680 "Remove all overlays with LaTeX fragment images in current buffer."
23681 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23682 (setq org-latex-fragment-image-overlays nil))
23684 (defun org-preview-latex-fragment (&optional subtree)
23685 "Preview the LaTeX fragment at point, or all locally or globally.
23686 If the cursor is in a LaTeX fragment, create the image and overlay
23687 it over the source code. If there is no fragment at point, display
23688 all fragments in the current text, from one headline to the next. With
23689 prefix SUBTREE, display all fragments in the current subtree. With a
23690 double prefix `C-u C-u', or when the cursor is before the first headline,
23691 display all fragments in the buffer.
23692 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23693 (interactive "P")
23694 (org-remove-latex-fragment-image-overlays)
23695 (save-excursion
23696 (save-restriction
23697 (let (beg end at msg)
23698 (cond
23699 ((or (equal subtree '(16))
23700 (not (save-excursion
23701 (re-search-backward (concat "^" outline-regexp) nil t))))
23702 (setq beg (point-min) end (point-max)
23703 msg "Creating images for buffer...%s"))
23704 ((equal subtree '(4))
23705 (org-back-to-heading)
23706 (setq beg (point) end (org-end-of-subtree t)
23707 msg "Creating images for subtree...%s"))
23709 (if (setq at (org-inside-LaTeX-fragment-p))
23710 (goto-char (max (point-min) (- (cdr at) 2)))
23711 (org-back-to-heading))
23712 (setq beg (point) end (progn (outline-next-heading) (point))
23713 msg (if at "Creating image...%s"
23714 "Creating images for entry...%s"))))
23715 (message msg "")
23716 (narrow-to-region beg end)
23717 (goto-char beg)
23718 (org-format-latex
23719 (concat "ltxpng/" (file-name-sans-extension
23720 (file-name-nondirectory
23721 buffer-file-name)))
23722 default-directory 'overlays msg at 'forbuffer)
23723 (message msg "done. Use `C-c C-c' to remove images.")))))
23725 (defvar org-latex-regexps
23726 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23727 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23728 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23729 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23730 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23731 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23732 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23733 "Regular expressions for matching embedded LaTeX.")
23735 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23736 "Replace LaTeX fragments with links to an image, and produce images."
23737 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23738 (let* ((prefixnodir (file-name-nondirectory prefix))
23739 (absprefix (expand-file-name prefix dir))
23740 (todir (file-name-directory absprefix))
23741 (opt org-format-latex-options)
23742 (matchers (plist-get opt :matchers))
23743 (re-list org-latex-regexps)
23744 (cnt 0) txt link beg end re e checkdir
23745 m n block linkfile movefile ov)
23746 ;; Check if there are old images files with this prefix, and remove them
23747 (when (file-directory-p todir)
23748 (mapc 'delete-file
23749 (directory-files
23750 todir 'full
23751 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23752 ;; Check the different regular expressions
23753 (while (setq e (pop re-list))
23754 (setq m (car e) re (nth 1 e) n (nth 2 e)
23755 block (if (nth 3 e) "\n\n" ""))
23756 (when (member m matchers)
23757 (goto-char (point-min))
23758 (while (re-search-forward re nil t)
23759 (when (or (not at) (equal (cdr at) (match-beginning n)))
23760 (setq txt (match-string n)
23761 beg (match-beginning n) end (match-end n)
23762 cnt (1+ cnt)
23763 linkfile (format "%s_%04d.png" prefix cnt)
23764 movefile (format "%s_%04d.png" absprefix cnt)
23765 link (concat block "[[file:" linkfile "]]" block))
23766 (if msg (message msg cnt))
23767 (goto-char beg)
23768 (unless checkdir ; make sure the directory exists
23769 (setq checkdir t)
23770 (or (file-directory-p todir) (make-directory todir)))
23771 (org-create-formula-image
23772 txt movefile opt forbuffer)
23773 (if overlays
23774 (progn
23775 (setq ov (org-make-overlay beg end))
23776 (if (featurep 'xemacs)
23777 (progn
23778 (org-overlay-put ov 'invisible t)
23779 (org-overlay-put
23780 ov 'end-glyph
23781 (make-glyph (vector 'png :file movefile))))
23782 (org-overlay-put
23783 ov 'display
23784 (list 'image :type 'png :file movefile :ascent 'center)))
23785 (push ov org-latex-fragment-image-overlays)
23786 (goto-char end))
23787 (delete-region beg end)
23788 (insert link))))))))
23790 ;; This function borrows from Ganesh Swami's latex2png.el
23791 (defun org-create-formula-image (string tofile options buffer)
23792 (let* ((tmpdir (if (featurep 'xemacs)
23793 (temp-directory)
23794 temporary-file-directory))
23795 (texfilebase (make-temp-name
23796 (expand-file-name "orgtex" tmpdir)))
23797 (texfile (concat texfilebase ".tex"))
23798 (dvifile (concat texfilebase ".dvi"))
23799 (pngfile (concat texfilebase ".png"))
23800 (fnh (face-attribute 'default :height nil))
23801 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23802 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23803 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23804 "Black"))
23805 (bg (or (plist-get options (if buffer :background :html-background))
23806 "Transparent")))
23807 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23808 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23809 (with-temp-file texfile
23810 (insert org-format-latex-header
23811 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23812 (let ((dir default-directory))
23813 (condition-case nil
23814 (progn
23815 (cd tmpdir)
23816 (call-process "latex" nil nil nil texfile))
23817 (error nil))
23818 (cd dir))
23819 (if (not (file-exists-p dvifile))
23820 (progn (message "Failed to create dvi file from %s" texfile) nil)
23821 (call-process "dvipng" nil nil nil
23822 "-E" "-fg" fg "-bg" bg
23823 "-D" dpi
23824 ;;"-x" scale "-y" scale
23825 "-T" "tight"
23826 "-o" pngfile
23827 dvifile)
23828 (if (not (file-exists-p pngfile))
23829 (progn (message "Failed to create png file from %s" texfile) nil)
23830 ;; Use the requested file name and clean up
23831 (copy-file pngfile tofile 'replace)
23832 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23833 (delete-file (concat texfilebase e)))
23834 pngfile))))
23836 (defun org-dvipng-color (attr)
23837 "Return an rgb color specification for dvipng."
23838 (apply 'format "rgb %s %s %s"
23839 (mapcar 'org-normalize-color
23840 (color-values (face-attribute 'default attr nil)))))
23842 (defun org-normalize-color (value)
23843 "Return string to be used as color value for an RGB component."
23844 (format "%g" (/ value 65535.0)))
23846 ;;;; Exporting
23848 ;;; Variables, constants, and parameter plists
23850 (defconst org-level-max 20)
23852 (defvar org-export-html-preamble nil
23853 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23854 (defvar org-export-html-postamble nil
23855 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23856 (defvar org-export-html-auto-preamble t
23857 "Should default preamble be inserted? Set by publishing functions.")
23858 (defvar org-export-html-auto-postamble t
23859 "Should default postamble be inserted? Set by publishing functions.")
23860 (defvar org-current-export-file nil) ; dynamically scoped parameter
23861 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23864 (defconst org-export-plist-vars
23865 '((:language . org-export-default-language)
23866 (:customtime . org-display-custom-times)
23867 (:headline-levels . org-export-headline-levels)
23868 (:section-numbers . org-export-with-section-numbers)
23869 (:table-of-contents . org-export-with-toc)
23870 (:preserve-breaks . org-export-preserve-breaks)
23871 (:archived-trees . org-export-with-archived-trees)
23872 (:emphasize . org-export-with-emphasize)
23873 (:sub-superscript . org-export-with-sub-superscripts)
23874 (:special-strings . org-export-with-special-strings)
23875 (:footnotes . org-export-with-footnotes)
23876 (:drawers . org-export-with-drawers)
23877 (:tags . org-export-with-tags)
23878 (:TeX-macros . org-export-with-TeX-macros)
23879 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23880 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23881 (:fixed-width . org-export-with-fixed-width)
23882 (:timestamps . org-export-with-timestamps)
23883 (:author-info . org-export-author-info)
23884 (:time-stamp-file . org-export-time-stamp-file)
23885 (:tables . org-export-with-tables)
23886 (:table-auto-headline . org-export-highlight-first-table-line)
23887 (:style . org-export-html-style)
23888 (:agenda-style . org-agenda-export-html-style)
23889 (:convert-org-links . org-export-html-link-org-files-as-html)
23890 (:inline-images . org-export-html-inline-images)
23891 (:html-extension . org-export-html-extension)
23892 (:html-table-tag . org-export-html-table-tag)
23893 (:expand-quoted-html . org-export-html-expand)
23894 (:timestamp . org-export-html-with-timestamp)
23895 (:publishing-directory . org-export-publishing-directory)
23896 (:preamble . org-export-html-preamble)
23897 (:postamble . org-export-html-postamble)
23898 (:auto-preamble . org-export-html-auto-preamble)
23899 (:auto-postamble . org-export-html-auto-postamble)
23900 (:author . user-full-name)
23901 (:email . user-mail-address)))
23903 (defun org-default-export-plist ()
23904 "Return the property list with default settings for the export variables."
23905 (let ((l org-export-plist-vars) rtn e)
23906 (while (setq e (pop l))
23907 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23908 rtn))
23910 (defun org-infile-export-plist ()
23911 "Return the property list with file-local settings for export."
23912 (save-excursion
23913 (save-restriction
23914 (widen)
23915 (goto-char 0)
23916 (let ((re (org-make-options-regexp
23917 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23918 p key val text options)
23919 (while (re-search-forward re nil t)
23920 (setq key (org-match-string-no-properties 1)
23921 val (org-match-string-no-properties 2))
23922 (cond
23923 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23924 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23925 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23926 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23927 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23928 ((string-equal key "TEXT")
23929 (setq text (if text (concat text "\n" val) val)))
23930 ((string-equal key "OPTIONS") (setq options val))))
23931 (setq p (plist-put p :text text))
23932 (when options
23933 (let ((op '(("H" . :headline-levels)
23934 ("num" . :section-numbers)
23935 ("toc" . :table-of-contents)
23936 ("\\n" . :preserve-breaks)
23937 ("@" . :expand-quoted-html)
23938 (":" . :fixed-width)
23939 ("|" . :tables)
23940 ("^" . :sub-superscript)
23941 ("-" . :special-strings)
23942 ("f" . :footnotes)
23943 ("d" . :drawers)
23944 ("tags" . :tags)
23945 ("*" . :emphasize)
23946 ("TeX" . :TeX-macros)
23947 ("LaTeX" . :LaTeX-fragments)
23948 ("skip" . :skip-before-1st-heading)
23949 ("author" . :author-info)
23950 ("timestamp" . :time-stamp-file)))
23952 (while (setq o (pop op))
23953 (if (string-match (concat (regexp-quote (car o))
23954 ":\\([^ \t\n\r;,.]*\\)")
23955 options)
23956 (setq p (plist-put p (cdr o)
23957 (car (read-from-string
23958 (match-string 1 options)))))))))
23959 p))))
23961 (defun org-export-directory (type plist)
23962 (let* ((val (plist-get plist :publishing-directory))
23963 (dir (if (listp val)
23964 (or (cdr (assoc type val)) ".")
23965 val)))
23966 dir))
23968 (defun org-skip-comments (lines)
23969 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23970 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23971 (re2 "^\\(\\*+\\)[ \t\n\r]")
23972 (case-fold-search nil)
23973 rtn line level)
23974 (while (setq line (pop lines))
23975 (cond
23976 ((and (string-match re1 line)
23977 (setq level (- (match-end 1) (match-beginning 1))))
23978 ;; Beginning of a COMMENT subtree. Skip it.
23979 (while (and (setq line (pop lines))
23980 (or (not (string-match re2 line))
23981 (> (- (match-end 1) (match-beginning 1)) level))))
23982 (setq lines (cons line lines)))
23983 ((string-match "^#" line)
23984 ;; an ordinary comment line
23986 ((and org-export-table-remove-special-lines
23987 (string-match "^[ \t]*|" line)
23988 (or (string-match "^[ \t]*| *[!_^] *|" line)
23989 (and (string-match "| *<[0-9]+> *|" line)
23990 (not (string-match "| *[^ <|]" line)))))
23991 ;; a special table line that should be removed
23993 (t (setq rtn (cons line rtn)))))
23994 (nreverse rtn)))
23996 (defun org-export (&optional arg)
23997 (interactive)
23998 (let ((help "[t] insert the export option template
23999 \[v] limit export to visible part of outline tree
24001 \[a] export as ASCII
24003 \[h] export as HTML
24004 \[H] export as HTML to temporary buffer
24005 \[R] export region as HTML
24006 \[b] export as HTML and browse immediately
24007 \[x] export as XOXO
24009 \[l] export as LaTeX
24010 \[L] export as LaTeX to temporary buffer
24012 \[i] export current file as iCalendar file
24013 \[I] export all agenda files as iCalendar files
24014 \[c] export agenda files into combined iCalendar file
24016 \[F] publish current file
24017 \[P] publish current project
24018 \[X] publish... (project will be prompted for)
24019 \[A] publish all projects")
24020 (cmds
24021 '((?t . org-insert-export-options-template)
24022 (?v . org-export-visible)
24023 (?a . org-export-as-ascii)
24024 (?h . org-export-as-html)
24025 (?b . org-export-as-html-and-open)
24026 (?H . org-export-as-html-to-buffer)
24027 (?R . org-export-region-as-html)
24028 (?x . org-export-as-xoxo)
24029 (?l . org-export-as-latex)
24030 (?L . org-export-as-latex-to-buffer)
24031 (?i . org-export-icalendar-this-file)
24032 (?I . org-export-icalendar-all-agenda-files)
24033 (?c . org-export-icalendar-combine-agenda-files)
24034 (?F . org-publish-current-file)
24035 (?P . org-publish-current-project)
24036 (?X . org-publish)
24037 (?A . org-publish-all)))
24038 r1 r2 ass)
24039 (save-window-excursion
24040 (delete-other-windows)
24041 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
24042 (princ help))
24043 (message "Select command: ")
24044 (setq r1 (read-char-exclusive)))
24045 (setq r2 (if (< r1 27) (+ r1 96) r1))
24046 (if (setq ass (assq r2 cmds))
24047 (call-interactively (cdr ass))
24048 (error "No command associated with key %c" r1))))
24050 (defconst org-html-entities
24051 '(("nbsp")
24052 ("iexcl")
24053 ("cent")
24054 ("pound")
24055 ("curren")
24056 ("yen")
24057 ("brvbar")
24058 ("vert" . "&#124;")
24059 ("sect")
24060 ("uml")
24061 ("copy")
24062 ("ordf")
24063 ("laquo")
24064 ("not")
24065 ("shy")
24066 ("reg")
24067 ("macr")
24068 ("deg")
24069 ("plusmn")
24070 ("sup2")
24071 ("sup3")
24072 ("acute")
24073 ("micro")
24074 ("para")
24075 ("middot")
24076 ("odot"."o")
24077 ("star"."*")
24078 ("cedil")
24079 ("sup1")
24080 ("ordm")
24081 ("raquo")
24082 ("frac14")
24083 ("frac12")
24084 ("frac34")
24085 ("iquest")
24086 ("Agrave")
24087 ("Aacute")
24088 ("Acirc")
24089 ("Atilde")
24090 ("Auml")
24091 ("Aring") ("AA"."&Aring;")
24092 ("AElig")
24093 ("Ccedil")
24094 ("Egrave")
24095 ("Eacute")
24096 ("Ecirc")
24097 ("Euml")
24098 ("Igrave")
24099 ("Iacute")
24100 ("Icirc")
24101 ("Iuml")
24102 ("ETH")
24103 ("Ntilde")
24104 ("Ograve")
24105 ("Oacute")
24106 ("Ocirc")
24107 ("Otilde")
24108 ("Ouml")
24109 ("times")
24110 ("Oslash")
24111 ("Ugrave")
24112 ("Uacute")
24113 ("Ucirc")
24114 ("Uuml")
24115 ("Yacute")
24116 ("THORN")
24117 ("szlig")
24118 ("agrave")
24119 ("aacute")
24120 ("acirc")
24121 ("atilde")
24122 ("auml")
24123 ("aring")
24124 ("aelig")
24125 ("ccedil")
24126 ("egrave")
24127 ("eacute")
24128 ("ecirc")
24129 ("euml")
24130 ("igrave")
24131 ("iacute")
24132 ("icirc")
24133 ("iuml")
24134 ("eth")
24135 ("ntilde")
24136 ("ograve")
24137 ("oacute")
24138 ("ocirc")
24139 ("otilde")
24140 ("ouml")
24141 ("divide")
24142 ("oslash")
24143 ("ugrave")
24144 ("uacute")
24145 ("ucirc")
24146 ("uuml")
24147 ("yacute")
24148 ("thorn")
24149 ("yuml")
24150 ("fnof")
24151 ("Alpha")
24152 ("Beta")
24153 ("Gamma")
24154 ("Delta")
24155 ("Epsilon")
24156 ("Zeta")
24157 ("Eta")
24158 ("Theta")
24159 ("Iota")
24160 ("Kappa")
24161 ("Lambda")
24162 ("Mu")
24163 ("Nu")
24164 ("Xi")
24165 ("Omicron")
24166 ("Pi")
24167 ("Rho")
24168 ("Sigma")
24169 ("Tau")
24170 ("Upsilon")
24171 ("Phi")
24172 ("Chi")
24173 ("Psi")
24174 ("Omega")
24175 ("alpha")
24176 ("beta")
24177 ("gamma")
24178 ("delta")
24179 ("epsilon")
24180 ("varepsilon"."&epsilon;")
24181 ("zeta")
24182 ("eta")
24183 ("theta")
24184 ("iota")
24185 ("kappa")
24186 ("lambda")
24187 ("mu")
24188 ("nu")
24189 ("xi")
24190 ("omicron")
24191 ("pi")
24192 ("rho")
24193 ("sigmaf") ("varsigma"."&sigmaf;")
24194 ("sigma")
24195 ("tau")
24196 ("upsilon")
24197 ("phi")
24198 ("chi")
24199 ("psi")
24200 ("omega")
24201 ("thetasym") ("vartheta"."&thetasym;")
24202 ("upsih")
24203 ("piv")
24204 ("bull") ("bullet"."&bull;")
24205 ("hellip") ("dots"."&hellip;")
24206 ("prime")
24207 ("Prime")
24208 ("oline")
24209 ("frasl")
24210 ("weierp")
24211 ("image")
24212 ("real")
24213 ("trade")
24214 ("alefsym")
24215 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
24216 ("uarr") ("uparrow"."&uarr;")
24217 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
24218 ("darr")("downarrow"."&darr;")
24219 ("harr") ("leftrightarrow"."&harr;")
24220 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
24221 ("lArr") ("Leftarrow"."&lArr;")
24222 ("uArr") ("Uparrow"."&uArr;")
24223 ("rArr") ("Rightarrow"."&rArr;")
24224 ("dArr") ("Downarrow"."&dArr;")
24225 ("hArr") ("Leftrightarrow"."&hArr;")
24226 ("forall")
24227 ("part") ("partial"."&part;")
24228 ("exist") ("exists"."&exist;")
24229 ("empty") ("emptyset"."&empty;")
24230 ("nabla")
24231 ("isin") ("in"."&isin;")
24232 ("notin")
24233 ("ni")
24234 ("prod")
24235 ("sum")
24236 ("minus")
24237 ("lowast") ("ast"."&lowast;")
24238 ("radic")
24239 ("prop") ("proptp"."&prop;")
24240 ("infin") ("infty"."&infin;")
24241 ("ang") ("angle"."&ang;")
24242 ("and") ("wedge"."&and;")
24243 ("or") ("vee"."&or;")
24244 ("cap")
24245 ("cup")
24246 ("int")
24247 ("there4")
24248 ("sim")
24249 ("cong") ("simeq"."&cong;")
24250 ("asymp")("approx"."&asymp;")
24251 ("ne") ("neq"."&ne;")
24252 ("equiv")
24253 ("le")
24254 ("ge")
24255 ("sub") ("subset"."&sub;")
24256 ("sup") ("supset"."&sup;")
24257 ("nsub")
24258 ("sube")
24259 ("supe")
24260 ("oplus")
24261 ("otimes")
24262 ("perp")
24263 ("sdot") ("cdot"."&sdot;")
24264 ("lceil")
24265 ("rceil")
24266 ("lfloor")
24267 ("rfloor")
24268 ("lang")
24269 ("rang")
24270 ("loz") ("Diamond"."&loz;")
24271 ("spades") ("spadesuit"."&spades;")
24272 ("clubs") ("clubsuit"."&clubs;")
24273 ("hearts") ("diamondsuit"."&hearts;")
24274 ("diams") ("diamondsuit"."&diams;")
24275 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
24276 ("quot")
24277 ("amp")
24278 ("lt")
24279 ("gt")
24280 ("OElig")
24281 ("oelig")
24282 ("Scaron")
24283 ("scaron")
24284 ("Yuml")
24285 ("circ")
24286 ("tilde")
24287 ("ensp")
24288 ("emsp")
24289 ("thinsp")
24290 ("zwnj")
24291 ("zwj")
24292 ("lrm")
24293 ("rlm")
24294 ("ndash")
24295 ("mdash")
24296 ("lsquo")
24297 ("rsquo")
24298 ("sbquo")
24299 ("ldquo")
24300 ("rdquo")
24301 ("bdquo")
24302 ("dagger")
24303 ("Dagger")
24304 ("permil")
24305 ("lsaquo")
24306 ("rsaquo")
24307 ("euro")
24309 ("arccos"."arccos")
24310 ("arcsin"."arcsin")
24311 ("arctan"."arctan")
24312 ("arg"."arg")
24313 ("cos"."cos")
24314 ("cosh"."cosh")
24315 ("cot"."cot")
24316 ("coth"."coth")
24317 ("csc"."csc")
24318 ("deg"."deg")
24319 ("det"."det")
24320 ("dim"."dim")
24321 ("exp"."exp")
24322 ("gcd"."gcd")
24323 ("hom"."hom")
24324 ("inf"."inf")
24325 ("ker"."ker")
24326 ("lg"."lg")
24327 ("lim"."lim")
24328 ("liminf"."liminf")
24329 ("limsup"."limsup")
24330 ("ln"."ln")
24331 ("log"."log")
24332 ("max"."max")
24333 ("min"."min")
24334 ("Pr"."Pr")
24335 ("sec"."sec")
24336 ("sin"."sin")
24337 ("sinh"."sinh")
24338 ("sup"."sup")
24339 ("tan"."tan")
24340 ("tanh"."tanh")
24342 "Entities for TeX->HTML translation.
24343 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
24344 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
24345 In that case, \"\\ent\" will be translated to \"&other;\".
24346 The list contains HTML entities for Latin-1, Greek and other symbols.
24347 It is supplemented by a number of commonly used TeX macros with appropriate
24348 translations. There is currently no way for users to extend this.")
24350 ;;; General functions for all backends
24352 (defun org-cleaned-string-for-export (string &rest parameters)
24353 "Cleanup a buffer STRING so that links can be created safely."
24354 (interactive)
24355 (let* ((re-radio (and org-target-link-regexp
24356 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
24357 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
24358 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
24359 (re-archive (concat ":" org-archive-tag ":"))
24360 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
24361 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
24362 (htmlp (plist-get parameters :for-html))
24363 (asciip (plist-get parameters :for-ascii))
24364 (latexp (plist-get parameters :for-LaTeX))
24365 (commentsp (plist-get parameters :comments))
24366 (archived-trees (plist-get parameters :archived-trees))
24367 (inhibit-read-only t)
24368 (drawers org-drawers)
24369 (exp-drawers (plist-get parameters :drawers))
24370 (outline-regexp "\\*+ ")
24371 a b xx
24372 rtn p)
24373 (with-current-buffer (get-buffer-create " org-mode-tmp")
24374 (erase-buffer)
24375 (insert string)
24376 ;; Remove license-to-kill stuff
24377 (while (setq p (text-property-any (point-min) (point-max)
24378 :org-license-to-kill t))
24379 (delete-region p (next-single-property-change p :org-license-to-kill)))
24381 (let ((org-inhibit-startup t)) (org-mode))
24382 (untabify (point-min) (point-max))
24384 ;; Get rid of drawers
24385 (unless (eq t exp-drawers)
24386 (goto-char (point-min))
24387 (let ((re (concat "^[ \t]*:\\("
24388 (mapconcat
24389 'identity
24390 (org-delete-all exp-drawers
24391 (copy-sequence drawers))
24392 "\\|")
24393 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
24394 (while (re-search-forward re nil t)
24395 (replace-match ""))))
24397 ;; Get the correct stuff before the first headline
24398 (when (plist-get parameters :skip-before-1st-heading)
24399 (goto-char (point-min))
24400 (when (re-search-forward "^\\*+[ \t]" nil t)
24401 (delete-region (point-min) (match-beginning 0))
24402 (goto-char (point-min))
24403 (insert "\n")))
24404 (when (plist-get parameters :add-text)
24405 (goto-char (point-min))
24406 (insert (plist-get parameters :add-text) "\n"))
24408 ;; Get rid of archived trees
24409 (when (not (eq archived-trees t))
24410 (goto-char (point-min))
24411 (while (re-search-forward re-archive nil t)
24412 (if (not (org-on-heading-p t))
24413 (org-end-of-subtree t)
24414 (beginning-of-line 1)
24415 (setq a (if archived-trees
24416 (1+ (point-at-eol)) (point))
24417 b (org-end-of-subtree t))
24418 (if (> b a) (delete-region a b)))))
24420 ;; Find targets in comments and move them out of comments,
24421 ;; but mark them as targets that should be invisible
24422 (goto-char (point-min))
24423 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
24424 (replace-match "\\1(INVISIBLE)"))
24426 ;; Protect backend specific stuff, throw away the others.
24427 (let ((formatters
24428 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
24429 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
24430 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
24431 fmt)
24432 (goto-char (point-min))
24433 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
24434 (goto-char (match-end 0))
24435 (while (not (looking-at "#\\+END_EXAMPLE"))
24436 (insert ": ")
24437 (beginning-of-line 2)))
24438 (goto-char (point-min))
24439 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
24440 (add-text-properties (match-beginning 0) (match-end 0)
24441 '(org-protected t)))
24442 (while formatters
24443 (setq fmt (pop formatters))
24444 (when (car fmt)
24445 (goto-char (point-min))
24446 (while (re-search-forward (concat "^#\\+" (cadr fmt)
24447 ":[ \t]*\\(.*\\)") nil t)
24448 (replace-match "\\1" t)
24449 (add-text-properties
24450 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
24451 '(org-protected t))))
24452 (goto-char (point-min))
24453 (while (re-search-forward
24454 (concat "^#\\+"
24455 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
24456 (cadddr fmt) "\\>.*\n?") nil t)
24457 (if (car fmt)
24458 (add-text-properties (match-beginning 1) (1+ (match-end 1))
24459 '(org-protected t))
24460 (delete-region (match-beginning 0) (match-end 0))))))
24462 ;; Protect quoted subtrees
24463 (goto-char (point-min))
24464 (while (re-search-forward re-quote nil t)
24465 (goto-char (match-beginning 0))
24466 (end-of-line 1)
24467 (add-text-properties (point) (org-end-of-subtree t)
24468 '(org-protected t)))
24470 ;; Protect verbatim elements
24471 (goto-char (point-min))
24472 (while (re-search-forward org-verbatim-re nil t)
24473 (add-text-properties (match-beginning 4) (match-end 4)
24474 '(org-protected t))
24475 (goto-char (1+ (match-end 4))))
24477 ;; Remove subtrees that are commented
24478 (goto-char (point-min))
24479 (while (re-search-forward re-commented nil t)
24480 (goto-char (match-beginning 0))
24481 (delete-region (point) (org-end-of-subtree t)))
24483 ;; Remove special table lines
24484 (when org-export-table-remove-special-lines
24485 (goto-char (point-min))
24486 (while (re-search-forward "^[ \t]*|" nil t)
24487 (beginning-of-line 1)
24488 (if (or (looking-at "[ \t]*| *[!_^] *|")
24489 (and (looking-at ".*?| *<[0-9]+> *|")
24490 (not (looking-at ".*?| *[^ <|]"))))
24491 (delete-region (max (point-min) (1- (point-at-bol)))
24492 (point-at-eol))
24493 (end-of-line 1))))
24495 ;; Specific LaTeX stuff
24496 (when latexp
24497 (require 'org-export-latex nil)
24498 (org-export-latex-cleaned-string))
24500 (when asciip
24501 (org-export-ascii-clean-string))
24503 ;; Specific HTML stuff
24504 (when htmlp
24505 ;; Convert LaTeX fragments to images
24506 (when (plist-get parameters :LaTeX-fragments)
24507 (org-format-latex
24508 (concat "ltxpng/" (file-name-sans-extension
24509 (file-name-nondirectory
24510 org-current-export-file)))
24511 org-current-export-dir nil "Creating LaTeX image %s"))
24512 (message "Exporting..."))
24514 ;; Remove or replace comments
24515 (goto-char (point-min))
24516 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24517 (if commentsp
24518 (progn (add-text-properties
24519 (match-beginning 0) (match-end 0) '(org-protected t))
24520 (replace-match (format commentsp (match-string 1)) t t))
24521 (replace-match "")))
24523 ;; Find matches for radio targets and turn them into internal links
24524 (goto-char (point-min))
24525 (when re-radio
24526 (while (re-search-forward re-radio nil t)
24527 (org-if-unprotected
24528 (replace-match "\\1[[\\2]]"))))
24530 ;; Find all links that contain a newline and put them into a single line
24531 (goto-char (point-min))
24532 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24533 (org-if-unprotected
24534 (replace-match "\\1 \\3")
24535 (goto-char (match-beginning 0))))
24538 ;; Normalize links: Convert angle and plain links into bracket links
24539 ;; Expand link abbreviations
24540 (goto-char (point-min))
24541 (while (re-search-forward re-plain-link nil t)
24542 (goto-char (1- (match-end 0)))
24543 (org-if-unprotected
24544 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24545 ":" (match-string 3) "]]")))
24546 ;; added 'org-link face to links
24547 (put-text-property 0 (length s) 'face 'org-link s)
24548 (replace-match s t t))))
24549 (goto-char (point-min))
24550 (while (re-search-forward re-angle-link nil t)
24551 (goto-char (1- (match-end 0)))
24552 (org-if-unprotected
24553 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24554 ":" (match-string 3) "]]")))
24555 (put-text-property 0 (length s) 'face 'org-link s)
24556 (replace-match s t t))))
24557 (goto-char (point-min))
24558 (while (re-search-forward org-bracket-link-regexp nil t)
24559 (org-if-unprotected
24560 (let* ((s (concat "[[" (setq xx (save-match-data
24561 (org-link-expand-abbrev (match-string 1))))
24563 (if (match-end 3)
24564 (match-string 2)
24565 (concat "[" xx "]"))
24566 "]")))
24567 (put-text-property 0 (length s) 'face 'org-link s)
24568 (replace-match s t t))))
24570 ;; Find multiline emphasis and put them into single line
24571 (when (plist-get parameters :emph-multiline)
24572 (goto-char (point-min))
24573 (while (re-search-forward org-emph-re nil t)
24574 (if (not (= (char-after (match-beginning 3))
24575 (char-after (match-beginning 4))))
24576 (org-if-unprotected
24577 (subst-char-in-region (match-beginning 0) (match-end 0)
24578 ?\n ?\ t)
24579 (goto-char (1- (match-end 0))))
24580 (goto-char (1+ (match-beginning 0))))))
24582 (setq rtn (buffer-string)))
24583 (kill-buffer " org-mode-tmp")
24584 rtn))
24586 (defun org-export-grab-title-from-buffer ()
24587 "Get a title for the current document, from looking at the buffer."
24588 (let ((inhibit-read-only t))
24589 (save-excursion
24590 (goto-char (point-min))
24591 (let ((end (save-excursion (outline-next-heading) (point))))
24592 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24593 ;; Mark the line so that it will not be exported as normal text.
24594 (org-unmodified
24595 (add-text-properties (match-beginning 0) (match-end 0)
24596 (list :org-license-to-kill t)))
24597 ;; Return the title string
24598 (org-trim (match-string 0)))))))
24600 (defun org-export-get-title-from-subtree ()
24601 "Return subtree title and exclude it from export."
24602 (let (title (m (mark)))
24603 (save-excursion
24604 (goto-char (region-beginning))
24605 (when (and (org-at-heading-p)
24606 (>= (org-end-of-subtree t t) (region-end)))
24607 ;; This is a subtree, we take the title from the first heading
24608 (goto-char (region-beginning))
24609 (looking-at org-todo-line-regexp)
24610 (setq title (match-string 3))
24611 (org-unmodified
24612 (add-text-properties (point) (1+ (point-at-eol))
24613 (list :org-license-to-kill t)))))
24614 title))
24616 (defun org-solidify-link-text (s &optional alist)
24617 "Take link text and make a safe target out of it."
24618 (save-match-data
24619 (let* ((rtn
24620 (mapconcat
24621 'identity
24622 (org-split-string s "[ \t\r\n]+") "--"))
24623 (a (assoc rtn alist)))
24624 (or (cdr a) rtn))))
24626 (defun org-get-min-level (lines)
24627 "Get the minimum level in LINES."
24628 (let ((re "^\\(\\*+\\) ") l min)
24629 (catch 'exit
24630 (while (setq l (pop lines))
24631 (if (string-match re l)
24632 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24633 1)))
24635 ;; Variable holding the vector with section numbers
24636 (defvar org-section-numbers (make-vector org-level-max 0))
24638 (defun org-init-section-numbers ()
24639 "Initialize the vector for the section numbers."
24640 (let* ((level -1)
24641 (numbers (nreverse (org-split-string "" "\\.")))
24642 (depth (1- (length org-section-numbers)))
24643 (i depth) number-string)
24644 (while (>= i 0)
24645 (if (> i level)
24646 (aset org-section-numbers i 0)
24647 (setq number-string (or (car numbers) "0"))
24648 (if (string-match "\\`[A-Z]\\'" number-string)
24649 (aset org-section-numbers i
24650 (- (string-to-char number-string) ?A -1))
24651 (aset org-section-numbers i (string-to-number number-string)))
24652 (pop numbers))
24653 (setq i (1- i)))))
24655 (defun org-section-number (&optional level)
24656 "Return a string with the current section number.
24657 When LEVEL is non-nil, increase section numbers on that level."
24658 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24659 (when level
24660 (when (> level -1)
24661 (aset org-section-numbers
24662 level (1+ (aref org-section-numbers level))))
24663 (setq idx (1+ level))
24664 (while (<= idx depth)
24665 (if (not (= idx 1))
24666 (aset org-section-numbers idx 0))
24667 (setq idx (1+ idx))))
24668 (setq idx 0)
24669 (while (<= idx depth)
24670 (setq n (aref org-section-numbers idx))
24671 (setq string (concat string (if (not (string= string "")) "." "")
24672 (int-to-string n)))
24673 (setq idx (1+ idx)))
24674 (save-match-data
24675 (if (string-match "\\`\\([@0]\\.\\)+" string)
24676 (setq string (replace-match "" t nil string)))
24677 (if (string-match "\\(\\.0\\)+\\'" string)
24678 (setq string (replace-match "" t nil string))))
24679 string))
24681 ;;; ASCII export
24683 (defvar org-last-level nil) ; dynamically scoped variable
24684 (defvar org-min-level nil) ; dynamically scoped variable
24685 (defvar org-levels-open nil) ; dynamically scoped parameter
24686 (defvar org-ascii-current-indentation nil) ; For communication
24688 (defun org-export-as-ascii (arg)
24689 "Export the outline as a pretty ASCII file.
24690 If there is an active region, export only the region.
24691 The prefix ARG specifies how many levels of the outline should become
24692 underlined headlines. The default is 3."
24693 (interactive "P")
24694 (setq-default org-todo-line-regexp org-todo-line-regexp)
24695 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24696 (org-infile-export-plist)))
24697 (region-p (org-region-active-p))
24698 (subtree-p
24699 (when region-p
24700 (save-excursion
24701 (goto-char (region-beginning))
24702 (and (org-at-heading-p)
24703 (>= (org-end-of-subtree t t) (region-end))))))
24704 (custom-times org-display-custom-times)
24705 (org-ascii-current-indentation '(0 . 0))
24706 (level 0) line txt
24707 (umax nil)
24708 (umax-toc nil)
24709 (case-fold-search nil)
24710 (filename (concat (file-name-as-directory
24711 (org-export-directory :ascii opt-plist))
24712 (file-name-sans-extension
24713 (or (and subtree-p
24714 (org-entry-get (region-beginning)
24715 "EXPORT_FILE_NAME" t))
24716 (file-name-nondirectory buffer-file-name)))
24717 ".txt"))
24718 (filename (if (equal (file-truename filename)
24719 (file-truename buffer-file-name))
24720 (concat filename ".txt")
24721 filename))
24722 (buffer (find-file-noselect filename))
24723 (org-levels-open (make-vector org-level-max nil))
24724 (odd org-odd-levels-only)
24725 (date (plist-get opt-plist :date))
24726 (author (plist-get opt-plist :author))
24727 (title (or (and subtree-p (org-export-get-title-from-subtree))
24728 (plist-get opt-plist :title)
24729 (and (not
24730 (plist-get opt-plist :skip-before-1st-heading))
24731 (org-export-grab-title-from-buffer))
24732 (file-name-sans-extension
24733 (file-name-nondirectory buffer-file-name))))
24734 (email (plist-get opt-plist :email))
24735 (language (plist-get opt-plist :language))
24736 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24737 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24738 (todo nil)
24739 (lang-words nil)
24740 (region
24741 (buffer-substring
24742 (if (org-region-active-p) (region-beginning) (point-min))
24743 (if (org-region-active-p) (region-end) (point-max))))
24744 (lines (org-split-string
24745 (org-cleaned-string-for-export
24746 region
24747 :for-ascii t
24748 :skip-before-1st-heading
24749 (plist-get opt-plist :skip-before-1st-heading)
24750 :drawers (plist-get opt-plist :drawers)
24751 :verbatim-multiline t
24752 :archived-trees
24753 (plist-get opt-plist :archived-trees)
24754 :add-text (plist-get opt-plist :text))
24755 "\n"))
24756 thetoc have-headings first-heading-pos
24757 table-open table-buffer)
24759 (let ((inhibit-read-only t))
24760 (org-unmodified
24761 (remove-text-properties (point-min) (point-max)
24762 '(:org-license-to-kill t))))
24764 (setq org-min-level (org-get-min-level lines))
24765 (setq org-last-level org-min-level)
24766 (org-init-section-numbers)
24768 (find-file-noselect filename)
24770 (setq lang-words (or (assoc language org-export-language-setup)
24771 (assoc "en" org-export-language-setup)))
24772 (switch-to-buffer-other-window buffer)
24773 (erase-buffer)
24774 (fundamental-mode)
24775 ;; create local variables for all options, to make sure all called
24776 ;; functions get the correct information
24777 (mapc (lambda (x)
24778 (set (make-local-variable (cdr x))
24779 (plist-get opt-plist (car x))))
24780 org-export-plist-vars)
24781 (org-set-local 'org-odd-levels-only odd)
24782 (setq umax (if arg (prefix-numeric-value arg)
24783 org-export-headline-levels))
24784 (setq umax-toc (if (integerp org-export-with-toc)
24785 (min org-export-with-toc umax)
24786 umax))
24788 ;; File header
24789 (if title (org-insert-centered title ?=))
24790 (insert "\n")
24791 (if (and (or author email)
24792 org-export-author-info)
24793 (insert (concat (nth 1 lang-words) ": " (or author "")
24794 (if email (concat " <" email ">") "")
24795 "\n")))
24797 (cond
24798 ((and date (string-match "%" date))
24799 (setq date (format-time-string date)))
24800 (date)
24801 (t (setq date (format-time-string "%Y/%m/%d %X"))))
24803 (if (and date org-export-time-stamp-file)
24804 (insert (concat (nth 2 lang-words) ": " date"\n")))
24806 (insert "\n\n")
24808 (if org-export-with-toc
24809 (progn
24810 (push (concat (nth 3 lang-words) "\n") thetoc)
24811 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24812 (mapc '(lambda (line)
24813 (if (string-match org-todo-line-regexp
24814 line)
24815 ;; This is a headline
24816 (progn
24817 (setq have-headings t)
24818 (setq level (- (match-end 1) (match-beginning 1))
24819 level (org-tr-level level)
24820 txt (match-string 3 line)
24821 todo
24822 (or (and org-export-mark-todo-in-toc
24823 (match-beginning 2)
24824 (not (member (match-string 2 line)
24825 org-done-keywords)))
24826 ; TODO, not DONE
24827 (and org-export-mark-todo-in-toc
24828 (= level umax-toc)
24829 (org-search-todo-below
24830 line lines level))))
24831 (setq txt (org-html-expand-for-ascii txt))
24833 (while (string-match org-bracket-link-regexp txt)
24834 (setq txt
24835 (replace-match
24836 (match-string (if (match-end 2) 3 1) txt)
24837 t t txt)))
24839 (if (and (memq org-export-with-tags '(not-in-toc nil))
24840 (string-match
24841 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24842 txt))
24843 (setq txt (replace-match "" t t txt)))
24844 (if (string-match quote-re0 txt)
24845 (setq txt (replace-match "" t t txt)))
24847 (if org-export-with-section-numbers
24848 (setq txt (concat (org-section-number level)
24849 " " txt)))
24850 (if (<= level umax-toc)
24851 (progn
24852 (push
24853 (concat
24854 (make-string
24855 (* (max 0 (- level org-min-level)) 4) ?\ )
24856 (format (if todo "%s (*)\n" "%s\n") txt))
24857 thetoc)
24858 (setq org-last-level level))
24859 ))))
24860 lines)
24861 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24863 (org-init-section-numbers)
24864 (while (setq line (pop lines))
24865 ;; Remove the quoted HTML tags.
24866 (setq line (org-html-expand-for-ascii line))
24867 ;; Remove targets
24868 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24869 (setq line (replace-match "" t t line)))
24870 ;; Replace internal links
24871 (while (string-match org-bracket-link-regexp line)
24872 (setq line (replace-match
24873 (if (match-end 3) "[\\3]" "[\\1]")
24874 t nil line)))
24875 (when custom-times
24876 (setq line (org-translate-time line)))
24877 (cond
24878 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24879 ;; a Headline
24880 (setq first-heading-pos (or first-heading-pos (point)))
24881 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24882 txt (match-string 2 line))
24883 (org-ascii-level-start level txt umax lines))
24885 ((and org-export-with-tables
24886 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24887 (if (not table-open)
24888 ;; New table starts
24889 (setq table-open t table-buffer nil))
24890 ;; Accumulate lines
24891 (setq table-buffer (cons line table-buffer))
24892 (when (or (not lines)
24893 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24894 (car lines))))
24895 (setq table-open nil
24896 table-buffer (nreverse table-buffer))
24897 (insert (mapconcat
24898 (lambda (x)
24899 (org-fix-indentation x org-ascii-current-indentation))
24900 (org-format-table-ascii table-buffer)
24901 "\n") "\n")))
24903 (setq line (org-fix-indentation line org-ascii-current-indentation))
24904 (if (and org-export-with-fixed-width
24905 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24906 (setq line (replace-match "\\1" nil nil line)))
24907 (insert line "\n"))))
24909 (normal-mode)
24911 ;; insert the table of contents
24912 (when thetoc
24913 (goto-char (point-min))
24914 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24915 (progn
24916 (goto-char (match-beginning 0))
24917 (replace-match ""))
24918 (goto-char first-heading-pos))
24919 (mapc 'insert thetoc)
24920 (or (looking-at "[ \t]*\n[ \t]*\n")
24921 (insert "\n\n")))
24923 ;; Convert whitespace place holders
24924 (goto-char (point-min))
24925 (let (beg end)
24926 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24927 (setq end (next-single-property-change beg 'org-whitespace))
24928 (goto-char beg)
24929 (delete-region beg end)
24930 (insert (make-string (- end beg) ?\ ))))
24932 (save-buffer)
24933 ;; remove display and invisible chars
24934 (let (beg end)
24935 (goto-char (point-min))
24936 (while (setq beg (next-single-property-change (point) 'display))
24937 (setq end (next-single-property-change beg 'display))
24938 (delete-region beg end)
24939 (goto-char beg)
24940 (insert "=>"))
24941 (goto-char (point-min))
24942 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24943 (setq end (next-single-property-change beg 'org-cwidth))
24944 (delete-region beg end)
24945 (goto-char beg)))
24946 (goto-char (point-min))))
24948 (defun org-export-ascii-clean-string ()
24949 "Do extra work for ASCII export"
24950 (goto-char (point-min))
24951 (while (re-search-forward org-verbatim-re nil t)
24952 (goto-char (match-end 2))
24953 (backward-delete-char 1) (insert "'")
24954 (goto-char (match-beginning 2))
24955 (delete-char 1) (insert "`")
24956 (goto-char (match-end 2))))
24958 (defun org-search-todo-below (line lines level)
24959 "Search the subtree below LINE for any TODO entries."
24960 (let ((rest (cdr (memq line lines)))
24961 (re org-todo-line-regexp)
24962 line lv todo)
24963 (catch 'exit
24964 (while (setq line (pop rest))
24965 (if (string-match re line)
24966 (progn
24967 (setq lv (- (match-end 1) (match-beginning 1))
24968 todo (and (match-beginning 2)
24969 (not (member (match-string 2 line)
24970 org-done-keywords))))
24971 ; TODO, not DONE
24972 (if (<= lv level) (throw 'exit nil))
24973 (if todo (throw 'exit t))))))))
24975 (defun org-html-expand-for-ascii (line)
24976 "Handle quoted HTML for ASCII export."
24977 (if org-export-html-expand
24978 (while (string-match "@<[^<>\n]*>" line)
24979 ;; We just remove the tags for now.
24980 (setq line (replace-match "" nil nil line))))
24981 line)
24983 (defun org-insert-centered (s &optional underline)
24984 "Insert the string S centered and underline it with character UNDERLINE."
24985 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24986 (insert (make-string ind ?\ ) s "\n")
24987 (if underline
24988 (insert (make-string ind ?\ )
24989 (make-string (string-width s) underline)
24990 "\n"))))
24992 (defun org-ascii-level-start (level title umax &optional lines)
24993 "Insert a new level in ASCII export."
24994 (let (char (n (- level umax 1)) (ind 0))
24995 (if (> level umax)
24996 (progn
24997 (insert (make-string (* 2 n) ?\ )
24998 (char-to-string (nth (% n (length org-export-ascii-bullets))
24999 org-export-ascii-bullets))
25000 " " title "\n")
25001 ;; find the indentation of the next non-empty line
25002 (catch 'stop
25003 (while lines
25004 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
25005 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
25006 (throw 'stop (setq ind (org-get-indentation (car lines)))))
25007 (pop lines)))
25008 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
25009 (if (or (not (equal (char-before) ?\n))
25010 (not (equal (char-before (1- (point))) ?\n)))
25011 (insert "\n"))
25012 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
25013 (unless org-export-with-tags
25014 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25015 (setq title (replace-match "" t t title))))
25016 (if org-export-with-section-numbers
25017 (setq title (concat (org-section-number level) " " title)))
25018 (insert title "\n" (make-string (string-width title) char) "\n")
25019 (setq org-ascii-current-indentation '(0 . 0)))))
25021 (defun org-export-visible (type arg)
25022 "Create a copy of the visible part of the current buffer, and export it.
25023 The copy is created in a temporary buffer and removed after use.
25024 TYPE is the final key (as a string) that also select the export command in
25025 the `C-c C-e' export dispatcher.
25026 As a special case, if the you type SPC at the prompt, the temporary
25027 org-mode file will not be removed but presented to you so that you can
25028 continue to use it. The prefix arg ARG is passed through to the exporting
25029 command."
25030 (interactive
25031 (list (progn
25032 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
25033 (read-char-exclusive))
25034 current-prefix-arg))
25035 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
25036 (error "Invalid export key"))
25037 (let* ((binding (cdr (assoc type
25038 '((?a . org-export-as-ascii)
25039 (?\C-a . org-export-as-ascii)
25040 (?b . org-export-as-html-and-open)
25041 (?\C-b . org-export-as-html-and-open)
25042 (?h . org-export-as-html)
25043 (?H . org-export-as-html-to-buffer)
25044 (?R . org-export-region-as-html)
25045 (?x . org-export-as-xoxo)))))
25046 (keepp (equal type ?\ ))
25047 (file buffer-file-name)
25048 (buffer (get-buffer-create "*Org Export Visible*"))
25049 s e)
25050 ;; Need to hack the drawers here.
25051 (save-excursion
25052 (goto-char (point-min))
25053 (while (re-search-forward org-drawer-regexp nil t)
25054 (goto-char (match-beginning 1))
25055 (or (org-invisible-p) (org-flag-drawer nil))))
25056 (with-current-buffer buffer (erase-buffer))
25057 (save-excursion
25058 (setq s (goto-char (point-min)))
25059 (while (not (= (point) (point-max)))
25060 (goto-char (org-find-invisible))
25061 (append-to-buffer buffer s (point))
25062 (setq s (goto-char (org-find-visible))))
25063 (org-cycle-hide-drawers 'all)
25064 (goto-char (point-min))
25065 (unless keepp
25066 ;; Copy all comment lines to the end, to make sure #+ settings are
25067 ;; still available for the second export step. Kind of a hack, but
25068 ;; does do the trick.
25069 (if (looking-at "#[^\r\n]*")
25070 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
25071 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
25072 (append-to-buffer buffer (1+ (match-beginning 0))
25073 (min (point-max) (1+ (match-end 0))))))
25074 (set-buffer buffer)
25075 (let ((buffer-file-name file)
25076 (org-inhibit-startup t))
25077 (org-mode)
25078 (show-all)
25079 (unless keepp (funcall binding arg))))
25080 (if (not keepp)
25081 (kill-buffer buffer)
25082 (switch-to-buffer-other-window buffer)
25083 (goto-char (point-min)))))
25085 (defun org-find-visible ()
25086 (let ((s (point)))
25087 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25088 (get-char-property s 'invisible)))
25090 (defun org-find-invisible ()
25091 (let ((s (point)))
25092 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25093 (not (get-char-property s 'invisible))))
25096 ;;; HTML export
25098 (defun org-get-current-options ()
25099 "Return a string with current options as keyword options.
25100 Does include HTML export options as well as TODO and CATEGORY stuff."
25101 (format
25102 "#+TITLE: %s
25103 #+AUTHOR: %s
25104 #+EMAIL: %s
25105 #+DATE: %s
25106 #+LANGUAGE: %s
25107 #+TEXT: Some descriptive text to be emitted. Several lines OK.
25108 #+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
25109 #+CATEGORY: %s
25110 #+SEQ_TODO: %s
25111 #+TYP_TODO: %s
25112 #+PRIORITIES: %c %c %c
25113 #+DRAWERS: %s
25114 #+STARTUP: %s %s %s %s %s
25115 #+TAGS: %s
25116 #+ARCHIVE: %s
25117 #+LINK: %s
25119 (buffer-name) (user-full-name) user-mail-address
25120 (format-time-string (car org-time-stamp-formats))
25121 org-export-default-language
25122 org-export-headline-levels
25123 org-export-with-section-numbers
25124 org-export-with-toc
25125 org-export-preserve-breaks
25126 org-export-html-expand
25127 org-export-with-fixed-width
25128 org-export-with-tables
25129 org-export-with-sub-superscripts
25130 org-export-with-special-strings
25131 org-export-with-footnotes
25132 org-export-with-emphasize
25133 org-export-with-TeX-macros
25134 org-export-with-LaTeX-fragments
25135 org-export-skip-text-before-1st-heading
25136 org-export-with-drawers
25137 org-export-with-tags
25138 (file-name-nondirectory buffer-file-name)
25139 "TODO FEEDBACK VERIFY DONE"
25140 "Me Jason Marie DONE"
25141 org-highest-priority org-lowest-priority org-default-priority
25142 (mapconcat 'identity org-drawers " ")
25143 (cdr (assoc org-startup-folded
25144 '((nil . "showall") (t . "overview") (content . "content"))))
25145 (if org-odd-levels-only "odd" "oddeven")
25146 (if org-hide-leading-stars "hidestars" "showstars")
25147 (if org-startup-align-all-tables "align" "noalign")
25148 (cond ((eq org-log-done t) "logdone")
25149 ((equal org-log-done 'note) "lognotedone")
25150 ((not org-log-done) "nologdone"))
25151 (or (mapconcat (lambda (x)
25152 (cond
25153 ((equal '(:startgroup) x) "{")
25154 ((equal '(:endgroup) x) "}")
25155 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
25156 (t (car x))))
25157 (or org-tag-alist (org-get-buffer-tags)) " ") "")
25158 org-archive-location
25159 "org file:~/org/%s.org"
25162 (defun org-insert-export-options-template ()
25163 "Insert into the buffer a template with information for exporting."
25164 (interactive)
25165 (if (not (bolp)) (newline))
25166 (let ((s (org-get-current-options)))
25167 (and (string-match "#\\+CATEGORY" s)
25168 (setq s (substring s 0 (match-beginning 0))))
25169 (insert s)))
25171 (defun org-toggle-fixed-width-section (arg)
25172 "Toggle the fixed-width export.
25173 If there is no active region, the QUOTE keyword at the current headline is
25174 inserted or removed. When present, it causes the text between this headline
25175 and the next to be exported as fixed-width text, and unmodified.
25176 If there is an active region, this command adds or removes a colon as the
25177 first character of this line. If the first character of a line is a colon,
25178 this line is also exported in fixed-width font."
25179 (interactive "P")
25180 (let* ((cc 0)
25181 (regionp (org-region-active-p))
25182 (beg (if regionp (region-beginning) (point)))
25183 (end (if regionp (region-end)))
25184 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
25185 (case-fold-search nil)
25186 (re "[ \t]*\\(:\\)")
25187 off)
25188 (if regionp
25189 (save-excursion
25190 (goto-char beg)
25191 (setq cc (current-column))
25192 (beginning-of-line 1)
25193 (setq off (looking-at re))
25194 (while (> nlines 0)
25195 (setq nlines (1- nlines))
25196 (beginning-of-line 1)
25197 (cond
25198 (arg
25199 (move-to-column cc t)
25200 (insert ":\n")
25201 (forward-line -1))
25202 ((and off (looking-at re))
25203 (replace-match "" t t nil 1))
25204 ((not off) (move-to-column cc t) (insert ":")))
25205 (forward-line 1)))
25206 (save-excursion
25207 (org-back-to-heading)
25208 (if (looking-at (concat outline-regexp
25209 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
25210 (replace-match "" t t nil 1)
25211 (if (looking-at outline-regexp)
25212 (progn
25213 (goto-char (match-end 0))
25214 (insert org-quote-string " "))))))))
25216 (defun org-export-as-html-and-open (arg)
25217 "Export the outline as HTML and immediately open it with a browser.
25218 If there is an active region, export only the region.
25219 The prefix ARG specifies how many levels of the outline should become
25220 headlines. The default is 3. Lower levels will become bulleted lists."
25221 (interactive "P")
25222 (org-export-as-html arg 'hidden)
25223 (org-open-file buffer-file-name))
25225 (defun org-export-as-html-batch ()
25226 "Call `org-export-as-html', may be used in batch processing as
25227 emacs --batch
25228 --load=$HOME/lib/emacs/org.el
25229 --eval \"(setq org-export-headline-levels 2)\"
25230 --visit=MyFile --funcall org-export-as-html-batch"
25231 (org-export-as-html org-export-headline-levels 'hidden))
25233 (defun org-export-as-html-to-buffer (arg)
25234 "Call `org-exort-as-html` with output to a temporary buffer.
25235 No file is created. The prefix ARG is passed through to `org-export-as-html'."
25236 (interactive "P")
25237 (org-export-as-html arg nil nil "*Org HTML Export*")
25238 (switch-to-buffer-other-window "*Org HTML Export*"))
25240 (defun org-replace-region-by-html (beg end)
25241 "Assume the current region has org-mode syntax, and convert it to HTML.
25242 This can be used in any buffer. For example, you could write an
25243 itemized list in org-mode syntax in an HTML buffer and then use this
25244 command to convert it."
25245 (interactive "r")
25246 (let (reg html buf pop-up-frames)
25247 (save-window-excursion
25248 (if (org-mode-p)
25249 (setq html (org-export-region-as-html
25250 beg end t 'string))
25251 (setq reg (buffer-substring beg end)
25252 buf (get-buffer-create "*Org tmp*"))
25253 (with-current-buffer buf
25254 (erase-buffer)
25255 (insert reg)
25256 (org-mode)
25257 (setq html (org-export-region-as-html
25258 (point-min) (point-max) t 'string)))
25259 (kill-buffer buf)))
25260 (delete-region beg end)
25261 (insert html)))
25263 (defun org-export-region-as-html (beg end &optional body-only buffer)
25264 "Convert region from BEG to END in org-mode buffer to HTML.
25265 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
25266 contents, and only produce the region of converted text, useful for
25267 cut-and-paste operations.
25268 If BUFFER is a buffer or a string, use/create that buffer as a target
25269 of the converted HTML. If BUFFER is the symbol `string', return the
25270 produced HTML as a string and leave not buffer behind. For example,
25271 a Lisp program could call this function in the following way:
25273 (setq html (org-export-region-as-html beg end t 'string))
25275 When called interactively, the output buffer is selected, and shown
25276 in a window. A non-interactive call will only retunr the buffer."
25277 (interactive "r\nP")
25278 (when (interactive-p)
25279 (setq buffer "*Org HTML Export*"))
25280 (let ((transient-mark-mode t) (zmacs-regions t)
25281 rtn)
25282 (goto-char end)
25283 (set-mark (point)) ;; to activate the region
25284 (goto-char beg)
25285 (setq rtn (org-export-as-html
25286 nil nil nil
25287 buffer body-only))
25288 (if (fboundp 'deactivate-mark) (deactivate-mark))
25289 (if (and (interactive-p) (bufferp rtn))
25290 (switch-to-buffer-other-window rtn)
25291 rtn)))
25293 (defvar html-table-tag nil) ; dynamically scoped into this.
25294 (defun org-export-as-html (arg &optional hidden ext-plist
25295 to-buffer body-only pub-dir)
25296 "Export the outline as a pretty HTML file.
25297 If there is an active region, export only the region. The prefix
25298 ARG specifies how many levels of the outline should become
25299 headlines. The default is 3. Lower levels will become bulleted
25300 lists. When HIDDEN is non-nil, don't display the HTML buffer.
25301 EXT-PLIST is a property list with external parameters overriding
25302 org-mode's default settings, but still inferior to file-local
25303 settings. When TO-BUFFER is non-nil, create a buffer with that
25304 name and export to that buffer. If TO-BUFFER is the symbol
25305 `string', don't leave any buffer behind but just return the
25306 resulting HTML as a string. When BODY-ONLY is set, don't produce
25307 the file header and footer, simply return the content of
25308 <body>...</body>, without even the body tags themselves. When
25309 PUB-DIR is set, use this as the publishing directory."
25310 (interactive "P")
25312 ;; Make sure we have a file name when we need it.
25313 (when (and (not (or to-buffer body-only))
25314 (not buffer-file-name))
25315 (if (buffer-base-buffer)
25316 (org-set-local 'buffer-file-name
25317 (with-current-buffer (buffer-base-buffer)
25318 buffer-file-name))
25319 (error "Need a file name to be able to export.")))
25321 (message "Exporting...")
25322 (setq-default org-todo-line-regexp org-todo-line-regexp)
25323 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
25324 (setq-default org-done-keywords org-done-keywords)
25325 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
25326 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25327 ext-plist
25328 (org-infile-export-plist)))
25330 (style (plist-get opt-plist :style))
25331 (html-extension (plist-get opt-plist :html-extension))
25332 (link-validate (plist-get opt-plist :link-validation-function))
25333 valid thetoc have-headings first-heading-pos
25334 (odd org-odd-levels-only)
25335 (region-p (org-region-active-p))
25336 (subtree-p
25337 (when region-p
25338 (save-excursion
25339 (goto-char (region-beginning))
25340 (and (org-at-heading-p)
25341 (>= (org-end-of-subtree t t) (region-end))))))
25342 ;; The following two are dynamically scoped into other
25343 ;; routines below.
25344 (org-current-export-dir
25345 (or pub-dir (org-export-directory :html opt-plist)))
25346 (org-current-export-file buffer-file-name)
25347 (level 0) (line "") (origline "") txt todo
25348 (umax nil)
25349 (umax-toc nil)
25350 (filename (if to-buffer nil
25351 (expand-file-name
25352 (concat
25353 (file-name-sans-extension
25354 (or (and subtree-p
25355 (org-entry-get (region-beginning)
25356 "EXPORT_FILE_NAME" t))
25357 (file-name-nondirectory buffer-file-name)))
25358 "." html-extension)
25359 (file-name-as-directory
25360 (or pub-dir (org-export-directory :html opt-plist))))))
25361 (current-dir (if buffer-file-name
25362 (file-name-directory buffer-file-name)
25363 default-directory))
25364 (buffer (if to-buffer
25365 (cond
25366 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
25367 (t (get-buffer-create to-buffer)))
25368 (find-file-noselect filename)))
25369 (org-levels-open (make-vector org-level-max nil))
25370 (date (plist-get opt-plist :date))
25371 (author (plist-get opt-plist :author))
25372 (title (or (and subtree-p (org-export-get-title-from-subtree))
25373 (plist-get opt-plist :title)
25374 (and (not
25375 (plist-get opt-plist :skip-before-1st-heading))
25376 (org-export-grab-title-from-buffer))
25377 (and buffer-file-name
25378 (file-name-sans-extension
25379 (file-name-nondirectory buffer-file-name)))
25380 "UNTITLED"))
25381 (html-table-tag (plist-get opt-plist :html-table-tag))
25382 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
25383 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
25384 (inquote nil)
25385 (infixed nil)
25386 (in-local-list nil)
25387 (local-list-num nil)
25388 (local-list-indent nil)
25389 (llt org-plain-list-ordered-item-terminator)
25390 (email (plist-get opt-plist :email))
25391 (language (plist-get opt-plist :language))
25392 (lang-words nil)
25393 (target-alist nil) tg
25394 (head-count 0) cnt
25395 (start 0)
25396 (coding-system (and (boundp 'buffer-file-coding-system)
25397 buffer-file-coding-system))
25398 (coding-system-for-write (or org-export-html-coding-system
25399 coding-system))
25400 (save-buffer-coding-system (or org-export-html-coding-system
25401 coding-system))
25402 (charset (and coding-system-for-write
25403 (fboundp 'coding-system-get)
25404 (coding-system-get coding-system-for-write
25405 'mime-charset)))
25406 (region
25407 (buffer-substring
25408 (if region-p (region-beginning) (point-min))
25409 (if region-p (region-end) (point-max))))
25410 (lines
25411 (org-split-string
25412 (org-cleaned-string-for-export
25413 region
25414 :emph-multiline t
25415 :for-html t
25416 :skip-before-1st-heading
25417 (plist-get opt-plist :skip-before-1st-heading)
25418 :drawers (plist-get opt-plist :drawers)
25419 :archived-trees
25420 (plist-get opt-plist :archived-trees)
25421 :add-text
25422 (plist-get opt-plist :text)
25423 :LaTeX-fragments
25424 (plist-get opt-plist :LaTeX-fragments))
25425 "[\r\n]"))
25426 table-open type
25427 table-buffer table-orig-buffer
25428 ind start-is-num starter didclose
25429 rpl path desc descp desc1 desc2 link
25430 snumber fnc
25433 (let ((inhibit-read-only t))
25434 (org-unmodified
25435 (remove-text-properties (point-min) (point-max)
25436 '(:org-license-to-kill t))))
25438 (message "Exporting...")
25440 (setq org-min-level (org-get-min-level lines))
25441 (setq org-last-level org-min-level)
25442 (org-init-section-numbers)
25444 (cond
25445 ((and date (string-match "%" date))
25446 (setq date (format-time-string date)))
25447 (date)
25448 (t (setq date (format-time-string "%Y/%m/%d %X"))))
25450 ;; Get the language-dependent settings
25451 (setq lang-words (or (assoc language org-export-language-setup)
25452 (assoc "en" org-export-language-setup)))
25454 ;; Switch to the output buffer
25455 (set-buffer buffer)
25456 (let ((inhibit-read-only t)) (erase-buffer))
25457 (fundamental-mode)
25459 (and (fboundp 'set-buffer-file-coding-system)
25460 (set-buffer-file-coding-system coding-system-for-write))
25462 (let ((case-fold-search nil)
25463 (org-odd-levels-only odd))
25464 ;; create local variables for all options, to make sure all called
25465 ;; functions get the correct information
25466 (mapc (lambda (x)
25467 (set (make-local-variable (cdr x))
25468 (plist-get opt-plist (car x))))
25469 org-export-plist-vars)
25470 (setq umax (if arg (prefix-numeric-value arg)
25471 org-export-headline-levels))
25472 (setq umax-toc (if (integerp org-export-with-toc)
25473 (min org-export-with-toc umax)
25474 umax))
25475 (unless body-only
25476 ;; File header
25477 (insert (format
25478 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25479 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25480 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25481 lang=\"%s\" xml:lang=\"%s\">
25482 <head>
25483 <title>%s</title>
25484 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25485 <meta name=\"generator\" content=\"Org-mode\"/>
25486 <meta name=\"generated\" content=\"%s\"/>
25487 <meta name=\"author\" content=\"%s\"/>
25489 </head><body>
25491 language language (org-html-expand title)
25492 (or charset "iso-8859-1") date author style))
25494 (insert (or (plist-get opt-plist :preamble) ""))
25496 (when (plist-get opt-plist :auto-preamble)
25497 (if title (insert (format org-export-html-title-format
25498 (org-html-expand title))))))
25500 (if (and org-export-with-toc (not body-only))
25501 (progn
25502 (push (format "<h%d>%s</h%d>\n"
25503 org-export-html-toplevel-hlevel
25504 (nth 3 lang-words)
25505 org-export-html-toplevel-hlevel)
25506 thetoc)
25507 (push "<div id=\"text-table-of-contents\">\n" thetoc)
25508 (push "<ul>\n<li>" thetoc)
25509 (setq lines
25510 (mapcar '(lambda (line)
25511 (if (string-match org-todo-line-regexp line)
25512 ;; This is a headline
25513 (progn
25514 (setq have-headings t)
25515 (setq level (- (match-end 1) (match-beginning 1))
25516 level (org-tr-level level)
25517 txt (save-match-data
25518 (org-html-expand
25519 (org-export-cleanup-toc-line
25520 (match-string 3 line))))
25521 todo
25522 (or (and org-export-mark-todo-in-toc
25523 (match-beginning 2)
25524 (not (member (match-string 2 line)
25525 org-done-keywords)))
25526 ; TODO, not DONE
25527 (and org-export-mark-todo-in-toc
25528 (= level umax-toc)
25529 (org-search-todo-below
25530 line lines level))))
25531 (if (string-match
25532 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25533 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25534 (if (string-match quote-re0 txt)
25535 (setq txt (replace-match "" t t txt)))
25536 (setq snumber (org-section-number level))
25537 (if org-export-with-section-numbers
25538 (setq txt (concat snumber " " txt)))
25539 (if (<= level (max umax umax-toc))
25540 (setq head-count (+ head-count 1)))
25541 (if (<= level umax-toc)
25542 (progn
25543 (if (> level org-last-level)
25544 (progn
25545 (setq cnt (- level org-last-level))
25546 (while (>= (setq cnt (1- cnt)) 0)
25547 (push "\n<ul>\n<li>" thetoc))
25548 (push "\n" thetoc)))
25549 (if (< level org-last-level)
25550 (progn
25551 (setq cnt (- org-last-level level))
25552 (while (>= (setq cnt (1- cnt)) 0)
25553 (push "</li>\n</ul>" thetoc))
25554 (push "\n" thetoc)))
25555 ;; Check for targets
25556 (while (string-match org-target-regexp line)
25557 (setq tg (match-string 1 line)
25558 line (replace-match
25559 (concat "@<span class=\"target\">" tg "@</span> ")
25560 t t line))
25561 (push (cons (org-solidify-link-text tg)
25562 (format "sec-%s" snumber))
25563 target-alist))
25564 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25565 (setq txt (replace-match "" t t txt)))
25566 (push
25567 (format
25568 (if todo
25569 "</li>\n<li><a href=\"#sec-%s\"><span class=\"todo\">%s</span></a>"
25570 "</li>\n<li><a href=\"#sec-%s\">%s</a>")
25571 snumber txt) thetoc)
25573 (setq org-last-level level))
25575 line)
25576 lines))
25577 (while (> org-last-level (1- org-min-level))
25578 (setq org-last-level (1- org-last-level))
25579 (push "</li>\n</ul>\n" thetoc))
25580 (push "</div>\n" thetoc)
25581 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25583 (setq head-count 0)
25584 (org-init-section-numbers)
25586 (while (setq line (pop lines) origline line)
25587 (catch 'nextline
25589 ;; end of quote section?
25590 (when (and inquote (string-match "^\\*+ " line))
25591 (insert "</pre>\n")
25592 (setq inquote nil))
25593 ;; inside a quote section?
25594 (when inquote
25595 (insert (org-html-protect line) "\n")
25596 (throw 'nextline nil))
25598 ;; verbatim lines
25599 (when (and org-export-with-fixed-width
25600 (string-match "^[ \t]*:\\(.*\\)" line))
25601 (when (not infixed)
25602 (setq infixed t)
25603 (insert "<pre>\n"))
25604 (insert (org-html-protect (match-string 1 line)) "\n")
25605 (when (and lines
25606 (not (string-match "^[ \t]*\\(:.*\\)"
25607 (car lines))))
25608 (setq infixed nil)
25609 (insert "</pre>\n"))
25610 (throw 'nextline nil))
25612 ;; Protected HTML
25613 (when (get-text-property 0 'org-protected line)
25614 (let (par)
25615 (when (re-search-backward
25616 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25617 (setq par (match-string 1))
25618 (replace-match "\\2\n"))
25619 (insert line "\n")
25620 (while (and lines
25621 (or (= (length (car lines)) 0)
25622 (get-text-property 0 'org-protected (car lines))))
25623 (insert (pop lines) "\n"))
25624 (and par (insert "<p>\n")))
25625 (throw 'nextline nil))
25627 ;; Horizontal line
25628 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25629 (insert "\n<hr/>\n")
25630 (throw 'nextline nil))
25632 ;; make targets to anchors
25633 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25634 (cond
25635 ((match-end 2)
25636 (setq line (replace-match
25637 (concat "@<a name=\""
25638 (org-solidify-link-text (match-string 1 line))
25639 "\">\\nbsp@</a>")
25640 t t line)))
25641 ((and org-export-with-toc (equal (string-to-char line) ?*))
25642 (setq line (replace-match
25643 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25644 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25645 t t line)))
25647 (setq line (replace-match
25648 (concat "@<a name=\""
25649 (org-solidify-link-text (match-string 1 line))
25650 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25651 t t line)))))
25653 (setq line (org-html-handle-time-stamps line))
25655 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25656 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25657 ;; Also handle sub_superscripts and checkboxes
25658 (or (string-match org-table-hline-regexp line)
25659 (setq line (org-html-expand line)))
25661 ;; Format the links
25662 (setq start 0)
25663 (while (string-match org-bracket-link-analytic-regexp line start)
25664 (setq start (match-beginning 0))
25665 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25666 (setq path (match-string 3 line))
25667 (setq desc1 (if (match-end 5) (match-string 5 line))
25668 desc2 (if (match-end 2) (concat type ":" path) path)
25669 descp (and desc1 (not (equal desc1 desc2)))
25670 desc (or desc1 desc2))
25671 ;; Make an image out of the description if that is so wanted
25672 (when (and descp (org-file-image-p desc))
25673 (save-match-data
25674 (if (string-match "^file:" desc)
25675 (setq desc (substring desc (match-end 0)))))
25676 (setq desc (concat "<img src=\"" desc "\"/>")))
25677 ;; FIXME: do we need to unescape here somewhere?
25678 (cond
25679 ((equal type "internal")
25680 (setq rpl
25681 (concat
25682 "<a href=\"#"
25683 (org-solidify-link-text
25684 (save-match-data (org-link-unescape path)) target-alist)
25685 "\">" desc "</a>")))
25686 ((member type '("http" "https"))
25687 ;; standard URL, just check if we need to inline an image
25688 (if (and (or (eq t org-export-html-inline-images)
25689 (and org-export-html-inline-images (not descp)))
25690 (org-file-image-p path))
25691 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25692 (setq link (concat type ":" path))
25693 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25694 ((member type '("ftp" "mailto" "news"))
25695 ;; standard URL
25696 (setq link (concat type ":" path))
25697 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25698 ((string= type "file")
25699 ;; FILE link
25700 (let* ((filename path)
25701 (abs-p (file-name-absolute-p filename))
25702 thefile file-is-image-p search)
25703 (save-match-data
25704 (if (string-match "::\\(.*\\)" filename)
25705 (setq search (match-string 1 filename)
25706 filename (replace-match "" t nil filename)))
25707 (setq valid
25708 (if (functionp link-validate)
25709 (funcall link-validate filename current-dir)
25711 (setq file-is-image-p (org-file-image-p filename))
25712 (setq thefile (if abs-p (expand-file-name filename) filename))
25713 (when (and org-export-html-link-org-files-as-html
25714 (string-match "\\.org$" thefile))
25715 (setq thefile (concat (substring thefile 0
25716 (match-beginning 0))
25717 "." html-extension))
25718 (if (and search
25719 ;; make sure this is can be used as target search
25720 (not (string-match "^[0-9]*$" search))
25721 (not (string-match "^\\*" search))
25722 (not (string-match "^/.*/$" search)))
25723 (setq thefile (concat thefile "#"
25724 (org-solidify-link-text
25725 (org-link-unescape search)))))
25726 (when (string-match "^file:" desc)
25727 (setq desc (replace-match "" t t desc))
25728 (if (string-match "\\.org$" desc)
25729 (setq desc (replace-match "" t t desc))))))
25730 (setq rpl (if (and file-is-image-p
25731 (or (eq t org-export-html-inline-images)
25732 (and org-export-html-inline-images
25733 (not descp))))
25734 (concat "<img src=\"" thefile "\"/>")
25735 (concat "<a href=\"" thefile "\">" desc "</a>")))
25736 (if (not valid) (setq rpl desc))))
25738 ((functionp (setq fnc (nth 2 (assoc type org-link-protocols))))
25739 (setq rpl
25740 (save-match-data
25741 (funcall fnc (org-link-unescape path) desc1 'html))))
25744 ;; just publish the path, as default
25745 (setq rpl (concat "<i>&lt;" type ":"
25746 (save-match-data (org-link-unescape path))
25747 "&gt;</i>"))))
25748 (setq line (replace-match rpl t t line)
25749 start (+ start (length rpl))))
25751 ;; TODO items
25752 (if (and (string-match org-todo-line-regexp line)
25753 (match-beginning 2))
25755 (setq line
25756 (concat (substring line 0 (match-beginning 2))
25757 "<span class=\""
25758 (if (member (match-string 2 line)
25759 org-done-keywords)
25760 "done" "todo")
25761 "\">" (match-string 2 line)
25762 "</span>" (substring line (match-end 2)))))
25764 ;; Does this contain a reference to a footnote?
25765 (when org-export-with-footnotes
25766 (setq start 0)
25767 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25768 (if (get-text-property (match-beginning 2) 'org-protected line)
25769 (setq start (match-end 2))
25770 (let ((n (match-string 2 line)))
25771 (setq line
25772 (replace-match
25773 (format
25774 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25775 (match-string 1 line) n n n)
25776 t t line))))))
25778 (cond
25779 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25780 ;; This is a headline
25781 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25782 txt (match-string 2 line))
25783 (if (string-match quote-re0 txt)
25784 (setq txt (replace-match "" t t txt)))
25785 (if (<= level (max umax umax-toc))
25786 (setq head-count (+ head-count 1)))
25787 (when in-local-list
25788 ;; Close any local lists before inserting a new header line
25789 (while local-list-num
25790 (org-close-li)
25791 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25792 (pop local-list-num))
25793 (setq local-list-indent nil
25794 in-local-list nil))
25795 (setq first-heading-pos (or first-heading-pos (point)))
25796 (org-html-level-start level txt umax
25797 (and org-export-with-toc (<= level umax))
25798 head-count)
25799 ;; QUOTES
25800 (when (string-match quote-re line)
25801 (insert "<pre>")
25802 (setq inquote t)))
25804 ((and org-export-with-tables
25805 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25806 (if (not table-open)
25807 ;; New table starts
25808 (setq table-open t table-buffer nil table-orig-buffer nil))
25809 ;; Accumulate lines
25810 (setq table-buffer (cons line table-buffer)
25811 table-orig-buffer (cons origline table-orig-buffer))
25812 (when (or (not lines)
25813 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25814 (car lines))))
25815 (setq table-open nil
25816 table-buffer (nreverse table-buffer)
25817 table-orig-buffer (nreverse table-orig-buffer))
25818 (org-close-par-maybe)
25819 (insert (org-format-table-html table-buffer table-orig-buffer))))
25821 ;; Normal lines
25822 (when (string-match
25823 (cond
25824 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25825 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25826 ((= llt ?\)) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25827 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25828 line)
25829 (setq ind (org-get-string-indentation line)
25830 start-is-num (match-beginning 4)
25831 starter (if (match-beginning 2)
25832 (substring (match-string 2 line) 0 -1))
25833 line (substring line (match-beginning 5)))
25834 (unless (string-match "[^ \t]" line)
25835 ;; empty line. Pretend indentation is large.
25836 (setq ind (if org-empty-line-terminates-plain-lists
25838 (1+ (or (car local-list-indent) 1)))))
25839 (setq didclose nil)
25840 (while (and in-local-list
25841 (or (and (= ind (car local-list-indent))
25842 (not starter))
25843 (< ind (car local-list-indent))))
25844 (setq didclose t)
25845 (org-close-li)
25846 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25847 (pop local-list-num) (pop local-list-indent)
25848 (setq in-local-list local-list-indent))
25849 (cond
25850 ((and starter
25851 (or (not in-local-list)
25852 (> ind (car local-list-indent))))
25853 ;; Start new (level of) list
25854 (org-close-par-maybe)
25855 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25856 (push start-is-num local-list-num)
25857 (push ind local-list-indent)
25858 (setq in-local-list t))
25859 (starter
25860 ;; continue current list
25861 (org-close-li)
25862 (insert "<li>\n"))
25863 (didclose
25864 ;; we did close a list, normal text follows: need <p>
25865 (org-open-par)))
25866 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25867 (setq line
25868 (replace-match
25869 (if (equal (match-string 1 line) "X")
25870 "<b>[X]</b>"
25871 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25872 t t line))))
25874 ;; Empty lines start a new paragraph. If hand-formatted lists
25875 ;; are not fully interpreted, lines starting with "-", "+", "*"
25876 ;; also start a new paragraph.
25877 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25879 ;; Is this the start of a footnote?
25880 (when org-export-with-footnotes
25881 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25882 (org-close-par-maybe)
25883 (let ((n (match-string 1 line)))
25884 (setq line (replace-match
25885 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25887 ;; Check if the line break needs to be conserved
25888 (cond
25889 ((string-match "\\\\\\\\[ \t]*$" line)
25890 (setq line (replace-match "<br/>" t t line)))
25891 (org-export-preserve-breaks
25892 (setq line (concat line "<br/>"))))
25894 (insert line "\n")))))
25896 ;; Properly close all local lists and other lists
25897 (when inquote (insert "</pre>\n"))
25898 (when in-local-list
25899 ;; Close any local lists before inserting a new header line
25900 (while local-list-num
25901 (org-close-li)
25902 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25903 (pop local-list-num))
25904 (setq local-list-indent nil
25905 in-local-list nil))
25906 (org-html-level-start 1 nil umax
25907 (and org-export-with-toc (<= level umax))
25908 head-count)
25909 ;; the </div> to lose the last text-... div.
25910 (insert "</div>\n")
25912 (unless body-only
25913 (when (plist-get opt-plist :auto-postamble)
25914 (insert "<div id=\"postamble\">")
25915 (when (and org-export-author-info author)
25916 (insert "<p class=\"author\"> "
25917 (nth 1 lang-words) ": " author "\n")
25918 (when email
25919 (if (listp (split-string email ",+ *"))
25920 (mapc (lambda(e)
25921 (insert "<a href=\"mailto:" e "\">&lt;"
25922 e "&gt;</a>\n"))
25923 (split-string email ",+ *"))
25924 (insert "<a href=\"mailto:" email "\">&lt;"
25925 email "&gt;</a>\n")))
25926 (insert "</p>\n"))
25927 (when (and date org-export-time-stamp-file)
25928 (insert "<p class=\"date\"> "
25929 (nth 2 lang-words) ": "
25930 date "</p>\n"))
25931 (insert "</div>"))
25933 (if org-export-html-with-timestamp
25934 (insert org-export-html-html-helper-timestamp))
25935 (insert (or (plist-get opt-plist :postamble) ""))
25936 (insert "</body>\n</html>\n"))
25938 (normal-mode)
25939 (if (eq major-mode default-major-mode) (html-mode))
25941 ;; insert the table of contents
25942 (goto-char (point-min))
25943 (when thetoc
25944 (if (or (re-search-forward
25945 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25946 (re-search-forward
25947 "\\[TABLE-OF-CONTENTS\\]" nil t))
25948 (progn
25949 (goto-char (match-beginning 0))
25950 (replace-match ""))
25951 (goto-char first-heading-pos)
25952 (when (looking-at "\\s-*</p>")
25953 (goto-char (match-end 0))
25954 (insert "\n")))
25955 (insert "<div id=\"table-of-contents\">\n")
25956 (mapc 'insert thetoc)
25957 (insert "</div>\n"))
25958 ;; remove empty paragraphs and lists
25959 (goto-char (point-min))
25960 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25961 (replace-match ""))
25962 (goto-char (point-min))
25963 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25964 (replace-match ""))
25965 (goto-char (point-min))
25966 (while (re-search-forward "</ul>\\s-*<ul>\n?" nil t)
25967 (replace-match ""))
25968 ;; Convert whitespace place holders
25969 (goto-char (point-min))
25970 (let (beg end n)
25971 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25972 (setq n (get-text-property beg 'org-whitespace)
25973 end (next-single-property-change beg 'org-whitespace))
25974 (goto-char beg)
25975 (delete-region beg end)
25976 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25977 (make-string n ?x)))))
25978 (or to-buffer (save-buffer))
25979 (goto-char (point-min))
25980 (message "Exporting... done")
25981 (if (eq to-buffer 'string)
25982 (prog1 (buffer-substring (point-min) (point-max))
25983 (kill-buffer (current-buffer)))
25984 (current-buffer)))))
25986 (defvar org-table-colgroup-info nil)
25987 (defun org-format-table-ascii (lines)
25988 "Format a table for ascii export."
25989 (if (stringp lines)
25990 (setq lines (org-split-string lines "\n")))
25991 (if (not (string-match "^[ \t]*|" (car lines)))
25992 ;; Table made by table.el - test for spanning
25993 lines
25995 ;; A normal org table
25996 ;; Get rid of hlines at beginning and end
25997 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25998 (setq lines (nreverse lines))
25999 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26000 (setq lines (nreverse lines))
26001 (when org-export-table-remove-special-lines
26002 ;; Check if the table has a marking column. If yes remove the
26003 ;; column and the special lines
26004 (setq lines (org-table-clean-before-export lines)))
26005 ;; Get rid of the vertical lines except for grouping
26006 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
26007 rtn line vl1 start)
26008 (while (setq line (pop lines))
26009 (if (string-match org-table-hline-regexp line)
26010 (and (string-match "|\\(.*\\)|" line)
26011 (setq line (replace-match " \\1" t nil line)))
26012 (setq start 0 vl1 vl)
26013 (while (string-match "|" line start)
26014 (setq start (match-end 0))
26015 (or (pop vl1) (setq line (replace-match " " t t line)))))
26016 (push line rtn))
26017 (nreverse rtn))))
26019 (defun org-colgroup-info-to-vline-list (info)
26020 (let (vl new last)
26021 (while info
26022 (setq last new new (pop info))
26023 (if (or (memq last '(:end :startend))
26024 (memq new '(:start :startend)))
26025 (push t vl)
26026 (push nil vl)))
26027 (setq vl (nreverse vl))
26028 (and vl (setcar vl nil))
26029 vl))
26031 (defun org-format-table-html (lines olines)
26032 "Find out which HTML converter to use and return the HTML code."
26033 (if (stringp lines)
26034 (setq lines (org-split-string lines "\n")))
26035 (if (string-match "^[ \t]*|" (car lines))
26036 ;; A normal org table
26037 (org-format-org-table-html lines)
26038 ;; Table made by table.el - test for spanning
26039 (let* ((hlines (delq nil (mapcar
26040 (lambda (x)
26041 (if (string-match "^[ \t]*\\+-" x) x
26042 nil))
26043 lines)))
26044 (first (car hlines))
26045 (ll (and (string-match "\\S-+" first)
26046 (match-string 0 first)))
26047 (re (concat "^[ \t]*" (regexp-quote ll)))
26048 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
26049 hlines))))
26050 (if (and (not spanning)
26051 (not org-export-prefer-native-exporter-for-tables))
26052 ;; We can use my own converter with HTML conversions
26053 (org-format-table-table-html lines)
26054 ;; Need to use the code generator in table.el, with the original text.
26055 (org-format-table-table-html-using-table-generate-source olines)))))
26057 (defun org-format-org-table-html (lines &optional splice)
26058 "Format a table into HTML."
26059 ;; Get rid of hlines at beginning and end
26060 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26061 (setq lines (nreverse lines))
26062 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26063 (setq lines (nreverse lines))
26064 (when org-export-table-remove-special-lines
26065 ;; Check if the table has a marking column. If yes remove the
26066 ;; column and the special lines
26067 (setq lines (org-table-clean-before-export lines)))
26069 (let ((head (and org-export-highlight-first-table-line
26070 (delq nil (mapcar
26071 (lambda (x) (string-match "^[ \t]*|-" x))
26072 (cdr lines)))))
26073 (nlines 0) fnum i
26074 tbopen line fields html gr colgropen)
26075 (if splice (setq head nil))
26076 (unless splice (push (if head "<thead>" "<tbody>") html))
26077 (setq tbopen t)
26078 (while (setq line (pop lines))
26079 (catch 'next-line
26080 (if (string-match "^[ \t]*|-" line)
26081 (progn
26082 (unless splice
26083 (push (if head "</thead>" "</tbody>") html)
26084 (if lines (push "<tbody>" html) (setq tbopen nil)))
26085 (setq head nil) ;; head ends here, first time around
26086 ;; ignore this line
26087 (throw 'next-line t)))
26088 ;; Break the line into fields
26089 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26090 (unless fnum (setq fnum (make-vector (length fields) 0)))
26091 (setq nlines (1+ nlines) i -1)
26092 (push (concat "<tr>"
26093 (mapconcat
26094 (lambda (x)
26095 (setq i (1+ i))
26096 (if (and (< i nlines)
26097 (string-match org-table-number-regexp x))
26098 (incf (aref fnum i)))
26099 (if head
26100 (concat (car org-export-table-header-tags) x
26101 (cdr org-export-table-header-tags))
26102 (concat (car org-export-table-data-tags) x
26103 (cdr org-export-table-data-tags))))
26104 fields "")
26105 "</tr>")
26106 html)))
26107 (unless splice (if tbopen (push "</tbody>" html)))
26108 (unless splice (push "</table>\n" html))
26109 (setq html (nreverse html))
26110 (unless splice
26111 ;; Put in col tags with the alignment (unfortuntely often ignored...)
26112 (push (mapconcat
26113 (lambda (x)
26114 (setq gr (pop org-table-colgroup-info))
26115 (format "%s<col align=\"%s\"></col>%s"
26116 (if (memq gr '(:start :startend))
26117 (prog1
26118 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
26119 (setq colgropen t))
26121 (if (> (/ (float x) nlines) org-table-number-fraction)
26122 "right" "left")
26123 (if (memq gr '(:end :startend))
26124 (progn (setq colgropen nil) "</colgroup>")
26125 "")))
26126 fnum "")
26127 html)
26128 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
26129 (push html-table-tag html))
26130 (concat (mapconcat 'identity html "\n") "\n")))
26132 (defun org-table-clean-before-export (lines)
26133 "Check if the table has a marking column.
26134 If yes remove the column and the special lines."
26135 (setq org-table-colgroup-info nil)
26136 (if (memq nil
26137 (mapcar
26138 (lambda (x) (or (string-match "^[ \t]*|-" x)
26139 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
26140 lines))
26141 (progn
26142 (setq org-table-clean-did-remove-column nil)
26143 (delq nil
26144 (mapcar
26145 (lambda (x)
26146 (cond
26147 ((string-match "^[ \t]*| */ *|" x)
26148 (setq org-table-colgroup-info
26149 (mapcar (lambda (x)
26150 (cond ((member x '("<" "&lt;")) :start)
26151 ((member x '(">" "&gt;")) :end)
26152 ((member x '("<>" "&lt;&gt;")) :startend)
26153 (t nil)))
26154 (org-split-string x "[ \t]*|[ \t]*")))
26155 nil)
26156 (t x)))
26157 lines)))
26158 (setq org-table-clean-did-remove-column t)
26159 (delq nil
26160 (mapcar
26161 (lambda (x)
26162 (cond
26163 ((string-match "^[ \t]*| */ *|" x)
26164 (setq org-table-colgroup-info
26165 (mapcar (lambda (x)
26166 (cond ((member x '("<" "&lt;")) :start)
26167 ((member x '(">" "&gt;")) :end)
26168 ((member x '("<>" "&lt;&gt;")) :startend)
26169 (t nil)))
26170 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
26171 nil)
26172 ((string-match "^[ \t]*| *[!_^/] *|" x)
26173 nil) ; ignore this line
26174 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
26175 (string-match "^\\([ \t]*\\)|[^|]*|" x))
26176 ;; remove the first column
26177 (replace-match "\\1|" t nil x))))
26178 lines))))
26180 (defun org-format-table-table-html (lines)
26181 "Format a table generated by table.el into HTML.
26182 This conversion does *not* use `table-generate-source' from table.el.
26183 This has the advantage that Org-mode's HTML conversions can be used.
26184 But it has the disadvantage, that no cell- or row-spanning is allowed."
26185 (let (line field-buffer
26186 (head org-export-highlight-first-table-line)
26187 fields html empty)
26188 (setq html (concat html-table-tag "\n"))
26189 (while (setq line (pop lines))
26190 (setq empty "&nbsp;")
26191 (catch 'next-line
26192 (if (string-match "^[ \t]*\\+-" line)
26193 (progn
26194 (if field-buffer
26195 (progn
26196 (setq
26197 html
26198 (concat
26199 html
26200 "<tr>"
26201 (mapconcat
26202 (lambda (x)
26203 (if (equal x "") (setq x empty))
26204 (if head
26205 (concat (car org-export-table-header-tags) x
26206 (cdr org-export-table-header-tags))
26207 (concat (car org-export-table-data-tags) x
26208 (cdr org-export-table-data-tags))))
26209 field-buffer "\n")
26210 "</tr>\n"))
26211 (setq head nil)
26212 (setq field-buffer nil)))
26213 ;; Ignore this line
26214 (throw 'next-line t)))
26215 ;; Break the line into fields and store the fields
26216 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26217 (if field-buffer
26218 (setq field-buffer (mapcar
26219 (lambda (x)
26220 (concat x "<br/>" (pop fields)))
26221 field-buffer))
26222 (setq field-buffer fields))))
26223 (setq html (concat html "</table>\n"))
26224 html))
26226 (defun org-format-table-table-html-using-table-generate-source (lines)
26227 "Format a table into html, using `table-generate-source' from table.el.
26228 This has the advantage that cell- or row-spanning is allowed.
26229 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
26230 (require 'table)
26231 (with-current-buffer (get-buffer-create " org-tmp1 ")
26232 (erase-buffer)
26233 (insert (mapconcat 'identity lines "\n"))
26234 (goto-char (point-min))
26235 (if (not (re-search-forward "|[^+]" nil t))
26236 (error "Error processing table"))
26237 (table-recognize-table)
26238 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
26239 (table-generate-source 'html " org-tmp2 ")
26240 (set-buffer " org-tmp2 ")
26241 (buffer-substring (point-min) (point-max))))
26243 (defun org-html-handle-time-stamps (s)
26244 "Format time stamps in string S, or remove them."
26245 (catch 'exit
26246 (let (r b)
26247 (while (string-match org-maybe-keyword-time-regexp s)
26248 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
26249 ;; never export CLOCK
26250 (throw 'exit ""))
26251 (or b (setq b (substring s 0 (match-beginning 0))))
26252 (if (not org-export-with-timestamps)
26253 (setq r (concat r (substring s 0 (match-beginning 0)))
26254 s (substring s (match-end 0)))
26255 (setq r (concat
26256 r (substring s 0 (match-beginning 0))
26257 (if (match-end 1)
26258 (format "@<span class=\"timestamp-kwd\">%s @</span>"
26259 (match-string 1 s)))
26260 (format " @<span class=\"timestamp\">%s@</span>"
26261 (substring
26262 (org-translate-time (match-string 3 s)) 1 -1)))
26263 s (substring s (match-end 0)))))
26264 ;; Line break if line started and ended with time stamp stuff
26265 (if (not r)
26267 (setq r (concat r s))
26268 (unless (string-match "\\S-" (concat b s))
26269 (setq r (concat r "@<br/>")))
26270 r))))
26272 (defun org-html-protect (s)
26273 ;; convert & to &amp;, < to &lt; and > to &gt;
26274 (let ((start 0))
26275 (while (string-match "&" s start)
26276 (setq s (replace-match "&amp;" t t s)
26277 start (1+ (match-beginning 0))))
26278 (while (string-match "<" s)
26279 (setq s (replace-match "&lt;" t t s)))
26280 (while (string-match ">" s)
26281 (setq s (replace-match "&gt;" t t s))))
26284 (defun org-export-cleanup-toc-line (s)
26285 "Remove tags and time staps from lines going into the toc."
26286 (when (memq org-export-with-tags '(not-in-toc nil))
26287 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
26288 (setq s (replace-match "" t t s))))
26289 (when org-export-remove-timestamps-from-toc
26290 (while (string-match org-maybe-keyword-time-regexp s)
26291 (setq s (replace-match "" t t s))))
26292 (while (string-match org-bracket-link-regexp s)
26293 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
26294 t t s)))
26297 (defun org-html-expand (string)
26298 "Prepare STRING for HTML export. Applies all active conversions.
26299 If there are links in the string, don't modify these."
26300 (let* ((re (concat org-bracket-link-regexp "\\|"
26301 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
26302 m s l res)
26303 (while (setq m (string-match re string))
26304 (setq s (substring string 0 m)
26305 l (match-string 0 string)
26306 string (substring string (match-end 0)))
26307 (push (org-html-do-expand s) res)
26308 (push l res))
26309 (push (org-html-do-expand string) res)
26310 (apply 'concat (nreverse res))))
26312 (defun org-html-do-expand (s)
26313 "Apply all active conversions to translate special ASCII to HTML."
26314 (setq s (org-html-protect s))
26315 (if org-export-html-expand
26316 (let ((start 0))
26317 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
26318 (setq s (replace-match "<\\1>" t nil s)))))
26319 (if org-export-with-emphasize
26320 (setq s (org-export-html-convert-emphasize s)))
26321 (if org-export-with-special-strings
26322 (setq s (org-export-html-convert-special-strings s)))
26323 (if org-export-with-sub-superscripts
26324 (setq s (org-export-html-convert-sub-super s)))
26325 (if org-export-with-TeX-macros
26326 (let ((start 0) wd ass)
26327 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
26328 (if (get-text-property (match-beginning 0) 'org-protected s)
26329 (setq start (match-end 0))
26330 (setq wd (match-string 1 s))
26331 (if (setq ass (assoc wd org-html-entities))
26332 (setq s (replace-match (or (cdr ass)
26333 (concat "&" (car ass) ";"))
26334 t t s))
26335 (setq start (+ start (length wd))))))))
26338 (defun org-create-multibrace-regexp (left right n)
26339 "Create a regular expression which will match a balanced sexp.
26340 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
26341 as single character strings.
26342 The regexp returned will match the entire expression including the
26343 delimiters. It will also define a single group which contains the
26344 match except for the outermost delimiters. The maximum depth of
26345 stacked delimiters is N. Escaping delimiters is not possible."
26346 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
26347 (or "\\|")
26348 (re nothing)
26349 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
26350 (while (> n 1)
26351 (setq n (1- n)
26352 re (concat re or next)
26353 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
26354 (concat left "\\(" re "\\)" right)))
26356 (defvar org-match-substring-regexp
26357 (concat
26358 "\\([^\\]\\)\\([_^]\\)\\("
26359 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26360 "\\|"
26361 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
26362 "\\|"
26363 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
26364 "The regular expression matching a sub- or superscript.")
26366 (defvar org-match-substring-with-braces-regexp
26367 (concat
26368 "\\([^\\]\\)\\([_^]\\)\\("
26369 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26370 "\\)")
26371 "The regular expression matching a sub- or superscript, forcing braces.")
26373 (defconst org-export-html-special-string-regexps
26374 '(("\\\\-" . "&shy;")
26375 ("---\\([^-]\\)" . "&mdash;\\1")
26376 ("--\\([^-]\\)" . "&ndash;\\1")
26377 ("\\.\\.\\." . "&hellip;"))
26378 "Regular expressions for special string conversion.")
26380 (defun org-export-html-convert-special-strings (string)
26381 "Convert special characters in STRING to HTML."
26382 (let ((all org-export-html-special-string-regexps)
26383 e a re rpl start)
26384 (while (setq a (pop all))
26385 (setq re (car a) rpl (cdr a) start 0)
26386 (while (string-match re string start)
26387 (if (get-text-property (match-beginning 0) 'org-protected string)
26388 (setq start (match-end 0))
26389 (setq string (replace-match rpl t nil string)))))
26390 string))
26392 (defun org-export-html-convert-sub-super (string)
26393 "Convert sub- and superscripts in STRING to HTML."
26394 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
26395 (while (string-match org-match-substring-regexp string s)
26396 (cond
26397 ((and requireb (match-end 8)) (setq s (match-end 2)))
26398 ((get-text-property (match-beginning 2) 'org-protected string)
26399 (setq s (match-end 2)))
26401 (setq s (match-end 1)
26402 key (if (string= (match-string 2 string) "_") "sub" "sup")
26403 c (or (match-string 8 string)
26404 (match-string 6 string)
26405 (match-string 5 string))
26406 string (replace-match
26407 (concat (match-string 1 string)
26408 "<" key ">" c "</" key ">")
26409 t t string)))))
26410 (while (string-match "\\\\\\([_^]\\)" string)
26411 (setq string (replace-match (match-string 1 string) t t string)))
26412 string))
26414 (defun org-export-html-convert-emphasize (string)
26415 "Apply emphasis."
26416 (let ((s 0) rpl)
26417 (while (string-match org-emph-re string s)
26418 (if (not (equal
26419 (substring string (match-beginning 3) (1+ (match-beginning 3)))
26420 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
26421 (setq s (match-beginning 0)
26423 (concat
26424 (match-string 1 string)
26425 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
26426 (match-string 4 string)
26427 (nth 3 (assoc (match-string 3 string)
26428 org-emphasis-alist))
26429 (match-string 5 string))
26430 string (replace-match rpl t t string)
26431 s (+ s (- (length rpl) 2)))
26432 (setq s (1+ s))))
26433 string))
26435 (defvar org-par-open nil)
26436 (defun org-open-par ()
26437 "Insert <p>, but first close previous paragraph if any."
26438 (org-close-par-maybe)
26439 (insert "\n<p>")
26440 (setq org-par-open t))
26441 (defun org-close-par-maybe ()
26442 "Close paragraph if there is one open."
26443 (when org-par-open
26444 (insert "</p>")
26445 (setq org-par-open nil)))
26446 (defun org-close-li ()
26447 "Close <li> if necessary."
26448 (org-close-par-maybe)
26449 (insert "</li>\n"))
26451 (defvar body-only) ; dynamically scoped into this.
26452 (defun org-html-level-start (level title umax with-toc head-count)
26453 "Insert a new level in HTML export.
26454 When TITLE is nil, just close all open levels."
26455 (org-close-par-maybe)
26456 (let ((l org-level-max) snumber)
26457 (while (>= l level)
26458 (if (aref org-levels-open (1- l))
26459 (progn
26460 (org-html-level-close l umax)
26461 (aset org-levels-open (1- l) nil)))
26462 (setq l (1- l)))
26463 (when title
26464 ;; If title is nil, this means this function is called to close
26465 ;; all levels, so the rest is done only if title is given
26466 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
26467 (setq title (replace-match
26468 (if org-export-with-tags
26469 (save-match-data
26470 (concat
26471 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
26472 (mapconcat 'identity (org-split-string
26473 (match-string 1 title) ":")
26474 "&nbsp;")
26475 "</span>"))
26477 t t title)))
26478 (if (> level umax)
26479 (progn
26480 (if (aref org-levels-open (1- level))
26481 (progn
26482 (org-close-li)
26483 (insert "<li>" title "<br/>\n"))
26484 (aset org-levels-open (1- level) t)
26485 (org-close-par-maybe)
26486 (insert "<ul>\n<li>" title "<br/>\n")))
26487 (aset org-levels-open (1- level) t)
26488 (setq snumber (org-section-number level))
26489 (if (and org-export-with-section-numbers (not body-only))
26490 (setq title (concat snumber " " title)))
26491 (setq level (+ level org-export-html-toplevel-hlevel -1))
26492 (unless (= head-count 1) (insert "\n</div>\n"))
26493 (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"
26494 snumber level level snumber title level snumber))
26495 (org-open-par)))))
26497 (defun org-html-level-close (level max-outline-level)
26498 "Terminate one level in HTML export."
26499 (if (<= level max-outline-level)
26500 (insert "</div>\n")
26501 (org-close-li)
26502 (insert "</ul>\n")))
26504 ;;; iCalendar export
26506 ;;;###autoload
26507 (defun org-export-icalendar-this-file ()
26508 "Export current file as an iCalendar file.
26509 The iCalendar file will be located in the same directory as the Org-mode
26510 file, but with extension `.ics'."
26511 (interactive)
26512 (org-export-icalendar nil buffer-file-name))
26514 ;;;###autoload
26515 (defun org-export-icalendar-all-agenda-files ()
26516 "Export all files in `org-agenda-files' to iCalendar .ics files.
26517 Each iCalendar file will be located in the same directory as the Org-mode
26518 file, but with extension `.ics'."
26519 (interactive)
26520 (apply 'org-export-icalendar nil (org-agenda-files t)))
26522 ;;;###autoload
26523 (defun org-export-icalendar-combine-agenda-files ()
26524 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26525 The file is stored under the name `org-combined-agenda-icalendar-file'."
26526 (interactive)
26527 (apply 'org-export-icalendar t (org-agenda-files t)))
26529 (defun org-export-icalendar (combine &rest files)
26530 "Create iCalendar files for all elements of FILES.
26531 If COMBINE is non-nil, combine all calendar entries into a single large
26532 file and store it under the name `org-combined-agenda-icalendar-file'."
26533 (save-excursion
26534 (org-prepare-agenda-buffers files)
26535 (let* ((dir (org-export-directory
26536 :ical (list :publishing-directory
26537 org-export-publishing-directory)))
26538 file ical-file ical-buffer category started org-agenda-new-buffers)
26539 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26540 (when combine
26541 (setq ical-file
26542 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26543 org-combined-agenda-icalendar-file
26544 (expand-file-name org-combined-agenda-icalendar-file dir))
26545 ical-buffer (org-get-agenda-file-buffer ical-file))
26546 (set-buffer ical-buffer) (erase-buffer))
26547 (while (setq file (pop files))
26548 (catch 'nextfile
26549 (org-check-agenda-file file)
26550 (set-buffer (org-get-agenda-file-buffer file))
26551 (unless combine
26552 (setq ical-file (concat (file-name-as-directory dir)
26553 (file-name-sans-extension
26554 (file-name-nondirectory buffer-file-name))
26555 ".ics"))
26556 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26557 (with-current-buffer ical-buffer (erase-buffer)))
26558 (setq category (or org-category
26559 (file-name-sans-extension
26560 (file-name-nondirectory buffer-file-name))))
26561 (if (symbolp category) (setq category (symbol-name category)))
26562 (let ((standard-output ical-buffer))
26563 (if combine
26564 (and (not started) (setq started t)
26565 (org-start-icalendar-file org-icalendar-combined-name))
26566 (org-start-icalendar-file category))
26567 (org-print-icalendar-entries combine)
26568 (when (or (and combine (not files)) (not combine))
26569 (org-finish-icalendar-file)
26570 (set-buffer ical-buffer)
26571 (save-buffer)
26572 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26573 (org-release-buffers org-agenda-new-buffers))))
26575 (defvar org-after-save-iCalendar-file-hook nil
26576 "Hook run after an iCalendar file has been saved.
26577 The iCalendar buffer is still current when this hook is run.
26578 A good way to use this is to tell a desktop calenndar application to re-read
26579 the iCalendar file.")
26581 (defun org-print-icalendar-entries (&optional combine)
26582 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26583 When COMBINE is non nil, add the category to each line."
26584 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26585 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26586 (dts (org-ical-ts-to-string
26587 (format-time-string (cdr org-time-stamp-formats) (current-time))
26588 "DTSTART"))
26589 hd ts ts2 state status (inc t) pos b sexp rrule
26590 scheduledp deadlinep tmp pri category entry location summary desc
26591 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26592 (org-refresh-category-properties)
26593 (save-excursion
26594 (goto-char (point-min))
26595 (while (re-search-forward re1 nil t)
26596 (catch :skip
26597 (org-agenda-skip)
26598 (when (boundp 'org-icalendar-verify-function)
26599 (unless (funcall org-icalendar-verify-function)
26600 (outline-next-heading)
26601 (backward-char 1)
26602 (throw :skip nil)))
26603 (setq pos (match-beginning 0)
26604 ts (match-string 0)
26605 inc t
26606 hd (org-get-heading)
26607 summary (org-icalendar-cleanup-string
26608 (org-entry-get nil "SUMMARY"))
26609 desc (org-icalendar-cleanup-string
26610 (or (org-entry-get nil "DESCRIPTION")
26611 (and org-icalendar-include-body (org-get-entry)))
26612 t org-icalendar-include-body)
26613 location (org-icalendar-cleanup-string
26614 (org-entry-get nil "LOCATION"))
26615 category (org-get-category))
26616 (if (looking-at re2)
26617 (progn
26618 (goto-char (match-end 0))
26619 (setq ts2 (match-string 1) inc nil))
26620 (setq tmp (buffer-substring (max (point-min)
26621 (- pos org-ds-keyword-length))
26622 pos)
26623 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26624 (progn
26625 (setq inc nil)
26626 (replace-match "\\1" t nil ts))
26628 deadlinep (string-match org-deadline-regexp tmp)
26629 scheduledp (string-match org-scheduled-regexp tmp)
26630 ;; donep (org-entry-is-done-p)
26632 (if (or (string-match org-tr-regexp hd)
26633 (string-match org-ts-regexp hd))
26634 (setq hd (replace-match "" t t hd)))
26635 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26636 (setq rrule
26637 (concat "\nRRULE:FREQ="
26638 (cdr (assoc
26639 (match-string 2 ts)
26640 '(("d" . "DAILY")("w" . "WEEKLY")
26641 ("m" . "MONTHLY")("y" . "YEARLY"))))
26642 ";INTERVAL=" (match-string 1 ts)))
26643 (setq rrule ""))
26644 (setq summary (or summary hd))
26645 (if (string-match org-bracket-link-regexp summary)
26646 (setq summary
26647 (replace-match (if (match-end 3)
26648 (match-string 3 summary)
26649 (match-string 1 summary))
26650 t t summary)))
26651 (if deadlinep (setq summary (concat "DL: " summary)))
26652 (if scheduledp (setq summary (concat "S: " summary)))
26653 (if (string-match "\\`<%%" ts)
26654 (with-current-buffer sexp-buffer
26655 (insert (substring ts 1 -1) " " summary "\n"))
26656 (princ (format "BEGIN:VEVENT
26658 %s%s
26659 SUMMARY:%s%s%s
26660 CATEGORIES:%s
26661 END:VEVENT\n"
26662 (org-ical-ts-to-string ts "DTSTART")
26663 (org-ical-ts-to-string ts2 "DTEND" inc)
26664 rrule summary
26665 (if (and desc (string-match "\\S-" desc))
26666 (concat "\nDESCRIPTION: " desc) "")
26667 (if (and location (string-match "\\S-" location))
26668 (concat "\nLOCATION: " location) "")
26669 category)))))
26671 (when (and org-icalendar-include-sexps
26672 (condition-case nil (require 'icalendar) (error nil))
26673 (fboundp 'icalendar-export-region))
26674 ;; Get all the literal sexps
26675 (goto-char (point-min))
26676 (while (re-search-forward "^&?%%(" nil t)
26677 (catch :skip
26678 (org-agenda-skip)
26679 (setq b (match-beginning 0))
26680 (goto-char (1- (match-end 0)))
26681 (forward-sexp 1)
26682 (end-of-line 1)
26683 (setq sexp (buffer-substring b (point)))
26684 (with-current-buffer sexp-buffer
26685 (insert sexp "\n"))
26686 (princ (org-diary-to-ical-string sexp-buffer)))))
26688 (when org-icalendar-include-todo
26689 (goto-char (point-min))
26690 (while (re-search-forward org-todo-line-regexp nil t)
26691 (catch :skip
26692 (org-agenda-skip)
26693 (when (boundp 'org-icalendar-verify-function)
26694 (unless (funcall org-icalendar-verify-function)
26695 (outline-next-heading)
26696 (backward-char 1)
26697 (throw :skip nil)))
26698 (setq state (match-string 2))
26699 (setq status (if (member state org-done-keywords)
26700 "COMPLETED" "NEEDS-ACTION"))
26701 (when (and state
26702 (or (not (member state org-done-keywords))
26703 (eq org-icalendar-include-todo 'all))
26704 (not (member org-archive-tag (org-get-tags-at)))
26706 (setq hd (match-string 3)
26707 summary (org-icalendar-cleanup-string
26708 (org-entry-get nil "SUMMARY"))
26709 desc (org-icalendar-cleanup-string
26710 (or (org-entry-get nil "DESCRIPTION")
26711 (and org-icalendar-include-body (org-get-entry)))
26712 t org-icalendar-include-body)
26713 location (org-icalendar-cleanup-string
26714 (org-entry-get nil "LOCATION")))
26715 (if (string-match org-bracket-link-regexp hd)
26716 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26717 (match-string 1 hd))
26718 t t hd)))
26719 (if (string-match org-priority-regexp hd)
26720 (setq pri (string-to-char (match-string 2 hd))
26721 hd (concat (substring hd 0 (match-beginning 1))
26722 (substring hd (match-end 1))))
26723 (setq pri org-default-priority))
26724 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26725 (- org-lowest-priority org-highest-priority))))))
26727 (princ (format "BEGIN:VTODO
26729 SUMMARY:%s%s%s
26730 CATEGORIES:%s
26731 SEQUENCE:1
26732 PRIORITY:%d
26733 STATUS:%s
26734 END:VTODO\n"
26736 (or summary hd)
26737 (if (and location (string-match "\\S-" location))
26738 (concat "\nLOCATION: " location) "")
26739 (if (and desc (string-match "\\S-" desc))
26740 (concat "\nDESCRIPTION: " desc) "")
26741 category pri status)))))))))
26743 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26744 "Take out stuff and quote what needs to be quoted.
26745 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26746 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26747 characters."
26748 (if (not s)
26750 (when is-body
26751 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26752 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26753 (while (string-match re s) (setq s (replace-match "" t t s)))
26754 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26755 (let ((start 0))
26756 (while (string-match "\\([,;\\]\\)" s start)
26757 (setq start (+ (match-beginning 0) 2)
26758 s (replace-match "\\\\\\1" nil nil s))))
26759 (when is-body
26760 (while (string-match "[ \t]*\n[ \t]*" s)
26761 (setq s (replace-match "\\n" t t s))))
26762 (setq s (org-trim s))
26763 (if is-body
26764 (if maxlength
26765 (if (and (numberp maxlength)
26766 (> (length s) maxlength))
26767 (setq s (substring s 0 maxlength)))))
26770 (defun org-get-entry ()
26771 "Clean-up description string."
26772 (save-excursion
26773 (org-back-to-heading t)
26774 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26776 (defun org-start-icalendar-file (name)
26777 "Start an iCalendar file by inserting the header."
26778 (let ((user user-full-name)
26779 (name (or name "unknown"))
26780 (timezone (cadr (current-time-zone))))
26781 (princ
26782 (format "BEGIN:VCALENDAR
26783 VERSION:2.0
26784 X-WR-CALNAME:%s
26785 PRODID:-//%s//Emacs with Org-mode//EN
26786 X-WR-TIMEZONE:%s
26787 CALSCALE:GREGORIAN\n" name user timezone))))
26789 (defun org-finish-icalendar-file ()
26790 "Finish an iCalendar file by inserting the END statement."
26791 (princ "END:VCALENDAR\n"))
26793 (defun org-ical-ts-to-string (s keyword &optional inc)
26794 "Take a time string S and convert it to iCalendar format.
26795 KEYWORD is added in front, to make a complete line like DTSTART....
26796 When INC is non-nil, increase the hour by two (if time string contains
26797 a time), or the day by one (if it does not contain a time)."
26798 (let ((t1 (org-parse-time-string s 'nodefault))
26799 t2 fmt have-time time)
26800 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26801 (setq t2 t1 have-time t)
26802 (setq t2 (org-parse-time-string s)))
26803 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26804 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26805 (when inc
26806 (if have-time
26807 (if org-agenda-default-appointment-duration
26808 (setq mi (+ org-agenda-default-appointment-duration mi))
26809 (setq h (+ 2 h)))
26810 (setq d (1+ d))))
26811 (setq time (encode-time s mi h d m y)))
26812 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26813 (concat keyword (format-time-string fmt time))))
26815 ;;; XOXO export
26817 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26818 (with-current-buffer buffer
26819 (apply 'insert output)))
26820 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26822 (defun org-export-as-xoxo (&optional buffer)
26823 "Export the org buffer as XOXO.
26824 The XOXO buffer is named *xoxo-<source buffer name>*"
26825 (interactive (list (current-buffer)))
26826 ;; A quickie abstraction
26828 ;; Output everything as XOXO
26829 (with-current-buffer (get-buffer buffer)
26830 (let* ((pos (point))
26831 (opt-plist (org-combine-plists (org-default-export-plist)
26832 (org-infile-export-plist)))
26833 (filename (concat (file-name-as-directory
26834 (org-export-directory :xoxo opt-plist))
26835 (file-name-sans-extension
26836 (file-name-nondirectory buffer-file-name))
26837 ".html"))
26838 (out (find-file-noselect filename))
26839 (last-level 1)
26840 (hanging-li nil))
26841 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26842 ;; Check the output buffer is empty.
26843 (with-current-buffer out (erase-buffer))
26844 ;; Kick off the output
26845 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26846 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26847 (let* ((hd (match-string-no-properties 1))
26848 (level (length hd))
26849 (text (concat
26850 (match-string-no-properties 2)
26851 (save-excursion
26852 (goto-char (match-end 0))
26853 (let ((str ""))
26854 (catch 'loop
26855 (while 't
26856 (forward-line)
26857 (if (looking-at "^[ \t]\\(.*\\)")
26858 (setq str (concat str (match-string-no-properties 1)))
26859 (throw 'loop str)))))))))
26861 ;; Handle level rendering
26862 (cond
26863 ((> level last-level)
26864 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26866 ((< level last-level)
26867 (dotimes (- (- last-level level) 1)
26868 (if hanging-li
26869 (org-export-as-xoxo-insert-into out "</li>\n"))
26870 (org-export-as-xoxo-insert-into out "</ol>\n"))
26871 (when hanging-li
26872 (org-export-as-xoxo-insert-into out "</li>\n")
26873 (setq hanging-li nil)))
26875 ((equal level last-level)
26876 (if hanging-li
26877 (org-export-as-xoxo-insert-into out "</li>\n")))
26880 (setq last-level level)
26882 ;; And output the new li
26883 (setq hanging-li 't)
26884 (if (equal ?+ (elt text 0))
26885 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26886 (org-export-as-xoxo-insert-into out "<li>" text))))
26888 ;; Finally finish off the ol
26889 (dotimes (- last-level 1)
26890 (if hanging-li
26891 (org-export-as-xoxo-insert-into out "</li>\n"))
26892 (org-export-as-xoxo-insert-into out "</ol>\n"))
26894 (goto-char pos)
26895 ;; Finish the buffer off and clean it up.
26896 (switch-to-buffer-other-window out)
26897 (indent-region (point-min) (point-max) nil)
26898 (save-buffer)
26899 (goto-char (point-min))
26903 ;;;; Key bindings
26905 ;; Make `C-c C-x' a prefix key
26906 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26908 ;; TAB key with modifiers
26909 (org-defkey org-mode-map "\C-i" 'org-cycle)
26910 (org-defkey org-mode-map [(tab)] 'org-cycle)
26911 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26912 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26913 (org-defkey org-mode-map "\M-\t" 'org-complete)
26914 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26915 ;; The following line is necessary under Suse GNU/Linux
26916 (unless (featurep 'xemacs)
26917 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26918 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26919 (define-key org-mode-map [backtab] 'org-shifttab)
26921 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26922 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26923 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26925 ;; Cursor keys with modifiers
26926 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26927 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26928 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26929 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26931 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26932 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26933 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26934 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26936 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26937 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26938 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26939 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26941 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26942 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26944 ;;; Extra keys for tty access.
26945 ;; We only set them when really needed because otherwise the
26946 ;; menus don't show the simple keys
26948 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26949 (not window-system))
26950 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26951 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26952 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26953 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26954 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26955 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26956 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26957 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26958 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26959 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26960 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26961 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26962 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26963 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26964 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26965 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26966 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26967 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26968 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26969 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26970 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26971 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26973 ;; All the other keys
26975 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26976 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26977 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26978 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26979 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26980 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26981 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26982 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26983 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26984 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26985 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26986 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26987 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26988 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26989 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26990 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26991 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26992 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26993 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26994 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26995 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26996 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26997 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26998 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26999 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
27000 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
27001 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
27002 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
27003 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
27004 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
27005 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
27006 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
27007 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
27008 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
27009 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
27010 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
27011 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
27012 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
27013 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
27014 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
27015 (org-defkey org-mode-map "\C-c^" 'org-sort)
27016 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
27017 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
27018 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
27019 (org-defkey org-mode-map "\C-m" 'org-return)
27020 (org-defkey org-mode-map "\C-j" 'org-return-indent)
27021 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
27022 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
27023 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
27024 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
27025 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
27026 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
27027 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
27028 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
27029 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
27030 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
27031 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
27032 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
27033 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
27034 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
27035 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
27037 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
27038 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
27039 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
27040 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
27042 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
27043 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
27044 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
27045 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
27046 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
27047 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
27048 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
27049 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
27050 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
27051 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
27052 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
27053 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
27055 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
27057 (when (featurep 'xemacs)
27058 (org-defkey org-mode-map 'button3 'popup-mode-menu))
27060 (defsubst org-table-p () (org-at-table-p))
27062 (defun org-self-insert-command (N)
27063 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
27064 If the cursor is in a table looking at whitespace, the whitespace is
27065 overwritten, and the table is not marked as requiring realignment."
27066 (interactive "p")
27067 (if (and (org-table-p)
27068 (progn
27069 ;; check if we blank the field, and if that triggers align
27070 (and org-table-auto-blank-field
27071 (member last-command
27072 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
27073 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
27074 ;; got extra space, this field does not determine column width
27075 (let (org-table-may-need-update) (org-table-blank-field))
27076 ;; no extra space, this field may determine column width
27077 (org-table-blank-field)))
27079 (eq N 1)
27080 (looking-at "[^|\n]* |"))
27081 (let (org-table-may-need-update)
27082 (goto-char (1- (match-end 0)))
27083 (delete-backward-char 1)
27084 (goto-char (match-beginning 0))
27085 (self-insert-command N))
27086 (setq org-table-may-need-update t)
27087 (self-insert-command N)
27088 (org-fix-tags-on-the-fly)))
27090 (defun org-fix-tags-on-the-fly ()
27091 (when (and (equal (char-after (point-at-bol)) ?*)
27092 (org-on-heading-p))
27093 (org-align-tags-here org-tags-column)))
27095 (defun org-delete-backward-char (N)
27096 "Like `delete-backward-char', insert whitespace at field end in tables.
27097 When deleting backwards, in tables this function will insert whitespace in
27098 front of the next \"|\" separator, to keep the table aligned. The table will
27099 still be marked for re-alignment if the field did fill the entire column,
27100 because, in this case the deletion might narrow the column."
27101 (interactive "p")
27102 (if (and (org-table-p)
27103 (eq N 1)
27104 (string-match "|" (buffer-substring (point-at-bol) (point)))
27105 (looking-at ".*?|"))
27106 (let ((pos (point))
27107 (noalign (looking-at "[^|\n\r]* |"))
27108 (c org-table-may-need-update))
27109 (backward-delete-char N)
27110 (skip-chars-forward "^|")
27111 (insert " ")
27112 (goto-char (1- pos))
27113 ;; noalign: if there were two spaces at the end, this field
27114 ;; does not determine the width of the column.
27115 (if noalign (setq org-table-may-need-update c)))
27116 (backward-delete-char N)
27117 (org-fix-tags-on-the-fly)))
27119 (defun org-delete-char (N)
27120 "Like `delete-char', but insert whitespace at field end in tables.
27121 When deleting characters, in tables this function will insert whitespace in
27122 front of the next \"|\" separator, to keep the table aligned. The table will
27123 still be marked for re-alignment if the field did fill the entire column,
27124 because, in this case the deletion might narrow the column."
27125 (interactive "p")
27126 (if (and (org-table-p)
27127 (not (bolp))
27128 (not (= (char-after) ?|))
27129 (eq N 1))
27130 (if (looking-at ".*?|")
27131 (let ((pos (point))
27132 (noalign (looking-at "[^|\n\r]* |"))
27133 (c org-table-may-need-update))
27134 (replace-match (concat
27135 (substring (match-string 0) 1 -1)
27136 " |"))
27137 (goto-char pos)
27138 ;; noalign: if there were two spaces at the end, this field
27139 ;; does not determine the width of the column.
27140 (if noalign (setq org-table-may-need-update c)))
27141 (delete-char N))
27142 (delete-char N)
27143 (org-fix-tags-on-the-fly)))
27145 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
27146 (put 'org-self-insert-command 'delete-selection t)
27147 (put 'orgtbl-self-insert-command 'delete-selection t)
27148 (put 'org-delete-char 'delete-selection 'supersede)
27149 (put 'org-delete-backward-char 'delete-selection 'supersede)
27151 ;; Make `flyspell-mode' delay after some commands
27152 (put 'org-self-insert-command 'flyspell-delayed t)
27153 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
27154 (put 'org-delete-char 'flyspell-delayed t)
27155 (put 'org-delete-backward-char 'flyspell-delayed t)
27157 ;; Make pabbrev-mode expand after org-mode commands
27158 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
27159 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
27161 ;; How to do this: Measure non-white length of current string
27162 ;; If equal to column width, we should realign.
27164 (defun org-remap (map &rest commands)
27165 "In MAP, remap the functions given in COMMANDS.
27166 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
27167 (let (new old)
27168 (while commands
27169 (setq old (pop commands) new (pop commands))
27170 (if (fboundp 'command-remapping)
27171 (org-defkey map (vector 'remap old) new)
27172 (substitute-key-definition old new map global-map)))))
27174 (when (eq org-enable-table-editor 'optimized)
27175 ;; If the user wants maximum table support, we need to hijack
27176 ;; some standard editing functions
27177 (org-remap org-mode-map
27178 'self-insert-command 'org-self-insert-command
27179 'delete-char 'org-delete-char
27180 'delete-backward-char 'org-delete-backward-char)
27181 (org-defkey org-mode-map "|" 'org-force-self-insert))
27183 (defun org-shiftcursor-error ()
27184 "Throw an error because Shift-Cursor command was applied in wrong context."
27185 (error "This command is active in special context like tables, headlines or timestamps"))
27187 (defun org-shifttab (&optional arg)
27188 "Global visibility cycling or move to previous table field.
27189 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
27190 on context.
27191 See the individual commands for more information."
27192 (interactive "P")
27193 (cond
27194 ((org-at-table-p) (call-interactively 'org-table-previous-field))
27195 (arg (message "Content view to level: ")
27196 (org-content (prefix-numeric-value arg))
27197 (setq org-cycle-global-status 'overview))
27198 (t (call-interactively 'org-global-cycle))))
27200 (defun org-shiftmetaleft ()
27201 "Promote subtree or delete table column.
27202 Calls `org-promote-subtree', `org-outdent-item',
27203 or `org-table-delete-column', depending on context.
27204 See the individual commands for more information."
27205 (interactive)
27206 (cond
27207 ((org-at-table-p) (call-interactively 'org-table-delete-column))
27208 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
27209 ((org-at-item-p) (call-interactively 'org-outdent-item))
27210 (t (org-shiftcursor-error))))
27212 (defun org-shiftmetaright ()
27213 "Demote subtree or insert table column.
27214 Calls `org-demote-subtree', `org-indent-item',
27215 or `org-table-insert-column', depending on context.
27216 See the individual commands for more information."
27217 (interactive)
27218 (cond
27219 ((org-at-table-p) (call-interactively 'org-table-insert-column))
27220 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
27221 ((org-at-item-p) (call-interactively 'org-indent-item))
27222 (t (org-shiftcursor-error))))
27224 (defun org-shiftmetaup (&optional arg)
27225 "Move subtree up or kill table row.
27226 Calls `org-move-subtree-up' or `org-table-kill-row' or
27227 `org-move-item-up' depending on context. See the individual commands
27228 for more information."
27229 (interactive "P")
27230 (cond
27231 ((org-at-table-p) (call-interactively 'org-table-kill-row))
27232 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27233 ((org-at-item-p) (call-interactively 'org-move-item-up))
27234 (t (org-shiftcursor-error))))
27235 (defun org-shiftmetadown (&optional arg)
27236 "Move subtree down or insert table row.
27237 Calls `org-move-subtree-down' or `org-table-insert-row' or
27238 `org-move-item-down', depending on context. See the individual
27239 commands for more information."
27240 (interactive "P")
27241 (cond
27242 ((org-at-table-p) (call-interactively 'org-table-insert-row))
27243 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27244 ((org-at-item-p) (call-interactively 'org-move-item-down))
27245 (t (org-shiftcursor-error))))
27247 (defun org-metaleft (&optional arg)
27248 "Promote heading or move table column to left.
27249 Calls `org-do-promote' or `org-table-move-column', depending on context.
27250 With no specific context, calls the Emacs default `backward-word'.
27251 See the individual commands for more information."
27252 (interactive "P")
27253 (cond
27254 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
27255 ((or (org-on-heading-p) (org-region-active-p))
27256 (call-interactively 'org-do-promote))
27257 ((org-at-item-p) (call-interactively 'org-outdent-item))
27258 (t (call-interactively 'backward-word))))
27260 (defun org-metaright (&optional arg)
27261 "Demote subtree or move table column to right.
27262 Calls `org-do-demote' or `org-table-move-column', depending on context.
27263 With no specific context, calls the Emacs default `forward-word'.
27264 See the individual commands for more information."
27265 (interactive "P")
27266 (cond
27267 ((org-at-table-p) (call-interactively 'org-table-move-column))
27268 ((or (org-on-heading-p) (org-region-active-p))
27269 (call-interactively 'org-do-demote))
27270 ((org-at-item-p) (call-interactively 'org-indent-item))
27271 (t (call-interactively 'forward-word))))
27273 (defun org-metaup (&optional arg)
27274 "Move subtree up or move table row up.
27275 Calls `org-move-subtree-up' or `org-table-move-row' or
27276 `org-move-item-up', depending on context. See the individual commands
27277 for more information."
27278 (interactive "P")
27279 (cond
27280 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
27281 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27282 ((org-at-item-p) (call-interactively 'org-move-item-up))
27283 (t (transpose-lines 1) (beginning-of-line -1))))
27285 (defun org-metadown (&optional arg)
27286 "Move subtree down or move table row down.
27287 Calls `org-move-subtree-down' or `org-table-move-row' or
27288 `org-move-item-down', depending on context. See the individual
27289 commands for more information."
27290 (interactive "P")
27291 (cond
27292 ((org-at-table-p) (call-interactively 'org-table-move-row))
27293 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27294 ((org-at-item-p) (call-interactively 'org-move-item-down))
27295 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
27297 (defun org-shiftup (&optional arg)
27298 "Increase item in timestamp or increase priority of current headline.
27299 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
27300 depending on context. See the individual commands for more information."
27301 (interactive "P")
27302 (cond
27303 ((org-at-timestamp-p t)
27304 (call-interactively (if org-edit-timestamp-down-means-later
27305 'org-timestamp-down 'org-timestamp-up)))
27306 ((org-on-heading-p) (call-interactively 'org-priority-up))
27307 ((org-at-item-p) (call-interactively 'org-previous-item))
27308 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
27310 (defun org-shiftdown (&optional arg)
27311 "Decrease item in timestamp or decrease priority of current headline.
27312 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
27313 depending on context. See the individual commands for more information."
27314 (interactive "P")
27315 (cond
27316 ((org-at-timestamp-p t)
27317 (call-interactively (if org-edit-timestamp-down-means-later
27318 'org-timestamp-up 'org-timestamp-down)))
27319 ((org-on-heading-p) (call-interactively 'org-priority-down))
27320 (t (call-interactively 'org-next-item))))
27322 (defun org-shiftright ()
27323 "Next TODO keyword or timestamp one day later, depending on context."
27324 (interactive)
27325 (cond
27326 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
27327 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
27328 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
27329 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
27330 (t (org-shiftcursor-error))))
27332 (defun org-shiftleft ()
27333 "Previous TODO keyword or timestamp one day earlier, depending on context."
27334 (interactive)
27335 (cond
27336 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
27337 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
27338 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
27339 ((org-at-property-p)
27340 (call-interactively 'org-property-previous-allowed-value))
27341 (t (org-shiftcursor-error))))
27343 (defun org-shiftcontrolright ()
27344 "Switch to next TODO set."
27345 (interactive)
27346 (cond
27347 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
27348 (t (org-shiftcursor-error))))
27350 (defun org-shiftcontrolleft ()
27351 "Switch to previous TODO set."
27352 (interactive)
27353 (cond
27354 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
27355 (t (org-shiftcursor-error))))
27357 (defun org-ctrl-c-ret ()
27358 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
27359 (interactive)
27360 (cond
27361 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
27362 (t (call-interactively 'org-insert-heading))))
27364 (defun org-copy-special ()
27365 "Copy region in table or copy current subtree.
27366 Calls `org-table-copy' or `org-copy-subtree', depending on context.
27367 See the individual commands for more information."
27368 (interactive)
27369 (call-interactively
27370 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
27372 (defun org-cut-special ()
27373 "Cut region in table or cut current subtree.
27374 Calls `org-table-copy' or `org-cut-subtree', depending on context.
27375 See the individual commands for more information."
27376 (interactive)
27377 (call-interactively
27378 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
27380 (defun org-paste-special (arg)
27381 "Paste rectangular region into table, or past subtree relative to level.
27382 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
27383 See the individual commands for more information."
27384 (interactive "P")
27385 (if (org-at-table-p)
27386 (org-table-paste-rectangle)
27387 (org-paste-subtree arg)))
27389 (defun org-ctrl-c-ctrl-c (&optional arg)
27390 "Set tags in headline, or update according to changed information at point.
27392 This command does many different things, depending on context:
27394 - If the cursor is in a headline, prompt for tags and insert them
27395 into the current line, aligned to `org-tags-column'. When called
27396 with prefix arg, realign all tags in the current buffer.
27398 - If the cursor is in one of the special #+KEYWORD lines, this
27399 triggers scanning the buffer for these lines and updating the
27400 information.
27402 - If the cursor is inside a table, realign the table. This command
27403 works even if the automatic table editor has been turned off.
27405 - If the cursor is on a #+TBLFM line, re-apply the formulas to
27406 the entire table.
27408 - If the cursor is a the beginning of a dynamic block, update it.
27410 - If the cursor is inside a table created by the table.el package,
27411 activate that table.
27413 - If the current buffer is a remember buffer, close note and file it.
27414 with a prefix argument, file it without further interaction to the default
27415 location.
27417 - If the cursor is on a <<<target>>>, update radio targets and corresponding
27418 links in this buffer.
27420 - If the cursor is on a numbered item in a plain list, renumber the
27421 ordered list.
27423 - If the cursor is on a checkbox, toggle it."
27424 (interactive "P")
27425 (let ((org-enable-table-editor t))
27426 (cond
27427 ((or org-clock-overlays
27428 org-occur-highlights
27429 org-latex-fragment-image-overlays)
27430 (org-remove-clock-overlays)
27431 (org-remove-occur-highlights)
27432 (org-remove-latex-fragment-image-overlays)
27433 (message "Temporary highlights/overlays removed from current buffer"))
27434 ((and (local-variable-p 'org-finish-function (current-buffer))
27435 (fboundp org-finish-function))
27436 (funcall org-finish-function))
27437 ((org-at-property-p)
27438 (call-interactively 'org-property-action))
27439 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
27440 ((org-on-heading-p) (call-interactively 'org-set-tags))
27441 ((org-at-table.el-p)
27442 (require 'table)
27443 (beginning-of-line 1)
27444 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
27445 (call-interactively 'table-recognize-table))
27446 ((org-at-table-p)
27447 (org-table-maybe-eval-formula)
27448 (if arg
27449 (call-interactively 'org-table-recalculate)
27450 (org-table-maybe-recalculate-line))
27451 (call-interactively 'org-table-align))
27452 ((org-at-item-checkbox-p)
27453 (call-interactively 'org-toggle-checkbox))
27454 ((org-at-item-p)
27455 (call-interactively 'org-maybe-renumber-ordered-list))
27456 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
27457 ;; Dynamic block
27458 (beginning-of-line 1)
27459 (org-update-dblock))
27460 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
27461 (cond
27462 ((equal (match-string 1) "TBLFM")
27463 ;; Recalculate the table before this line
27464 (save-excursion
27465 (beginning-of-line 1)
27466 (skip-chars-backward " \r\n\t")
27467 (if (org-at-table-p)
27468 (org-call-with-arg 'org-table-recalculate t))))
27470 (call-interactively 'org-mode-restart))))
27471 (t (error "C-c C-c can do nothing useful at this location.")))))
27473 (defun org-mode-restart ()
27474 "Restart Org-mode, to scan again for special lines.
27475 Also updates the keyword regular expressions."
27476 (interactive)
27477 (let ((org-inhibit-startup t)) (org-mode))
27478 (message "Org-mode restarted to refresh keyword and special line setup"))
27480 (defun org-kill-note-or-show-branches ()
27481 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
27482 (interactive)
27483 (if (not org-finish-function)
27484 (call-interactively 'show-branches)
27485 (let ((org-note-abort t))
27486 (funcall org-finish-function))))
27488 (defun org-return (&optional indent)
27489 "Goto next table row or insert a newline.
27490 Calls `org-table-next-row' or `newline', depending on context.
27491 See the individual commands for more information."
27492 (interactive)
27493 (cond
27494 ((bobp) (if indent (newline-and-indent) (newline)))
27495 ((and (org-at-heading-p)
27496 (looking-at
27497 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27498 (org-show-entry)
27499 (end-of-line 1)
27500 (newline))
27501 ((org-at-table-p)
27502 (org-table-justify-field-maybe)
27503 (call-interactively 'org-table-next-row))
27504 (t (if indent (newline-and-indent) (newline)))))
27506 (defun org-return-indent ()
27507 "Goto next table row or insert a newline and indent.
27508 Calls `org-table-next-row' or `newline-and-indent', depending on
27509 context. See the individual commands for more information."
27510 (interactive)
27511 (org-return t))
27513 (defun org-ctrl-c-star ()
27514 "Compute table, or change heading status of lines.
27515 Calls `org-table-recalculate' or `org-toggle-region-headlines',
27516 depending on context. This will also turn a plain list item or a normal
27517 line into a subheading."
27518 (interactive)
27519 (cond
27520 ((org-at-table-p)
27521 (call-interactively 'org-table-recalculate))
27522 ((org-region-active-p)
27523 ;; Convert all lines in region to list items
27524 (call-interactively 'org-toggle-region-headings))
27525 ((org-on-heading-p)
27526 (org-toggle-region-headings (point-at-bol)
27527 (min (1+ (point-at-eol)) (point-max))))
27528 ((org-at-item-p)
27529 ;; Convert to heading
27530 (let ((level (save-match-data
27531 (save-excursion
27532 (condition-case nil
27533 (progn
27534 (org-back-to-heading t)
27535 (funcall outline-level))
27536 (error 0))))))
27537 (replace-match
27538 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
27539 (t (org-toggle-region-headings (point-at-bol)
27540 (min (1+ (point-at-eol)) (point-max))))))
27542 (defun org-ctrl-c-minus ()
27543 "Insert separator line in table or modify bullet status of line.
27544 Also turns a plain line or a region of lines into list items.
27545 Calls `org-table-insert-hline', `org-toggle-region-items', or
27546 `org-cycle-list-bullet', depending on context."
27547 (interactive)
27548 (cond
27549 ((org-at-table-p)
27550 (call-interactively 'org-table-insert-hline))
27551 ((org-on-heading-p)
27552 ;; Convert to item
27553 (save-excursion
27554 (beginning-of-line 1)
27555 (if (looking-at "\\*+ ")
27556 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
27557 ((org-region-active-p)
27558 ;; Convert all lines in region to list items
27559 (call-interactively 'org-toggle-region-items))
27560 ((org-in-item-p)
27561 (call-interactively 'org-cycle-list-bullet))
27562 (t (org-toggle-region-items (point-at-bol)
27563 (min (1+ (point-at-eol)) (point-max))))))
27565 (defun org-toggle-region-items (beg end)
27566 "Convert all lines in region to list items.
27567 If the first line is already an item, convert all list items in the region
27568 to normal lines."
27569 (interactive "r")
27570 (let (l2 l)
27571 (save-excursion
27572 (goto-char end)
27573 (setq l2 (org-current-line))
27574 (goto-char beg)
27575 (beginning-of-line 1)
27576 (setq l (1- (org-current-line)))
27577 (if (org-at-item-p)
27578 ;; We already have items, de-itemize
27579 (while (< (setq l (1+ l)) l2)
27580 (when (org-at-item-p)
27581 (goto-char (match-beginning 2))
27582 (delete-region (match-beginning 2) (match-end 2))
27583 (and (looking-at "[ \t]+") (replace-match "")))
27584 (beginning-of-line 2))
27585 (while (< (setq l (1+ l)) l2)
27586 (unless (org-at-item-p)
27587 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27588 (replace-match "\\1- \\2")))
27589 (beginning-of-line 2))))))
27591 (defun org-toggle-region-headings (beg end)
27592 "Convert all lines in region to list items.
27593 If the first line is already an item, convert all list items in the region
27594 to normal lines."
27595 (interactive "r")
27596 (let (l2 l)
27597 (save-excursion
27598 (goto-char end)
27599 (setq l2 (org-current-line))
27600 (goto-char beg)
27601 (beginning-of-line 1)
27602 (setq l (1- (org-current-line)))
27603 (if (org-on-heading-p)
27604 ;; We already have headlines, de-star them
27605 (while (< (setq l (1+ l)) l2)
27606 (when (org-on-heading-p t)
27607 (and (looking-at outline-regexp) (replace-match "")))
27608 (beginning-of-line 2))
27609 (let* ((stars (save-excursion
27610 (re-search-backward org-complex-heading-regexp nil t)
27611 (or (match-string 1) "*")))
27612 (add-stars (if org-odd-levels-only "**" "*"))
27613 (rpl (concat stars add-stars " \\2")))
27614 (while (< (setq l (1+ l)) l2)
27615 (unless (org-on-heading-p)
27616 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27617 (replace-match rpl)))
27618 (beginning-of-line 2)))))))
27620 (defun org-meta-return (&optional arg)
27621 "Insert a new heading or wrap a region in a table.
27622 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27623 See the individual commands for more information."
27624 (interactive "P")
27625 (cond
27626 ((org-at-table-p)
27627 (call-interactively 'org-table-wrap-region))
27628 (t (call-interactively 'org-insert-heading))))
27630 ;;; Menu entries
27632 ;; Define the Org-mode menus
27633 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27634 '("Tbl"
27635 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27636 ["Next Field" org-cycle (org-at-table-p)]
27637 ["Previous Field" org-shifttab (org-at-table-p)]
27638 ["Next Row" org-return (org-at-table-p)]
27639 "--"
27640 ["Blank Field" org-table-blank-field (org-at-table-p)]
27641 ["Edit Field" org-table-edit-field (org-at-table-p)]
27642 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27643 "--"
27644 ("Column"
27645 ["Move Column Left" org-metaleft (org-at-table-p)]
27646 ["Move Column Right" org-metaright (org-at-table-p)]
27647 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27648 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27649 ("Row"
27650 ["Move Row Up" org-metaup (org-at-table-p)]
27651 ["Move Row Down" org-metadown (org-at-table-p)]
27652 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27653 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27654 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27655 "--"
27656 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27657 ("Rectangle"
27658 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27659 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27660 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27661 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27662 "--"
27663 ("Calculate"
27664 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27665 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27666 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27667 "--"
27668 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27669 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27670 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27671 "--"
27672 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27673 "--"
27674 ["Sum Column/Rectangle" org-table-sum
27675 (or (org-at-table-p) (org-region-active-p))]
27676 ["Which Column?" org-table-current-column (org-at-table-p)])
27677 ["Debug Formulas"
27678 org-table-toggle-formula-debugger
27679 :style toggle :selected org-table-formula-debug]
27680 ["Show Col/Row Numbers"
27681 org-table-toggle-coordinate-overlays
27682 :style toggle :selected org-table-overlay-coordinates]
27683 "--"
27684 ["Create" org-table-create (and (not (org-at-table-p))
27685 org-enable-table-editor)]
27686 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27687 ["Import from File" org-table-import (not (org-at-table-p))]
27688 ["Export to File" org-table-export (org-at-table-p)]
27689 "--"
27690 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27692 (easy-menu-define org-org-menu org-mode-map "Org menu"
27693 '("Org"
27694 ("Show/Hide"
27695 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27696 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27697 ["Sparse Tree" org-occur t]
27698 ["Reveal Context" org-reveal t]
27699 ["Show All" show-all t]
27700 "--"
27701 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27702 "--"
27703 ["New Heading" org-insert-heading t]
27704 ("Navigate Headings"
27705 ["Up" outline-up-heading t]
27706 ["Next" outline-next-visible-heading t]
27707 ["Previous" outline-previous-visible-heading t]
27708 ["Next Same Level" outline-forward-same-level t]
27709 ["Previous Same Level" outline-backward-same-level t]
27710 "--"
27711 ["Jump" org-goto t])
27712 ("Edit Structure"
27713 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27714 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27715 "--"
27716 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27717 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27718 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27719 "--"
27720 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27721 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27722 ["Demote Heading" org-metaright (not (org-at-table-p))]
27723 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27724 "--"
27725 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27726 "--"
27727 ["Convert to odd levels" org-convert-to-odd-levels t]
27728 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27729 ("Editing"
27730 ["Emphasis..." org-emphasize t])
27731 ("Archive"
27732 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27733 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27734 ; :active t :keys "C-u C-c C-x C-a"]
27735 ["Sparse trees open ARCHIVE trees"
27736 (setq org-sparse-tree-open-archived-trees
27737 (not org-sparse-tree-open-archived-trees))
27738 :style toggle :selected org-sparse-tree-open-archived-trees]
27739 ["Cycling opens ARCHIVE trees"
27740 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27741 :style toggle :selected org-cycle-open-archived-trees]
27742 ["Agenda includes ARCHIVE trees"
27743 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27744 :style toggle :selected (not org-agenda-skip-archived-trees)]
27745 "--"
27746 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27747 ; ["Check and Move Children" (org-archive-subtree '(4))
27748 ; :active t :keys "C-u C-c C-x C-s"]
27750 "--"
27751 ("TODO Lists"
27752 ["TODO/DONE/-" org-todo t]
27753 ("Select keyword"
27754 ["Next keyword" org-shiftright (org-on-heading-p)]
27755 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27756 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27757 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27758 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27759 ["Show TODO Tree" org-show-todo-tree t]
27760 ["Global TODO list" org-todo-list t]
27761 "--"
27762 ["Set Priority" org-priority t]
27763 ["Priority Up" org-shiftup t]
27764 ["Priority Down" org-shiftdown t])
27765 ("TAGS and Properties"
27766 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27767 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27768 "--"
27769 ["Set property" 'org-set-property t]
27770 ["Column view of properties" org-columns t]
27771 ["Insert Column View DBlock" org-insert-columns-dblock t])
27772 ("Dates and Scheduling"
27773 ["Timestamp" org-time-stamp t]
27774 ["Timestamp (inactive)" org-time-stamp-inactive t]
27775 ("Change Date"
27776 ["1 Day Later" org-shiftright t]
27777 ["1 Day Earlier" org-shiftleft t]
27778 ["1 ... Later" org-shiftup t]
27779 ["1 ... Earlier" org-shiftdown t])
27780 ["Compute Time Range" org-evaluate-time-range t]
27781 ["Schedule Item" org-schedule t]
27782 ["Deadline" org-deadline t]
27783 "--"
27784 ["Custom time format" org-toggle-time-stamp-overlays
27785 :style radio :selected org-display-custom-times]
27786 "--"
27787 ["Goto Calendar" org-goto-calendar t]
27788 ["Date from Calendar" org-date-from-calendar t])
27789 ("Logging work"
27790 ["Clock in" org-clock-in t]
27791 ["Clock out" org-clock-out t]
27792 ["Clock cancel" org-clock-cancel t]
27793 ["Goto running clock" org-clock-goto t]
27794 ["Display times" org-clock-display t]
27795 ["Create clock table" org-clock-report t]
27796 "--"
27797 ["Record DONE time"
27798 (progn (setq org-log-done (not org-log-done))
27799 (message "Switching to %s will %s record a timestamp"
27800 (car org-done-keywords)
27801 (if org-log-done "automatically" "not")))
27802 :style toggle :selected org-log-done])
27803 "--"
27804 ["Agenda Command..." org-agenda t]
27805 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27806 ("File List for Agenda")
27807 ("Special views current file"
27808 ["TODO Tree" org-show-todo-tree t]
27809 ["Check Deadlines" org-check-deadlines t]
27810 ["Timeline" org-timeline t]
27811 ["Tags Tree" org-tags-sparse-tree t])
27812 "--"
27813 ("Hyperlinks"
27814 ["Store Link (Global)" org-store-link t]
27815 ["Insert Link" org-insert-link t]
27816 ["Follow Link" org-open-at-point t]
27817 "--"
27818 ["Next link" org-next-link t]
27819 ["Previous link" org-previous-link t]
27820 "--"
27821 ["Descriptive Links"
27822 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27823 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27824 ["Literal Links"
27825 (progn
27826 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27827 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27828 "--"
27829 ["Export/Publish..." org-export t]
27830 ("LaTeX"
27831 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27832 :selected org-cdlatex-mode]
27833 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27834 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27835 ["Modify math symbol" org-cdlatex-math-modify
27836 (org-inside-LaTeX-fragment-p)]
27837 ["Export LaTeX fragments as images"
27838 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27839 :style toggle :selected org-export-with-LaTeX-fragments])
27840 "--"
27841 ("Documentation"
27842 ["Show Version" org-version t]
27843 ["Info Documentation" org-info t])
27844 ("Customize"
27845 ["Browse Org Group" org-customize t]
27846 "--"
27847 ["Expand This Menu" org-create-customize-menu
27848 (fboundp 'customize-menu-create)])
27849 "--"
27850 ["Refresh setup" org-mode-restart t]
27853 (defun org-info (&optional node)
27854 "Read documentation for Org-mode in the info system.
27855 With optional NODE, go directly to that node."
27856 (interactive)
27857 (info (format "(org)%s" (or node ""))))
27859 (defun org-install-agenda-files-menu ()
27860 (let ((bl (buffer-list)))
27861 (save-excursion
27862 (while bl
27863 (set-buffer (pop bl))
27864 (if (org-mode-p) (setq bl nil)))
27865 (when (org-mode-p)
27866 (easy-menu-change
27867 '("Org") "File List for Agenda"
27868 (append
27869 (list
27870 ["Edit File List" (org-edit-agenda-file-list) t]
27871 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27872 ["Remove Current File from List" org-remove-file t]
27873 ["Cycle through agenda files" org-cycle-agenda-files t]
27874 ["Occur in all agenda files" org-occur-in-agenda-files t]
27875 "--")
27876 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27878 ;;;; Documentation
27880 (defun org-customize ()
27881 "Call the customize function with org as argument."
27882 (interactive)
27883 (customize-browse 'org))
27885 (defun org-create-customize-menu ()
27886 "Create a full customization menu for Org-mode, insert it into the menu."
27887 (interactive)
27888 (if (fboundp 'customize-menu-create)
27889 (progn
27890 (easy-menu-change
27891 '("Org") "Customize"
27892 `(["Browse Org group" org-customize t]
27893 "--"
27894 ,(customize-menu-create 'org)
27895 ["Set" Custom-set t]
27896 ["Save" Custom-save t]
27897 ["Reset to Current" Custom-reset-current t]
27898 ["Reset to Saved" Custom-reset-saved t]
27899 ["Reset to Standard Settings" Custom-reset-standard t]))
27900 (message "\"Org\"-menu now contains full customization menu"))
27901 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27903 ;;;; Miscellaneous stuff
27906 ;;; Generally useful functions
27908 (defun org-context ()
27909 "Return a list of contexts of the current cursor position.
27910 If several contexts apply, all are returned.
27911 Each context entry is a list with a symbol naming the context, and
27912 two positions indicating start and end of the context. Possible
27913 contexts are:
27915 :headline anywhere in a headline
27916 :headline-stars on the leading stars in a headline
27917 :todo-keyword on a TODO keyword (including DONE) in a headline
27918 :tags on the TAGS in a headline
27919 :priority on the priority cookie in a headline
27920 :item on the first line of a plain list item
27921 :item-bullet on the bullet/number of a plain list item
27922 :checkbox on the checkbox in a plain list item
27923 :table in an org-mode table
27924 :table-special on a special filed in a table
27925 :table-table in a table.el table
27926 :link on a hyperlink
27927 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27928 :target on a <<target>>
27929 :radio-target on a <<<radio-target>>>
27930 :latex-fragment on a LaTeX fragment
27931 :latex-preview on a LaTeX fragment with overlayed preview image
27933 This function expects the position to be visible because it uses font-lock
27934 faces as a help to recognize the following contexts: :table-special, :link,
27935 and :keyword."
27936 (let* ((f (get-text-property (point) 'face))
27937 (faces (if (listp f) f (list f)))
27938 (p (point)) clist o)
27939 ;; First the large context
27940 (cond
27941 ((org-on-heading-p t)
27942 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27943 (when (progn
27944 (beginning-of-line 1)
27945 (looking-at org-todo-line-tags-regexp))
27946 (push (org-point-in-group p 1 :headline-stars) clist)
27947 (push (org-point-in-group p 2 :todo-keyword) clist)
27948 (push (org-point-in-group p 4 :tags) clist))
27949 (goto-char p)
27950 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27951 (if (looking-at "\\[#[A-Z0-9]\\]")
27952 (push (org-point-in-group p 0 :priority) clist)))
27954 ((org-at-item-p)
27955 (push (org-point-in-group p 2 :item-bullet) clist)
27956 (push (list :item (point-at-bol)
27957 (save-excursion (org-end-of-item) (point)))
27958 clist)
27959 (and (org-at-item-checkbox-p)
27960 (push (org-point-in-group p 0 :checkbox) clist)))
27962 ((org-at-table-p)
27963 (push (list :table (org-table-begin) (org-table-end)) clist)
27964 (if (memq 'org-formula faces)
27965 (push (list :table-special
27966 (previous-single-property-change p 'face)
27967 (next-single-property-change p 'face)) clist)))
27968 ((org-at-table-p 'any)
27969 (push (list :table-table) clist)))
27970 (goto-char p)
27972 ;; Now the small context
27973 (cond
27974 ((org-at-timestamp-p)
27975 (push (org-point-in-group p 0 :timestamp) clist))
27976 ((memq 'org-link faces)
27977 (push (list :link
27978 (previous-single-property-change p 'face)
27979 (next-single-property-change p 'face)) clist))
27980 ((memq 'org-special-keyword faces)
27981 (push (list :keyword
27982 (previous-single-property-change p 'face)
27983 (next-single-property-change p 'face)) clist))
27984 ((org-on-target-p)
27985 (push (org-point-in-group p 0 :target) clist)
27986 (goto-char (1- (match-beginning 0)))
27987 (if (looking-at org-radio-target-regexp)
27988 (push (org-point-in-group p 0 :radio-target) clist))
27989 (goto-char p))
27990 ((setq o (car (delq nil
27991 (mapcar
27992 (lambda (x)
27993 (if (memq x org-latex-fragment-image-overlays) x))
27994 (org-overlays-at (point))))))
27995 (push (list :latex-fragment
27996 (org-overlay-start o) (org-overlay-end o)) clist)
27997 (push (list :latex-preview
27998 (org-overlay-start o) (org-overlay-end o)) clist))
27999 ((org-inside-LaTeX-fragment-p)
28000 ;; FIXME: positions wrong.
28001 (push (list :latex-fragment (point) (point)) clist)))
28003 (setq clist (nreverse (delq nil clist)))
28004 clist))
28006 ;; FIXME: Compare with at-regexp-p Do we need both?
28007 (defun org-in-regexp (re &optional nlines visually)
28008 "Check if point is inside a match of regexp.
28009 Normally only the current line is checked, but you can include NLINES extra
28010 lines both before and after point into the search.
28011 If VISUALLY is set, require that the cursor is not after the match but
28012 really on, so that the block visually is on the match."
28013 (catch 'exit
28014 (let ((pos (point))
28015 (eol (point-at-eol (+ 1 (or nlines 0))))
28016 (inc (if visually 1 0)))
28017 (save-excursion
28018 (beginning-of-line (- 1 (or nlines 0)))
28019 (while (re-search-forward re eol t)
28020 (if (and (<= (match-beginning 0) pos)
28021 (>= (+ inc (match-end 0)) pos))
28022 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
28024 (defun org-at-regexp-p (regexp)
28025 "Is point inside a match of REGEXP in the current line?"
28026 (catch 'exit
28027 (save-excursion
28028 (let ((pos (point)) (end (point-at-eol)))
28029 (beginning-of-line 1)
28030 (while (re-search-forward regexp end t)
28031 (if (and (<= (match-beginning 0) pos)
28032 (>= (match-end 0) pos))
28033 (throw 'exit t)))
28034 nil))))
28036 (defun org-occur-in-agenda-files (regexp &optional nlines)
28037 "Call `multi-occur' with buffers for all agenda files."
28038 (interactive "sOrg-files matching: \np")
28039 (let* ((files (org-agenda-files))
28040 (tnames (mapcar 'file-truename files))
28041 (extra org-agenda-text-search-extra-files)
28043 (while (setq f (pop extra))
28044 (unless (member (file-truename f) tnames)
28045 (add-to-list 'files f 'append)
28046 (add-to-list 'tnames (file-truename f) 'append)))
28047 (multi-occur
28048 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
28049 regexp)))
28051 (if (boundp 'occur-mode-find-occurrence-hook)
28052 ;; Emacs 23
28053 (add-hook 'occur-mode-find-occurrence-hook
28054 (lambda ()
28055 (when (org-mode-p)
28056 (org-reveal))))
28057 ;; Emacs 22
28058 (defadvice occur-mode-goto-occurrence
28059 (after org-occur-reveal activate)
28060 (and (org-mode-p) (org-reveal)))
28061 (defadvice occur-mode-goto-occurrence-other-window
28062 (after org-occur-reveal activate)
28063 (and (org-mode-p) (org-reveal)))
28064 (defadvice occur-mode-display-occurrence
28065 (after org-occur-reveal activate)
28066 (when (org-mode-p)
28067 (let ((pos (occur-mode-find-occurrence)))
28068 (with-current-buffer (marker-buffer pos)
28069 (save-excursion
28070 (goto-char pos)
28071 (org-reveal)))))))
28073 (defun org-uniquify (list)
28074 "Remove duplicate elements from LIST."
28075 (let (res)
28076 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
28077 res))
28079 (defun org-delete-all (elts list)
28080 "Remove all elements in ELTS from LIST."
28081 (while elts
28082 (setq list (delete (pop elts) list)))
28083 list)
28085 (defun org-back-over-empty-lines ()
28086 "Move backwards over witespace, to the beginning of the first empty line.
28087 Returns the number of empty lines passed."
28088 (let ((pos (point)))
28089 (skip-chars-backward " \t\n\r")
28090 (beginning-of-line 2)
28091 (goto-char (min (point) pos))
28092 (count-lines (point) pos)))
28094 (defun org-skip-whitespace ()
28095 (skip-chars-forward " \t\n\r"))
28097 (defun org-point-in-group (point group &optional context)
28098 "Check if POINT is in match-group GROUP.
28099 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
28100 match. If the match group does ot exist or point is not inside it,
28101 return nil."
28102 (and (match-beginning group)
28103 (>= point (match-beginning group))
28104 (<= point (match-end group))
28105 (if context
28106 (list context (match-beginning group) (match-end group))
28107 t)))
28109 (defun org-switch-to-buffer-other-window (&rest args)
28110 "Switch to buffer in a second window on the current frame.
28111 In particular, do not allow pop-up frames."
28112 (let (pop-up-frames special-display-buffer-names special-display-regexps
28113 special-display-function)
28114 (apply 'switch-to-buffer-other-window args)))
28116 (defun org-combine-plists (&rest plists)
28117 "Create a single property list from all plists in PLISTS.
28118 The process starts by copying the first list, and then setting properties
28119 from the other lists. Settings in the last list are the most significant
28120 ones and overrule settings in the other lists."
28121 (let ((rtn (copy-sequence (pop plists)))
28122 p v ls)
28123 (while plists
28124 (setq ls (pop plists))
28125 (while ls
28126 (setq p (pop ls) v (pop ls))
28127 (setq rtn (plist-put rtn p v))))
28128 rtn))
28130 (defun org-move-line-down (arg)
28131 "Move the current line down. With prefix argument, move it past ARG lines."
28132 (interactive "p")
28133 (let ((col (current-column))
28134 beg end pos)
28135 (beginning-of-line 1) (setq beg (point))
28136 (beginning-of-line 2) (setq end (point))
28137 (beginning-of-line (+ 1 arg))
28138 (setq pos (move-marker (make-marker) (point)))
28139 (insert (delete-and-extract-region beg end))
28140 (goto-char pos)
28141 (move-to-column col)))
28143 (defun org-move-line-up (arg)
28144 "Move the current line up. With prefix argument, move it past ARG lines."
28145 (interactive "p")
28146 (let ((col (current-column))
28147 beg end pos)
28148 (beginning-of-line 1) (setq beg (point))
28149 (beginning-of-line 2) (setq end (point))
28150 (beginning-of-line (- arg))
28151 (setq pos (move-marker (make-marker) (point)))
28152 (insert (delete-and-extract-region beg end))
28153 (goto-char pos)
28154 (move-to-column col)))
28156 (defun org-replace-escapes (string table)
28157 "Replace %-escapes in STRING with values in TABLE.
28158 TABLE is an association list with keys like \"%a\" and string values.
28159 The sequences in STRING may contain normal field width and padding information,
28160 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
28161 so values can contain further %-escapes if they are define later in TABLE."
28162 (let ((case-fold-search nil)
28163 e re rpl)
28164 (while (setq e (pop table))
28165 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
28166 (while (string-match re string)
28167 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
28168 (cdr e)))
28169 (setq string (replace-match rpl t t string))))
28170 string))
28173 (defun org-sublist (list start end)
28174 "Return a section of LIST, from START to END.
28175 Counting starts at 1."
28176 (let (rtn (c start))
28177 (setq list (nthcdr (1- start) list))
28178 (while (and list (<= c end))
28179 (push (pop list) rtn)
28180 (setq c (1+ c)))
28181 (nreverse rtn)))
28183 (defun org-find-base-buffer-visiting (file)
28184 "Like `find-buffer-visiting' but alway return the base buffer and
28185 not an indirect buffer."
28186 (let ((buf (find-buffer-visiting file)))
28187 (if buf
28188 (or (buffer-base-buffer buf) buf)
28189 nil)))
28191 (defun org-image-file-name-regexp ()
28192 "Return regexp matching the file names of images."
28193 (if (fboundp 'image-file-name-regexp)
28194 (image-file-name-regexp)
28195 (let ((image-file-name-extensions
28196 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
28197 "xbm" "xpm" "pbm" "pgm" "ppm")))
28198 (concat "\\."
28199 (regexp-opt (nconc (mapcar 'upcase
28200 image-file-name-extensions)
28201 image-file-name-extensions)
28203 "\\'"))))
28205 (defun org-file-image-p (file)
28206 "Return non-nil if FILE is an image."
28207 (save-match-data
28208 (string-match (org-image-file-name-regexp) file)))
28210 ;;; Paragraph filling stuff.
28211 ;; We want this to be just right, so use the full arsenal.
28213 (defun org-indent-line-function ()
28214 "Indent line like previous, but further if previous was headline or item."
28215 (interactive)
28216 (let* ((pos (point))
28217 (itemp (org-at-item-p))
28218 column bpos bcol tpos tcol bullet btype bullet-type)
28219 ;; Find the previous relevant line
28220 (beginning-of-line 1)
28221 (cond
28222 ((looking-at "#") (setq column 0))
28223 ((looking-at "\\*+ ") (setq column 0))
28225 (beginning-of-line 0)
28226 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
28227 (beginning-of-line 0))
28228 (cond
28229 ((looking-at "\\*+[ \t]+")
28230 (goto-char (match-end 0))
28231 (setq column (current-column)))
28232 ((org-in-item-p)
28233 (org-beginning-of-item)
28234 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28235 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
28236 (setq bpos (match-beginning 1) tpos (match-end 0)
28237 bcol (progn (goto-char bpos) (current-column))
28238 tcol (progn (goto-char tpos) (current-column))
28239 bullet (match-string 1)
28240 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
28241 (if (not itemp)
28242 (setq column tcol)
28243 (goto-char pos)
28244 (beginning-of-line 1)
28245 (if (looking-at "\\S-")
28246 (progn
28247 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28248 (setq bullet (match-string 1)
28249 btype (if (string-match "[0-9]" bullet) "n" bullet))
28250 (setq column (if (equal btype bullet-type) bcol tcol)))
28251 (setq column (org-get-indentation)))))
28252 (t (setq column (org-get-indentation))))))
28253 (goto-char pos)
28254 (if (<= (current-column) (current-indentation))
28255 (indent-line-to column)
28256 (save-excursion (indent-line-to column)))
28257 (setq column (current-column))
28258 (beginning-of-line 1)
28259 (if (looking-at
28260 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
28261 (replace-match (concat "\\1" (format org-property-format
28262 (match-string 2) (match-string 3)))
28263 t nil))
28264 (move-to-column column)))
28266 (defun org-set-autofill-regexps ()
28267 (interactive)
28268 ;; In the paragraph separator we include headlines, because filling
28269 ;; text in a line directly attached to a headline would otherwise
28270 ;; fill the headline as well.
28271 (org-set-local 'comment-start-skip "^#+[ \t]*")
28272 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
28273 ;; The paragraph starter includes hand-formatted lists.
28274 (org-set-local 'paragraph-start
28275 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
28276 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
28277 ;; But only if the user has not turned off tables or fixed-width regions
28278 (org-set-local
28279 'auto-fill-inhibit-regexp
28280 (concat "\\*+ \\|#\\+"
28281 "\\|[ \t]*" org-keyword-time-regexp
28282 (if (or org-enable-table-editor org-enable-fixed-width-editor)
28283 (concat
28284 "\\|[ \t]*["
28285 (if org-enable-table-editor "|" "")
28286 (if org-enable-fixed-width-editor ":" "")
28287 "]"))))
28288 ;; We use our own fill-paragraph function, to make sure that tables
28289 ;; and fixed-width regions are not wrapped. That function will pass
28290 ;; through to `fill-paragraph' when appropriate.
28291 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
28292 ; Adaptive filling: To get full control, first make sure that
28293 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
28294 (org-set-local 'adaptive-fill-regexp "\000")
28295 (org-set-local 'adaptive-fill-function
28296 'org-adaptive-fill-function)
28297 (org-set-local
28298 'align-mode-rules-list
28299 '((org-in-buffer-settings
28300 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
28301 (modes . '(org-mode))))))
28303 (defun org-fill-paragraph (&optional justify)
28304 "Re-align a table, pass through to fill-paragraph if no table."
28305 (let ((table-p (org-at-table-p))
28306 (table.el-p (org-at-table.el-p)))
28307 (cond ((and (equal (char-after (point-at-bol)) ?*)
28308 (save-excursion (goto-char (point-at-bol))
28309 (looking-at outline-regexp)))
28310 t) ; skip headlines
28311 (table.el-p t) ; skip table.el tables
28312 (table-p (org-table-align) t) ; align org-mode tables
28313 (t nil)))) ; call paragraph-fill
28315 ;; For reference, this is the default value of adaptive-fill-regexp
28316 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
28318 (defun org-adaptive-fill-function ()
28319 "Return a fill prefix for org-mode files.
28320 In particular, this makes sure hanging paragraphs for hand-formatted lists
28321 work correctly."
28322 (cond ((looking-at "#[ \t]+")
28323 (match-string 0))
28324 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
28325 (save-excursion
28326 (goto-char (match-end 0))
28327 (make-string (current-column) ?\ )))
28328 (t nil)))
28330 ;;;; Functions extending outline functionality
28333 (defun org-beginning-of-line (&optional arg)
28334 "Go to the beginning of the current line. If that is invisible, continue
28335 to a visible line beginning. This makes the function of C-a more intuitive.
28336 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28337 first attempt, and only move to after the tags when the cursor is already
28338 beyond the end of the headline."
28339 (interactive "P")
28340 (let ((pos (point)))
28341 (beginning-of-line 1)
28342 (if (bobp)
28344 (backward-char 1)
28345 (if (org-invisible-p)
28346 (while (and (not (bobp)) (org-invisible-p))
28347 (backward-char 1)
28348 (beginning-of-line 1))
28349 (forward-char 1)))
28350 (when org-special-ctrl-a/e
28351 (cond
28352 ((and (looking-at org-todo-line-regexp)
28353 (= (char-after (match-end 1)) ?\ ))
28354 (goto-char
28355 (if (eq org-special-ctrl-a/e t)
28356 (cond ((> pos (match-beginning 3)) (match-beginning 3))
28357 ((= pos (point)) (match-beginning 3))
28358 (t (point)))
28359 (cond ((> pos (point)) (point))
28360 ((not (eq last-command this-command)) (point))
28361 (t (match-beginning 3))))))
28362 ((org-at-item-p)
28363 (goto-char
28364 (if (eq org-special-ctrl-a/e t)
28365 (cond ((> pos (match-end 4)) (match-end 4))
28366 ((= pos (point)) (match-end 4))
28367 (t (point)))
28368 (cond ((> pos (point)) (point))
28369 ((not (eq last-command this-command)) (point))
28370 (t (match-end 4))))))))))
28372 (defun org-end-of-line (&optional arg)
28373 "Go to the end of the line.
28374 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28375 first attempt, and only move to after the tags when the cursor is already
28376 beyond the end of the headline."
28377 (interactive "P")
28378 (if (or (not org-special-ctrl-a/e)
28379 (not (org-on-heading-p)))
28380 (end-of-line arg)
28381 (let ((pos (point)))
28382 (beginning-of-line 1)
28383 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
28384 (if (eq org-special-ctrl-a/e t)
28385 (if (or (< pos (match-beginning 1))
28386 (= pos (match-end 0)))
28387 (goto-char (match-beginning 1))
28388 (goto-char (match-end 0)))
28389 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
28390 (goto-char (match-end 0))
28391 (goto-char (match-beginning 1))))
28392 (end-of-line arg)))))
28394 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
28395 (define-key org-mode-map "\C-e" 'org-end-of-line)
28397 (defun org-kill-line (&optional arg)
28398 "Kill line, to tags or end of line."
28399 (interactive "P")
28400 (cond
28401 ((or (not org-special-ctrl-k)
28402 (bolp)
28403 (not (org-on-heading-p)))
28404 (call-interactively 'kill-line))
28405 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
28406 (kill-region (point) (match-beginning 1))
28407 (org-set-tags nil t))
28408 (t (kill-region (point) (point-at-eol)))))
28410 (define-key org-mode-map "\C-k" 'org-kill-line)
28412 (defun org-invisible-p ()
28413 "Check if point is at a character currently not visible."
28414 ;; Early versions of noutline don't have `outline-invisible-p'.
28415 (if (fboundp 'outline-invisible-p)
28416 (outline-invisible-p)
28417 (get-char-property (point) 'invisible)))
28419 (defun org-invisible-p2 ()
28420 "Check if point is at a character currently not visible."
28421 (save-excursion
28422 (if (and (eolp) (not (bobp))) (backward-char 1))
28423 ;; Early versions of noutline don't have `outline-invisible-p'.
28424 (if (fboundp 'outline-invisible-p)
28425 (outline-invisible-p)
28426 (get-char-property (point) 'invisible))))
28428 (defalias 'org-back-to-heading 'outline-back-to-heading)
28429 (defalias 'org-on-heading-p 'outline-on-heading-p)
28430 (defalias 'org-at-heading-p 'outline-on-heading-p)
28431 (defun org-at-heading-or-item-p ()
28432 (or (org-on-heading-p) (org-at-item-p)))
28434 (defun org-on-target-p ()
28435 (or (org-in-regexp org-radio-target-regexp)
28436 (org-in-regexp org-target-regexp)))
28438 (defun org-up-heading-all (arg)
28439 "Move to the heading line of which the present line is a subheading.
28440 This function considers both visible and invisible heading lines.
28441 With argument, move up ARG levels."
28442 (if (fboundp 'outline-up-heading-all)
28443 (outline-up-heading-all arg) ; emacs 21 version of outline.el
28444 (outline-up-heading arg t))) ; emacs 22 version of outline.el
28446 (defun org-up-heading-safe ()
28447 "Move to the heading line of which the present line is a subheading.
28448 This version will not throw an error. It will return the level of the
28449 headline found, or nil if no higher level is found."
28450 (let ((pos (point)) start-level level
28451 (re (concat "^" outline-regexp)))
28452 (catch 'exit
28453 (outline-back-to-heading t)
28454 (setq start-level (funcall outline-level))
28455 (if (equal start-level 1) (throw 'exit nil))
28456 (while (re-search-backward re nil t)
28457 (setq level (funcall outline-level))
28458 (if (< level start-level) (throw 'exit level)))
28459 nil)))
28461 (defun org-first-sibling-p ()
28462 "Is this heading the first child of its parents?"
28463 (interactive)
28464 (let ((re (concat "^" outline-regexp))
28465 level l)
28466 (unless (org-at-heading-p t)
28467 (error "Not at a heading"))
28468 (setq level (funcall outline-level))
28469 (save-excursion
28470 (if (not (re-search-backward re nil t))
28472 (setq l (funcall outline-level))
28473 (< l level)))))
28475 (defun org-goto-sibling (&optional previous)
28476 "Goto the next sibling, even if it is invisible.
28477 When PREVIOUS is set, go to the previous sibling instead. Returns t
28478 when a sibling was found. When none is found, return nil and don't
28479 move point."
28480 (let ((fun (if previous 're-search-backward 're-search-forward))
28481 (pos (point))
28482 (re (concat "^" outline-regexp))
28483 level l)
28484 (when (condition-case nil (org-back-to-heading t) (error nil))
28485 (setq level (funcall outline-level))
28486 (catch 'exit
28487 (or previous (forward-char 1))
28488 (while (funcall fun re nil t)
28489 (setq l (funcall outline-level))
28490 (when (< l level) (goto-char pos) (throw 'exit nil))
28491 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
28492 (goto-char pos)
28493 nil))))
28495 (defun org-show-siblings ()
28496 "Show all siblings of the current headline."
28497 (save-excursion
28498 (while (org-goto-sibling) (org-flag-heading nil)))
28499 (save-excursion
28500 (while (org-goto-sibling 'previous)
28501 (org-flag-heading nil))))
28503 (defun org-show-hidden-entry ()
28504 "Show an entry where even the heading is hidden."
28505 (save-excursion
28506 (org-show-entry)))
28508 (defun org-flag-heading (flag &optional entry)
28509 "Flag the current heading. FLAG non-nil means make invisible.
28510 When ENTRY is non-nil, show the entire entry."
28511 (save-excursion
28512 (org-back-to-heading t)
28513 ;; Check if we should show the entire entry
28514 (if entry
28515 (progn
28516 (org-show-entry)
28517 (save-excursion
28518 (and (outline-next-heading)
28519 (org-flag-heading nil))))
28520 (outline-flag-region (max (point-min) (1- (point)))
28521 (save-excursion (outline-end-of-heading) (point))
28522 flag))))
28524 (defun org-end-of-subtree (&optional invisible-OK to-heading)
28525 ;; This is an exact copy of the original function, but it uses
28526 ;; `org-back-to-heading', to make it work also in invisible
28527 ;; trees. And is uses an invisible-OK argument.
28528 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
28529 (org-back-to-heading invisible-OK)
28530 (let ((first t)
28531 (level (funcall outline-level)))
28532 (while (and (not (eobp))
28533 (or first (> (funcall outline-level) level)))
28534 (setq first nil)
28535 (outline-next-heading))
28536 (unless to-heading
28537 (if (memq (preceding-char) '(?\n ?\^M))
28538 (progn
28539 ;; Go to end of line before heading
28540 (forward-char -1)
28541 (if (memq (preceding-char) '(?\n ?\^M))
28542 ;; leave blank line before heading
28543 (forward-char -1))))))
28544 (point))
28546 (defun org-show-subtree ()
28547 "Show everything after this heading at deeper levels."
28548 (outline-flag-region
28549 (point)
28550 (save-excursion
28551 (outline-end-of-subtree) (outline-next-heading) (point))
28552 nil))
28554 (defun org-show-entry ()
28555 "Show the body directly following this heading.
28556 Show the heading too, if it is currently invisible."
28557 (interactive)
28558 (save-excursion
28559 (condition-case nil
28560 (progn
28561 (org-back-to-heading t)
28562 (outline-flag-region
28563 (max (point-min) (1- (point)))
28564 (save-excursion
28565 (re-search-forward
28566 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
28567 (or (match-beginning 1) (point-max)))
28568 nil))
28569 (error nil))))
28571 (defun org-make-options-regexp (kwds)
28572 "Make a regular expression for keyword lines."
28573 (concat
28575 "#?[ \t]*\\+\\("
28576 (mapconcat 'regexp-quote kwds "\\|")
28577 "\\):[ \t]*"
28578 "\\(.+\\)"))
28580 ;; Make isearch reveal the necessary context
28581 (defun org-isearch-end ()
28582 "Reveal context after isearch exits."
28583 (when isearch-success ; only if search was successful
28584 (if (featurep 'xemacs)
28585 ;; Under XEmacs, the hook is run in the correct place,
28586 ;; we directly show the context.
28587 (org-show-context 'isearch)
28588 ;; In Emacs the hook runs *before* restoring the overlays.
28589 ;; So we have to use a one-time post-command-hook to do this.
28590 ;; (Emacs 22 has a special variable, see function `org-mode')
28591 (unless (and (boundp 'isearch-mode-end-hook-quit)
28592 isearch-mode-end-hook-quit)
28593 ;; Only when the isearch was not quitted.
28594 (org-add-hook 'post-command-hook 'org-isearch-post-command
28595 'append 'local)))))
28597 (defun org-isearch-post-command ()
28598 "Remove self from hook, and show context."
28599 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28600 (org-show-context 'isearch))
28603 ;;;; Integration with and fixes for other packages
28605 ;;; Imenu support
28607 (defvar org-imenu-markers nil
28608 "All markers currently used by Imenu.")
28609 (make-variable-buffer-local 'org-imenu-markers)
28611 (defun org-imenu-new-marker (&optional pos)
28612 "Return a new marker for use by Imenu, and remember the marker."
28613 (let ((m (make-marker)))
28614 (move-marker m (or pos (point)))
28615 (push m org-imenu-markers)
28618 (defun org-imenu-get-tree ()
28619 "Produce the index for Imenu."
28620 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28621 (setq org-imenu-markers nil)
28622 (let* ((n org-imenu-depth)
28623 (re (concat "^" outline-regexp))
28624 (subs (make-vector (1+ n) nil))
28625 (last-level 0)
28626 m tree level head)
28627 (save-excursion
28628 (save-restriction
28629 (widen)
28630 (goto-char (point-max))
28631 (while (re-search-backward re nil t)
28632 (setq level (org-reduced-level (funcall outline-level)))
28633 (when (<= level n)
28634 (looking-at org-complex-heading-regexp)
28635 (setq head (org-match-string-no-properties 4)
28636 m (org-imenu-new-marker))
28637 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28638 (if (>= level last-level)
28639 (push (cons head m) (aref subs level))
28640 (push (cons head (aref subs (1+ level))) (aref subs level))
28641 (loop for i from (1+ level) to n do (aset subs i nil)))
28642 (setq last-level level)))))
28643 (aref subs 1)))
28645 (eval-after-load "imenu"
28646 '(progn
28647 (add-hook 'imenu-after-jump-hook
28648 (lambda () (org-show-context 'org-goto)))))
28650 ;; Speedbar support
28652 (defun org-speedbar-set-agenda-restriction ()
28653 "Restrict future agenda commands to the location at point in speedbar.
28654 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28655 (interactive)
28656 (let (p m tp np dir txt w)
28657 (cond
28658 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28659 'org-imenu t))
28660 (setq m (get-text-property p 'org-imenu-marker))
28661 (save-excursion
28662 (save-restriction
28663 (set-buffer (marker-buffer m))
28664 (goto-char m)
28665 (org-agenda-set-restriction-lock 'subtree))))
28666 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28667 'speedbar-function 'speedbar-find-file))
28668 (setq tp (previous-single-property-change
28669 (1+ p) 'speedbar-function)
28670 np (next-single-property-change
28671 tp 'speedbar-function)
28672 dir (speedbar-line-directory)
28673 txt (buffer-substring-no-properties (or tp (point-min))
28674 (or np (point-max))))
28675 (save-excursion
28676 (save-restriction
28677 (set-buffer (find-file-noselect
28678 (let ((default-directory dir))
28679 (expand-file-name txt))))
28680 (unless (org-mode-p)
28681 (error "Cannot restrict to non-Org-mode file"))
28682 (org-agenda-set-restriction-lock 'file))))
28683 (t (error "Don't know how to restrict Org-mode's agenda")))
28684 (org-move-overlay org-speedbar-restriction-lock-overlay
28685 (point-at-bol) (point-at-eol))
28686 (setq current-prefix-arg nil)
28687 (org-agenda-maybe-redo)))
28689 (eval-after-load "speedbar"
28690 '(progn
28691 (speedbar-add-supported-extension ".org")
28692 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28693 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28694 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28695 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28696 (add-hook 'speedbar-visiting-tag-hook
28697 (lambda () (org-show-context 'org-goto)))))
28700 ;;; Fixes and Hacks
28702 ;; Make flyspell not check words in links, to not mess up our keymap
28703 (defun org-mode-flyspell-verify ()
28704 "Don't let flyspell put overlays at active buttons."
28705 (not (get-text-property (point) 'keymap)))
28707 ;; Make `bookmark-jump' show the jump location if it was hidden.
28708 (eval-after-load "bookmark"
28709 '(if (boundp 'bookmark-after-jump-hook)
28710 ;; We can use the hook
28711 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28712 ;; Hook not available, use advice
28713 (defadvice bookmark-jump (after org-make-visible activate)
28714 "Make the position visible."
28715 (org-bookmark-jump-unhide))))
28717 (defun org-bookmark-jump-unhide ()
28718 "Unhide the current position, to show the bookmark location."
28719 (and (org-mode-p)
28720 (or (org-invisible-p)
28721 (save-excursion (goto-char (max (point-min) (1- (point))))
28722 (org-invisible-p)))
28723 (org-show-context 'bookmark-jump)))
28725 ;; Make session.el ignore our circular variable
28726 (eval-after-load "session"
28727 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28729 ;;;; Experimental code
28731 (defun org-closed-in-range ()
28732 "Sparse tree of items closed in a certain time range.
28733 Still experimental, may disappear in the future."
28734 (interactive)
28735 ;; Get the time interval from the user.
28736 (let* ((time1 (time-to-seconds
28737 (org-read-date nil 'to-time nil "Starting date: ")))
28738 (time2 (time-to-seconds
28739 (org-read-date nil 'to-time nil "End date:")))
28740 ;; callback function
28741 (callback (lambda ()
28742 (let ((time
28743 (time-to-seconds
28744 (apply 'encode-time
28745 (org-parse-time-string
28746 (match-string 1))))))
28747 ;; check if time in interval
28748 (and (>= time time1) (<= time time2))))))
28749 ;; make tree, check each match with the callback
28750 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28753 ;;;; Finish up
28755 (provide 'org)
28757 (run-hooks 'org-load-hook)
28759 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28760 ;;; org.el ends here