Release 4.36
[org-mode.git] / org.el
blob853c28f5565f2c3a75c41cc91a77a4699601444b
1 ;;; org.el --- Outline-based notes management and organize
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <dominik at science dot uva dot nl>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://www.astro.uva.nl/~dominik/Tools/org/
8 ;; Version: 4.36
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 2, 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.
49 ;; Installation
50 ;; ------------
51 ;; If Org-mode is part of the Emacs distribution or an XEmacs package, you
52 ;; only need to copy the following lines to your .emacs file. The last two
53 ;; lines define *global* keys for the commands `org-store-link' and
54 ;; `org-agenda' - please choose suitable keys yourself.
56 ;; (add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
57 ;; (define-key global-map "\C-cl" 'org-store-link)
58 ;; (define-key global-map "\C-ca" 'org-agenda)
60 ;; Furthermore you need to activate font-lock-mode in org-mode buffers.
61 ;; either of the following two lins will do the trick:
63 ;; (global-font-lock-mode 1) ; for all buffers
64 ;; (add-hook 'org-mode-hook 'turn-on-font-lock) ; org-mode buffers only
66 ;; If you have downloaded Org-mode from the Web, you have to take additional
67 ;; action: Byte-compile org.el and org-publish.el and put them together with
68 ;; org-install.el on your load path. Then also add to your .emacs file:
70 ;; (require 'org-install)
73 ;; Activation
74 ;; ----------
75 ;; The setup above will put all files with extension ".org" into Org-mode.
76 ;; As an alternative, make the first line of a file look like this:
78 ;; MY PROJECTS -*- mode: org; -*-
80 ;; which will select Org-mode for this buffer no matter what the file's
81 ;; name is.
83 ;; Documentation
84 ;; -------------
85 ;; The documentation of Org-mode can be found in the TeXInfo file. The
86 ;; distribution also contains a PDF version of it. At the homepage of
87 ;; Org-mode, you can read the same text online as HTML. There is also an
88 ;; excellent reference card made by Philip Rooke. This card can be found
89 ;; in the etc/ directory of Emacs 22.
91 ;; Recent changes
92 ;; --------------
93 ;; Version 4.36
94 ;; - Improved indentation of ASCII export, when headlines become items.
95 ;; - Handling of 12am and 12pm fixed. Times beyond 24:00 can be used
96 ;; and will not lead to conflicts.
97 ;; - Support for mutually exclusive TAGS with the fast tags interface.
98 ;; - Bug fixes.
100 ;; Version 4.35
101 ;; - HTML export is now valid XHTML.
102 ;; - Timeline can also show dates without entries. See new option
103 ;; `org-timeline-show-empty-dates'.
104 ;; - The bullets created by the ASCII exporter can now be configured.
105 ;; See the new option `org-export-ascii-bullets'.
106 ;; - New face `org-upcoming-deadline' (was `org-scheduled-previously').
107 ;; - New function `org-context' to allow testing for local context.
109 ;; Version 4.34
110 ;; - Bug fixes.
112 ;; Version 4.33
113 ;; - New commands to move through plain lists: S-up and S-down.
114 ;; - Bug fixes and documentation update.
116 ;; Version 4.32
117 ;; - Fast (single-key-per-tag) interface for setting TAGS.
118 ;; - The list of legal tags can be configured globally and locally.
119 ;; - Elisp and Info links (thanks to Todd Neal).
120 ;; - `org-export-publishing-directory' can be an alist, with different
121 ;; directories for different export types.
122 ;; - All context-sensitive commands use `call-interactively' to dispatch.
123 ;; - `org-confirm-shell-links' renamed to `org-confirm-shell-link-function'.
124 ;; - Bug fixes.
126 ;; Version 4.31
127 ;; - Bug fixes.
129 ;; Version 4.30
130 ;; - Modified installation: Autoloads have been collected in org-install.el.
131 ;; - Logging (org-log-done) is now a #+STARTUP option.
132 ;; - Checkboxes in plain list items, following up on Frank Ruell's idea.
133 ;; - File links inserted with C-c C-l will use relative paths if the linked
134 ;; file is in the current directory or a subdirectory of it.
135 ;; - New variable `org-link-file-path-type' to specify preference for
136 ;; relative and absolute paths.
137 ;; - New CSS classes for tags, timestamps, timestamp keywords.
138 ;; - Bug and typo fixes.
140 ;; Version 4.29
141 ;; - Inlining images in HTML export now depends on wheather the link
142 ;; contains a description or not.
143 ;; - TODO items can be scheduled from the global TODO list using C-c C-s.
144 ;; - TODO items already scheduled can be made to disappear from the global
145 ;; todo list, see `org-agenda-todo-ignore-scheduled'.
146 ;; - In Tables, formulas may also be Lisp forms.
147 ;; - Exporting the visible part of an outline with `C-c C-x v' works now
148 ;; for all available exporters.
149 ;; - Bug fixes, lots of them :-(
151 ;; Version 4.28
152 ;; - Bug fixes.
154 ;; Version 4.27
155 ;; - HTML exporter generalized to receive external options.
156 ;; As part of the process, author, email and date have been moved to the
157 ;; end of the HTML file.
158 ;; - Support for customizable file search in file links.
159 ;; - BibTeX database links as first application of the above.
160 ;; - New option `org-agenda-todo-list-sublevels' to turn off listing TODO
161 ;; entries that are sublevels of another TODO entry.
164 ;;; Code:
166 (eval-when-compile
167 (require 'cl)
168 (require 'calendar))
169 (require 'outline)
170 (require 'time-date)
171 (require 'easymenu)
173 ;;; Customization variables
175 (defvar org-version "4.36"
176 "The version number of the file org.el.")
177 (defun org-version ()
178 (interactive)
179 (message "Org-mode version %s" org-version))
181 ;; The following constant is for compatibility with different versions
182 ;; of outline.el.
183 (defconst org-noutline-p (featurep 'noutline)
184 "Are we using the new outline mode?")
185 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
186 (defconst org-format-transports-properties-p
187 (let ((x "a"))
188 (add-text-properties 0 1 '(test t) x)
189 (get-text-property 0 'test (format "%s" x)))
190 "Does format transport text properties?")
192 (defgroup org nil
193 "Outline-based notes management and organizer."
194 :tag "Org"
195 :group 'outlines
196 :group 'hypermedia
197 :group 'calendar)
199 (defgroup org-startup nil
200 "Options concerning startup of Org-mode."
201 :tag "Org Startup"
202 :group 'org)
204 (defcustom org-startup-folded t
205 "Non-nil means, entering Org-mode will switch to OVERVIEW.
206 This can also be configured on a per-file basis by adding one of
207 the following lines anywhere in the buffer:
209 #+STARTUP: fold
210 #+STARTUP: nofold
211 #+STARTUP: content"
212 :group 'org-startup
213 :type '(choice
214 (const :tag "nofold: show all" nil)
215 (const :tag "fold: overview" t)
216 (const :tag "content: all headlines" content)))
218 (defcustom org-startup-truncated t
219 "Non-nil means, entering Org-mode will set `truncate-lines'.
220 This is useful since some lines containing links can be very long and
221 uninteresting. Also tables look terrible when wrapped."
222 :group 'org-startup
223 :type 'boolean)
225 (defcustom org-startup-align-all-tables nil
226 "Non-nil means, align all tables when visiting a file.
227 This is useful when the column width in tables is forced with <N> cookies
228 in table fields. Such tables will look correct only after the first re-align.
229 This can also be configured on a per-file basis by adding one of
230 the following lines anywhere in the buffer:
231 #+STARTUP: align
232 #+STARTUP: noalign"
233 :group 'org-startup
234 :type 'boolean)
236 (defcustom org-startup-with-deadline-check nil
237 "Non-nil means, entering Org-mode will run the deadline check.
238 This means, if you start editing an org file, you will get an
239 immediate reminder of any due deadlines.
240 This can also be configured on a per-file basis by adding one of
241 the following lines anywhere in the buffer:
242 #+STARTUP: dlcheck
243 #+STARTUP: nodlcheck"
244 :group 'org-startup
245 :type 'boolean)
247 (defcustom org-insert-mode-line-in-empty-file nil
248 "Non-nil means insert the first line setting Org-mode in empty files.
249 When the function `org-mode' is called interactively in an empty file, this
250 normally means that the file name does not automatically trigger Org-mode.
251 To ensure that the file will always be in Org-mode in the future, a
252 line enforcing Org-mode will be inserted into the buffer, if this option
253 has been set."
254 :group 'org-startup
255 :type 'boolean)
257 (defcustom org-CUA-compatible nil
258 "Non-nil means use alternative key bindings for S-<cursor movement>.
259 Org-mode used S-<cursor movement> for changing timestamps and priorities.
260 S-<cursor movement> is also used for example by `CUA-mode' to select text.
261 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
262 alternative bindings. Setting this variable to t will replace the following
263 keys both in Org-mode and in the Org-agenda buffer.
265 S-RET -> C-S-RET
266 S-up -> M-p
267 S-down -> M-n
268 S-left -> M--
269 S-right -> M-+
271 If you do not like the alternative keys, take a look at the variable
272 `org-disputed-keys'.
274 This option is only relevant at load-time of Org-mode. Changing it requires
275 a restart of Emacs to become effective."
276 :group 'org-startup
277 :type 'boolean)
279 (defvar org-disputed-keys
280 '((S-up [(shift up)] [(meta ?p)])
281 (S-down [(shift down)] [(meta ?n)])
282 (S-left [(shift left)] [(meta ?-)])
283 (S-right [(shift right)] [(meta ?+)])
284 (S-return [(shift return)] [(control shift return)]))
285 "Keys for which Org-mode and other modes compete.
286 This is an alist, cars are symbols for lookup, 1st element is the default key,
287 second element will be used when `org-CUA-compatible' is t.")
289 (defun org-key (key)
290 "Select a key according to `org-CUA-compatible'."
291 (nth (if org-CUA-compatible 2 1)
292 (or (assq key org-disputed-keys)
293 (error "Invalid Key %s in `org-key'" key))))
295 (defcustom org-ellipsis nil
296 "The ellipsis to use in the Org-mode outline.
297 When nil, just use the standard three dots. When a string, use that instead,
298 and just in Org-mode (which will then use its own display table).
299 Changing this requires executing `M-x org-mode' in a buffer to become
300 effective."
301 :group 'org-startup
302 :type '(choice (const :tag "Default" nil)
303 (string :tag "String" :value "...#")))
305 (defvar org-display-table nil
306 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
308 (defgroup org-keywords nil
309 "Keywords in Org-mode."
310 :tag "Org Keywords"
311 :group 'org)
313 (defcustom org-deadline-string "DEADLINE:"
314 "String to mark deadline entries.
315 A deadline is this string, followed by a time stamp. Should be a word,
316 terminated by a colon. You can insert a schedule keyword and
317 a timestamp with \\[org-deadline].
318 Changes become only effective after restarting Emacs."
319 :group 'org-keywords
320 :type 'string)
322 (defcustom org-scheduled-string "SCHEDULED:"
323 "String to mark scheduled TODO entries.
324 A schedule is this string, followed by a time stamp. Should be a word,
325 terminated by a colon. You can insert a schedule keyword and
326 a timestamp with \\[org-schedule].
327 Changes become only effective after restarting Emacs."
328 :group 'org-keywords
329 :type 'string)
331 (defcustom org-closed-string "CLOSED:"
332 "String used as the prefix for timestamps logging closing a TODO entry."
333 :group 'org-keywords
334 :type 'string)
336 (defcustom org-comment-string "COMMENT"
337 "Entries starting with this keyword will never be exported.
338 An entry can be toggled between COMMENT and normal with
339 \\[org-toggle-comment].
340 Changes become only effective after restarting Emacs."
341 :group 'org-keywords
342 :type 'string)
344 (defcustom org-quote-string "QUOTE"
345 "Entries starting with this keyword will be exported in fixed-width font.
346 Quoting applies only to the text in the entry following the headline, and does
347 not extend beyond the next headline, even if that is lower level.
348 An entry can be toggled between QUOTE and normal with
349 \\[org-toggle-fixed-width-section]."
350 :group 'org-keywords
351 :type 'string)
353 (defgroup org-structure nil
354 "Options concerning the general structure of Org-mode files."
355 :tag "Org Structure"
356 :group 'org)
358 (defgroup org-cycle nil
359 "Options concerning visibility cycling in Org-mode."
360 :tag "Org Cycle"
361 :group 'org-structure)
363 (defcustom org-cycle-global-at-bob t
364 "Cycle globally if cursor is at beginning of buffer and not at a headline.
365 This makes it possible to do global cycling without having to use S-TAB or
366 C-u TAB. For this special case to work, the first line of the buffer
367 must not be a headline - it may be empty ot some other text. When used in
368 this way, `org-cycle-hook' is disables temporarily, to make sure the
369 cursor stays at the beginning of the buffer.
370 When this option is nil, don't do anything special at the beginning
371 of the buffer."
372 :group 'org-cycle
373 :type 'boolean)
375 (defcustom org-cycle-emulate-tab t
376 "Where should `org-cycle' emulate TAB.
377 nil Never
378 white Only in completely white lines
379 whitestart Only at the beginning of lines, before the first non-white char.
380 t Everywhere except in headlines
381 If TAB is used in a place where it does not emulate TAB, the current subtree
382 visibility is cycled."
383 :group 'org-cycle
384 :type '(choice (const :tag "Never" nil)
385 (const :tag "Only in completely white lines" white)
386 (const :tag "Before first char in a line" whitestart)
387 (const :tag "Everywhere except in headlines" t)
390 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
391 "Hook that is run after `org-cycle' has changed the buffer visibility.
392 The function(s) in this hook must accept a single argument which indicates
393 the new state that was set by the most recent `org-cycle' command. The
394 argument is a symbol. After a global state change, it can have the values
395 `overview', `content', or `all'. After a local state change, it can have
396 the values `folded', `children', or `subtree'."
397 :group 'org-cycle
398 :type 'hook)
400 (defgroup org-edit-structure nil
401 "Options concerning structure editing in Org-mode."
402 :tag "Org Edit Structure"
403 :group 'org-structure)
405 (defcustom org-odd-levels-only nil
406 "Non-nil means, skip even levels and only use odd levels for the outline.
407 This has the effect that two stars are being added/taken away in
408 promotion/demotion commands. It also influences how levels are
409 handled by the exporters.
410 Changing it requires restart of `font-lock-mode' to become effective
411 for fontification also in regions already fontified.
412 You may also set this on a per-file basis by adding one of the following
413 lines to the buffer:
415 #+STARTUP: odd
416 #+STARTUP: oddeven"
417 :group 'org-edit-structure
418 :group 'org-font-lock
419 :type 'boolean)
421 (defcustom org-adapt-indentation t
422 "Non-nil means, adapt indentation when promoting and demoting.
423 When this is set and the *entire* text in an entry is indented, the
424 indentation is increased by one space in a demotion command, and
425 decreased by one in a promotion command. If any line in the entry
426 body starts at column 0, indentation is not changed at all."
427 :group 'org-edit-structure
428 :type 'boolean)
430 (defcustom org-insert-heading-hook nil
431 "Hook being run after inserting a new heading."
432 :group 'org-edit-structure
433 :type 'boolean)
435 (defcustom org-enable-fixed-width-editor t
436 "Non-nil means, lines starting with \":\" are treated as fixed-width.
437 This currently only means, they are never auto-wrapped.
438 When nil, such lines will be treated like ordinary lines.
439 See also the QUOTE keyword."
440 :group 'org-edit-structure
441 :type 'boolean)
443 (defgroup org-sparse-trees nil
444 "Options concerning sparse trees in Org-mode."
445 :tag "Org Sparse Trees"
446 :group 'org-structure)
448 (defcustom org-highlight-sparse-tree-matches t
449 "Non-nil means, highlight all matches that define a sparse tree.
450 The highlights will automatically disappear the next time the buffer is
451 changed by an edit command."
452 :group 'org-sparse-trees
453 :type 'boolean)
455 (defcustom org-show-hierarchy-above t
456 "Non-nil means, show full hierarchy when showing a spot in the tree.
457 Turning this off makes sparse trees more compact, but also less clear."
458 :group 'org-sparse-trees
459 :type 'boolean)
461 (defcustom org-show-following-heading t
462 "Non-nil means, show heading following match in `org-occur'.
463 When doing an `org-occur' it is useful to show the headline which
464 follows the match, even if they do not match the regexp. This makes it
465 easier to edit directly inside the sparse tree. However, if you use
466 `org-occur' mainly as an overview, the following headlines are
467 unnecessary clutter."
468 :group 'org-sparse-trees
469 :type 'boolean)
471 (defcustom org-occur-hook '(org-first-headline-recenter)
472 "Hook that is run after `org-occur' has constructed a sparse tree.
473 This can be used to recenter the window to show as much of the structure
474 as possible."
475 :group 'org-sparse-trees
476 :type 'hook)
478 (defgroup org-plain-lists nil
479 "Options concerning plain lists in Org-mode."
480 :tag "Org Plain lists"
481 :group 'org-structure)
483 (defcustom org-cycle-include-plain-lists nil
484 "Non-nil means, include plain lists into visibility cycling.
485 This means that during cycling, plain list items will *temporarily* be
486 interpreted as outline headlines with a level given by 1000+i where i is the
487 indentation of the bullet. In all other operations, plain list items are
488 not seen as headlines. For example, you cannot assign a TODO keyword to
489 such an item."
490 :group 'org-plain-lists
491 :type 'boolean)
494 (defcustom org-plain-list-ordered-item-terminator t
495 "The character that makes a line with leading number an ordered list item.
496 Valid values are ?. and ?\). To get both terminators, use t. While
497 ?. may look nicer, it creates the danger that a line with leading
498 number may be incorrectly interpreted as an item. ?\) therefore is
499 the safe choice."
500 :group 'org-plain-lists
501 :type '(choice (const :tag "dot like in \"2.\"" ?.)
502 (const :tag "paren like in \"2)\"" ?\))
503 (const :tab "both" t)))
505 (defcustom org-auto-renumber-ordered-lists t
506 "Non-nil means, automatically renumber ordered plain lists.
507 Renumbering happens when the sequence have been changed with
508 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
509 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
510 :group 'org-plain-lists
511 :type 'boolean)
513 (defgroup org-archive nil
514 "Options concerning archiving in Org-mode."
515 :tag "Org Archive"
516 :group 'org-structure)
518 (defcustom org-archive-location "%s_archive::"
519 "The location where subtrees should be archived.
520 This string consists of two parts, separated by a double-colon.
522 The first part is a file name - when omitted, archiving happens in the same
523 file. %s will be replaced by the current file name (without directory part).
524 Archiving to a different file is useful to keep archived entries from
525 contributing to the Org-mode Agenda.
527 The part after the double colon is a headline. The archived entries will be
528 filed under that headline. When omitted, the subtrees are simply filed away
529 at the end of the file, as top-level entries.
531 Here are a few examples:
532 \"%s_archive::\"
533 If the current file is Projects.org, archive in file
534 Projects.org_archive, as top-level trees. This is the default.
536 \"::* Archived Tasks\"
537 Archive in the current file, under the top-level headline
538 \"* Archived Tasks\".
540 \"~/org/archive.org::\"
541 Archive in file ~/org/archive.org (absolute path), as top-level trees.
543 \"basement::** Finished Tasks\"
544 Archive in file ./basement (relative path), as level 3 trees
545 below the level 2 heading \"** Finished Tasks\".
547 You may set this option on a per-file basis by adding to the buffer a
548 line like
550 #+ARCHIVE: basement::** Finished Tasks"
551 :group 'org-archive
552 :type 'string)
554 (defcustom org-archive-mark-done t
555 "Non-nil means, mark archived entries as DONE."
556 :group 'org-archive
557 :type 'boolean)
559 (defcustom org-archive-stamp-time t
560 "Non-nil means, add a time stamp to archived entries.
561 The time stamp will be added directly after the TODO state keyword in the
562 first line, so it is probably best to use this in combinations with
563 `org-archive-mark-done'."
564 :group 'org-archive
565 :type 'boolean)
567 (defgroup org-table nil
568 "Options concerning tables in Org-mode."
569 :tag "Org Table"
570 :group 'org)
572 (defcustom org-enable-table-editor 'optimized
573 "Non-nil means, lines starting with \"|\" are handled by the table editor.
574 When nil, such lines will be treated like ordinary lines.
576 When equal to the symbol `optimized', the table editor will be optimized to
577 do the following:
578 - Use automatic overwrite mode in front of whitespace in table fields.
579 This make the structure of the table stay in tact as long as the edited
580 field does not exceed the column width.
581 - Minimize the number of realigns. Normally, the table is aligned each time
582 TAB or RET are pressed to move to another field. With optimization this
583 happens only if changes to a field might have changed the column width.
584 Optimization requires replacing the functions `self-insert-command',
585 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
586 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
587 very good at guessing when a re-align will be necessary, but you can always
588 force one with \\[org-ctrl-c-ctrl-c].
590 If you would like to use the optimized version in Org-mode, but the
591 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
593 This variable can be used to turn on and off the table editor during a session,
594 but in order to toggle optimization, a restart is required.
596 See also the variable `org-table-auto-blank-field'."
597 :group 'org-table
598 :type '(choice
599 (const :tag "off" nil)
600 (const :tag "on" t)
601 (const :tag "on, optimized" optimized)))
603 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
604 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
605 In the optimized version, the table editor takes over all simple keys that
606 normally just insert a character. In tables, the characters are inserted
607 in a way to minimize disturbing the table structure (i.e. in overwrite mode
608 for empty fields). Outside tables, the correct binding of the keys is
609 restored.
611 The default for this option is t if the optimized version is also used in
612 Org-mode. See the variable `org-enable-table-editor' for details. Changing
613 this variable requires a restart of Emacs to become effective."
614 :group 'org-table
615 :type 'boolean)
617 (defgroup org-table-settings nil
618 "Settings for tables in Org-mode."
619 :tag "Org Table Settings"
620 :group 'org-table)
622 (defcustom org-table-default-size "5x2"
623 "The default size for newly created tables, Columns x Rows."
624 :group 'org-table-settings
625 :type 'string)
627 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
628 "Regular expression for recognizing numbers in table columns.
629 If a table column contains mostly numbers, it will be aligned to the
630 right. If not, it will be aligned to the left.
632 The default value of this option is a regular expression which allows
633 anything which looks remotely like a number as used in scientific
634 context. For example, all of the following will be considered a
635 number:
636 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
638 Other options offered by the customize interface are more restrictive."
639 :group 'org-table-settings
640 :type '(choice
641 (const :tag "Positive Integers"
642 "^[0-9]+$")
643 (const :tag "Integers"
644 "^[-+]?[0-9]+$")
645 (const :tag "Floating Point Numbers"
646 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
647 (const :tag "Floating Point Number or Integer"
648 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
649 (const :tag "Exponential, Floating point, Integer"
650 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
651 (const :tag "Very General Number-Like"
652 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
653 (string :tag "Regexp:")))
655 (defcustom org-table-number-fraction 0.5
656 "Fraction of numbers in a column required to make the column align right.
657 In a column all non-white fields are considered. If at least this
658 fraction of fields is matched by `org-table-number-fraction',
659 alignment to the right border applies."
660 :group 'org-table-settings
661 :type 'number)
663 (defgroup org-table-editing nil
664 "Bahavior of tables during editing in Org-mode."
665 :tag "Org Table Editing"
666 :group 'org-table)
668 (defcustom org-table-automatic-realign t
669 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
670 When nil, aligning is only done with \\[org-table-align], or after column
671 removal/insertion."
672 :group 'org-table-editing
673 :type 'boolean)
675 (defcustom org-table-limit-column-width t ;kw
676 "Non-nil means, allow to limit the width of table columns with <N> fields."
677 :group 'org-table-editing
678 :type 'boolean)
680 (defcustom org-table-auto-blank-field t
681 "Non-nil means, automatically blank table field when starting to type into it.
682 This only happens when typing immediately after a field motion
683 command (TAB, S-TAB or RET).
684 Only relevant when `org-enable-table-editor' is equal to `optimized'."
685 :group 'org-table-editing
686 :type 'boolean)
688 (defcustom org-table-tab-jumps-over-hlines t
689 "Non-nil means, tab in the last column of a table with jump over a hline.
690 If a horizontal separator line is following the current line,
691 `org-table-next-field' can either create a new row before that line, or jump
692 over the line. When this option is nil, a new line will be created before
693 this line."
694 :group 'org-table-editing
695 :type 'boolean)
697 (defcustom org-table-tab-recognizes-table.el t
698 "Non-nil means, TAB will automatically notice a table.el table.
699 When it sees such a table, it moves point into it and - if necessary -
700 calls `table-recognize-table'."
701 :group 'org-table-editing
702 :type 'boolean)
704 (defgroup org-table-calculation nil
705 "Options concerning tables in Org-mode."
706 :tag "Org Table Calculation"
707 :group 'org-table)
709 (defcustom org-table-copy-increment t
710 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
711 :group 'org-table-calculation
712 :type 'boolean)
714 (defcustom org-calc-default-modes
715 '(calc-internal-prec 12
716 calc-float-format (float 5)
717 calc-angle-mode deg
718 calc-prefer-frac nil
719 calc-symbolic-mode nil
720 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
721 calc-display-working-message t
723 "List with Calc mode settings for use in calc-eval for table formulas.
724 The list must contain alternating symbols (Calc modes variables and values).
725 Don't remove any of the default settings, just change the values. Org-mode
726 relies on the variables to be present in the list."
727 :group 'org-table-calculation
728 :type 'plist)
730 (defcustom org-table-formula-evaluate-inline t
731 "Non-nil means, TAB and RET evaluate a formula in current table field.
732 If the current field starts with an equal sign, it is assumed to be a formula
733 which should be evaluated as described in the manual and in the documentation
734 string of the command `org-table-eval-formula'. This feature requires the
735 Emacs calc package.
736 When this variable is nil, formula calculation is only available through
737 the command \\[org-table-eval-formula]."
738 :group 'org-table-calculation
739 :type 'boolean)
742 (defcustom org-table-formula-use-constants t
743 "Non-nil means, interpret constants in formulas in tables.
744 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
745 by the value given in `org-table-formula-constants', or by a value obtained
746 from the `constants.el' package."
747 :group 'org-table-calculation
748 :type 'boolean)
750 (defcustom org-table-formula-constants nil
751 "Alist with constant names and values, for use in table formulas.
752 The car of each element is a name of a constant, without the `$' before it.
753 The cdr is the value as a string. For example, if you'd like to use the
754 speed of light in a formula, you would configure
756 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
758 and then use it in an equation like `$1*$c'."
759 :group 'org-table-calculation
760 :type '(repeat
761 (cons (string :tag "name")
762 (string :tag "value"))))
764 (defcustom org-table-formula-numbers-only nil
765 "Non-nil means, calculate only with numbers in table formulas.
766 Then all input fields will be converted to a number, and the result
767 must also be a number. When nil, calc's full potential is available
768 in table calculations, including symbolics etc."
769 :group 'org-table-calculation
770 :type 'boolean)
772 (defcustom org-table-allow-automatic-line-recalculation t
773 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
774 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
775 :group 'org-table-calculation
776 :type 'boolean)
778 (defgroup org-link nil
779 "Options concerning links in Org-mode."
780 :tag "Org Link"
781 :group 'org)
783 (defcustom org-descriptive-links t
784 "Non-nil means, hide link part and only show description of bracket links.
785 Bracket links are like [[link][descritpion]]. This variable sets the initial
786 state in new org-mode buffers. The setting can then be toggled on a
787 per-buffer basis from the Org->Hyperlinks menu."
788 :group 'org-link
789 :type 'boolean)
791 (defcustom org-link-style 'bracket
792 "The style of links to be inserted with \\[org-insert-link].
793 Possible values are:
794 bracket [[link][description]]. This is recommended
795 plain Description \\n link. The old way, no longer recommended."
796 :group 'org-link
797 :type '(choice
798 (const :tag "Bracket (recommended)" bracket)
799 (const :tag "Plain (no longer recommended)" plain)))
801 (defcustom org-link-format "%s"
802 "Default format for external, URL-like linkes in the buffer.
803 This is a format string for printf, %s will be replaced by the link text.
804 The recommended value is just \"%s\", since links will be protected by
805 enclosing them in double brackets. If you prefer plain links (see variable
806 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
807 additional URL: prefix, so the format would be \"<URL:%s>\"."
808 :group 'org-link
809 :type '(choice
810 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
811 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
812 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
813 (string :tag "Other" :value "<%s>")))
815 (defcustom org-link-file-path-type 'adaptive
816 "How the path name in file links should be stored.
817 Valid values are:
819 relative relative to the current directory, i.e. the directory of the file
820 into which the link is being inserted.
821 absolute absolute path, if possible with ~ for home directory.
822 noabbrev absolute path, no abbreviation of home directory.
823 adaptive Use relative path for files in the current directory and sub-
824 directories of it. For other files, use an absolute path."
825 :group 'org-link
826 :type '(choice
827 (const relative)
828 (const absolute)
829 (const noabbrev)
830 (const adaptive)))
832 (defcustom org-activate-links '(bracket angle plain radio tag date)
833 "Types of links that should be activated in Org-mode files.
834 This is a list of symbols, each leading to the activation of a certain link
835 type. In principle, it does not hurt to turn on most link types - there may
836 be a small gain when turning off unused link types. The types are:
838 bracket The recommended [[link][description]] or [[link]] links with hiding.
839 angular Links in angular brackes that may contain whitespace like
840 <bbdb:Carsten Dominik>.
841 plain Plain links in normal text, no whitespace, like http://google.com.
842 radio Text that is matched by a radio target, see manual for details.
843 tag Tag settings in a headline (link to tag search).
844 date Time stamps (link to calendar).
845 camel CamelCase words defining text searches.
847 Changing this variable requires a restart of Emacs to become effective."
848 :group 'org-link
849 :type '(set (const :tag "Double bracket links (new style)" bracket)
850 (const :tag "Angular bracket links (old style)" angular)
851 (const :tag "plain text links" plain)
852 (const :tag "Radio target matches" radio)
853 (const :tag "Tags" tag)
854 (const :tag "Timestamps" date)
855 (const :tag "CamelCase words" camel)))
857 (defgroup org-link-store nil
858 "Options concerning storing links in Org-mode"
859 :tag "Org Store Link"
860 :group 'org-link)
862 (defcustom org-context-in-file-links t
863 "Non-nil means, file links from `org-store-link' contain context.
864 A search string will be added to the file name with :: as separator and
865 used to find the context when the link is activated by the command
866 `org-open-at-point'.
867 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
868 negates this setting for the duration of the command."
869 :group 'org-link-store
870 :type 'boolean)
872 (defcustom org-file-link-context-use-camel-case nil
873 "Non-nil means, use CamelCase to store a search context in a file link.
874 When nil, the search string simply consists of the words of the string.
875 CamelCase is deprecated, and support for it may be dropped in the future."
876 :group 'org-link-store
877 :type 'boolean)
879 (defcustom org-keep-stored-link-after-insertion nil
880 "Non-nil means, keep link in list for entire session.
882 The command `org-store-link' adds a link pointing to the current
883 location to an internal list. These links accumulate during a session.
884 The command `org-insert-link' can be used to insert links into any
885 Org-mode file (offering completion for all stored links). When this
886 option is nil, every link which has been inserted once using \\[org-insert-link]
887 will be removed from the list, to make completing the unused links
888 more efficient."
889 :group 'org-link-store
890 :type 'boolean)
892 (defcustom org-usenet-links-prefer-google nil
893 "Non-nil means, `org-store-link' will create web links to Google groups.
894 When nil, Gnus will be used for such links.
895 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
896 negates this setting for the duration of the command."
897 :group 'org-link-store
898 :type 'boolean)
900 (defgroup org-link-follow nil
901 "Options concerning following links in Org-mode"
902 :tag "Org Follow Link"
903 :group 'org-link)
905 (defcustom org-tab-follows-link nil
906 "Non-nil means, on links TAB will follow the link.
907 Needs to be set before org.el is loaded."
908 :group 'org-link-follow
909 :type 'boolean)
911 (defcustom org-return-follows-link nil
912 "Non-nil means, on links RET will follow the link.
913 Needs to be set before org.el is loaded."
914 :group 'org-link-follow
915 :type 'boolean)
917 (defcustom org-mouse-1-follows-link t
918 "Non-nil means, mouse-1 on a link will follow the link.
919 A longer mouse click will still set point. Does not wortk on XEmacs.
920 Needs to be set before org.el is loaded."
921 :group 'org-link-follow
922 :type 'boolean)
924 (defcustom org-mark-ring-length 4
925 "Number of different positions to be recorded in the ring
926 Changing this requires a restart of Emacs to work correctly."
927 :group 'org-link-follow
928 :type 'interger)
930 (defcustom org-link-frame-setup
931 '((vm . vm-visit-folder-other-frame)
932 (gnus . gnus-other-frame)
933 (file . find-file-other-window))
934 "Setup the frame configuration for following links.
935 When following a link with Emacs, it may often be useful to display
936 this link in another window or frame. This variable can be used to
937 set this up for the different types of links.
938 For VM, use any of
939 `vm-visit-folder'
940 `vm-visit-folder-other-frame'
941 For Gnus, use any of
942 `gnus'
943 `gnus-other-frame'
944 For FILE, use any of
945 `find-file'
946 `find-file-other-window'
947 `find-file-other-frame'
948 For the calendar, use the variable `calendar-setup'.
949 For BBDB, it is currently only possible to display the matches in
950 another window."
951 :group 'org-link-follow
952 :type '(list
953 (cons (const vm)
954 (choice
955 (const vm-visit-folder)
956 (const vm-visit-folder-other-window)
957 (const vm-visit-folder-other-frame)))
958 (cons (const gnus)
959 (choice
960 (const gnus)
961 (const gnus-other-frame)))
962 (cons (const file)
963 (choice
964 (const find-file)
965 (const find-file-other-window)
966 (const find-file-other-frame)))))
968 (defcustom org-open-non-existing-files nil
969 "Non-nil means, `org-open-file' will open non-existing file.
970 When nil, an error will be generated."
971 :group 'org-link-follow
972 :type 'boolean)
974 (defcustom org-confirm-shell-link-function 'yes-or-no-p
975 "Non-nil means, ask for confirmation before executing shell links.
976 Shell links can be dangerous, just thing about a link
978 [[shell:rm -rf ~/*][Google Search]]
980 This link would show up in your Org-mode document as \"Google Search\"
981 but really it would remove your entire home directory.
982 Therefore I *definitely* advise against setting this variable to nil.
983 Just change it to `y-or-n-p' of you want to confirm with a single key press
984 rather than having to type \"yes\"."
985 :group 'org-link-follow
986 :type '(choice
987 (const :tag "with yes-or-no (safer)" yes-or-no-p)
988 (const :tag "with y-or-n (faster)" y-or-n-p)
989 (const :tag "no confirmation (dangerous)" nil)))
991 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
992 "Non-nil means, ask for confirmation before executing elisp links.
993 Elisp links can be dangerous, just thing about a link
995 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
997 This link would show up in your Org-mode document as \"Google Search\"
998 but really it would remove your entire home directory.
999 Therefore I *definitely* advise against setting this variable to nil.
1000 Just change it to `y-or-n-p' of you want to confirm with a single key press
1001 rather than having to type \"yes\"."
1002 :group 'org-link-follow
1003 :type '(choice
1004 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1005 (const :tag "with y-or-n (faster)" y-or-n-p)
1006 (const :tag "no confirmation (dangerous)" nil)))
1008 (defconst org-file-apps-defaults-gnu
1009 '((t . mailcap))
1010 "Default file applications on a UNIX or GNU/Linux system.
1011 See `org-file-apps'.")
1013 (defconst org-file-apps-defaults-macosx
1014 '((t . "open %s")
1015 ("ps" . "gv %s")
1016 ("ps.gz" . "gv %s")
1017 ("eps" . "gv %s")
1018 ("eps.gz" . "gv %s")
1019 ("dvi" . "xdvi %s")
1020 ("fig" . "xfig %s"))
1021 "Default file applications on a MacOS X system.
1022 The system \"open\" is known as a default, but we use X11 applications
1023 for some files for which the OS does not have a good default.
1024 See `org-file-apps'.")
1026 (defconst org-file-apps-defaults-windowsnt
1027 (list (cons t
1028 (list (if (featurep 'xemacs)
1029 'mswindows-shell-execute
1030 'w32-shell-execute)
1031 "open" 'file)))
1032 "Default file applications on a Windows NT system.
1033 The system \"open\" is used for most files.
1034 See `org-file-apps'.")
1036 (defcustom org-file-apps
1038 ("txt" . emacs)
1039 ("tex" . emacs)
1040 ("ltx" . emacs)
1041 ("org" . emacs)
1042 ("el" . emacs)
1043 ("bib" . emacs)
1045 "External applications for opening `file:path' items in a document.
1046 Org-mode uses system defaults for different file types, but
1047 you can use this variable to set the application for a given file
1048 extension. The entries in this list are cons cells where the car identifies
1049 files and the cdr the corresponding command. Possible values for the
1050 file identifier are
1051 \"ext\" A string identifying an extension
1052 `directory' Matches a directory
1053 t Default for all remaining files
1055 Possible values for the command are:
1056 `emacs' The file will be visited by the current Emacs process.
1057 `default' Use the default application for this file type.
1058 string A command to be executed by a shell; %s will be replaced
1059 by the path to the file.
1060 sexp A Lisp form which will be evaluated. The file path will
1061 be available in the Lisp variable `file'.
1062 For more examples, see the system specific constants
1063 `org-file-apps-defaults-macosx'
1064 `org-file-apps-defaults-windowsnt'
1065 `org-file-apps-defaults-gnu'."
1066 :group 'org-link-follow
1067 :type '(repeat
1068 (cons (choice :value ""
1069 (string :tag "Extension")
1070 (const :tag "Default for unrecognized files" t)
1071 (const :tag "Links to a directory" directory))
1072 (choice :value ""
1073 (const :tag "Visit with Emacs" emacs)
1074 (const :tag "Use system default" default)
1075 (string :tag "Command")
1076 (sexp :tag "Lisp form")))))
1078 (defcustom org-mhe-search-all-folders nil
1079 "Non-nil means, that the search for the mh-message will be extended to
1080 all folders if the message cannot be found in the folder given in the link.
1081 Searching all folders is very effective with one of the search engines
1082 supported by MH-E, but will be slow with pick."
1083 :group 'org-link-follow
1084 :type 'boolean)
1086 (defgroup org-remember nil
1087 "Options concerning interaction with remember.el."
1088 :tag "Org Remember"
1089 :group 'org)
1091 (defcustom org-directory "~/org"
1092 "Directory with org files.
1093 This directory will be used as default to prompt for org files.
1094 Used by the hooks for remember.el."
1095 :group 'org-remember
1096 :type 'directory)
1098 (defcustom org-default-notes-file "~/.notes"
1099 "Default target for storing notes.
1100 Used by the hooks for remember.el. This can be a string, or nil to mean
1101 the value of `remember-data-file'."
1102 :group 'org-remember
1103 :type '(choice
1104 (const :tag "Default from remember-data-file" nil)
1105 file))
1107 (defcustom org-remember-templates nil
1108 "Templates for the creation of remember buffers.
1109 When nil, just let remember make the buffer.
1110 When not nil, this is a list of 3-element lists. In each entry, the first
1111 element is a character, a unique key to select this template.
1112 The second element is the template. The third element is optional and can
1113 specify a destination file for remember items created with this template.
1114 The default file is given by `org-default-notes-file'.
1116 The template specifies the structure of the remember buffer. It should have
1117 a first line starting with a star, to act as the org-mode headline.
1118 Furthermore, the following %-escapes will be replaced with content:
1119 %t time stamp, date only
1120 %T time stamp with date and time
1121 %u inactive time stamp, date only
1122 %U inactive time stamp with date and time
1123 %n user name
1124 %a annotation, normally the link created with org-store-link
1125 %i initial content, the region when remember is called with C-u.
1126 If %i is indented, the entire inserted text will be indented as well.
1127 %? This will be removed, and the cursor placed at this position."
1128 :group 'org-remember
1129 :type '(repeat :tag "enabled"
1130 (list :value (?a "\n" nil)
1131 (character :tag "Selection Key")
1132 (string :tag "Template")
1133 (file :tag "Destination file (optional)"))))
1135 (defcustom org-reverse-note-order nil
1136 "Non-nil means, store new notes at the beginning of a file or entry.
1137 When nil, new notes will be filed to the end of a file or entry."
1138 :group 'org-remember
1139 :type '(choice
1140 (const :tag "Reverse always" t)
1141 (const :tag "Reverse never" nil)
1142 (repeat :tag "By file name regexp"
1143 (cons regexp boolean))))
1145 (defgroup org-todo nil
1146 "Options concerning TODO items in Org-mode."
1147 :tag "Org TODO"
1148 :group 'org)
1150 (defcustom org-todo-keywords '("TODO" "DONE")
1151 "List of TODO entry keywords.
1152 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1153 considered to mean that the entry is \"done\". All the other mean that
1154 action is required, and will make the entry show up in todo lists, diaries
1155 etc.
1156 The command \\[org-todo] cycles an entry through these states, and an
1157 additional state where no keyword is present. For details about this
1158 cycling, see also the variable `org-todo-interpretation'
1159 Changes become only effective after restarting Emacs."
1160 :group 'org-todo
1161 :group 'org-keywords
1162 :type '(repeat (string :tag "Keyword")))
1164 (defcustom org-todo-interpretation 'sequence
1165 "Controls how TODO keywords are interpreted.
1166 This variable is only relevant if `org-todo-keywords' contains more than two
1167 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1169 When `sequence', \\[org-todo] will always switch to the next state in the
1170 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1171 to state when executed several times in direct succession. Otherwise, it
1172 switches directly to DONE from any state.
1173 See the manual for more information."
1174 :group 'org-todo
1175 :group 'org-keywords
1176 :type '(choice (const sequence)
1177 (const type)))
1179 (defcustom org-after-todo-state-change-hook nil
1180 "Hook which is run after the state of a TODO item was changed.
1181 The new state (a string with a TODO keyword, or nil) is available in the
1182 Lisp variable `state'."
1183 :group 'org-todo
1184 :type 'hook)
1186 (defcustom org-log-done nil
1187 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1188 When the state of an entry is changed from nothing to TODO, remove a previous
1189 closing date.
1190 This can also be configured on a per-file basis by adding one of
1191 the following lines anywhere in the buffer:
1193 #+STARTUP: logging
1194 #+STARTUP: nologging"
1195 :group 'org-todo
1196 :type 'boolean)
1198 (defgroup org-priorities nil
1199 "Priorities in Org-mode."
1200 :tag "Org Priorities"
1201 :group 'org-todo)
1203 (defcustom org-default-priority ?B
1204 "The default priority of TODO items.
1205 This is the priority an item get if no explicit priority is given."
1206 :group 'org-priorities
1207 :type 'character)
1209 (defcustom org-lowest-priority ?C
1210 "The lowest priority of TODO items. A character like ?A, ?B etc."
1211 :group 'org-priorities
1212 :type 'character)
1214 (defgroup org-time nil
1215 "Options concerning time stamps and deadlines in Org-mode."
1216 :tag "Org Time"
1217 :group 'org)
1219 (defcustom org-insert-labeled-timestamps-at-point nil
1220 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1221 When nil, these labeled time stamps are forces into the second line of an
1222 entry, just after the headline. When scheduling from the global TODO list,
1223 the time stamp will always be forced into the second line."
1224 :group 'org-time
1225 :type 'boolean)
1227 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1228 "Formats for `format-time-string' which are used for time stamps.
1229 It is not recommended to change this constant.")
1231 (defcustom org-time-stamp-rounding-minutes 0
1232 "Number of minutes to round time stamps to upon insertion.
1233 When zero, insert the time unmodified. Useful rounding numbers
1234 should be factors of 60, so for example 5, 10, 15.
1235 When this is not zero, you can still force an exact time-stamp by using
1236 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1237 :group 'org-time
1238 :type 'integer)
1240 (defcustom org-deadline-warning-days 30
1241 "No. of days before expiration during which a deadline becomes active.
1242 This variable governs the display in the org file."
1243 :group 'org-time
1244 :type 'number)
1246 (defcustom org-popup-calendar-for-date-prompt t
1247 "Non-nil means, pop up a calendar when prompting for a date.
1248 In the calendar, the date can be selected with mouse-1. However, the
1249 minibuffer will also be active, and you can simply enter the date as well.
1250 When nil, only the minibuffer will be available."
1251 :group 'org-time
1252 :type 'boolean)
1254 (defcustom org-calendar-follow-timestamp-change t
1255 "Non-nil means, make the calendar window follow timestamp changes.
1256 When a timestamp is modified and the calendar window is visible, it will be
1257 moved to the new date."
1258 :group 'org-time
1259 :type 'boolean)
1261 (defgroup org-tags nil
1262 "Options concerning tags in Org-mode."
1263 :tag "Org Tags"
1264 :group 'org)
1266 (defcustom org-tag-alist nil
1267 "List of tags allowed in Org-mode files.
1268 When this list is nil, Org-mode will base TAG input on what is already in the
1269 buffer.
1270 The value of this variable is an alist, the car may be (and should) be a
1271 character that is used to select that tag through the fast-tag-selection
1272 interface. See the manual for details."
1273 :group 'org-tags
1274 :type '(repeat
1275 (choice
1276 (cons (string :tag "Tag name")
1277 (character :tag "Access char"))
1278 (const :tag "Start radio group" (:startgroup))
1279 (const :tag "End radio group" (:endgroup)))))
1281 (defcustom org-use-fast-tag-selection 'auto
1282 "Non-nil means, use fast tag selection scheme.
1283 This is a special interface to select and deselect tags with single keys.
1284 When nil, fast selection is never used.
1285 When the symbol `auto', fast selection is used if and only if selection
1286 characters for tags have been configured, either through the variable
1287 `org-tag-alist' or through a #+TAGS line in the buffer.
1288 When t, fast selection is always used and selection keys are assigned
1289 automatically if necessary."
1290 :group 'org-tags
1291 :type '(choice
1292 (const :tag "Always" t)
1293 (const :tag "Never" nil)
1294 (const :tag "When selection characters are configured" 'auto)))
1296 (defcustom org-tags-column 48
1297 "The column to which tags should be indented in a headline.
1298 If this number is positive, it specifies the column. If it is negative,
1299 it means that the tags should be flushright to that column. For example,
1300 -79 works well for a normal 80 character screen."
1301 :group 'org-tags
1302 :type 'integer)
1304 (defcustom org-auto-align-tags t
1305 "Non-nil means, realign tags after pro/demotion of TODO state change.
1306 These operations change the length of a headline and therefore shift
1307 the tags around. With this options turned on, after each such operation
1308 the tags are again aligned to `org-tags-column'."
1309 :group 'org-tags
1310 :type 'boolean)
1312 (defcustom org-use-tag-inheritance t
1313 "Non-nil means, tags in levels apply also for sublevels.
1314 When nil, only the tags directly given in a specific line apply there.
1315 If you turn off this option, you very likely want to turn on the
1316 companion option `org-tags-match-list-sublevels'."
1317 :group 'org-tags
1318 :type 'boolean)
1320 (defcustom org-tags-match-list-sublevels nil
1321 "Non-nil means list also sublevels of headlines matching tag search.
1322 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1323 the sublevels of a headline matching a tag search often also match
1324 the same search. Listing all of them can create very long lists.
1325 Setting this variable to nil causes subtrees of a match to be skipped.
1326 This option is off by default, because inheritance in on. If you turn
1327 inheritance off, you very likely want to turn this option on.
1329 As a special case, if the tag search is restricted to TODO items, the
1330 value of this variable is ignored and sublevels are always checked, to
1331 make sure all corresponding TODO items find their way into the list."
1332 :group 'org-tags
1333 :type 'boolean)
1335 (defvar org-tags-history nil
1336 "History of minibuffer reads for tags.")
1337 (defvar org-last-tags-completion-table nil
1338 "The last used completion table for tags.")
1340 (defgroup org-agenda nil
1341 "Options concerning agenda display Org-mode."
1342 :tag "Org Agenda"
1343 :group 'org)
1345 (defvar org-category nil
1346 "Variable used by org files to set a category for agenda display.
1347 Such files should use a file variable to set it, for example
1349 -*- mode: org; org-category: \"ELisp\"
1351 or contain a special line
1353 #+CATEGORY: ELisp
1355 If the file does not specify a category, then file's base name
1356 is used instead.")
1357 (make-variable-buffer-local 'org-category)
1359 (defcustom org-agenda-files nil
1360 "The files to be used for agenda display.
1361 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1362 \\[org-remove-file]. You can also use customize to edit the list.
1364 If the value of the variable is not a list but a single file name, then
1365 the list of agenda files is actually stored and maintained in that file, one
1366 agenda file per line."
1367 :group 'org-agenda
1368 :type '(choice
1369 (repeat :tag "List of files" file)
1370 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1372 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1373 "Custom commands for the agenda.
1374 These commands will be offered on the splash screen displayed by the
1375 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
1377 key The key (a single char as a string) to be associated with the command.
1378 type The command type, any of the following symbols:
1379 todo Entries with a specific TODO keyword, in all agenda files.
1380 tags Tags match in all agenda files.
1381 tags-todo Tags match in all agenda files, TODO entries only.
1382 todo-tree Sparse tree of specific TODO keyword in *current* file.
1383 tags-tree Sparse tree with all tags matches in *current* file.
1384 occur-tree Occur sparse tree for current file.
1385 match What to search for:
1386 - a single keyword for TODO keyword searches
1387 - a tags match expression for tags searches
1388 - a regular expression for occur searches"
1389 :group 'org-agenda
1390 :type '(repeat
1391 (list (string :tag "Key")
1392 (choice :tag "Type"
1393 (const :tag "Tags search in all agenda files" tags)
1394 (const :tag "Tags search of TODO entries, all agenda files" tags-todo)
1395 (const :tag "TODO keyword search in all agenda files" todo)
1396 (const :tag "Tags sparse tree in current buffer" tags-tree)
1397 (const :tag "TODO keyword tree in current buffer" todo-tree)
1398 (const :tag "Occur tree in current buffer" occur-tree))
1399 (string :tag "Match"))))
1401 (defcustom org-agenda-todo-list-sublevels t
1402 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1403 When nil, the sublevels of a TODO entry are not checked, resulting in
1404 potentially much shorter TODO lists."
1405 :group 'org-agenda
1406 :group 'org-todo
1407 :type 'boolean)
1409 (defcustom org-agenda-todo-ignore-scheduled nil
1410 "Non-nil means, don't show scheduled entries in the global todo list.
1411 The idea behind this is that by scheduling it, you have already taken care
1412 of this item."
1413 :group 'org-agenda
1414 :group 'org-todo
1415 :type 'boolean)
1417 (defcustom org-agenda-include-all-todo nil
1418 "Non-nil means, the agenda will always contain all TODO entries.
1419 When nil, date-less entries will only be shown if `org-agenda' is called
1420 with a prefix argument.
1421 When non-nil, the TODO entries will be listed at the top of the agenda, before
1422 the entries for specific days."
1423 :group 'org-agenda
1424 :type 'boolean)
1426 (defcustom org-agenda-include-diary nil
1427 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1428 :group 'org-agenda
1429 :type 'boolean)
1431 (defcustom org-calendar-to-agenda-key [?c]
1432 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1433 The command `org-calendar-goto-agenda' will be bound to this key. The
1434 default is the character `c' because then `c' can be used to switch back and
1435 forth between agenda and calendar."
1436 :group 'org-agenda
1437 :type 'sexp)
1439 (defgroup org-agenda-setup nil
1440 "Options concerning setting up the Agenda window in Org Mode."
1441 :tag "Org Agenda Window Setup"
1442 :group 'org-agenda)
1444 (defcustom org-agenda-mouse-1-follows-link nil
1445 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1446 A longer mouse click will still set point. Does not wortk on XEmacs.
1447 Needs to be set before org.el is loaded."
1448 :group 'org-agenda-setup
1449 :type 'boolean)
1451 (defcustom org-agenda-start-with-follow-mode nil
1452 "The initial value of follwo-mode in a newly created agenda window."
1453 :group 'org-agenda-setup
1454 :type 'boolean)
1456 (defcustom org-select-agenda-window t
1457 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1458 When nil, cursor will remain in the current window."
1459 :group 'org-agenda-setup
1460 :type 'boolean)
1462 (defcustom org-fit-agenda-window t
1463 "Non-nil means, change window size of agenda to fit content."
1464 :group 'org-agenda-setup
1465 :type 'boolean)
1467 (defgroup org-agenda-display nil
1468 "Options concerning what to display initially in Agenda."
1469 :tag "Org Agenda Display"
1470 :group 'org-agenda)
1472 (defcustom org-agenda-show-all-dates t
1473 "Non-nil means, `org-agenda' shows every day in the selected range.
1474 When nil, only the days which actually have entries are shown."
1475 :group 'org-agenda-display
1476 :type 'boolean)
1478 (defcustom org-agenda-start-on-weekday 1
1479 "Non-nil means, start the overview always on the specified weekday.
1480 0 denotes Sunday, 1 denotes Monday etc.
1481 When nil, always start on the current day."
1482 :group 'org-agenda-display
1483 :type '(choice (const :tag "Today" nil)
1484 (number :tag "Weekday No.")))
1486 (defcustom org-agenda-ndays 7
1487 "Number of days to include in overview display.
1488 Should be 1 or 7."
1489 :group 'org-agenda-display
1490 :type 'number)
1492 (defcustom org-agenda-use-time-grid t
1493 "Non-nil means, show a time grid in the agenda schedule.
1494 A time grid is a set of lines for specific times (like every two hours between
1495 8:00 and 20:00). The items scheduled for a day at specific times are
1496 sorted in between these lines.
1497 For details about when the grid will be shown, and what it will look like, see
1498 the variable `org-agenda-time-grid'."
1499 :group 'org-agenda-display
1500 :type 'boolean)
1502 (defcustom org-agenda-time-grid
1503 '((daily today require-timed)
1504 "----------------"
1505 (800 1000 1200 1400 1600 1800 2000))
1507 "The settings for time grid for agenda display.
1508 This is a list of three items. The first item is again a list. It contains
1509 symbols specifying conditions when the grid should be displayed:
1511 daily if the agenda shows a single day
1512 weekly if the agenda shows an entire week
1513 today show grid on current date, independent of daily/weekly display
1514 require-timed show grid only if at least on item has a time specification
1516 The second item is a string which will be places behing the grid time.
1518 The third item is a list of integers, indicating the times that should have
1519 a grid line."
1520 :group 'org-agenda-display
1521 :type
1522 '(list
1523 (set :greedy t :tag "Grid Display Options"
1524 (const :tag "Show grid in single day agenda display" daily)
1525 (const :tag "Show grid in weekly agenda display" weekly)
1526 (const :tag "Always show grid for today" today)
1527 (const :tag "Show grid only if any timed entries are present"
1528 require-timed)
1529 (const :tag "Skip grid times already present in an entry"
1530 remove-match))
1531 (string :tag "Grid String")
1532 (repeat :tag "Grid Times" (integer :tag "Time"))))
1534 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
1535 "Sorting structure for the agenda items of a single day.
1536 This is a list of symbols which will be used in sequence to determine
1537 if an entry should be listed before another entry. The following
1538 symbols are recognized:
1540 time-up Put entries with time-of-day indications first, early first
1541 time-down Put entries with time-of-day indications first, late first
1542 category-keep Keep the default order of categories, corresponding to the
1543 sequence in `org-agenda-files'.
1544 category-up Sort alphabetically by category, A-Z.
1545 category-down Sort alphabetically by category, Z-A.
1546 priority-up Sort numerically by priority, high priority last.
1547 priority-down Sort numerically by priority, high priority first.
1549 The different possibilities will be tried in sequence, and testing stops
1550 if one comparison returns a \"not-equal\". For example, the default
1551 '(time-up category-keep priority-down)
1552 means: Pull out all entries having a specified time of day and sort them,
1553 in order to make a time schedule for the current day the first thing in the
1554 agenda listing for the day. Of the entries without a time indication, keep
1555 the grouped in categories, don't sort the categories, but keep them in
1556 the sequence given in `org-agenda-files'. Within each category sort by
1557 priority.
1559 Leaving out `category-keep' would mean that items will be sorted across
1560 categories by priority."
1561 :group 'org-agenda-display
1562 :type '(repeat
1563 (choice
1564 (const time-up)
1565 (const time-down)
1566 (const category-keep)
1567 (const category-up)
1568 (const category-down)
1569 (const priority-up)
1570 (const priority-down))))
1572 (defcustom org-sort-agenda-notime-is-late t
1573 "Non-nil means, items without time are considered late.
1574 This is only relevant for sorting. When t, items which have no explicit
1575 time like 15:30 will be considered as 99:01, i.e. later than any items which
1576 do have a time. When nil, the default time is before 0:00. You can use this
1577 option to decide if the schedule for today should come before or after timeless
1578 agenda entries."
1579 :group 'org-agenda-display
1580 :type 'boolean)
1583 (defgroup org-agenda-prefix nil
1584 "Options concerning the entry prefix in the Org-mode agenda display."
1585 :tag "Org Agenda Prefix"
1586 :group 'org-agenda)
1588 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
1589 "Format specification for the prefix of items in the agenda buffer.
1590 This format works similar to a printf format, with the following meaning:
1592 %c the category of the item, \"Diary\" for entries from the diary, or
1593 as given by the CATEGORY keyword or derived from the file name.
1594 %T the first tag of the item.
1595 %t the time-of-day specification if one applies to the entry, in the
1596 format HH:MM
1597 %s Scheduling/Deadline information, a short string
1599 All specifiers work basically like the standard `%s' of printf, but may
1600 contain two additional characters: A question mark just after the `%' and
1601 a whitespace/punctuation character just before the final letter.
1603 If the first character after `%' is a question mark, the entire field
1604 will only be included if the corresponding value applies to the
1605 current entry. This is useful for fields which should have fixed
1606 width when present, but zero width when absent. For example,
1607 \"%?-12t\" will result in a 12 character time field if a time of the
1608 day is specified, but will completely disappear in entries which do
1609 not contain a time.
1611 If there is punctuation or whitespace character just before the final
1612 format letter, this character will be appended to the field value if
1613 the value is not empty. For example, the format \"%-12:c\" leads to
1614 \"Diary: \" if the category is \"Diary\". If the category were be
1615 empty, no additional colon would be interted.
1617 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1618 - Indent the line with two space characters
1619 - Give the category in a 12 chars wide field, padded with whitespace on
1620 the right (because of `-'). Append a colon if there is a category
1621 (because of `:').
1622 - If there is a time-of-day, put it into a 12 chars wide field. If no
1623 time, don't put in an empty field, just skip it (because of '?').
1624 - Finally, put the scheduling information and append a whitespace.
1626 As another example, if you don't want the time-of-day of entries in
1627 the prefix, you could use:
1629 (setq org-agenda-prefix-format \" %-11:c% s\")
1631 See also the variables `org-agenda-remove-times-when-in-prefix' and
1632 `org-agenda-remove-tags-when-in-prefix'."
1633 :type 'string
1634 :group 'org-agenda-prefix)
1636 (defvar org-prefix-format-compiled nil
1637 "The compiled version of the most recently used prefix format.
1638 Depending on which command was used last, this may be the compiled version
1639 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
1641 (defcustom org-agenda-remove-times-when-in-prefix t
1642 "Non-nil means, remove duplicate time specifications in agenda items.
1643 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1644 time-of-day specification in a headline or diary entry is extracted and
1645 placed into the prefix. If this option is non-nil, the original specification
1646 \(a timestamp or -range, or just a plain time(range) specification like
1647 11:30-4pm) will be removed for agenda display. This makes the agenda less
1648 cluttered.
1649 The option can be t or nil. It may also be the symbol `beg', indicating
1650 that the time should only be removed what it is located at the beginning of
1651 the headline/diary entry."
1652 :group 'org-agenda-prefix
1653 :type '(choice
1654 (const :tag "Always" t)
1655 (const :tag "Never" nil)
1656 (const :tag "When at beginning of entry" beg)))
1658 (defcustom org-agenda-remove-tags-when-in-prefix nil
1659 "Non-nil means, remove the tags from the headline copy in the agenda.
1660 When this is the symbol `prefix', only remove tags when
1661 `org-agenda-prefix-format' contains a `%T' specifier."
1662 :group 'org-agenda-prefix
1663 :type '(choice
1664 (const :tag "Always" t)
1665 (const :tag "Never" nil)
1666 (const :tag "When prefix format contains %T" prefix)))
1668 (defgroup org-agenda-timeline nil
1669 "Options concerning the timeline buffer in Org Mode."
1670 :tag "Org Agenda Timeline"
1671 :group 'org-agenda)
1673 (defcustom org-timeline-prefix-format " % s"
1674 "Like `org-agenda-prefix-format', but for the timeline of a single file."
1675 :type 'string
1676 :group 'org-agenda-timeline)
1678 (defcustom org-select-timeline-window t
1679 "Non-nil means, after creating a timeline, move cursor into Timeline window.
1680 When nil, cursor will remain in the current window."
1681 :group 'org-agenda-timeline
1682 :type 'boolean)
1684 (defcustom org-timeline-show-empty-dates 3
1685 "Non-nil means, `org-timeline' also shows dates without an entry.
1686 When nil, only the days which actually have entries are shown.
1687 When t, all days between the first and the last date are shown.
1688 When an integer, show also empty dates, but if there is a gap of more than
1689 N days, just insert a special line indicating the size of the gap."
1690 :group 'org-agenda-timeline
1691 :type '(choice
1692 (const :tag "None" nil)
1693 (const :tag "All" t)
1694 (number :tag "at most")))
1696 (defgroup org-export nil
1697 "Options for exporting org-listings."
1698 :tag "Org Export"
1699 :group 'org)
1701 (defgroup org-export-general nil
1702 "General options for exporting Org-mode files."
1703 :tag "Org Export General"
1704 :group 'org-export)
1706 (defcustom org-export-publishing-directory "."
1707 "Path to the location where exported files should be located.
1708 This path may be relative to the directory where the Org-mode file lives.
1709 The default is to put them into the same directory as the Org-mode file.
1710 The variable may also be an alist with export types `:html', `:ascii',
1711 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
1712 is relative, it is interpreted relative to the directory where the exported
1713 Org-mode files lives."
1714 :group 'org-export-general
1715 :type '(choice
1716 (directory)
1717 (repeat
1718 (cons
1719 (choice :tag "Type"
1720 (const :html) (const :ascii) (const :ical) (const :xoxo))
1721 (directory)))))
1723 (defcustom org-export-language-setup
1724 '(("en" "Author" "Date" "Table of Contents")
1725 ("da" "Ophavsmand" "Dato" "Indhold")
1726 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1727 ("es" "Autor" "Fecha" "\xccndice")
1728 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1729 ("it" "Autore" "Data" "Indice")
1730 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1731 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1732 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1733 "Terms used in export text, translated to different languages.
1734 Use the variable `org-export-default-language' to set the language,
1735 or use the +OPTION lines for a per-file setting."
1736 :group 'org-export-general
1737 :type '(repeat
1738 (list
1739 (string :tag "HTML language tag")
1740 (string :tag "Author")
1741 (string :tag "Date")
1742 (string :tag "Table of Contents"))))
1744 (defcustom org-export-default-language "en"
1745 "The default language of HTML export, as a string.
1746 This should have an association in `org-export-language-setup'."
1747 :group 'org-export-general
1748 :type 'string)
1750 (defcustom org-export-headline-levels 3
1751 "The last level which is still exported as a headline.
1752 Inferior levels will produce itemize lists when exported.
1753 Note that a numeric prefix argument to an exporter function overrides
1754 this setting.
1756 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1757 :group 'org-export-general
1758 :type 'number)
1760 (defcustom org-export-with-section-numbers t
1761 "Non-nil means, add section numbers to headlines when exporting.
1763 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1764 :group 'org-export-general
1765 :type 'boolean)
1767 (defcustom org-export-with-toc t
1768 "Non-nil means, create a table of contents in exported files.
1769 The TOC contains headlines with levels up to`org-export-headline-levels'.
1771 Headlines which contain any TODO items will be marked with \"(*)\" in
1772 ASCII export, and with red color in HTML output.
1774 In HTML output, the TOC will be clickable.
1776 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1777 :group 'org-export-general
1778 :type 'boolean)
1780 (defcustom org-export-mark-todo-in-toc nil
1781 "Non-nil means, mark TOC lines that contain any open TODO items."
1782 :group 'org-export-general
1783 :type 'boolean)
1785 (defcustom org-export-preserve-breaks nil
1786 "Non-nil means, preserve all line breaks when exporting.
1787 Normally, in HTML output paragraphs will be reformatted. In ASCII
1788 export, line breaks will always be preserved, regardless of this variable.
1790 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1791 :group 'org-export-general
1792 :type 'boolean)
1794 (defcustom org-export-with-timestamps t
1795 "Nil means, do not export time stamps and associated keywords."
1796 :group 'org-export
1797 :type 'boolean)
1799 (defcustom org-export-with-tags t
1800 "Nil means, do not export tags, just remove them from headlines."
1801 :group 'org-export-general
1802 :type 'boolean)
1804 (defcustom org-export-with-timestamps t
1805 "Nil means, do not export timestamps and associated keywords."
1806 :group 'org-export-general
1807 :type 'boolean)
1809 (defgroup org-export-translation nil
1810 "Options for translating special ascii sequences for the export backends."
1811 :tag "Org Export Translation"
1812 :group 'org-export)
1814 (defcustom org-export-with-emphasize t
1815 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1816 If the export target supports emphasizing text, the word will be
1817 typeset in bold, italic, or underlined, respectively. Works only for
1818 single words, but you can say: I *really* *mean* *this*.
1819 Not all export backends support this.
1821 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1822 :group 'org-export-translation
1823 :type 'boolean)
1825 (defcustom org-export-with-sub-superscripts t
1826 "Non-nil means, interpret \"_\" and \"^\" for export.
1827 When this option is turned on, you can use TeX-like syntax for sub- and
1828 superscripts. Several characters after \"_\" or \"^\" will be
1829 considered as a single item - so grouping with {} is normally not
1830 needed. For example, the following things will be parsed as single
1831 sub- or superscripts.
1833 10^24 or 10^tau several digits will be considered 1 item.
1834 10^-12 or 10^-tau a leading sign with digits or a word
1835 x^2-y^3 will be read as x^2 - y^3, because items are
1836 terminated by almost any nonword/nondigit char.
1837 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1839 Still, ambiguity is possible - so when in doubt use {} to enclose the
1840 sub/superscript.
1841 Not all export backends support this, but HTML does.
1843 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1844 :group 'org-export-translation
1845 :type 'boolean)
1847 (defcustom org-export-with-TeX-macros t
1848 "Non-nil means, interpret simple TeX-like macros when exporting.
1849 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1850 No only real TeX macros will work here, but the standard HTML entities
1851 for math can be used as macro names as well. For a list of supported
1852 names in HTML export, see the constant `org-html-entities'.
1853 Not all export backends support this.
1855 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1856 :group 'org-export-translation
1857 :type 'boolean)
1859 (defcustom org-export-with-fixed-width t
1860 "Non-nil means, lines starting with \":\" will be in fixed width font.
1861 This can be used to have pre-formatted text, fragments of code etc. For
1862 example:
1863 : ;; Some Lisp examples
1864 : (while (defc cnt)
1865 : (ding))
1866 will be looking just like this in also HTML. See also the QUOTE keyword.
1867 Not all export backends support this.
1869 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1870 :group 'org-export-translation
1871 :type 'boolean)
1873 (defcustom org-match-sexp-depth 3
1874 "Number of stacked braces for sub/superscript matching.
1875 This has to be set before loading org.el to be effective."
1876 :group 'org-export-translation
1877 :type 'integer)
1879 (defgroup org-export-tables nil
1880 "Options for exporting tables in Org-mode."
1881 :tag "Org Export Tables"
1882 :group 'org-export)
1884 (defcustom org-export-with-tables t
1885 "If non-nil, lines starting with \"|\" define a table.
1886 For example:
1888 | Name | Address | Birthday |
1889 |-------------+----------+-----------|
1890 | Arthur Dent | England | 29.2.2100 |
1892 Not all export backends support this.
1894 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1895 :group 'org-export-tables
1896 :type 'boolean)
1898 (defcustom org-export-highlight-first-table-line t
1899 "Non-nil means, highlight the first table line.
1900 In HTML export, this means use <th> instead of <td>.
1901 In tables created with table.el, this applies to the first table line.
1902 In Org-mode tables, all lines before the first horizontal separator
1903 line will be formatted with <th> tags."
1904 :group 'org-export-tables
1905 :type 'boolean)
1907 (defcustom org-export-table-remove-special-lines t
1908 "Remove special lines and marking characters in calculating tables.
1909 This removes the special marking character column from tables that are set
1910 up for spreadsheet calculations. It also removes the entire lines
1911 marked with `!', `_', or `^'. The lines with `$' are kept, because
1912 the values of constants may be useful to have."
1913 :group 'org-export-tables
1914 :type 'boolean)
1916 (defcustom org-export-prefer-native-exporter-for-tables nil
1917 "Non-nil means, always export tables created with table.el natively.
1918 Natively means, use the HTML code generator in table.el.
1919 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1920 the table does not use row- or column-spanning). This has the
1921 advantage, that the automatic HTML conversions for math symbols and
1922 sub/superscripts can be applied. Org-mode's HTML generator is also
1923 much faster."
1924 :group 'org-export-tables
1925 :type 'boolean)
1927 (defgroup org-export-ascii nil
1928 "Options specific for ASCII export of Org-mode files."
1929 :tag "Org Export ASCII"
1930 :group 'org-export)
1932 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
1933 "Characters for underlining headings in ASCII export.
1934 In the given sequence, these characters will be used for level 1, 2, ..."
1935 :group 'org-export-ascii
1936 :type '(repeat character))
1938 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
1939 "Bullet characters for headlines converted to lists in ASCII export.
1940 The first character is is used for the first lest level generated in this
1941 way, and so on. If there are more levels than characters given here,
1942 the list will be repeated.
1943 Note that plain lists will keep the same bullets as the have in the
1944 Org-mode file."
1945 :group 'org-export-ascii
1946 :type '(repeat character))
1948 (defcustom org-export-ascii-show-new-buffer t
1949 "Non-nil means, popup buffer containing the exported ASCII text.
1950 Otherwise the buffer will just be saved to a file and stay hidden."
1951 :group 'org-export-ascii
1952 :type 'boolean)
1954 (defgroup org-export-xml nil
1955 "Options specific for XML export of Org-mode files."
1956 :tag "Org Export XML"
1957 :group 'org-export)
1959 (defgroup org-export-html nil
1960 "Options specific for HTML export of Org-mode files."
1961 :tag "Org Export HTML"
1962 :group 'org-export)
1964 (defcustom org-export-html-style
1965 "<style type=\"text/css\">
1966 html {
1967 font-family: Times, serif;
1968 font-size: 12pt;
1970 .title { text-align: center; }
1971 .todo { color: red; }
1972 .done { color: green; }
1973 .timestamp { color: grey }
1974 .timestamp-kwd { color: CadetBlue }
1975 .tag { background-color:lightblue; font-weight:normal }
1976 .target { background-color: lavender; }
1977 pre {
1978 border: 1pt solid #AEBDCC;
1979 background-color: #F3F5F7;
1980 padding: 5pt;
1981 font-family: courier, monospace;
1983 table { border-collapse: collapse; }
1984 td, th {
1985 vertical-align: top;
1986 border: 1pt solid #ADB9CC;
1988 </style>"
1989 "The default style specification for exported HTML files.
1990 Since there are different ways of setting style information, this variable
1991 needs to contain the full HTML structure to provide a style, including the
1992 surrounding HTML tags. The style specifications should include definitions
1993 for new classes todo, done, title, and deadline. For example, legal values
1994 would be:
1996 <style type=\"text/css\">
1997 p { font-weight: normal; color: gray; }
1998 h1 { color: black; }
1999 .title { text-align: center; }
2000 .todo, .deadline { color: red; }
2001 .done { color: green; }
2002 </style>
2004 or, if you want to keep the style in a file,
2006 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2008 As the value of this option simply gets inserted into the HTML <head> header,
2009 you can \"misuse\" it to add arbitrary text to the header."
2010 :group 'org-export-html
2011 :type 'string)
2013 (defcustom org-export-html-link-org-files-as-html t
2014 "Non-nil means, make file links to `file.org' point to `file.html'.
2015 When org-mode is exporting an org-mode file to HTML, links to
2016 non-html files are directly put into a href tag in HTML.
2017 However, links to other Org-mode files (recognized by the
2018 extension `.org.) should become links to the corresponding html
2019 file, assuming that the linked org-mode file will also be
2020 converted to HTML.
2021 When nil, the links still point to the plain `.org' file."
2022 :group 'org-export-html
2023 :type 'boolean)
2025 (defcustom org-export-html-inline-images 'maybe
2026 "Non-nil means, inline images into exported HTML pages.
2027 This is done using an <img> tag. When nil, an anchor with href is used to
2028 link to the image. If this option is `maybe', then images in links with
2029 an empty description will be inlined, while images with a description will
2030 be linked only."
2031 :group 'org-export-html
2032 :type '(choice (const :tag "Never" nil)
2033 (const :tag "Always" t)
2034 (const :tag "When there is no description" maybe)))
2036 (defcustom org-export-html-expand t
2037 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2038 When nil, these tags will be exported as plain text and therefore
2039 not be interpreted by a browser.
2041 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2042 :group 'org-export-html
2043 :type 'boolean)
2045 (defcustom org-export-html-table-tag
2046 "<table border=\"1\" cellspacing=\"0\" cellpadding=\"6\">"
2047 "The HTML tag used to start a table.
2048 This must be a <table> tag, but you may change the options like
2049 borders and spacing."
2050 :group 'org-export-html
2051 :type 'string)
2053 (defcustom org-export-html-with-timestamp nil
2054 "If non-nil, write `org-export-html-html-helper-timestamp'
2055 into the exported HTML text. Otherwise, the buffer will just be saved
2056 to a file."
2057 :group 'org-export-html
2058 :type 'boolean)
2060 (defcustom org-export-html-html-helper-timestamp
2061 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2062 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2063 :group 'org-export-html
2064 :type 'string)
2066 (defcustom org-export-html-show-new-buffer nil
2067 "Non-nil means, popup buffer containing the exported html text.
2068 Otherwise, the buffer will just be saved to a file and stay hidden."
2069 :group 'org-export-html
2070 :type 'boolean)
2072 (defgroup org-export-icalendar nil
2073 "Options specific for iCalendar export of Org-mode files."
2074 :tag "Org Export iCalendar"
2075 :group 'org-export)
2077 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2078 "The file name for the iCalendar file covering all agenda files.
2079 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2080 The file name should be absolute."
2081 :group 'org-export-icalendar
2082 :type 'file)
2084 (defcustom org-icalendar-include-todo nil
2085 "Non-nil means, export to iCalendar files should also cover TODO items."
2086 :group 'org-export-icalendar
2087 :type 'boolean)
2089 (defcustom org-icalendar-combined-name "OrgMode"
2090 "Calendar name for the combined iCalendar representing all agenda files."
2091 :group 'org-export-icalendar
2092 :type 'string)
2094 (defgroup org-font-lock nil
2095 "Font-lock settings for highlighting in Org-mode."
2096 :tag "Org Font Lock"
2097 :group 'org)
2099 (defcustom org-level-color-stars-only nil
2100 "Non-nil means fontify only the stars in each headline.
2101 When nil, the entire headline is fontified.
2102 Changing it requires restart of `font-lock-mode' to become effective
2103 also in regions already fontified."
2104 :group 'org-font-lock
2105 :type 'boolean)
2107 (defcustom org-hide-leading-stars nil
2108 "Non-nil means, hide the first N-1 stars in a headline.
2109 This works by using the face `org-hide' for these stars. This
2110 face is white for a light background, and black for a dark
2111 background. You may have to customize the face `org-hide' to
2112 make this work.
2113 Changing it requires restart of `font-lock-mode' to become effective
2114 also in regions already fontified.
2115 You may also set this on a per-file basis by adding one of the following
2116 lines to the buffer:
2118 #+STARTUP: hidestars
2119 #+STARTUP: showstars"
2120 :group 'org-font-lock
2121 :type 'boolean)
2123 (defcustom org-fontify-done-headline nil
2124 "Non-nil means, change the face of a headline if it is marked DONE.
2125 Normally, only the TODO/DONE keyword indicates the state of a headline.
2126 When this is non-nil, the headline after the keyword is set to the
2127 `org-headline-done' as an additional indication."
2128 :group 'org-font-lock
2129 :type 'boolean)
2131 (defcustom org-fontify-emphasized-text t
2132 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2133 Changing this variable requires a restart of Emacs to take effect."
2134 :group 'org-font-lock
2135 :type 'boolean)
2137 (defgroup org-faces nil
2138 "Faces in Org-mode."
2139 :tag "Org Faces"
2140 :group 'org-font-lock)
2142 (defun org-compatible-face (specs)
2143 "Make a compatible face specification.
2144 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2145 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2146 to the top of the list. The `min-colors' attribute will be removed from
2147 any other entries, and any resulting duplicates will be removed entirely."
2148 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2149 (let (r e a)
2150 (while (setq e (pop specs))
2151 (cond
2152 ((memq (car e) '(t default)) (push e r))
2153 ((setq a (member '(min-colors 8) (car e)))
2154 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2155 (cdr e)))))
2156 ((setq a (assq 'min-colors (car e)))
2157 (setq e (cons (delq a (car e)) (cdr e)))
2158 (or (assoc (car e) r) (push e r)))
2159 (t (or (assoc (car e) r) (push e r)))))
2160 (nreverse r))
2161 specs))
2163 (defface org-hide
2164 '((((background light)) (:foreground "white"))
2165 (((background dark)) (:foreground "black")))
2166 "Face used to hide leading stars in headlines.
2167 The forground color of this face should be equal to the background
2168 color of the frame."
2169 :group 'org-faces)
2171 (defface org-level-1 ;; font-lock-function-name-face
2172 (org-compatible-face
2173 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2174 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2175 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2176 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2177 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2178 (t (:bold t))))
2179 "Face used for level 1 headlines."
2180 :group 'org-faces)
2182 (defface org-level-2 ;; font-lock-variable-name-face
2183 (org-compatible-face
2184 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2185 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2186 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2187 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2188 (t (:bold t))))
2189 "Face used for level 2 headlines."
2190 :group 'org-faces)
2192 (defface org-level-3 ;; font-lock-keyword-face
2193 (org-compatible-face
2194 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2195 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2196 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2197 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2198 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2199 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2200 (t (:bold t))))
2201 "Face used for level 3 headlines."
2202 :group 'org-faces)
2204 (defface org-level-4 ;; font-lock-comment-face
2205 (org-compatible-face
2206 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2207 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2208 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2209 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2210 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2211 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2212 (t (:bold t))))
2213 "Face used for level 4 headlines."
2214 :group 'org-faces)
2216 (defface org-level-5 ;; font-lock-type-face
2217 (org-compatible-face
2218 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2219 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2220 (((class color) (min-colors 8)) (:foreground "green"))))
2221 "Face used for level 5 headlines."
2222 :group 'org-faces)
2224 (defface org-level-6 ;; font-lock-constant-face
2225 (org-compatible-face
2226 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2227 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2228 (((class color) (min-colors 8)) (:foreground "magenta"))))
2229 "Face used for level 6 headlines."
2230 :group 'org-faces)
2232 (defface org-level-7 ;; font-lock-builtin-face
2233 (org-compatible-face
2234 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2235 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2236 (((class color) (min-colors 8)) (:foreground "blue"))))
2237 "Face used for level 7 headlines."
2238 :group 'org-faces)
2240 (defface org-level-8 ;; font-lock-string-face
2241 (org-compatible-face
2242 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2243 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2244 (((class color) (min-colors 8)) (:foreground "green"))))
2245 "Face used for level 8 headlines."
2246 :group 'org-faces)
2248 (defface org-special-keyword ;; font-lock-string-face
2249 (org-compatible-face
2250 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2251 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2252 (t (:italic t))))
2253 "Face used for special keywords."
2254 :group 'org-faces)
2256 (defface org-warning ;; font-lock-warning-face
2257 (org-compatible-face
2258 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2259 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2260 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2261 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2262 (t (:bold t))))
2263 "Face for deadlines and TODO keywords."
2264 :group 'org-faces)
2266 (defface org-headline-done ;; font-lock-string-face
2267 (org-compatible-face
2268 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2269 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2270 (((class color) (min-colors 8) (background light)) (:bold nil))))
2271 "Face used to indicate that a headline is DONE.
2272 This face is only used if `org-fontify-done-headline' is set."
2273 :group 'org-faces)
2275 (defface org-link
2276 '((((class color) (background light)) (:foreground "Purple" :underline t))
2277 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2278 (t (:underline t)))
2279 "Face for links."
2280 :group 'org-faces)
2282 (defface org-date
2283 '((((class color) (background light)) (:foreground "Purple" :underline t))
2284 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2285 (t (:underline t)))
2286 "Face for links."
2287 :group 'org-faces)
2289 (defface org-tag
2290 '((t (:bold t)))
2291 "Face for tags."
2292 :group 'org-faces)
2294 (defface org-todo ;; font-lock-warning-face
2295 (org-compatible-face
2296 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2297 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2298 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2299 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2300 (t (:inverse-video t :bold t))))
2301 "Face for TODO keywords."
2302 :group 'org-faces)
2304 (defface org-done ;; font-lock-type-face
2305 (org-compatible-face
2306 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2307 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2308 (((class color) (min-colors 8)) (:foreground "green"))
2309 (t (:bold t))))
2310 "Face used for DONE."
2311 :group 'org-faces)
2313 (defface org-table ;; font-lock-function-name-face
2314 (org-compatible-face
2315 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2316 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2317 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2318 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2319 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2320 (((class color) (min-colors 8) (background dark)))))
2321 "Face used for tables."
2322 :group 'org-faces)
2324 (defface org-formula
2325 (org-compatible-face
2326 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2327 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2328 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2329 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2330 (t (:bold t :italic t))))
2331 "Face for formulas."
2332 :group 'org-faces)
2334 (defface org-scheduled-today
2335 (org-compatible-face
2336 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2337 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2338 (((class color) (min-colors 8)) (:foreground "green"))
2339 (t (:bold t :italic t))))
2340 "Face for items scheduled for a certain day."
2341 :group 'org-faces)
2343 (defface org-scheduled-previously
2344 (org-compatible-face
2345 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2346 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2347 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2348 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2349 (t (:bold t))))
2350 "Face for items scheduled previously, and not yet done."
2351 :group 'org-faces)
2353 (defface org-upcoming-deadline
2354 (org-compatible-face
2355 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2356 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2357 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2358 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2359 (t (:bold t))))
2360 "Face for items scheduled previously, and not yet done."
2361 :group 'org-faces)
2363 (defface org-time-grid ;; font-lock-variable-name-face
2364 (org-compatible-face
2365 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2366 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2367 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
2368 "Face used for time grids."
2369 :group 'org-faces)
2371 (defconst org-level-faces
2372 '(org-level-1 org-level-2 org-level-3 org-level-4
2373 org-level-5 org-level-6 org-level-7 org-level-8
2375 (defconst org-n-levels (length org-level-faces))
2377 (defconst org-bold-re
2378 (if (featurep 'xemacs)
2379 "\\([ ]\\|^\\)\\(\\*\\(\\w[a-zA-Z0-9-_ ]*?\\w\\)\\*\\)\\([ ,.]\\|$\\)"
2380 "\\([ ]\\|^\\)\\(\\*\\(\\w[[:word:] -_]*?\\w\\)\\*\\)\\([ ,.]\\|$\\)")
2381 "Regular expression for bold emphasis.")
2382 (defconst org-italic-re
2383 (if (featurep 'xemacs)
2384 "\\([ ]\\|^\\)\\(/\\(\\w[a-zA-Z0-9-_ ]*?\\w\\)/\\)\\([ ,.]\\|$\\)"
2385 "\\([ ]\\|^\\)\\(/\\(\\w[[:word:] -_]*?\\w\\)/\\)\\([ ,.]\\|$\\)")
2386 "Regular expression for italic emphasis.")
2387 (defconst org-underline-re
2388 (if (featurep 'xemacs)
2389 "\\([ ]\\|^\\)\\(_\\(\\w[a-zA-Z0-9-_ ]*?\\w\\)_\\)\\([ ,.]\\|$\\)"
2390 "\\([ ]\\|^\\)\\(_\\(\\w[[:word:] -_]*?\\w\\)_\\)\\([ ,.]\\|$\\)")
2391 "Regular expression for underline emphasis.")
2393 ;; Variables for pre-computed regular expressions, all buffer local
2394 (defvar org-done-string nil
2395 "The last string in `org-todo-keywords', indicating an item is DONE.")
2396 (make-variable-buffer-local 'org-done-string)
2397 (defvar org-todo-regexp nil
2398 "Matches any of the TODO state keywords.")
2399 (make-variable-buffer-local 'org-todo-regexp)
2400 (defvar org-not-done-regexp nil
2401 "Matches any of the TODO state keywords except the last one.")
2402 (make-variable-buffer-local 'org-not-done-regexp)
2403 (defvar org-todo-line-regexp nil
2404 "Matches a headline and puts TODO state into group 2 if present.")
2405 (make-variable-buffer-local 'org-todo-line-regexp)
2406 (defvar org-todo-line-tags-regexp nil
2407 "Matches a headline and puts TODO state into group 2 if present.
2408 Also put tags into group 4 if tags are present.")
2409 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2410 (defvar org-nl-done-regexp nil
2411 "Matches newline followed by a headline with the DONE keyword.")
2412 (make-variable-buffer-local 'org-nl-done-regexp)
2413 (defvar org-looking-at-done-regexp nil
2414 "Matches the DONE keyword a point.")
2415 (make-variable-buffer-local 'org-looking-at-done-regexp)
2416 (defvar org-todo-kwd-priority-p nil
2417 "Do TODO items have priorities?")
2418 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2419 (defvar org-todo-kwd-max-priority nil
2420 "Maximum priority of TODO items.")
2421 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2422 (defvar org-ds-keyword-length 12
2423 "Maximum length of the Deadline and SCHEDULED keywords.")
2424 (make-variable-buffer-local 'org-ds-keyword-length)
2425 (defvar org-deadline-regexp nil
2426 "Matches the DEADLINE keyword.")
2427 (make-variable-buffer-local 'org-deadline-regexp)
2428 (defvar org-deadline-time-regexp nil
2429 "Matches the DEADLINE keyword together with a time stamp.")
2430 (make-variable-buffer-local 'org-deadline-time-regexp)
2431 (defvar org-deadline-line-regexp nil
2432 "Matches the DEADLINE keyword and the rest of the line.")
2433 (make-variable-buffer-local 'org-deadline-line-regexp)
2434 (defvar org-scheduled-regexp nil
2435 "Matches the SCHEDULED keyword.")
2436 (make-variable-buffer-local 'org-scheduled-regexp)
2437 (defvar org-scheduled-time-regexp nil
2438 "Matches the SCHEDULED keyword together with a time stamp.")
2439 (make-variable-buffer-local 'org-scheduled-time-regexp)
2440 (defvar org-closed-time-regexp nil
2441 "Matches the CLOSED keyword together with a time stamp.")
2442 (make-variable-buffer-local 'org-closed-time-regexp)
2444 (defvar org-keyword-time-regexp nil
2445 "Matches any of the 3 keywords, together with the time stamp.")
2446 (make-variable-buffer-local 'org-keyword-time-regexp)
2447 (defvar org-maybe-keyword-time-regexp nil
2448 "Matches a timestamp, possibly preceeded by a keyword.")
2449 (make-variable-buffer-local 'org-keyword-time-regexp)
2451 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2452 mouse-map t)
2453 "Properties to remove when a string without properties is wanted.")
2455 (defsubst org-match-string-no-properties (num &optional string)
2456 (if (featurep 'xemacs)
2457 (let ((s (match-string num string)))
2458 (remove-text-properties 0 (length s) org-rm-props s)
2460 (match-string-no-properties num string)))
2462 (defsubst org-no-properties (s)
2463 (remove-text-properties 0 (length s) org-rm-props s)
2466 (defun org-set-regexps-and-options ()
2467 "Precompute regular expressions for current buffer."
2468 (when (eq major-mode 'org-mode)
2469 (let ((re (org-make-options-regexp
2470 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2471 "STARTUP" "ARCHIVE" "TAGS")))
2472 (splitre "[ \t]+")
2473 kwds int key value cat arch tags)
2474 (save-excursion
2475 (save-restriction
2476 (widen)
2477 (goto-char (point-min))
2478 (while (re-search-forward re nil t)
2479 (setq key (match-string 1) value (org-match-string-no-properties 2))
2480 (cond
2481 ((equal key "CATEGORY")
2482 (if (string-match "[ \t]+$" value)
2483 (setq value (replace-match "" t t value)))
2484 (setq cat (intern value)))
2485 ((equal key "SEQ_TODO")
2486 (setq int 'sequence
2487 kwds (append kwds (org-split-string value splitre))))
2488 ((equal key "PRI_TODO")
2489 (setq int 'priority
2490 kwds (append kwds (org-split-string value splitre))))
2491 ((equal key "TYP_TODO")
2492 (setq int 'type
2493 kwds (append kwds (org-split-string value splitre))))
2494 ((equal key "TAGS")
2495 (setq tags (append tags (org-split-string value splitre))))
2496 ((equal key "STARTUP")
2497 (let ((opts (org-split-string value splitre))
2498 (set '(("fold" org-startup-folded t)
2499 ("overview" org-startup-folded t)
2500 ("nofold" org-startup-folded nil)
2501 ("showall" org-startup-folded nil)
2502 ("content" org-startup-folded content)
2503 ("hidestars" org-hide-leading-stars t)
2504 ("showstars" org-hide-leading-stars nil)
2505 ("odd" org-odd-levels-only t)
2506 ("oddeven" org-odd-levels-only nil)
2507 ("align" org-startup-align-all-tables t)
2508 ("noalign" org-startup-align-all-tables nil)
2509 ("logging" org-log-done t)
2510 ("nologging" org-log-done nil)
2511 ("dlcheck" org-startup-with-deadline-check t)
2512 ("nodlcheck" org-startup-with-deadline-check nil)))
2513 l var val)
2514 (while (setq l (assoc (pop opts) set))
2515 (setq var (nth 1 l) val (nth 2 l))
2516 (set (make-local-variable var) val))))
2517 ((equal key "ARCHIVE")
2518 (string-match " *$" value)
2519 (setq arch (replace-match "" t t value))
2520 (remove-text-properties 0 (length arch)
2521 '(face t fontified t) arch)))
2523 (and cat (set (make-local-variable 'org-category) cat))
2524 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
2525 (and arch (set (make-local-variable 'org-archive-location) arch))
2526 (and int (set (make-local-variable 'org-todo-interpretation) int))
2527 (when tags
2528 (let (e tg c tgs)
2529 (while (setq e (pop tags))
2530 (cond
2531 ((equal e "{") (push '(:startgroup) tgs))
2532 ((equal e "}") (push '(:endgroup) tgs))
2533 ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
2534 (push (cons (match-string 1 e)
2535 (string-to-char (match-string 2 e)))
2536 tgs))
2537 (t (push (list e) tgs))))
2538 (set (make-local-variable 'org-tag-alist) nil)
2539 (while (setq e (pop tgs))
2540 (or (and (stringp (car e))
2541 (assoc (car e) org-tag-alist))
2542 (push e org-tag-alist))))))
2544 ;; Compute the regular expressions and other local variables
2545 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2546 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2547 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2548 (length org-scheduled-string)))
2549 org-done-string
2550 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2551 org-todo-regexp
2552 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2553 "\\|") "\\)\\>")
2554 org-not-done-regexp
2555 (concat "\\<\\("
2556 (mapconcat 'regexp-quote
2557 (nreverse (cdr (reverse org-todo-keywords)))
2558 "\\|")
2559 "\\)\\>")
2560 org-todo-line-regexp
2561 (concat "^\\(\\*+\\)[ \t]*\\("
2562 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2563 "\\)? *\\(.*\\)")
2564 org-nl-done-regexp
2565 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2566 org-todo-line-tags-regexp
2567 (concat "^\\(\\*+\\)[ \t]*\\("
2568 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2569 "\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
2570 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2571 org-deadline-regexp (concat "\\<" org-deadline-string)
2572 org-deadline-time-regexp
2573 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2574 org-deadline-line-regexp
2575 (concat "\\<\\(" org-deadline-string "\\).*")
2576 org-scheduled-regexp
2577 (concat "\\<" org-scheduled-string)
2578 org-scheduled-time-regexp
2579 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2580 org-closed-time-regexp
2581 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2582 org-keyword-time-regexp
2583 (concat "\\<\\(" org-scheduled-string
2584 "\\|" org-deadline-string
2585 "\\|" org-closed-string "\\)"
2586 " *[[<]\\([^]>]+\\)[]>]")
2587 org-maybe-keyword-time-regexp
2588 (concat "\\(\\<\\(" org-scheduled-string
2589 "\\|" org-deadline-string
2590 "\\|" org-closed-string "\\)\\)?"
2591 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
2593 (org-set-font-lock-defaults)))
2595 ;; Tell the compiler about dynamically scoped variables,
2596 ;; and variables from other packages
2597 (defvar calc-embedded-close-formula) ; defined by the calc package
2598 (defvar calc-embedded-open-formula) ; defined by the calc package
2599 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
2600 (defvar zmacs-regions) ; XEmacs regions
2601 (defvar original-date) ; dynamically scoped in calendar
2602 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
2603 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
2604 (defvar org-html-entities) ; defined later in this file
2605 (defvar org-goto-start-pos) ; dynamically scoped parameter
2606 (defvar org-time-was-given) ; dynamically scoped parameter
2607 (defvar org-ts-what) ; dynamically scoped parameter
2608 (defvar mark-active) ; Emacs only, not available in XEmacs.
2609 (defvar timecnt) ; dynamically scoped parameter
2610 (defvar levels-open) ; dynamically scoped parameter
2611 (defvar entry) ; dynamically scoped parameter
2612 (defvar date) ; dynamically scoped parameter
2613 (defvar description) ; dynamically scoped parameter
2614 (defvar ans1) ; dynamically scoped parameter
2615 (defvar ans2) ; dynamically scoped parameter
2616 (defvar starting-day) ; local variable
2617 (defvar include-all-loc) ; local variable
2618 (defvar vm-message-pointer) ; from vm
2619 (defvar vm-folder-directory) ; from vm
2620 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
2621 (defvar wl-summary-buffer-folder-name) ; from wanderlust
2622 (defvar gnus-group-name) ; from gnus
2623 (defvar gnus-article-current) ; from gnus
2624 (defvar w3m-current-url) ; from w3m
2625 (defvar mh-progs) ; from MH-E
2626 (defvar mh-current-folder) ; from MH-E
2627 (defvar mh-show-folder-buffer) ; from MH-E
2628 (defvar mh-index-folder) ; from MH-E
2629 (defvar mh-searcher) ; from MH-E
2630 (defvar org-selected-point) ; dynamically scoped parameter
2631 (defvar calendar-mode-map) ; from calendar.el
2632 (defvar last-arg) ; local variable
2633 (defvar remember-save-after-remembering) ; from remember.el
2634 (defvar remember-data-file) ; from remember.el
2635 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
2636 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
2637 (defvar orgtbl-mode) ; defined later in this file
2638 (defvar Info-current-file) ; from info.el
2639 (defvar Info-current-node) ; from info.el
2641 ;;; Define the mode
2643 (defvar org-mode-map
2644 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2645 (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.")
2646 (copy-keymap outline-mode-map))
2647 "Keymap for Org-mode.")
2649 (defvar org-struct-menu) ; defined later in this file
2650 (defvar org-org-menu) ; defined later in this file
2651 (defvar org-tbl-menu) ; defined later in this file
2653 ;; We use a before-change function to check if a table might need
2654 ;; an update.
2655 (defvar org-table-may-need-update t
2656 "Indicates that a table might need an update.
2657 This variable is set by `org-before-change-function'.
2658 `org-table-align' sets it back to nil.")
2659 (defvar org-mode-hook nil)
2660 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2661 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2664 ;;;###autoload
2665 (define-derived-mode org-mode outline-mode "Org"
2666 "Outline-based notes management and organizer, alias
2667 \"Carsten's outline-mode for keeping track of everything.\"
2669 Org-mode develops organizational tasks around a NOTES file which
2670 contains information about projects as plain text. Org-mode is
2671 implemented on top of outline-mode, which is ideal to keep the content
2672 of large files well structured. It supports ToDo items, deadlines and
2673 time stamps, which magically appear in the diary listing of the Emacs
2674 calendar. Tables are easily created with a built-in table editor.
2675 Plain text URL-like links connect to websites, emails (VM), Usenet
2676 messages (Gnus), BBDB entries, and any files related to the project.
2677 For printing and sharing of notes, an Org-mode file (or a part of it)
2678 can be exported as a structured ASCII or HTML file.
2680 The following commands are available:
2682 \\{org-mode-map}"
2684 ;; Get rid of Outline menus, they are not needed
2685 ;; Need to do this here because define-derived-mode sets up
2686 ;; the keymap so late.
2687 (if (featurep 'xemacs)
2688 (if org-noutline-p
2689 (progn
2690 (easy-menu-remove outline-mode-menu-heading)
2691 (easy-menu-remove outline-mode-menu-show)
2692 (easy-menu-remove outline-mode-menu-hide))
2693 (delete-menu-item '("Headings"))
2694 (delete-menu-item '("Show"))
2695 (delete-menu-item '("Hide"))
2696 (set-menubar-dirty-flag))
2697 (define-key org-mode-map [menu-bar headings] 'undefined)
2698 (define-key org-mode-map [menu-bar hide] 'undefined)
2699 (define-key org-mode-map [menu-bar show] 'undefined))
2701 (easy-menu-add org-org-menu)
2702 (easy-menu-add org-tbl-menu)
2703 (org-install-agenda-files-menu)
2704 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
2705 (org-add-to-invisibility-spec '(org-cwidth))
2706 (when (featurep 'xemacs)
2707 (set (make-local-variable 'line-move-ignore-invisible) t))
2708 (setq outline-regexp "\\*+")
2709 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2710 (setq outline-level 'org-outline-level)
2711 (when (and org-ellipsis (stringp org-ellipsis))
2712 (unless org-display-table
2713 (setq org-display-table (make-display-table)))
2714 (set-display-table-slot org-display-table
2715 4 (string-to-vector org-ellipsis))
2716 (setq buffer-display-table org-display-table))
2717 (org-set-regexps-and-options)
2718 (if org-startup-truncated (setq truncate-lines t))
2719 (set (make-local-variable 'font-lock-unfontify-region-function)
2720 'org-unfontify-region)
2721 ;; Activate before-change-function
2722 (set (make-local-variable 'org-table-may-need-update) t)
2723 (org-add-hook 'before-change-functions 'org-before-change-function nil
2724 'local)
2725 ;; Paragraphs and auto-filling
2726 (org-set-autofill-regexps)
2727 (org-update-radio-target-regexp)
2728 ;; Settings for Calc embedded mode
2729 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2730 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2731 (if (and org-insert-mode-line-in-empty-file
2732 (interactive-p)
2733 (= (point-min) (point-max)))
2734 (insert " -*- mode: org -*-\n\n"))
2736 (unless org-inhibit-startup
2737 (if org-startup-align-all-tables
2738 (org-table-map-tables 'org-table-align))
2739 (if org-startup-with-deadline-check
2740 (call-interactively 'org-check-deadlines)
2741 (cond
2742 ((eq org-startup-folded t)
2743 (org-cycle '(4)))
2744 ((eq org-startup-folded 'content)
2745 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2746 (org-cycle '(4)) (org-cycle '(4))))))))
2748 (defsubst org-call-with-arg (command arg)
2749 "Call COMMAND interactively, but pretend prefix are was ARG."
2750 (let ((current-prefix-arg arg)) (call-interactively command)))
2752 (defsubst org-current-line (&optional pos)
2753 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2755 (defun org-current-time ()
2756 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
2757 (if (> org-time-stamp-rounding-minutes 0)
2758 (let ((r org-time-stamp-rounding-minutes)
2759 (time (decode-time)))
2760 (apply 'encode-time
2761 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
2762 (nthcdr 2 time))))
2763 (current-time)))
2765 (defun org-add-props (string plist &rest props)
2766 "Add text properties to entire string, from beginning to end.
2767 PLIST may be a list of properties, PROPS are individual properties and values
2768 that will be added to PLIST. Returns the string that was modified."
2769 (add-text-properties
2770 0 (length string) (if props (append plist props) plist) string)
2771 string)
2772 (put 'org-add-props 'lisp-indent-function 2)
2775 ;;; Font-Lock stuff
2777 (defvar org-mouse-map (make-sparse-keymap))
2778 (define-key org-mouse-map
2779 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
2780 (define-key org-mouse-map
2781 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
2782 (when org-mouse-1-follows-link
2783 (define-key org-mouse-map [follow-link] 'mouse-face))
2784 (when org-tab-follows-link
2785 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2786 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2787 (when org-return-follows-link
2788 (define-key org-mouse-map [(return)] 'org-open-at-point)
2789 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2791 (require 'font-lock)
2793 (defconst org-non-link-chars "]\t\n\r<>")
2794 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
2795 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
2796 (defconst org-link-re-with-space
2797 (concat
2798 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2799 "\\([^" org-non-link-chars " ]"
2800 "[^" org-non-link-chars "]*"
2801 "[^" org-non-link-chars " ]\\)>?")
2802 "Matches a link with spaces, optional angular brackets around it.")
2804 (defconst org-link-re-with-space2
2805 (concat
2806 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2807 "\\([^" org-non-link-chars " ]"
2808 "[^]\t\n\r]*"
2809 "[^" org-non-link-chars " ]\\)>?")
2810 "Matches a link with spaces, optional angular brackets around it.")
2812 (defconst org-angle-link-re
2813 (concat
2814 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2815 "\\([^" org-non-link-chars " ]"
2816 "[^" org-non-link-chars "]*"
2817 "\\)>")
2818 "Matches link with angular brackets, spaces are allowed.")
2819 (defconst org-plain-link-re
2820 (concat
2821 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2822 "\\([^]\t\n\r<>,;() ]+\\)")
2823 "Matches plain link, without spaces.")
2825 (defconst org-bracket-link-regexp
2826 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
2827 "Matches a link in double brackets.")
2829 (defconst org-bracket-link-analytic-regexp
2830 (concat
2831 "\\[\\["
2832 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
2833 "\\([^]]+\\)"
2834 "\\]"
2835 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
2836 "\\]"))
2837 ; 1: http:
2838 ; 2: http
2839 ; 3: path
2840 ; 4: [desc]
2841 ; 5: desc
2844 (defconst org-ts-lengths
2845 (cons (length (format-time-string (car org-time-stamp-formats)))
2846 (length (format-time-string (cdr org-time-stamp-formats))))
2847 "This holds the lengths of the two different time formats.")
2848 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2849 "Regular expression for fast time stamp matching.")
2850 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2851 "Regular expression for fast time stamp matching.")
2852 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2853 "Regular expression matching time strings for analysis.")
2854 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2855 "Regular expression matching time stamps, with groups.")
2856 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2857 "Regular expression matching a time stamp range.")
2858 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2859 org-ts-regexp "\\)?")
2860 "Regular expression matching a time stamp or time stamp range.")
2862 (defun org-activate-plain-links (limit)
2863 "Run through the buffer and add overlays to links."
2864 (if (re-search-forward org-plain-link-re limit t)
2865 (progn
2866 (add-text-properties (match-beginning 0) (match-end 0)
2867 (list 'mouse-face 'highlight
2868 'keymap org-mouse-map
2870 t)))
2872 (defun org-activate-angle-links (limit)
2873 "Run through the buffer and add overlays to links."
2874 (if (re-search-forward org-angle-link-re limit t)
2875 (progn
2876 (add-text-properties (match-beginning 0) (match-end 0)
2877 (list 'mouse-face 'highlight
2878 'keymap org-mouse-map
2880 t)))
2882 (defun org-activate-bracket-links (limit)
2883 "Run through the buffer and add overlays to bracketed links."
2884 (if (re-search-forward org-bracket-link-regexp limit t)
2885 (let* ((help (concat "LINK: "
2886 (org-match-string-no-properties 1)))
2887 ;; FIXME: above we should remove the escapes.
2888 ;; but that requires another match, protecting match data,
2889 ;; a lot of overhead for font-lock.
2890 (ip (list 'invisible 'org-link 'intangible t 'rear-nonsticky t
2891 'keymap org-mouse-map 'mouse-face 'highlight
2892 'help-echo help))
2893 (vp (list 'rear-nonsticky t
2894 'keymap org-mouse-map 'mouse-face 'highlight
2895 'help-echo help)))
2896 ;; We need to remove the invisible property here. Table narrowing
2897 ;; may have made some of this invisible.
2898 (remove-text-properties (match-beginning 0) (match-end 0)
2899 '(invisible nil))
2900 (if (match-end 3)
2901 (progn
2902 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
2903 (add-text-properties (match-beginning 3) (match-end 3) vp)
2904 (add-text-properties (match-end 3) (match-end 0) ip))
2905 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
2906 (add-text-properties (match-beginning 1) (match-end 1) vp)
2907 (add-text-properties (match-end 1) (match-end 0) ip))
2908 t)))
2910 (defun org-activate-dates (limit)
2911 "Run through the buffer and add overlays to dates."
2912 (if (re-search-forward org-tsr-regexp limit t)
2913 (progn
2914 (add-text-properties (match-beginning 0) (match-end 0)
2915 (list 'mouse-face 'highlight
2916 'keymap org-mouse-map))
2917 t)))
2919 (defvar org-target-link-regexp nil
2920 "Regular expression matching radio targets in plain text.")
2921 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
2922 "Regular expression matching a link target.")
2923 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
2924 "Regular expression matching a link target.")
2926 (defun org-activate-target-links (limit)
2927 "Run through the buffer and add overlays to target matches."
2928 (when org-target-link-regexp
2929 (let ((case-fold-search t))
2930 (if (re-search-forward org-target-link-regexp limit t)
2931 (progn
2932 (add-text-properties (match-beginning 0) (match-end 0)
2933 (list 'mouse-face 'highlight
2934 'keymap org-mouse-map
2935 'help-echo "Radio target link"
2936 'org-linked-text t))
2937 t)))))
2939 (defun org-update-radio-target-regexp ()
2940 "Find all radio targets in this file and update the regular expression."
2941 (interactive)
2942 (when (memq 'radio org-activate-links)
2943 (setq org-target-link-regexp
2944 (org-make-target-link-regexp (org-all-targets 'radio)))
2945 (org-restart-font-lock)))
2947 (defun org-hide-wide-columns (limit)
2948 (let (s e)
2949 (setq s (text-property-any (point) (or limit (point-max))
2950 'org-cwidth t))
2951 (when s
2952 (setq e (next-single-property-change s 'org-cwidth))
2953 (add-text-properties s e '(invisible org-cwidth intangible t))
2954 (goto-char e)
2955 t)))
2957 (defun org-restart-font-lock ()
2958 "Restart font-lock-mode, to force refontification."
2959 (when (and (boundp 'font-lock-mode) font-lock-mode)
2960 (font-lock-mode -1)
2961 (font-lock-mode 1)))
2963 (defun org-all-targets (&optional radio)
2964 "Return a list of all targets in this file.
2965 With optional argument RADIO, only find radio targets."
2966 (let ((re (if radio org-radio-target-regexp org-target-regexp))
2967 rtn)
2968 (save-excursion
2969 (goto-char (point-min))
2970 (while (re-search-forward re nil t)
2971 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
2972 rtn)))
2974 (defun org-make-target-link-regexp (targets)
2975 "Make regular expression matching all strings in TARGETS.
2976 The regular expression finds the targets also if there is a line break
2977 between words."
2978 (and targets
2979 (concat
2980 "\\<\\("
2981 (mapconcat
2982 (lambda (x)
2983 (while (string-match " +" x)
2984 (setq x (replace-match "\\s-+" t t x)))
2986 targets
2987 "\\|")
2988 "\\)\\>")))
2990 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2991 "Matches CamelCase words, possibly with a star before it.")
2993 (defun org-activate-camels (limit)
2994 "Run through the buffer and add overlays to dates."
2995 (if (re-search-forward org-camel-regexp limit t)
2996 (progn
2997 (add-text-properties (match-beginning 0) (match-end 0)
2998 (list 'mouse-face 'highlight
2999 'keymap org-mouse-map))
3000 t)))
3002 (defun org-activate-tags (limit)
3003 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3004 (progn
3005 (add-text-properties (match-beginning 1) (match-end 1)
3006 (list 'mouse-face 'highlight
3007 'keymap org-mouse-map))
3008 t)))
3010 (defun org-font-lock-level ()
3011 (save-excursion
3012 (org-back-to-heading t)
3013 (- (match-end 0) (match-beginning 0))))
3015 (defun org-outline-level ()
3016 (save-excursion
3017 (looking-at outline-regexp)
3018 (if (match-beginning 1)
3019 (+ (org-get-string-indentation (match-string 1)) 1000)
3020 (- (match-end 0) (match-beginning 0)))))
3022 (defvar org-font-lock-keywords nil)
3024 (defun org-set-font-lock-defaults ()
3025 (let* ((em org-fontify-emphasized-text)
3026 (lk org-activate-links)
3027 (org-font-lock-extra-keywords
3028 ;; Headlines
3029 (list
3030 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3031 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3032 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3033 (1 'org-table))
3034 ;; Links
3035 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3036 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3037 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3038 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3039 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3040 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
3041 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3042 (if org-table-limit-column-width
3043 '(org-hide-wide-columns (0 nil append)))
3044 ;; TODO lines
3045 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3046 '(1 'org-todo t))
3047 ;; Priorities
3048 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3049 ;; Special keywords
3050 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3051 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3052 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3053 ;; Emphasis
3054 (if em (list org-bold-re 2 ''bold 'prepend))
3055 (if em (list org-italic-re 2 ''italic 'prepend))
3056 (if em (list org-underline-re 2 ''underline 'prepend))
3057 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
3058 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
3059 2 'bold prepend)
3060 ;; COMMENT
3061 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
3062 "\\|" org-quote-string "\\)\\>")
3063 '(1 'org-special-keyword t))
3064 '("^#.*" (0 'font-lock-comment-face t))
3065 ;; DONE
3066 (if org-fontify-done-headline
3067 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
3068 '(1 'org-done t) '(2 'org-headline-done t))
3069 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
3070 '(1 'org-done t)))
3071 ;; Table stuff
3072 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
3073 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3074 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
3075 (if org-format-transports-properties-p
3076 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3078 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3079 ;; Now set the full font-lock-keywords
3080 (set (make-local-variable 'org-font-lock-keywords)
3081 org-font-lock-extra-keywords)
3082 (set (make-local-variable 'font-lock-defaults)
3083 '(org-font-lock-keywords t nil nil backward-paragraph))
3084 (kill-local-variable 'font-lock-keywords) nil))
3086 (defvar org-m nil)
3087 (defvar org-l nil)
3088 (defvar org-f nil)
3089 (defun org-get-level-face (n)
3090 "Get the right face for match N in font-lock matching of healdines."
3091 (setq org-l (- (match-end 2) (match-beginning 1)))
3092 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3093 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
3094 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
3095 (cond
3096 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3097 ((eq n 2) org-f)
3098 (t (if org-level-color-stars-only nil org-f))))
3100 (defun org-unfontify-region (beg end &optional maybe_loudly)
3101 "Remove fontification and activation overlays from links."
3102 (font-lock-default-unfontify-region beg end)
3103 (let* ((buffer-undo-list t)
3104 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3105 (inhibit-modification-hooks t)
3106 deactivate-mark buffer-file-name buffer-file-truename)
3107 (remove-text-properties beg end
3108 '(mouse-face nil keymap nil org-linked-text nil
3109 invisible nil intangible nil))))
3110 ;;; Visibility cycling
3112 (defvar org-cycle-global-status nil)
3113 (make-variable-buffer-local 'org-cycle-global-status)
3114 (defvar org-cycle-subtree-status nil)
3115 (make-variable-buffer-local 'org-cycle-subtree-status)
3117 ;;;###autoload
3118 (defun org-cycle (&optional arg)
3119 "Visibility cycling for Org-mode.
3121 - When this function is called with a prefix argument, rotate the entire
3122 buffer through 3 states (global cycling)
3123 1. OVERVIEW: Show only top-level headlines.
3124 2. CONTENTS: Show all headlines of all levels, but no body text.
3125 3. SHOW ALL: Show everything.
3127 - When point is at the beginning of a headline, rotate the subtree started
3128 by this line through 3 different states (local cycling)
3129 1. FOLDED: Only the main headline is shown.
3130 2. CHILDREN: The main headline and the direct children are shown.
3131 From this state, you can move to one of the children
3132 and zoom in further.
3133 3. SUBTREE: Show the entire subtree, including body text.
3135 - When there is a numeric prefix, go up to a heading with level ARG, do
3136 a `show-subtree' and return to the previous cursor position. If ARG
3137 is negative, go up that many levels.
3139 - When point is not at the beginning of a headline, execute
3140 `indent-relative', like TAB normally does. See the option
3141 `org-cycle-emulate-tab' for details.
3143 - Special case: if point is the the beginning of the buffer and there is
3144 no headline in line 1, this function will act as if called with prefix arg."
3145 (interactive "P")
3147 (let* ((outline-regexp
3148 (if org-cycle-include-plain-lists
3149 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
3150 outline-regexp))
3151 (bob-special (and org-cycle-global-at-bob (bobp)
3152 (not (looking-at outline-regexp))))
3153 (org-cycle-hook (if bob-special nil org-cycle-hook))
3154 (pos (point)))
3156 (if (or bob-special (equal arg '(4)))
3157 ;; special case: use global cycling
3158 (setq arg t))
3160 (cond
3162 ((org-at-table-p 'any)
3163 ;; Enter the table or move to the next field in the table
3164 (or (org-table-recognize-table.el)
3165 (progn
3166 (if arg (org-table-edit-field t)
3167 (org-table-justify-field-maybe)
3168 (call-interactively 'org-table-next-field)))))
3170 ((eq arg t) ;; Global cycling
3172 (cond
3173 ((and (eq last-command this-command)
3174 (eq org-cycle-global-status 'overview))
3175 ;; We just created the overview - now do table of contents
3176 ;; This can be slow in very large buffers, so indicate action
3177 (message "CONTENTS...")
3178 (org-content)
3179 (message "CONTENTS...done")
3180 (setq org-cycle-global-status 'contents)
3181 (run-hook-with-args 'org-cycle-hook 'contents))
3183 ((and (eq last-command this-command)
3184 (eq org-cycle-global-status 'contents))
3185 ;; We just showed the table of contents - now show everything
3186 (show-all)
3187 (message "SHOW ALL")
3188 (setq org-cycle-global-status 'all)
3189 (run-hook-with-args 'org-cycle-hook 'all))
3192 ;; Default action: go to overview
3193 (org-overview)
3194 (message "OVERVIEW")
3195 (setq org-cycle-global-status 'overview)
3196 (run-hook-with-args 'org-cycle-hook 'overview))))
3198 ((integerp arg)
3199 ;; Show-subtree, ARG levels up from here.
3200 (save-excursion
3201 (org-back-to-heading)
3202 (outline-up-heading (if (< arg 0) (- arg)
3203 (- (funcall outline-level) arg)))
3204 (org-show-subtree)))
3206 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3207 ;; At a heading: rotate between three different views
3208 (org-back-to-heading)
3209 (let ((goal-column 0) eoh eol eos)
3210 ;; First, some boundaries
3211 (save-excursion
3212 (org-back-to-heading)
3213 (save-excursion
3214 (beginning-of-line 2)
3215 (while (and (not (eobp)) ;; this is like `next-line'
3216 (get-char-property (1- (point)) 'invisible))
3217 (beginning-of-line 2)) (setq eol (point)))
3218 (outline-end-of-heading) (setq eoh (point))
3219 (org-end-of-subtree t) (setq eos (point))
3220 (outline-next-heading))
3221 ;; Find out what to do next and set `this-command'
3222 (cond
3223 ((and (= eos eoh)
3224 ;; Nothing is hidden behind this heading
3225 (message "EMPTY ENTRY")
3226 (setq org-cycle-subtree-status nil)))
3227 ((>= eol eos)
3228 ;; Entire subtree is hidden in one line: open it
3229 (org-show-entry)
3230 (show-children)
3231 (message "CHILDREN")
3232 (setq org-cycle-subtree-status 'children)
3233 (run-hook-with-args 'org-cycle-hook 'children))
3234 ((and (eq last-command this-command)
3235 (eq org-cycle-subtree-status 'children))
3236 ;; We just showed the children, now show everything.
3237 (org-show-subtree)
3238 (message "SUBTREE")
3239 (setq org-cycle-subtree-status 'subtree)
3240 (run-hook-with-args 'org-cycle-hook 'subtree))
3242 ;; Default action: hide the subtree.
3243 (hide-subtree)
3244 (message "FOLDED")
3245 (setq org-cycle-subtree-status 'folded)
3246 (run-hook-with-args 'org-cycle-hook 'folded)))))
3248 ;; TAB emulation
3249 (buffer-read-only (org-back-to-heading))
3250 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3251 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3252 (or (and (eq org-cycle-emulate-tab 'white)
3253 (= (match-end 0) (point-at-eol)))
3254 (and (eq org-cycle-emulate-tab 'whitestart)
3255 (>= (match-end 0) pos))))
3257 (eq org-cycle-emulate-tab t))
3258 (if (and (looking-at "[ \n\r\t]")
3259 (string-match "^[ \t]*$" (buffer-substring
3260 (point-at-bol) (point))))
3261 (progn
3262 (beginning-of-line 1)
3263 (and (looking-at "[ \t]+") (replace-match ""))))
3264 (indent-relative))
3266 (t (save-excursion
3267 (org-back-to-heading)
3268 (org-cycle))))))
3270 ;;;###autoload
3271 (defun org-global-cycle ()
3272 "Cycle the global visibility. For details see `org-cycle'."
3273 (interactive)
3274 (org-cycle '(4)))
3276 (defun org-overview ()
3277 "Switch to overview mode, shoing only top-level headlines.
3278 Really, this shows all headlines with level equal or greater than the level
3279 of the first headline in the buffer. This is important, because if the
3280 first headline is not level one, then (hide-sublevels 1) gives confusing
3281 results."
3282 (interactive)
3283 (hide-sublevels (save-excursion
3284 (goto-char (point-min))
3285 (if (re-search-forward (concat "^" outline-regexp) nil t)
3286 (progn
3287 (goto-char (match-beginning 0))
3288 (funcall outline-level))
3289 1))))
3291 ;; FIXME: allow an argument to give a limiting level for this.
3292 (defun org-content ()
3293 "Show all headlines in the buffer, like a table of contents"
3294 (interactive)
3295 (save-excursion
3296 ;; Visit all headings and show their offspring
3297 (goto-char (point-max))
3298 (catch 'exit
3299 (while (and (progn (condition-case nil
3300 (outline-previous-visible-heading 1)
3301 (error (goto-char (point-min))))
3303 (looking-at outline-regexp))
3304 (show-branches)
3305 (if (bobp) (throw 'exit nil))))))
3308 (defun org-optimize-window-after-visibility-change (state)
3309 "Adjust the window after a change in outline visibility.
3310 This function is the default value of the hook `org-cycle-hook'."
3311 (when (get-buffer-window (current-buffer))
3312 (cond
3313 ((eq state 'overview) (org-first-headline-recenter 1))
3314 ((eq state 'content) nil)
3315 ((eq state 'all) nil)
3316 ((eq state 'folded) nil)
3317 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3318 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3320 (defun org-subtree-end-visible-p ()
3321 "Is the end of the current subtree visible?"
3322 (pos-visible-in-window-p
3323 (save-excursion (org-end-of-subtree t) (point))))
3325 (defun org-first-headline-recenter (&optional N)
3326 "Move cursor to the first headline and recenter the headline.
3327 Optional argument N means, put the headline into the Nth line of the window."
3328 (goto-char (point-min))
3329 (when (re-search-forward (concat "^" outline-regexp) nil t)
3330 (beginning-of-line)
3331 (recenter (prefix-numeric-value N))))
3333 (defvar org-goto-window-configuration nil)
3334 (defvar org-goto-marker nil)
3335 (defvar org-goto-map (make-sparse-keymap))
3336 (let ((cmds '(isearch-forward isearch-backward)) cmd)
3337 (while (setq cmd (pop cmds))
3338 (substitute-key-definition cmd cmd org-goto-map global-map)))
3339 (define-key org-goto-map "\C-m" 'org-goto-ret)
3340 (define-key org-goto-map [(left)] 'org-goto-left)
3341 (define-key org-goto-map [(right)] 'org-goto-right)
3342 (define-key org-goto-map [(?q)] 'org-goto-quit)
3343 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
3344 (define-key org-goto-map "\C-i" 'org-cycle)
3345 (define-key org-goto-map [(tab)] 'org-cycle)
3346 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
3347 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
3348 (define-key org-goto-map "n" 'outline-next-visible-heading)
3349 (define-key org-goto-map "p" 'outline-previous-visible-heading)
3350 (define-key org-goto-map "f" 'outline-forward-same-level)
3351 (define-key org-goto-map "b" 'outline-backward-same-level)
3352 (define-key org-goto-map "u" 'outline-up-heading)
3353 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
3354 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
3355 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
3356 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
3357 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
3358 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3359 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
3361 (defconst org-goto-help
3362 "Select a location to jump to, press RET
3363 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
3365 (defun org-goto ()
3366 "Go to a different location of the document, keeping current visibility.
3368 When you want to go to a different location in a document, the fastest way
3369 is often to fold the entire buffer and then dive into the tree. This
3370 method has the disadvantage, that the previous location will be folded,
3371 which may not be what you want.
3373 This command works around this by showing a copy of the current buffer in
3374 overview mode. You can dive into the tree in that copy, to find the
3375 location you want to reach. When pressing RET, the command returns to the
3376 original buffer in which the visibility is still unchanged. It then jumps
3377 to the new location, making it and the headline hierarchy above it visible."
3378 (interactive)
3379 (let* ((org-goto-start-pos (point))
3380 (selected-point
3381 (org-get-location (current-buffer) org-goto-help)))
3382 (if selected-point
3383 (progn
3384 (org-mark-ring-push org-goto-start-pos)
3385 (goto-char selected-point)
3386 (if (or (org-invisible-p) (org-invisible-p2))
3387 (org-show-hierarchy-above)))
3388 (error "Quit"))))
3390 (defun org-get-location (buf help)
3391 "Let the user select a location in the Org-mode buffer BUF.
3392 This function uses a recursive edit. It returns the selected position
3393 or nil."
3394 (let (org-selected-point)
3395 (save-excursion
3396 (save-window-excursion
3397 (delete-other-windows)
3398 (switch-to-buffer (get-buffer-create "*org-goto*"))
3399 (with-output-to-temp-buffer "*Help*"
3400 (princ help))
3401 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
3402 (setq buffer-read-only nil)
3403 (erase-buffer)
3404 (insert-buffer-substring buf)
3405 (let ((org-startup-truncated t)
3406 (org-startup-folded t)
3407 (org-startup-align-all-tables nil)
3408 (org-startup-with-deadline-check nil))
3409 (org-mode))
3410 (setq buffer-read-only t)
3411 (if (boundp 'org-goto-start-pos)
3412 (goto-char org-goto-start-pos)
3413 (goto-char (point-min)))
3414 (org-beginning-of-line)
3415 (message "Select location and press RET")
3416 ;; now we make sure that during selection, ony very few keys work
3417 ;; and that it is impossible to switch to another window.
3418 (let ((gm (current-global-map))
3419 (overriding-local-map org-goto-map))
3420 (unwind-protect
3421 (progn
3422 (use-global-map org-goto-map)
3423 (recursive-edit))
3424 (use-global-map gm)))))
3425 (kill-buffer "*org-goto*")
3426 org-selected-point))
3428 (defun org-goto-ret (&optional arg)
3429 "Finish `org-goto' by going to the new location."
3430 (interactive "P")
3431 (setq org-selected-point (point)
3432 current-prefix-arg arg)
3433 (throw 'exit nil))
3435 (defun org-goto-left ()
3436 "Finish `org-goto' by going to the new location."
3437 (interactive)
3438 (if (org-on-heading-p)
3439 (progn
3440 (beginning-of-line 1)
3441 (setq org-selected-point (point)
3442 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3443 (throw 'exit nil))
3444 (error "Not on a heading")))
3446 (defun org-goto-right ()
3447 "Finish `org-goto' by going to the new location."
3448 (interactive)
3449 (if (org-on-heading-p)
3450 (progn
3451 (outline-end-of-subtree)
3452 (or (eobp) (forward-char 1))
3453 (setq org-selected-point (point)
3454 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3455 (throw 'exit nil))
3456 (error "Not on a heading")))
3458 (defun org-goto-quit ()
3459 "Finish `org-goto' without cursor motion."
3460 (interactive)
3461 (setq org-selected-point nil)
3462 (throw 'exit nil))
3464 ;;; Promotion, Demotion, Inserting new headlines
3466 (defvar org-ignore-region nil
3467 "To temporarily disable the active region.")
3469 (defun org-insert-heading (&optional force-heading)
3470 "Insert a new heading or item with same depth at point.
3471 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
3472 If point is at the beginning of a headline, insert a sibling before the
3473 current headline. If point is in the middle of a headline, split the headline
3474 at that position and make the rest of the headline part of the sibling below
3475 the current headline."
3476 (interactive "P")
3477 (if (= (buffer-size) 0)
3478 (insert "\n* ")
3479 (when (or force-heading (not (org-insert-item)))
3480 (let* ((head (save-excursion
3481 (condition-case nil
3482 (progn
3483 (org-back-to-heading)
3484 (match-string 0))
3485 (error "*"))))
3486 pos)
3487 (cond
3488 ((and (org-on-heading-p) (bolp)
3489 (save-excursion (backward-char 1) (not (org-invisible-p))))
3490 (open-line 1))
3491 ((bolp) nil)
3492 (t (newline)))
3493 (insert head) (just-one-space)
3494 (setq pos (point))
3495 (end-of-line 1)
3496 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
3497 (run-hooks 'org-insert-heading-hook)))))
3499 (defun org-insert-item (&optional checkbox)
3500 "Insert a new item at the current level.
3501 Return t when things worked, nil when we are not in an item."
3502 (when (save-excursion
3503 (condition-case nil
3504 (progn
3505 (org-beginning-of-item)
3506 (org-at-item-p)
3508 (error nil)))
3509 (let* ((bul (match-string 0))
3510 (end (match-end 0))
3511 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
3512 (match-end 0)))
3513 (eowcol (save-excursion (goto-char eow) (current-column)))
3514 pos)
3515 (cond
3516 ((and (org-at-item-p) (<= (point) eow))
3517 ;; before the bullet
3518 (beginning-of-line 1)
3519 (open-line 1))
3520 ((<= (point) eow)
3521 (beginning-of-line 1))
3522 (t (newline)))
3523 (insert bul (if checkbox "[ ]" ""))
3524 (just-one-space)
3525 (setq pos (point))
3526 (end-of-line 1)
3527 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
3528 (org-maybe-renumber-ordered-list)
3531 (defun org-insert-todo-heading (arg)
3532 "Insert a new heading with the same level and TODO state as current heading.
3533 If the heading has no TODO state, or if the state is DONE, use the first
3534 state (TODO by default). Also with prefix arg, force first state."
3535 (interactive "P")
3536 (when (not (org-insert-item 'checkbox))
3537 (org-insert-heading)
3538 (save-excursion
3539 (org-back-to-heading)
3540 (if org-noutline-p
3541 (outline-previous-heading)
3542 (outline-previous-visible-heading t))
3543 (looking-at org-todo-line-regexp))
3544 (if (or arg
3545 (not (match-beginning 2))
3546 (equal (match-string 2) org-done-string))
3547 (insert (car org-todo-keywords) " ")
3548 (insert (match-string 2) " "))))
3550 (defun org-promote-subtree ()
3551 "Promote the entire subtree.
3552 See also `org-promote'."
3553 (interactive)
3554 (save-excursion
3555 (org-map-tree 'org-promote)))
3557 (defun org-demote-subtree ()
3558 "Demote the entire subtree. See `org-demote'.
3559 See also `org-promote'."
3560 (interactive)
3561 (save-excursion
3562 (org-map-tree 'org-demote)))
3564 (defun org-do-promote ()
3565 "Promote the current heading higher up the tree.
3566 If the region is active in `transient-mark-mode', promote all headings
3567 in the region."
3568 (interactive)
3569 (save-excursion
3570 (if (org-region-active-p)
3571 (org-map-region 'org-promote (region-beginning) (region-end))
3572 (org-promote)))
3573 (org-fix-position-after-promote))
3575 (defun org-do-demote ()
3576 "Demote the current heading lower down the tree.
3577 If the region is active in `transient-mark-mode', demote all headings
3578 in the region."
3579 (interactive)
3580 (save-excursion
3581 (if (org-region-active-p)
3582 (org-map-region 'org-demote (region-beginning) (region-end))
3583 (org-demote)))
3584 (org-fix-position-after-promote))
3586 (defun org-fix-position-after-promote ()
3587 "Make sure that after pro/demotion cursor position is right."
3588 (and (equal (char-after) ?\ )
3589 (equal (char-before) ?*)
3590 (forward-char 1)))
3592 (defun org-get-legal-level (level change)
3593 "Rectify a level change under the influence of `org-odd-levels-only'
3594 LEVEL is a current level, CHANGE is by how much the level should be
3595 modified. Even if CHANGE is nil, LEVEL may be returned modified because
3596 even level numbers will become the next higher odd number."
3597 (if org-odd-levels-only
3598 (cond ((not change) (1+ (* 2 (/ level 2))))
3599 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
3600 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
3601 (max 1 (+ level change))))
3603 (defun org-promote ()
3604 "Promote the current heading higher up the tree.
3605 If the region is active in `transient-mark-mode', promote all headings
3606 in the region."
3607 (org-back-to-heading t)
3608 (let* ((level (save-match-data (funcall outline-level)))
3609 (up-head (make-string (org-get-legal-level level -1) ?*))
3610 (diff (abs (- level (length up-head)))))
3611 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
3612 (replace-match up-head nil t)
3613 ;; Fixup tag positioning
3614 (and org-auto-align-tags (org-set-tags nil t))
3615 (if org-adapt-indentation
3616 (org-fixup-indentation (if (> diff 1) "^ " "^ ") ""
3617 (if (> diff 1) "^ ? ?\\S-" "^ ?\\S-")))))
3619 (defun org-demote ()
3620 "Demote the current heading lower down the tree.
3621 If the region is active in `transient-mark-mode', demote all headings
3622 in the region."
3623 (org-back-to-heading t)
3624 (let* ((level (save-match-data (funcall outline-level)))
3625 (down-head (make-string (org-get-legal-level level 1) ?*))
3626 (diff (abs (- level (length down-head)))))
3627 (replace-match down-head nil t)
3628 ;; Fixup tag positioning
3629 (and org-auto-align-tags (org-set-tags nil t))
3630 (if org-adapt-indentation
3631 (org-fixup-indentation "^ " (if (> diff 1) " " " ") "^\\S-"))))
3633 (defun org-map-tree (fun)
3634 "Call FUN for every heading underneath the current one."
3635 (org-back-to-heading)
3636 (let ((level (funcall outline-level)))
3637 (save-excursion
3638 (funcall fun)
3639 (while (and (progn
3640 (outline-next-heading)
3641 (> (funcall outline-level) level))
3642 (not (eobp)))
3643 (funcall fun)))))
3645 (defun org-map-region (fun beg end)
3646 "Call FUN for every heading between BEG and END."
3647 (let ((org-ignore-region t))
3648 (save-excursion
3649 (setq end (copy-marker end))
3650 (goto-char beg)
3651 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
3652 (< (point) end))
3653 (funcall fun))
3654 (while (and (progn
3655 (outline-next-heading)
3656 (< (point) end))
3657 (not (eobp)))
3658 (funcall fun)))))
3660 (defun org-fixup-indentation (from to prohibit)
3661 "Change the indentation in the current entry by re-replacing FROM with TO.
3662 However, if the regexp PROHIBIT matches at all, don't do anything.
3663 This is being used to change indentation along with the length of the
3664 heading marker. But if there are any lines which are not indented, nothing
3665 is changed at all."
3666 (save-excursion
3667 (let ((end (save-excursion (outline-next-heading)
3668 (point-marker))))
3669 (unless (save-excursion (re-search-forward prohibit end t))
3670 (while (re-search-forward from end t)
3671 (replace-match to)
3672 (beginning-of-line 2)))
3673 (move-marker end nil))))
3675 ;;; Vertical tree motion, cutting and pasting of subtrees
3677 (defun org-move-subtree-up (&optional arg)
3678 "Move the current subtree up past ARG headlines of the same level."
3679 (interactive "p")
3680 (org-move-subtree-down (- (prefix-numeric-value arg))))
3682 (defun org-move-subtree-down (&optional arg)
3683 "Move the current subtree down past ARG headlines of the same level."
3684 (interactive "p")
3685 (setq arg (prefix-numeric-value arg))
3686 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
3687 'outline-get-last-sibling))
3688 (ins-point (make-marker))
3689 (cnt (abs arg))
3690 beg end txt folded)
3691 ;; Select the tree
3692 (org-back-to-heading)
3693 (setq beg (point))
3694 (save-match-data
3695 (save-excursion (outline-end-of-heading)
3696 (setq folded (org-invisible-p)))
3697 (outline-end-of-subtree))
3698 (outline-next-heading)
3699 (setq end (point))
3700 ;; Find insertion point, with error handling
3701 (goto-char beg)
3702 (while (> cnt 0)
3703 (or (and (funcall movfunc) (looking-at outline-regexp))
3704 (progn (goto-char beg)
3705 (error "Cannot move past superior level or buffer limit")))
3706 (setq cnt (1- cnt)))
3707 (if (> arg 0)
3708 ;; Moving forward - still need to move over subtree
3709 (progn (outline-end-of-subtree)
3710 (outline-next-heading)
3711 (if (not (or (looking-at (concat "^" outline-regexp))
3712 (bolp)))
3713 (newline))))
3714 (move-marker ins-point (point))
3715 (setq txt (buffer-substring beg end))
3716 (delete-region beg end)
3717 (insert txt)
3718 (goto-char ins-point)
3719 (if folded (hide-subtree))
3720 (move-marker ins-point nil)))
3722 (defvar org-subtree-clip ""
3723 "Clipboard for cut and paste of subtrees.
3724 This is actually only a copy of the kill, because we use the normal kill
3725 ring. We need it to check if the kill was created by `org-copy-subtree'.")
3727 (defvar org-subtree-clip-folded nil
3728 "Was the last copied subtree folded?
3729 This is used to fold the tree back after pasting.")
3731 (defun org-cut-subtree ()
3732 "Cut the current subtree into the clipboard.
3733 This is a short-hand for marking the subtree and then cutting it."
3734 (interactive)
3735 (org-copy-subtree 'cut))
3737 (defun org-copy-subtree (&optional cut)
3738 "Cut the current subtree into the clipboard.
3739 This is a short-hand for marking the subtree and then copying it.
3740 If CUT is non nil, actually cut the subtree."
3741 (interactive)
3742 (let (beg end folded)
3743 (org-back-to-heading)
3744 (setq beg (point))
3745 (save-match-data
3746 (save-excursion (outline-end-of-heading)
3747 (setq folded (org-invisible-p)))
3748 (outline-end-of-subtree))
3749 (if (equal (char-after) ?\n) (forward-char 1))
3750 (setq end (point))
3751 (goto-char beg)
3752 (when (> end beg)
3753 (setq org-subtree-clip-folded folded)
3754 (if cut (kill-region beg end) (copy-region-as-kill beg end))
3755 (setq org-subtree-clip (current-kill 0))
3756 (message "%s: Subtree with %d characters"
3757 (if cut "Cut" "Copied")
3758 (length org-subtree-clip)))))
3760 (defun org-paste-subtree (&optional level tree)
3761 "Paste the clipboard as a subtree, with modification of headline level.
3762 The entire subtree is promoted or demoted in order to match a new headline
3763 level. By default, the new level is derived from the visible headings
3764 before and after the insertion point, and taken to be the inferior headline
3765 level of the two. So if the previous visible heading is level 3 and the
3766 next is level 4 (or vice versa), level 4 will be used for insertion.
3767 This makes sure that the subtree remains an independent subtree and does
3768 not swallow low level entries.
3770 You can also force a different level, either by using a numeric prefix
3771 argument, or by inserting the heading marker by hand. For example, if the
3772 cursor is after \"*****\", then the tree will be shifted to level 5.
3774 If you want to insert the tree as is, just use \\[yank].
3776 If optional TREE is given, use this text instead of the kill ring."
3777 (interactive "P")
3778 (unless (org-kill-is-subtree-p tree)
3779 (error
3780 (substitute-command-keys
3781 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
3782 (let* ((txt (or tree (and kill-ring (current-kill 0))))
3783 (^re (concat "^\\(" outline-regexp "\\)"))
3784 (re (concat "\\(" outline-regexp "\\)"))
3785 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
3787 (old-level (if (string-match ^re txt)
3788 (- (match-end 0) (match-beginning 0))
3789 -1))
3790 (force-level (cond (level (prefix-numeric-value level))
3791 ((string-match
3792 ^re_ (buffer-substring (point-at-bol) (point)))
3793 (- (match-end 0) (match-beginning 0)))
3794 (t nil)))
3795 (previous-level (save-excursion
3796 (condition-case nil
3797 (progn
3798 (outline-previous-visible-heading 1)
3799 (if (looking-at re)
3800 (- (match-end 0) (match-beginning 0))
3802 (error 1))))
3803 (next-level (save-excursion
3804 (condition-case nil
3805 (progn
3806 (outline-next-visible-heading 1)
3807 (if (looking-at re)
3808 (- (match-end 0) (match-beginning 0))
3810 (error 1))))
3811 (new-level (or force-level (max previous-level next-level)))
3812 (shift (if (or (= old-level -1)
3813 (= new-level -1)
3814 (= old-level new-level))
3816 (- new-level old-level)))
3817 (shift1 shift)
3818 (delta (if (> shift 0) -1 1))
3819 (func (if (> shift 0) 'org-demote 'org-promote))
3820 (org-odd-levels-only nil)
3821 beg end)
3822 ;; Remove the forces level indicator
3823 (if force-level
3824 (delete-region (point-at-bol) (point)))
3825 ;; Make sure we start at the beginning of an empty line
3826 (if (not (bolp)) (insert "\n"))
3827 (if (not (looking-at "[ \t]*$"))
3828 (progn (insert "\n") (backward-char 1)))
3829 ;; Paste
3830 (setq beg (point))
3831 (if (string-match "[ \t\r\n]+\\'" txt)
3832 (setq txt (replace-match "\n" t t txt)))
3833 (insert txt)
3834 (setq end (point))
3835 (if (looking-at "[ \t\r\n]+")
3836 (replace-match "\n"))
3837 (goto-char beg)
3838 ;; Shift if necessary
3839 (if (= shift 0)
3840 (message "Pasted at level %d, without shift" new-level)
3841 (save-restriction
3842 (narrow-to-region beg end)
3843 (while (not (= shift 0))
3844 (org-map-region func (point-min) (point-max))
3845 (setq shift (+ delta shift)))
3846 (goto-char (point-min))
3847 (message "Pasted at level %d, with shift by %d levels"
3848 new-level shift1)))
3849 (if (and kill-ring
3850 (eq org-subtree-clip (current-kill 0))
3851 org-subtree-clip-folded)
3852 ;; The tree was folded before it was killed/copied
3853 (hide-subtree))))
3855 (defun org-kill-is-subtree-p (&optional txt)
3856 "Check if the current kill is an outline subtree, or a set of trees.
3857 Returns nil if kill does not start with a headline, or if the first
3858 headline level is not the largest headline level in the tree.
3859 So this will actually accept several entries of equal levels as well,
3860 which is OK for `org-paste-subtree'.
3861 If optional TXT is given, check this string instead of the current kill."
3862 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
3863 (start-level (and kill
3864 (string-match (concat "\\`" outline-regexp) kill)
3865 (- (match-end 0) (match-beginning 0))))
3866 (re (concat "^" outline-regexp))
3867 (start 1))
3868 (if (not start-level)
3869 nil ;; does not even start with a heading
3870 (catch 'exit
3871 (while (setq start (string-match re kill (1+ start)))
3872 (if (< (- (match-end 0) (match-beginning 0)) start-level)
3873 (throw 'exit nil)))
3874 t))))
3876 ;;; Plain list items
3878 (defun org-at-item-p ()
3879 "Is point in a line starting a hand-formatted item?"
3880 (let ((llt org-plain-list-ordered-item-terminator))
3881 (save-excursion
3882 (goto-char (point-at-bol))
3883 (looking-at
3884 (cond
3885 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3886 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3887 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3888 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
3890 (defun org-at-item-checkbox-p ()
3891 "Is point at a line starting a plain-list item with a checklet?"
3892 (and (org-at-item-p)
3893 (save-excursion
3894 (goto-char (match-end 0))
3895 (skip-chars-forward " \t")
3896 (looking-at "\\[[ X]\\]"))))
3898 (defun org-toggle-checkbox ()
3899 "Toggle the checkbox in the current line."
3900 (interactive)
3901 (save-excursion
3902 (if (org-at-item-checkbox-p)
3903 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))))
3905 (defun org-get-indentation (&optional line)
3906 "Get the indentation of the current line, interpreting tabs.
3907 When LINE is given, assume it represents a line and compute its indentation."
3908 (if line
3909 (if (string-match "^ *" (org-remove-tabs line))
3910 (match-end 0))
3911 (save-excursion
3912 (beginning-of-line 1)
3913 (skip-chars-forward " \t")
3914 (current-column))))
3916 (defun org-remove-tabs (s &optional width)
3917 "Replace tabulators in S with spaces.
3918 Assumes that s is a single line, starting in column 0."
3919 (setq width (or width tab-width))
3920 (while (string-match "\t" s)
3921 (setq s (replace-match
3922 (make-string
3923 (- (* width (/ (+ (match-beginning 0) width) width))
3924 (match-beginning 0)) ?\ )
3925 t t s)))
3928 ;; FIXME: document properly.
3929 (defun org-fix-indentation (line ind)
3930 "If the current indenation is smaller than ind1, leave it alone.
3931 If it is larger than ind, reduce it by ind."
3932 (let* ((l (org-remove-tabs line))
3933 (i (org-get-indentation l))
3934 (i1 (car ind)) (i2 (cdr ind)))
3935 (if (>= i i2) (setq l (substring line i2)))
3936 (if (> i1 0)
3937 (concat (make-string i1 ?\ ) l)
3938 l)))
3940 (defun org-beginning-of-item ()
3941 "Go to the beginning of the current hand-formatted item.
3942 If the cursor is not in an item, throw an error."
3943 (interactive)
3944 (let ((pos (point))
3945 (limit (save-excursion (org-back-to-heading)
3946 (beginning-of-line 2) (point)))
3947 ind ind1)
3948 (if (org-at-item-p)
3949 (beginning-of-line 1)
3950 (beginning-of-line 1)
3951 (skip-chars-forward " \t")
3952 (setq ind (current-column))
3953 (if (catch 'exit
3954 (while t
3955 (beginning-of-line 0)
3956 (if (< (point) limit) (throw 'exit nil))
3957 (unless (looking-at " \t]*$")
3958 (skip-chars-forward " \t")
3959 (setq ind1 (current-column))
3960 (if (< ind1 ind)
3961 (throw 'exit (org-at-item-p))))))
3963 (goto-char pos)
3964 (error "Not in an item")))))
3966 (defun org-end-of-item ()
3967 "Go to the end of the current hand-formatted item.
3968 If the cursor is not in an item, throw an error."
3969 (interactive)
3970 (let ((pos (point))
3971 (limit (save-excursion (outline-next-heading) (point)))
3972 (ind (save-excursion
3973 (org-beginning-of-item)
3974 (skip-chars-forward " \t")
3975 (current-column)))
3976 ind1)
3977 (if (catch 'exit
3978 (while t
3979 (beginning-of-line 2)
3980 (if (>= (point) limit) (throw 'exit t))
3981 (unless (looking-at "[ \t]*$")
3982 (skip-chars-forward " \t")
3983 (setq ind1 (current-column))
3984 (if (<= ind1 ind) (throw 'exit t)))))
3985 (beginning-of-line 1)
3986 (goto-char pos)
3987 (error "Not in an item"))))
3989 (defun org-next-item ()
3990 "Move to the beginning of the next item in the current plain list.
3991 Error if not at a plain list, or if this is the last item in the list."
3992 (interactive)
3993 (let (beg end ind ind1 (pos (point)) txt)
3994 (org-beginning-of-item)
3995 (setq beg (point))
3996 (setq ind (org-get-indentation))
3997 (org-end-of-item)
3998 (setq end (point))
3999 (setq ind1 (org-get-indentation))
4000 (unless (and (org-at-item-p) (= ind ind1))
4001 (goto-char pos)
4002 (error "On last item"))))
4004 (defun org-previous-item ()
4005 "Move to the beginning of the previous item in the current plain list.
4006 Error if not at a plain list, or if this is the last item in the list."
4007 (interactive)
4008 (let (beg end ind ind1 (pos (point)) txt)
4009 (org-beginning-of-item)
4010 (setq beg (point))
4011 (setq ind (org-get-indentation))
4012 (goto-char beg)
4013 (catch 'exit
4014 (while t
4015 (beginning-of-line 0)
4016 (if (looking-at "[ \t]*$")
4018 (if (<= (setq ind1 (org-get-indentation)) ind)
4019 (throw 'exit t)))))
4020 (condition-case nil
4021 (org-beginning-of-item)
4022 (error (goto-char pos)
4023 (error "On first item")))))
4025 (defun org-move-item-down ()
4026 "Move the plain list item at point down, i.e. swap with following item.
4027 Subitems (items with larger indentation) are considered part of the item,
4028 so this really moves item trees."
4029 (interactive)
4030 (let (beg end ind ind1 (pos (point)) txt)
4031 (org-beginning-of-item)
4032 (setq beg (point))
4033 (setq ind (org-get-indentation))
4034 (org-end-of-item)
4035 (setq end (point))
4036 (setq ind1 (org-get-indentation))
4037 (if (and (org-at-item-p) (= ind ind1))
4038 (progn
4039 (org-end-of-item)
4040 (setq txt (buffer-substring beg end))
4041 (save-excursion
4042 (delete-region beg end))
4043 (setq pos (point))
4044 (insert txt)
4045 (goto-char pos)
4046 (org-maybe-renumber-ordered-list))
4047 (goto-char pos)
4048 (error "Cannot move this item further down"))))
4050 (defun org-move-item-up (arg)
4051 "Move the plain list item at point up, i.e. swap with previous item.
4052 Subitems (items with larger indentation) are considered part of the item,
4053 so this really moves item trees."
4054 (interactive "p")
4055 (let (beg end ind ind1 (pos (point)) txt)
4056 (org-beginning-of-item)
4057 (setq beg (point))
4058 (setq ind (org-get-indentation))
4059 (org-end-of-item)
4060 (setq end (point))
4061 (goto-char beg)
4062 (catch 'exit
4063 (while t
4064 (beginning-of-line 0)
4065 (if (looking-at "[ \t]*$")
4067 (if (<= (setq ind1 (org-get-indentation)) ind)
4068 (throw 'exit t)))))
4069 (condition-case nil
4070 (org-beginning-of-item)
4071 (error (goto-char beg)
4072 (error "Cannot move this item further up")))
4073 (setq ind1 (org-get-indentation))
4074 (if (and (org-at-item-p) (= ind ind1))
4075 (progn
4076 (setq txt (buffer-substring beg end))
4077 (save-excursion
4078 (delete-region beg end))
4079 (setq pos (point))
4080 (insert txt)
4081 (goto-char pos)
4082 (org-maybe-renumber-ordered-list))
4083 (goto-char pos)
4084 (error "Cannot move this item further up"))))
4086 (defun org-maybe-renumber-ordered-list ()
4087 "Renumber the ordered list at point if setup allows it.
4088 This tests the user option `org-auto-renumber-ordered-lists' before
4089 doing the renumbering."
4090 (and org-auto-renumber-ordered-lists
4091 (org-at-item-p)
4092 (match-beginning 3)
4093 (org-renumber-ordered-list 1)))
4095 (defun org-get-string-indentation (s)
4096 "What indentation has S due to SPACE and TAB at the beginning of the string?"
4097 (let ((n -1) (i 0) (w tab-width) c)
4098 (catch 'exit
4099 (while (< (setq n (1+ n)) (length s))
4100 (setq c (aref s n))
4101 (cond ((= c ?\ ) (setq i (1+ i)))
4102 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
4103 (t (throw 'exit t)))))
4106 (defun org-renumber-ordered-list (arg)
4107 "Renumber an ordered plain list.
4108 Cursor needs to be in the first line of an item, the line that starts
4109 with something like \"1.\" or \"2)\"."
4110 (interactive "p")
4111 (unless (and (org-at-item-p)
4112 (match-beginning 3))
4113 (error "This is not an ordered list"))
4114 (let ((line (org-current-line))
4115 (col (current-column))
4116 (ind (org-get-string-indentation
4117 (buffer-substring (point-at-bol) (match-beginning 3))))
4118 ;; (term (substring (match-string 3) -1))
4119 ind1 (n (1- arg)))
4120 ;; find where this list begins
4121 (catch 'exit
4122 (while t
4123 (catch 'next
4124 (beginning-of-line 0)
4125 (if (looking-at "[ \t]*$") (throw 'next t))
4126 (skip-chars-forward " \t") (setq ind1 (current-column))
4127 (if (or (< ind1 ind)
4128 (and (= ind1 ind)
4129 (not (org-at-item-p))))
4130 (throw 'exit t)))))
4131 ;; Walk forward and replace these numbers
4132 (catch 'exit
4133 (while t
4134 (catch 'next
4135 (beginning-of-line 2)
4136 (if (eobp) (throw 'exit nil))
4137 (if (looking-at "[ \t]*$") (throw 'next nil))
4138 (skip-chars-forward " \t") (setq ind1 (current-column))
4139 (if (> ind1 ind) (throw 'next t))
4140 (if (< ind1 ind) (throw 'exit t))
4141 (if (not (org-at-item-p)) (throw 'exit nil))
4142 (if (not (match-beginning 3))
4143 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
4144 (delete-region (match-beginning 3) (1- (match-end 3)))
4145 (goto-char (match-beginning 3))
4146 (insert (format "%d" (setq n (1+ n)))))))
4147 (goto-line line)
4148 (move-to-column col)))
4150 (defvar org-last-indent-begin-marker (make-marker))
4151 (defvar org-last-indent-end-marker (make-marker))
4153 (defun org-outdent-item (arg)
4154 "Outdent a local list item."
4155 (interactive "p")
4156 (org-indent-item (- arg)))
4158 (defun org-indent-item (arg)
4159 "Indent a local list item."
4160 (interactive "p")
4161 (unless (org-at-item-p)
4162 (error "Not on an item"))
4163 (save-excursion
4164 (let (beg end ind ind1)
4165 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
4166 (setq beg org-last-indent-begin-marker
4167 end org-last-indent-end-marker)
4168 (org-beginning-of-item)
4169 (setq beg (move-marker org-last-indent-begin-marker (point)))
4170 (org-end-of-item)
4171 (setq end (move-marker org-last-indent-end-marker (point))))
4172 (goto-char beg)
4173 (skip-chars-forward " \t") (setq ind (current-column))
4174 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
4175 (while (< (point) end)
4176 (beginning-of-line 1)
4177 (skip-chars-forward " \t") (setq ind1 (current-column))
4178 (delete-region (point-at-bol) (point))
4179 (indent-to-column (+ ind1 arg))
4180 (beginning-of-line 2)))))
4182 ;;; Archiving
4184 (defun org-archive-subtree ()
4185 "Move the current subtree to the archive.
4186 The archive can be a certain top-level heading in the current file, or in
4187 a different file. The tree will be moved to that location, the subtree
4188 heading be marked DONE, and the current time will be added."
4189 (interactive)
4190 ;; Save all relevant TODO keyword-relatex variables
4191 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
4192 (tr-org-todo-keywords org-todo-keywords)
4193 (tr-org-todo-interpretation org-todo-interpretation)
4194 (tr-org-done-string org-done-string)
4195 (tr-org-todo-regexp org-todo-regexp)
4196 (tr-org-todo-line-regexp org-todo-line-regexp)
4197 (this-buffer (current-buffer))
4198 file heading buffer level newfile-p)
4199 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
4200 (progn
4201 (setq file (format (match-string 1 org-archive-location)
4202 (file-name-nondirectory buffer-file-name))
4203 heading (match-string 2 org-archive-location)))
4204 (error "Invalid `org-archive-location'"))
4205 (if (> (length file) 0)
4206 (setq newfile-p (not (file-exists-p file))
4207 buffer (find-file-noselect file))
4208 (setq buffer (current-buffer)))
4209 (unless buffer
4210 (error "Cannot access file \"%s\"" file))
4211 (if (and (> (length heading) 0)
4212 (string-match "^\\*+" heading))
4213 (setq level (match-end 0))
4214 (setq heading nil level 0))
4215 (save-excursion
4216 ;; We first only copy, in case something goes wrong
4217 ;; we need to protect this-command, to avoid kill-region sets it,
4218 ;; which would lead to duplication of subtrees
4219 (let (this-command) (org-copy-subtree))
4220 (set-buffer buffer)
4221 ;; Enforce org-mode for the archive buffer
4222 (if (not (eq major-mode 'org-mode))
4223 ;; Force the mode for future visits.
4224 (let ((org-insert-mode-line-in-empty-file t))
4225 (call-interactively 'org-mode)))
4226 (when newfile-p
4227 (goto-char (point-max))
4228 (insert (format "\nArchived entries from file %s\n\n"
4229 (buffer-file-name this-buffer))))
4230 ;; Force the TODO keywords of the original buffer
4231 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
4232 (org-todo-keywords tr-org-todo-keywords)
4233 (org-todo-interpretation tr-org-todo-interpretation)
4234 (org-done-string tr-org-done-string)
4235 (org-todo-regexp tr-org-todo-regexp)
4236 (org-todo-line-regexp tr-org-todo-line-regexp))
4237 (goto-char (point-min))
4238 (if heading
4239 (progn
4240 (if (re-search-forward
4241 (concat "\\(^\\|\r\\)"
4242 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
4243 nil t)
4244 (goto-char (match-end 0))
4245 ;; Heading not found, just insert it at the end
4246 (goto-char (point-max))
4247 (or (bolp) (insert "\n"))
4248 (insert "\n" heading "\n")
4249 (end-of-line 0))
4250 ;; Make the subtree visible
4251 (show-subtree)
4252 (org-end-of-subtree t)
4253 (skip-chars-backward " \t\r\n]")
4254 (and (looking-at "[ \t\r\n]*")
4255 (replace-match "\n\n")))
4256 ;; No specific heading, just go to end of file.
4257 (goto-char (point-max)) (insert "\n"))
4258 ;; Paste
4259 (org-paste-subtree (1+ level))
4260 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
4261 (if org-archive-mark-done
4262 (org-todo (length org-todo-keywords)))
4263 ;; Move cursor to right after the TODO keyword
4264 (when org-archive-stamp-time
4265 (beginning-of-line 1)
4266 (looking-at org-todo-line-regexp)
4267 (goto-char (or (match-end 2) (match-beginning 3)))
4268 (insert "(" (format-time-string (cdr org-time-stamp-formats)
4269 (org-current-time))
4270 ")"))
4271 ;; Save the buffer, if it is not the same buffer.
4272 (if (not (eq this-buffer buffer)) (save-buffer))))
4273 ;; Here we are back in the original buffer. Everything seems to have
4274 ;; worked. So now cut the tree and finish up.
4275 (let (this-command) (org-cut-subtree))
4276 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
4277 (message "Subtree archived %s"
4278 (if (eq this-buffer buffer)
4279 (concat "under heading: " heading)
4280 (concat "in file: " (abbreviate-file-name file))))))
4282 ;;; Completion
4284 (defun org-complete (&optional arg)
4285 "Perform completion on word at point.
4286 At the beginning of a headline, this completes TODO keywords as given in
4287 `org-todo-keywords'.
4288 If the current word is preceded by a backslash, completes the TeX symbols
4289 that are supported for HTML support.
4290 If the current word is preceded by \"#+\", completes special words for
4291 setting file options.
4292 At all other locations, this simply calls `ispell-complete-word'."
4293 (interactive "P")
4294 (catch 'exit
4295 (let* ((end (point))
4296 (beg1 (save-excursion
4297 (if (equal (char-before (point)) ?\ ) (backward-char 1))
4298 (skip-chars-backward "a-zA-Z_@0-9")
4299 (point)))
4300 (beg (save-excursion
4301 (if (equal (char-before (point)) ?\ ) (backward-char 1))
4302 (skip-chars-backward "a-zA-Z0-9_:$")
4303 (point)))
4304 (confirm (lambda (x) (stringp (car x))))
4305 (camel (equal (char-before beg) ?*))
4306 (tag (equal (char-before beg1) ?:))
4307 (texp (equal (char-before beg) ?\\))
4308 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
4309 beg)
4310 "#+"))
4311 (completion-ignore-case opt)
4312 (type nil)
4313 (tbl nil)
4314 (table (cond
4315 (opt
4316 (setq type :opt)
4317 (mapcar (lambda (x)
4318 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
4319 (cons (match-string 2 x) (match-string 1 x)))
4320 (org-split-string (org-get-current-options) "\n")))
4321 (texp
4322 (setq type :tex)
4323 org-html-entities)
4324 ((string-match "\\`\\*+[ \t]*\\'"
4325 (buffer-substring (point-at-bol) beg))
4326 (setq type :todo)
4327 (mapcar 'list org-todo-keywords))
4328 (camel
4329 (setq type :camel)
4330 (save-excursion
4331 (goto-char (point-min))
4332 (while (re-search-forward org-todo-line-regexp nil t)
4333 (push (list
4334 (if org-file-link-context-use-camel-case
4335 (org-make-org-heading-camel (match-string 3) t)
4336 (org-make-org-heading-search-string
4337 (match-string 3) t)))
4338 tbl)))
4339 tbl)
4340 (tag (setq type :tag beg beg1)
4341 (or org-tag-alist (org-get-buffer-tags)))
4342 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
4343 (pattern (buffer-substring-no-properties beg end))
4344 (completion (try-completion pattern table confirm)))
4345 (cond ((eq completion t)
4346 (if (equal type :opt)
4347 (insert (substring (cdr (assoc (upcase pattern) table))
4348 (length pattern)))))
4349 ((null completion)
4350 (message "Can't find completion for \"%s\"" pattern)
4351 (ding))
4352 ((not (string= pattern completion))
4353 (delete-region beg end)
4354 (if (string-match " +$" completion)
4355 (setq completion (replace-match "" t t completion)))
4356 (insert completion)
4357 (if (get-buffer-window "*Completions*")
4358 (delete-window (get-buffer-window "*Completions*")))
4359 (if (assoc completion table)
4360 (if (eq type :todo) (insert " ")
4361 (if (eq type :tag) (insert ":"))))
4362 (if (and (equal type :opt) (assoc completion table))
4363 (message "%s" (substitute-command-keys
4364 "Press \\[org-complete] again to insert example settings"))))
4366 (message "Making completion list...")
4367 (let ((list (sort (all-completions pattern table confirm)
4368 'string<)))
4369 (with-output-to-temp-buffer "*Completions*"
4370 (condition-case nil
4371 ;; Protection needed for XEmacs and emacs 21
4372 (display-completion-list list pattern)
4373 (error (display-completion-list list)))))
4374 (message "Making completion list...%s" "done"))))))
4376 ;;; Comments, TODO and DEADLINE
4378 (defun org-toggle-comment ()
4379 "Change the COMMENT state of an entry."
4380 (interactive)
4381 (save-excursion
4382 (org-back-to-heading)
4383 (if (looking-at (concat outline-regexp
4384 "\\( +\\<" org-comment-string "\\>\\)"))
4385 (replace-match "" t t nil 1)
4386 (if (looking-at outline-regexp)
4387 (progn
4388 (goto-char (match-end 0))
4389 (insert " " org-comment-string))))))
4391 (defvar org-last-todo-state-is-todo nil
4392 "This is non-nil when the last TODO state change led to a TODO state.
4393 If the last change removed the TODO tag or switched to DONE, then
4394 this is nil.")
4396 (defun org-todo (&optional arg)
4397 "Change the TODO state of an item.
4398 The state of an item is given by a keyword at the start of the heading,
4399 like
4400 *** TODO Write paper
4401 *** DONE Call mom
4403 The different keywords are specified in the variable `org-todo-keywords'.
4404 By default the available states are \"TODO\" and \"DONE\".
4405 So for this example: when the item starts with TODO, it is changed to DONE.
4406 When it starts with DONE, the DONE is removed. And when neither TODO nor
4407 DONE are present, add TODO at the beginning of the heading.
4409 With prefix arg, use completion to determine the new state. With numeric
4410 prefix arg, switch to that state."
4411 (interactive "P")
4412 (save-excursion
4413 (org-back-to-heading)
4414 (if (looking-at outline-regexp) (goto-char (match-end 0)))
4415 (or (looking-at (concat " +" org-todo-regexp " *"))
4416 (looking-at " *"))
4417 (let* ((this (match-string 1))
4418 (completion-ignore-case t)
4419 (member (member this org-todo-keywords))
4420 (tail (cdr member))
4421 (state (cond
4422 ((equal arg '(4))
4423 ;; Read a state with completion
4424 (completing-read "State: " (mapcar (lambda(x) (list x))
4425 org-todo-keywords)
4426 nil t))
4427 ((eq arg 'right)
4428 (if this
4429 (if tail (car tail) nil)
4430 (car org-todo-keywords)))
4431 ((eq arg 'left)
4432 (if (equal member org-todo-keywords)
4434 (if this
4435 (nth (- (length org-todo-keywords) (length tail) 2)
4436 org-todo-keywords)
4437 org-done-string)))
4438 (arg
4439 ;; user requests a specific state
4440 (nth (1- (prefix-numeric-value arg))
4441 org-todo-keywords))
4442 ((null member) (car org-todo-keywords))
4443 ((null tail) nil) ;; -> first entry
4444 ((eq org-todo-interpretation 'sequence)
4445 (car tail))
4446 ((memq org-todo-interpretation '(type priority))
4447 (if (eq this-command last-command)
4448 (car tail)
4449 (if (> (length tail) 0) org-done-string nil)))
4450 (t nil)))
4451 (next (if state (concat " " state " ") " ")))
4452 (replace-match next t t)
4453 (setq org-last-todo-state-is-todo
4454 (not (equal state org-done-string)))
4455 (when org-log-done
4456 (if (equal state org-done-string)
4457 (org-add-planning-info 'closed (current-time) 'scheduled)
4458 (if (not this)
4459 (org-add-planning-info nil nil 'closed))))
4460 ;; Fixup tag positioning
4461 (and org-auto-align-tags (org-set-tags nil t))
4462 (run-hooks 'org-after-todo-state-change-hook)))
4463 ;; Fixup cursor location if close to the keyword
4464 (if (and (outline-on-heading-p)
4465 (not (bolp))
4466 (save-excursion (beginning-of-line 1)
4467 (looking-at org-todo-line-regexp))
4468 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
4469 (progn
4470 (goto-char (or (match-end 2) (match-end 1)))
4471 (just-one-space))))
4473 (defun org-log-done (&optional undone)
4474 "Add a time stamp logging that a TODO entry has been closed.
4475 When UNDONE is non-nil, remove such a time stamp again."
4476 (interactive)
4477 (let (beg end col)
4478 (save-excursion
4479 (org-back-to-heading t)
4480 (setq beg (point))
4481 (looking-at (concat outline-regexp " *"))
4482 (goto-char (match-end 0))
4483 (setq col (current-column))
4484 (outline-next-heading)
4485 (setq end (point))
4486 (goto-char beg)
4487 (when (re-search-forward (concat
4488 "[\r\n]\\([ \t]*"
4489 (regexp-quote org-closed-string)
4490 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
4491 (delete-region (match-beginning 1) (match-end 1)))
4492 (unless undone
4493 (org-back-to-heading t)
4494 (skip-chars-forward "^\n\r")
4495 (goto-char (min (1+ (point)) (point-max)))
4496 (when (not (member (char-before) '(?\r ?\n)))
4497 (insert "\n"))
4498 (indent-to col)
4499 (insert org-closed-string " "
4500 (format-time-string
4501 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
4502 (org-current-time))
4503 "\n")))))
4505 (defun org-show-todo-tree (arg)
4506 "Make a compact tree which shows all headlines marked with TODO.
4507 The tree will show the lines where the regexp matches, and all higher
4508 headlines above the match.
4509 With \\[universal-argument] prefix, also show the DONE entries.
4510 With a numeric prefix N, construct a sparse tree for the Nth element
4511 of `org-todo-keywords'."
4512 (interactive "P")
4513 (let ((case-fold-search nil)
4514 (kwd-re
4515 (cond ((null arg) org-not-done-regexp)
4516 ((equal arg '(4)) org-todo-regexp)
4517 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
4518 (regexp-quote (nth (1- (prefix-numeric-value arg))
4519 org-todo-keywords)))
4520 (t (error "Invalid prefix argument: %s" arg)))))
4521 (message "%d TODO entries found"
4522 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
4524 (defun org-deadline ()
4525 "Insert the DEADLINE: string to make a deadline.
4526 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
4527 to modify it to the correct date."
4528 (interactive)
4529 (org-add-planning-info 'deadline nil 'closed))
4531 (defun org-schedule ()
4532 "Insert the SCHEDULED: string to schedule a TODO item.
4533 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
4534 to modify it to the correct date."
4535 (interactive)
4536 (org-add-planning-info 'scheduled nil 'closed))
4538 (defun org-add-planning-info (what &optional time &rest remove)
4539 "Insert new timestamp with keyword in the line directly after the headline.
4540 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
4541 If non is given, the user is prompted for a date.
4542 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
4543 be removed."
4544 (interactive)
4545 (when what (setq time (or time (org-read-date nil 'to-time))))
4546 (when (and org-insert-labeled-timestamps-at-point
4547 (member what '(scheduled deadline)))
4548 (insert
4549 (if (eq what 'scheduled) org-scheduled-string org-deadline-string)
4551 (format-time-string (car org-time-stamp-formats) time))
4552 (setq what nil))
4553 (save-excursion
4554 (let (beg end col list elt (buffer-invisibility-spec nil) ts)
4555 (org-back-to-heading t)
4556 (setq beg (point))
4557 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
4558 (goto-char (match-end 1))
4559 (setq col (current-column))
4560 (goto-char (1+ (match-end 0)))
4561 (if (and (not (looking-at outline-regexp))
4562 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
4563 "[^\r\n]*")))
4564 (narrow-to-region (match-beginning 0) (match-end 0))
4565 (insert "\n")
4566 (backward-char 1)
4567 (narrow-to-region (point) (point))
4568 (indent-to-column col))
4569 ;; Check if we have to remove something.
4570 (setq list (cons what remove))
4571 (while list
4572 (setq elt (pop list))
4573 (goto-char (point-min))
4574 (when (or (and (eq elt 'scheduled)
4575 (re-search-forward org-scheduled-time-regexp nil t))
4576 (and (eq elt 'deadline)
4577 (re-search-forward org-deadline-time-regexp nil t))
4578 (and (eq elt 'closed)
4579 (re-search-forward org-closed-time-regexp nil t)))
4580 (replace-match "")
4581 (if (looking-at " +") (replace-match ""))))
4582 (goto-char (point-max))
4583 (when what
4584 (insert
4585 (if (not (equal (char-before) ?\ )) " " "")
4586 (cond ((eq what 'scheduled) org-scheduled-string)
4587 ((eq what 'deadline) org-deadline-string)
4588 ((eq what 'closed) org-closed-string))
4589 " ")
4590 (insert
4591 (setq ts
4592 (format-time-string
4593 (if (eq what 'closed)
4594 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
4595 (car org-time-stamp-formats))
4596 time))))
4597 (goto-char (point-min))
4598 (widen)
4599 (if (looking-at "[ \t]+\r?\n")
4600 (replace-match ""))
4601 ts)))
4603 (defun org-occur (regexp &optional callback)
4604 "Make a compact tree which shows all matches of REGEXP.
4605 The tree will show the lines where the regexp matches, and all higher
4606 headlines above the match. It will also show the heading after the match,
4607 to make sure editing the matching entry is easy.
4608 If CALLBACK is non-nil, it is a function which is called to confirm
4609 that the match should indeed be shown."
4610 (interactive "sRegexp: ")
4611 (org-remove-occur-highlights nil nil t)
4612 (setq regexp (org-check-occur-regexp regexp))
4613 (let ((cnt 0))
4614 (save-excursion
4615 (goto-char (point-min))
4616 (org-overview)
4617 (while (re-search-forward regexp nil t)
4618 (when (or (not callback)
4619 (save-match-data (funcall callback)))
4620 (setq cnt (1+ cnt))
4621 (org-highlight-new-match (match-beginning 0) (match-end 0))
4622 (org-show-hierarchy-above))))
4623 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
4624 nil 'local)
4625 (run-hooks 'org-occur-hook)
4626 (if (interactive-p)
4627 (message "%d match(es) for regexp %s" cnt regexp))
4628 cnt))
4630 (defun org-show-hierarchy-above ()
4631 "Make sure point and the headings hierarchy above is visible."
4632 (catch 'exit
4633 (if (org-on-heading-p t)
4634 (org-flag-heading nil) ; only show the heading
4635 (and (or (org-invisible-p) (org-invisible-p2))
4636 (org-show-hidden-entry))) ; show entire entry
4637 (save-excursion
4638 (and org-show-following-heading
4639 (outline-next-heading)
4640 (org-flag-heading nil))) ; show the next heading
4641 (when org-show-hierarchy-above
4642 (save-excursion ; show all higher headings
4643 (while (and (condition-case nil
4644 (progn (org-up-heading-all 1) t)
4645 (error nil))
4646 (not (bobp)))
4647 (org-flag-heading nil))))))
4649 ;; Overlay compatibility functions
4650 (defun org-make-overlay (beg end &optional buffer)
4651 (if (featurep 'xemacs)
4652 (make-extent beg end buffer)
4653 (make-overlay beg end buffer)))
4654 (defun org-delete-overlay (ovl)
4655 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4656 (defun org-detatch-overlay (ovl)
4657 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4658 (defun org-move-overlay (ovl beg end &optional buffer)
4659 (if (featurep 'xemacs)
4660 (set-extent-endpoints ovl beg end buffer)
4661 (move-overlay ovl beg end buffer)))
4662 (defun org-overlay-put (ovl prop value)
4663 (if (featurep 'xemacs)
4664 (set-extent-property ovl prop value)
4665 (overlay-put ovl prop value)))
4667 (defvar org-occur-highlights nil)
4668 (defun org-highlight-new-match (beg end)
4669 "Highlight from BEG to END and mark the highlight is an occur headline."
4670 (let ((ov (org-make-overlay beg end)))
4671 (org-overlay-put ov 'face 'secondary-selection)
4672 (push ov org-occur-highlights)))
4674 (defun org-remove-occur-highlights (&optional beg end noremove)
4675 "Remove the occur highlights from the buffer.
4676 BEG and END are ignored. If NOREMOVE is nil, remove this function
4677 from the `before-change-functions' in the current buffer."
4678 (interactive)
4679 (mapc 'org-delete-overlay org-occur-highlights)
4680 (setq org-occur-highlights nil)
4681 (unless noremove
4682 (remove-hook 'before-change-functions
4683 'org-remove-occur-highlights 'local)))
4685 ;;; Priorities
4687 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
4688 "Regular expression matching the priority indicator.")
4690 (defvar org-remove-priority-next-time nil)
4692 (defun org-priority-up ()
4693 "Increase the priority of the current item."
4694 (interactive)
4695 (org-priority 'up))
4697 (defun org-priority-down ()
4698 "Decrease the priority of the current item."
4699 (interactive)
4700 (org-priority 'down))
4702 (defun org-priority (&optional action)
4703 "Change the priority of an item by ARG.
4704 ACTION can be set, up, or down."
4705 (interactive)
4706 (setq action (or action 'set))
4707 (let (current new news have remove)
4708 (save-excursion
4709 (org-back-to-heading)
4710 (if (looking-at org-priority-regexp)
4711 (setq current (string-to-char (match-string 2))
4712 have t)
4713 (setq current org-default-priority))
4714 (cond
4715 ((eq action 'set)
4716 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
4717 (setq new (read-char-exclusive))
4718 (cond ((equal new ?\ ) (setq remove t))
4719 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
4720 (error "Priority must be between `%c' and `%c'"
4721 ?A org-lowest-priority))))
4722 ((eq action 'up)
4723 (setq new (1- current)))
4724 ((eq action 'down)
4725 (setq new (1+ current)))
4726 (t (error "Invalid action")))
4727 (setq new (min (max ?A (upcase new)) org-lowest-priority))
4728 (setq news (format "%c" new))
4729 (if have
4730 (if remove
4731 (replace-match "" t t nil 1)
4732 (replace-match news t t nil 2))
4733 (if remove
4734 (error "No priority cookie found in line")
4735 (looking-at org-todo-line-regexp)
4736 (if (match-end 2)
4737 (progn
4738 (goto-char (match-end 2))
4739 (insert " [#" news "]"))
4740 (goto-char (match-beginning 3))
4741 (insert "[#" news "] ")))))
4742 (if remove
4743 (message "Priority removed")
4744 (message "Priority of current item set to %s" news))))
4747 (defun org-get-priority (s)
4748 "Find priority cookie and return priority."
4749 (save-match-data
4750 (if (not (string-match org-priority-regexp s))
4751 (* 1000 (- org-lowest-priority org-default-priority))
4752 (* 1000 (- org-lowest-priority
4753 (string-to-char (match-string 2 s)))))))
4755 ;;; Timestamps
4757 (defvar org-last-changed-timestamp nil)
4759 (defun org-time-stamp (arg)
4760 "Prompt for a date/time and insert a time stamp.
4761 If the user specifies a time like HH:MM, or if this command is called
4762 with a prefix argument, the time stamp will contain date and time.
4763 Otherwise, only the date will be included. All parts of a date not
4764 specified by the user will be filled in from the current date/time.
4765 So if you press just return without typing anything, the time stamp
4766 will represent the current date/time. If there is already a timestamp
4767 at the cursor, it will be modified."
4768 (interactive "P")
4769 (let ((fmt (if arg (cdr org-time-stamp-formats)
4770 (car org-time-stamp-formats)))
4771 (org-time-was-given nil)
4772 time)
4773 (cond
4774 ((and (org-at-timestamp-p)
4775 (eq last-command 'org-time-stamp)
4776 (eq this-command 'org-time-stamp))
4777 (insert "--")
4778 (setq time (let ((this-command this-command))
4779 (org-read-date arg 'totime)))
4780 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4781 (insert (format-time-string fmt time)))
4782 ((org-at-timestamp-p)
4783 (setq time (let ((this-command this-command))
4784 (org-read-date arg 'totime)))
4785 (and (org-at-timestamp-p) (replace-match
4786 (setq org-last-changed-timestamp
4787 (format-time-string fmt time))
4788 t t))
4789 (message "Timestamp updated"))
4791 (setq time (let ((this-command this-command))
4792 (org-read-date arg 'totime)))
4793 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4794 (insert (format-time-string fmt time))))))
4796 (defun org-time-stamp-inactive (&optional arg)
4797 "Insert an inactive time stamp.
4798 An inactive time stamp is enclosed in square brackets instead of angle
4799 brackets. It is inactive in the sense that it does not trigger agenda entries,
4800 does not link to the calendar and cannot be changed with the S-cursor keys.
4801 So these are more for recording a certain time/date."
4802 (interactive "P")
4803 (let ((fmt (if arg (cdr org-time-stamp-formats)
4804 (car org-time-stamp-formats)))
4805 (org-time-was-given nil)
4806 time)
4807 (setq time (org-read-date arg 'totime))
4808 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4809 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
4810 (insert (format-time-string fmt time))))
4812 (defvar org-date-ovl (org-make-overlay 1 1))
4813 (org-overlay-put org-date-ovl 'face 'org-warning)
4814 (org-detatch-overlay org-date-ovl)
4816 (defun org-read-date (&optional with-time to-time)
4817 "Read a date and make things smooth for the user.
4818 The prompt will suggest to enter an ISO date, but you can also enter anything
4819 which will at least partially be understood by `parse-time-string'.
4820 Unrecognized parts of the date will default to the current day, month, year,
4821 hour and minute. For example,
4822 3-2-5 --> 2003-02-05
4823 feb 15 --> currentyear-02-15
4824 sep 12 9 --> 2009-09-12
4825 12:45 --> today 12:45
4826 22 sept 0:34 --> currentyear-09-22 0:34
4827 12 --> currentyear-currentmonth-12
4828 Fri --> nearest Friday (today or later)
4829 etc.
4830 The function understands only English month and weekday abbreviations,
4831 but this can be configured with the variables `parse-time-months' and
4832 `parse-time-weekdays'.
4834 While prompting, a calendar is popped up - you can also select the
4835 date with the mouse (button 1). The calendar shows a period of three
4836 months. To scroll it to other months, use the keys `>' and `<'.
4837 If you don't like the calendar, turn it off with
4838 \(setq org-popup-calendar-for-date-prompt nil)
4840 With optional argument TO-TIME, the date will immediately be converted
4841 to an internal time.
4842 With an optional argument WITH-TIME, the prompt will suggest to also
4843 insert a time. Note that when WITH-TIME is not set, you can still
4844 enter a time, and this function will inform the calling routine about
4845 this change. The calling routine may then choose to change the format
4846 used to insert the time stamp into the buffer to include the time."
4847 (require 'parse-time)
4848 (let* ((org-time-stamp-rounding-minutes
4849 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
4850 (ct (org-current-time))
4851 (default-time
4852 ;; Default time is either today, or, when entering a range,
4853 ;; the range start.
4854 (if (save-excursion
4855 (re-search-backward
4856 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
4857 (- (point) 20) t))
4858 (apply
4859 'encode-time
4860 (mapcar (lambda(x) (or x 0))
4861 (parse-time-string (match-string 1))))
4862 ct))
4863 (calendar-move-hook nil)
4864 (view-diary-entries-initially nil)
4865 (view-calendar-holidays-initially nil)
4866 (timestr (format-time-string
4867 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
4868 (prompt (format "YYYY-MM-DD [%s]: " timestr))
4869 ans ans1 ans2
4870 second minute hour day month year tl wday wday1)
4872 (if org-popup-calendar-for-date-prompt
4873 (save-excursion
4874 (save-window-excursion
4875 (calendar)
4876 (calendar-forward-day (- (time-to-days default-time)
4877 (calendar-absolute-from-gregorian
4878 (calendar-current-date))))
4879 (org-eval-in-calendar nil)
4880 (let* ((old-map (current-local-map))
4881 (map (copy-keymap calendar-mode-map))
4882 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
4883 (define-key map (kbd "RET") 'org-calendar-select)
4884 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
4885 'org-calendar-select-mouse)
4886 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
4887 'org-calendar-select-mouse)
4888 (define-key minibuffer-local-map [(meta shift left)]
4889 (lambda () (interactive)
4890 (org-eval-in-calendar '(calendar-backward-month 1))))
4891 (define-key minibuffer-local-map [(meta shift right)]
4892 (lambda () (interactive)
4893 (org-eval-in-calendar '(calendar-forward-month 1))))
4894 (define-key minibuffer-local-map [(shift up)]
4895 (lambda () (interactive)
4896 (org-eval-in-calendar '(calendar-backward-week 1))))
4897 (define-key minibuffer-local-map [(shift down)]
4898 (lambda () (interactive)
4899 (org-eval-in-calendar '(calendar-forward-week 1))))
4900 (define-key minibuffer-local-map [(shift left)]
4901 (lambda () (interactive)
4902 (org-eval-in-calendar '(calendar-backward-day 1))))
4903 (define-key minibuffer-local-map [(shift right)]
4904 (lambda () (interactive)
4905 (org-eval-in-calendar '(calendar-forward-day 1))))
4906 (define-key minibuffer-local-map ">"
4907 (lambda () (interactive)
4908 (org-eval-in-calendar '(scroll-calendar-left 1))))
4909 (define-key minibuffer-local-map "<"
4910 (lambda () (interactive)
4911 (org-eval-in-calendar '(scroll-calendar-right 1))))
4912 (unwind-protect
4913 (progn
4914 (use-local-map map)
4915 (setq ans (read-string prompt "" nil nil))
4916 (if (not (string-match "\\S-" ans)) (setq ans nil))
4917 (setq ans (or ans1 ans ans2)))
4918 (use-local-map old-map)))))
4919 ;; Naked prompt only
4920 (setq ans (read-string prompt "" nil timestr)))
4921 (org-detatch-overlay org-date-ovl)
4923 (if (string-match
4924 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
4925 (progn
4926 (setq year (if (match-end 2)
4927 (string-to-number (match-string 2 ans))
4928 (string-to-number (format-time-string "%Y")))
4929 month (string-to-number (match-string 3 ans))
4930 day (string-to-number (match-string 4 ans)))
4931 (if (< year 100) (setq year (+ 2000 year)))
4932 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
4933 t nil ans))))
4934 (setq tl (parse-time-string ans)
4935 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
4936 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
4937 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
4938 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
4939 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
4940 second (or (nth 0 tl) 0)
4941 wday (nth 6 tl))
4942 (when (and wday (not (nth 3 tl)))
4943 ;; Weekday was given, but no day, so pick that day in the week
4944 ;; on or after the derived date.
4945 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
4946 (unless (equal wday wday1)
4947 (setq day (+ day (% (- wday wday1 -7) 7)))))
4948 (if (and (boundp 'org-time-was-given)
4949 (nth 2 tl))
4950 (setq org-time-was-given t))
4951 (if (< year 100) (setq year (+ 2000 year)))
4952 (if to-time
4953 (encode-time second minute hour day month year)
4954 (if (or (nth 1 tl) (nth 2 tl))
4955 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
4956 (format "%04d-%02d-%02d" year month day)))))
4958 (defun org-eval-in-calendar (form)
4959 "Eval FORM in the calendar window and return to current window.
4960 Also, store the cursor date in variable ans2."
4961 (let ((sw (selected-window)))
4962 (select-window (get-buffer-window "*Calendar*"))
4963 (eval form)
4964 (when (calendar-cursor-to-date)
4965 (let* ((date (calendar-cursor-to-date))
4966 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4967 (setq ans2 (format-time-string "%Y-%m-%d" time))))
4968 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
4969 (select-window sw)))
4971 (defun org-calendar-select ()
4972 "Return to `org-read-date' with the date currently selected.
4973 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4974 (interactive)
4975 (when (calendar-cursor-to-date)
4976 (let* ((date (calendar-cursor-to-date))
4977 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4978 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4979 (if (active-minibuffer-window) (exit-minibuffer))))
4981 (defun org-calendar-select-mouse (ev)
4982 "Return to `org-read-date' with the date currently selected.
4983 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4984 (interactive "e")
4985 (mouse-set-point ev)
4986 (when (calendar-cursor-to-date)
4987 (let* ((date (calendar-cursor-to-date))
4988 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4989 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4990 (if (active-minibuffer-window) (exit-minibuffer))))
4992 (defun org-check-deadlines (ndays)
4993 "Check if there are any deadlines due or past due.
4994 A deadline is considered due if it happens within `org-deadline-warning-days'
4995 days from today's date. If the deadline appears in an entry marked DONE,
4996 it is not shown. The prefix arg NDAYS can be used to test that many
4997 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
4998 (interactive "P")
4999 (let* ((org-warn-days
5000 (cond
5001 ((equal ndays '(4)) 100000)
5002 (ndays (prefix-numeric-value ndays))
5003 (t org-deadline-warning-days)))
5004 (case-fold-search nil)
5005 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
5006 (callback
5007 (lambda ()
5008 (and (let ((d1 (time-to-days (current-time)))
5009 (d2 (time-to-days
5010 (org-time-string-to-time (match-string 1)))))
5011 (< (- d2 d1) org-warn-days))
5012 (not (org-entry-is-done-p))))))
5013 (message "%d deadlines past-due or due within %d days"
5014 (org-occur regexp callback)
5015 org-warn-days)))
5017 (defun org-evaluate-time-range (&optional to-buffer)
5018 "Evaluate a time range by computing the difference between start and end.
5019 Normally the result is just printed in the echo area, but with prefix arg
5020 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
5021 If the time range is actually in a table, the result is inserted into the
5022 next column.
5023 For time difference computation, a year is assumed to be exactly 365
5024 days in order to avoid rounding problems."
5025 (interactive "P")
5026 (save-excursion
5027 (unless (org-at-date-range-p)
5028 (goto-char (point-at-bol))
5029 (re-search-forward org-tr-regexp (point-at-eol) t))
5030 (if (not (org-at-date-range-p))
5031 (error "Not at a time-stamp range, and none found in current line")))
5032 (let* ((ts1 (match-string 1))
5033 (ts2 (match-string 2))
5034 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
5035 (match-end (match-end 0))
5036 (time1 (org-time-string-to-time ts1))
5037 (time2 (org-time-string-to-time ts2))
5038 (t1 (time-to-seconds time1))
5039 (t2 (time-to-seconds time2))
5040 (diff (abs (- t2 t1)))
5041 (negative (< (- t2 t1) 0))
5042 ;; (ys (floor (* 365 24 60 60)))
5043 (ds (* 24 60 60))
5044 (hs (* 60 60))
5045 (fy "%dy %dd %02d:%02d")
5046 (fy1 "%dy %dd")
5047 (fd "%dd %02d:%02d")
5048 (fd1 "%dd")
5049 (fh "%02d:%02d")
5050 y d h m align)
5051 (if havetime
5052 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5054 d (floor (/ diff ds)) diff (mod diff ds)
5055 h (floor (/ diff hs)) diff (mod diff hs)
5056 m (floor (/ diff 60)))
5057 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5059 d (floor (+ (/ diff ds) 0.5))
5060 h 0 m 0))
5061 (if (not to-buffer)
5062 (message (org-make-tdiff-string y d h m))
5063 (when (org-at-table-p)
5064 (goto-char match-end)
5065 (setq align t)
5066 (and (looking-at " *|") (goto-char (match-end 0))))
5067 (if (looking-at
5068 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
5069 (replace-match ""))
5070 (if negative (insert " -"))
5071 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
5072 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
5073 (insert " " (format fh h m))))
5074 (if align (org-table-align))
5075 (message "Time difference inserted"))))
5077 (defun org-make-tdiff-string (y d h m)
5078 (let ((fmt "")
5079 (l nil))
5080 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
5081 l (push y l)))
5082 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
5083 l (push d l)))
5084 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
5085 l (push h l)))
5086 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
5087 l (push m l)))
5088 (apply 'format fmt (nreverse l))))
5090 (defun org-time-string-to-time (s)
5091 (apply 'encode-time (org-parse-time-string s)))
5093 (defun org-parse-time-string (s &optional nodefault)
5094 "Parse the standard Org-mode time string.
5095 This should be a lot faster than the normal `parse-time-string'.
5096 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
5097 hour and minute fields will be nil if not given."
5098 (if (string-match org-ts-regexp1 s)
5099 (list 0
5100 (if (or (match-beginning 8) (not nodefault))
5101 (string-to-number (or (match-string 8 s) "0")))
5102 (if (or (match-beginning 7) (not nodefault))
5103 (string-to-number (or (match-string 7 s) "0")))
5104 (string-to-number (match-string 4 s))
5105 (string-to-number (match-string 3 s))
5106 (string-to-number (match-string 2 s))
5107 nil nil nil)
5108 (make-list 9 0)))
5110 (defun org-timestamp-up (&optional arg)
5111 "Increase the date item at the cursor by one.
5112 If the cursor is on the year, change the year. If it is on the month or
5113 the day, change that.
5114 With prefix ARG, change by that many units."
5115 (interactive "p")
5116 (org-timestamp-change (prefix-numeric-value arg)))
5118 (defun org-timestamp-down (&optional arg)
5119 "Decrease the date item at the cursor by one.
5120 If the cursor is on the year, change the year. If it is on the month or
5121 the day, change that.
5122 With prefix ARG, change by that many units."
5123 (interactive "p")
5124 (org-timestamp-change (- (prefix-numeric-value arg))))
5126 (defun org-timestamp-up-day (&optional arg)
5127 "Increase the date in the time stamp by one day.
5128 With prefix ARG, change that many days."
5129 (interactive "p")
5130 (if (and (not (org-at-timestamp-p))
5131 (org-on-heading-p))
5132 (org-todo 'up)
5133 (org-timestamp-change (prefix-numeric-value arg) 'day)))
5135 (defun org-timestamp-down-day (&optional arg)
5136 "Decrease the date in the time stamp by one day.
5137 With prefix ARG, change that many days."
5138 (interactive "p")
5139 (if (and (not (org-at-timestamp-p))
5140 (org-on-heading-p))
5141 (org-todo 'down)
5142 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
5144 (defsubst org-pos-in-match-range (pos n)
5145 (and (match-beginning n)
5146 (<= (match-beginning n) pos)
5147 (>= (match-end n) pos)))
5149 (defun org-at-timestamp-p ()
5150 "Determine if the cursor is in or at a timestamp."
5151 (interactive)
5152 (let* ((tsr org-ts-regexp2)
5153 (pos (point))
5154 (ans (or (looking-at tsr)
5155 (save-excursion
5156 (skip-chars-backward "^<\n\r\t")
5157 (if (> (point) 1) (backward-char 1))
5158 (and (looking-at tsr)
5159 (> (- (match-end 0) pos) -1))))))
5160 (and (boundp 'org-ts-what)
5161 (setq org-ts-what
5162 (cond
5163 ((org-pos-in-match-range pos 2) 'year)
5164 ((org-pos-in-match-range pos 3) 'month)
5165 ((org-pos-in-match-range pos 7) 'hour)
5166 ((org-pos-in-match-range pos 8) 'minute)
5167 ((or (org-pos-in-match-range pos 4)
5168 (org-pos-in-match-range pos 5)) 'day)
5169 (t 'day))))
5170 ans))
5172 (defun org-timestamp-change (n &optional what)
5173 "Change the date in the time stamp at point.
5174 The date will be changed by N times WHAT. WHAT can be `day', `month',
5175 `year', `minute', `second'. If WHAT is not given, the cursor position
5176 in the timestamp determines what will be changed."
5177 (let ((fmt (car org-time-stamp-formats))
5178 org-ts-what
5179 (pos (point))
5180 ts time time0)
5181 (if (not (org-at-timestamp-p))
5182 (error "Not at a timestamp"))
5183 (setq org-ts-what (or what org-ts-what))
5184 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
5185 (- (match-end 0) (match-beginning 0))))
5187 (cdr org-time-stamp-formats)
5188 (car org-time-stamp-formats)))
5189 (setq ts (match-string 0))
5190 (replace-match "")
5191 (setq time0 (org-parse-time-string ts))
5192 (setq time
5193 (apply 'encode-time
5194 (append
5195 (list (or (car time0) 0))
5196 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
5197 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
5198 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
5199 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
5200 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
5201 (nthcdr 6 time0))))
5202 (if (eq what 'calendar)
5203 (let ((cal-date
5204 (save-excursion
5205 (save-match-data
5206 (set-buffer "*Calendar*")
5207 (calendar-cursor-to-date)))))
5208 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
5209 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
5210 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
5211 (setcar time0 (or (car time0) 0))
5212 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
5213 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
5214 (setq time (apply 'encode-time time0))))
5215 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
5216 (goto-char pos)
5217 ;; Try to recenter the calendar window, if any
5218 (if (and org-calendar-follow-timestamp-change
5219 (get-buffer-window "*Calendar*" t)
5220 (memq org-ts-what '(day month year)))
5221 (org-recenter-calendar (time-to-days time)))))
5223 (defun org-recenter-calendar (date)
5224 "If the calendar is visible, recenter it to DATE."
5225 (let* ((win (selected-window))
5226 (cwin (get-buffer-window "*Calendar*" t))
5227 (calendar-move-hook nil))
5228 (when cwin
5229 (select-window cwin)
5230 (calendar-goto-date (if (listp date) date
5231 (calendar-gregorian-from-absolute date)))
5232 (select-window win))))
5234 (defun org-goto-calendar (&optional arg)
5235 "Go to the Emacs calendar at the current date.
5236 If there is a time stamp in the current line, go to that date.
5237 A prefix ARG can be used to force the current date."
5238 (interactive "P")
5239 (let ((tsr org-ts-regexp) diff
5240 (calendar-move-hook nil)
5241 (view-calendar-holidays-initially nil)
5242 (view-diary-entries-initially nil))
5243 (if (or (org-at-timestamp-p)
5244 (save-excursion
5245 (beginning-of-line 1)
5246 (looking-at (concat ".*" tsr))))
5247 (let ((d1 (time-to-days (current-time)))
5248 (d2 (time-to-days
5249 (org-time-string-to-time (match-string 1)))))
5250 (setq diff (- d2 d1))))
5251 (calendar)
5252 (calendar-goto-today)
5253 (if (and diff (not arg)) (calendar-forward-day diff))))
5255 (defun org-date-from-calendar ()
5256 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
5257 If there is already a time stamp at the cursor position, update it."
5258 (interactive)
5259 (org-timestamp-change 0 'calendar))
5261 ;;; Agenda, and Diary Integration
5263 ;;; Define the mode
5265 (defvar org-agenda-mode-map (make-sparse-keymap)
5266 "Keymap for `org-agenda-mode'.")
5268 (defvar org-agenda-menu) ; defined later in this file.
5269 (defvar org-agenda-follow-mode nil)
5270 (defvar org-agenda-show-log nil)
5271 (defvar org-agenda-buffer-name "*Org Agenda*")
5272 (defvar org-agenda-redo-command nil)
5273 (defvar org-agenda-mode-hook nil)
5274 (defvar org-agenda-type nil)
5275 (defvar org-agenda-force-single-file nil)
5277 (defun org-agenda-mode ()
5278 "Mode for time-sorted view on action items in Org-mode files.
5280 The following commands are available:
5282 \\{org-agenda-mode-map}"
5283 (interactive)
5284 (kill-all-local-variables)
5285 (setq major-mode 'org-agenda-mode)
5286 (setq mode-name "Org-Agenda")
5287 (use-local-map org-agenda-mode-map)
5288 (easy-menu-add org-agenda-menu)
5289 (if org-startup-truncated (setq truncate-lines t))
5290 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
5291 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
5292 (unless org-agenda-keep-modes
5293 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
5294 org-agenda-show-log nil))
5295 (easy-menu-change
5296 '("Agenda") "Agenda Files"
5297 (append
5298 (list
5299 (vector
5300 (if (get 'org-agenda-files 'org-restrict)
5301 "Restricted to single file"
5302 "Edit File List")
5303 '(org-edit-agenda-file-list)
5304 (not (get 'org-agenda-files 'org-restrict)))
5305 "--")
5306 (mapcar 'org-file-menu-entry (org-agenda-files))))
5307 (org-agenda-set-mode-name)
5308 (apply
5309 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
5310 (list 'org-agenda-mode-hook)))
5312 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
5313 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
5314 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
5315 (define-key org-agenda-mode-map " " 'org-agenda-show)
5316 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
5317 (define-key org-agenda-mode-map "o" 'delete-other-windows)
5318 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
5319 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
5320 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
5321 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
5322 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
5323 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
5324 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
5325 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
5326 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
5327 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
5329 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
5330 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
5331 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
5332 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
5333 (while l (define-key org-agenda-mode-map
5334 (int-to-string (pop l)) 'digit-argument)))
5336 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
5337 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
5338 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
5339 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
5340 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
5341 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
5342 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
5343 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
5344 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
5345 (define-key org-agenda-mode-map "n" 'next-line)
5346 (define-key org-agenda-mode-map "p" 'previous-line)
5347 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
5348 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
5349 (define-key org-agenda-mode-map "," 'org-agenda-priority)
5350 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
5351 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
5352 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
5353 (eval-after-load "calendar"
5354 '(define-key calendar-mode-map org-calendar-to-agenda-key
5355 'org-calendar-goto-agenda))
5356 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
5357 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
5358 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
5359 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
5360 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
5361 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
5362 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
5363 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
5364 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
5365 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
5366 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
5367 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
5368 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
5369 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
5370 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
5371 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
5372 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
5373 "Local keymap for agenda entries from Org-mode.")
5375 (define-key org-agenda-keymap
5376 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
5377 (define-key org-agenda-keymap
5378 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
5379 (when org-agenda-mouse-1-follows-link
5380 (define-key org-agenda-keymap [follow-link] 'mouse-face))
5381 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
5382 '("Agenda"
5383 ("Agenda Files")
5384 "--"
5385 ["Show" org-agenda-show t]
5386 ["Go To (other window)" org-agenda-goto t]
5387 ["Go To (one window)" org-agenda-switch-to t]
5388 ["Follow Mode" org-agenda-follow-mode
5389 :style toggle :selected org-agenda-follow-mode :active t]
5390 "--"
5391 ["Cycle TODO" org-agenda-todo t]
5392 ("Tags"
5393 ["Show all Tags" org-agenda-show-tags t]
5394 ["Set Tags" org-agenda-set-tags t])
5395 ("Schedule"
5396 ["Schedule" org-agenda-schedule t]
5397 ["Set Deadline" org-agenda-deadline t]
5398 "--"
5399 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
5400 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
5401 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
5402 ("Priority"
5403 ["Set Priority" org-agenda-priority t]
5404 ["Increase Priority" org-agenda-priority-up t]
5405 ["Decrease Priority" org-agenda-priority-down t]
5406 ["Show Priority" org-agenda-show-priority t])
5407 "--"
5408 ;; ["New agenda command" org-agenda t]
5409 ["Rebuild buffer" org-agenda-redo t]
5410 "--"
5411 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
5412 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
5413 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
5414 "--"
5415 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
5416 :style radio :selected (equal org-agenda-ndays 1)]
5417 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
5418 :style radio :selected (equal org-agenda-ndays 7)]
5419 "--"
5420 ["Show Logbook entries" org-agenda-log-mode
5421 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
5422 ["Include Diary" org-agenda-toggle-diary
5423 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
5424 ["Use Time Grid" org-agenda-toggle-time-grid
5425 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
5426 "--"
5427 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
5428 ("Calendar Commands"
5429 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
5430 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
5431 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
5432 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
5433 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
5434 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
5435 "--"
5436 ["Quit" org-agenda-quit t]
5437 ["Exit and Release Buffers" org-agenda-exit t]
5440 ;;;###autoload
5441 (defun org-agenda (arg)
5442 "Dispatch agenda commands to collect entries to the agenda buffer.
5443 Prompts for a character to select a command. Any prefix arg will be passed
5444 on to the selected command. The default selections are:
5446 a Call `org-agenda' to display the agenda for the current day or week.
5447 t Call `org-todo-list' to display the global todo list.
5448 T Call `org-todo-list' to display the global todo list, select only
5449 entries with a specific TODO keyword (the user gets a prompt).
5450 m Call `org-tags-view' to display headlines with tags matching
5451 a condition (the user is prompted for the condition).
5452 M Like `m', but select only TODO entries, no ordinary headlines.
5454 More commands can be added by configuring the variable
5455 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
5456 searches can be pre-defined in this way.
5458 If the current buffer is in Org-mode and visiting a file, you can also
5459 first press `1' to indicate that the agenda should be temporarily (until the
5460 next use of \\[org-agenda]) restricted to the current file."
5461 (interactive "P")
5462 (catch 'exit
5463 (let ((restrict-ok (and buffer-file-name (eq major-mode 'org-mode)))
5464 (bfn buffer-file-name)
5465 (custom org-agenda-custom-commands)
5466 c entry key type string)
5467 (put 'org-agenda-files 'org-restrict nil)
5468 (save-window-excursion
5469 (delete-other-windows)
5470 (switch-to-buffer-other-window " *Agenda Commands*")
5471 (erase-buffer)
5472 (insert
5473 "Press key for an agenda command:
5474 --------------------------------
5475 a Agenda for current week or day
5476 t List of all TODO entries T Entries with special TODO kwd
5477 m Match a TAGS query M Like m, but only TODO entries
5478 C Configure your own agenda commands")
5479 (while (setq entry (pop custom))
5480 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
5481 (insert (format "\n%-4s%-14s: %s"
5483 (cond
5484 ((eq type 'tags) "Tags query")
5485 ((eq type 'todo) "TODO keyword")
5486 ((eq type 'tags-tree) "Tags tree")
5487 ((eq type 'todo-tree) "TODO kwd tree")
5488 ((eq type 'occur-tree) "Occur tree")
5489 (t "???"))
5490 (org-add-props string nil 'face 'org-warning))))
5491 (goto-char (point-min))
5492 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
5493 (message "Press key for agenda command%s"
5494 (if restrict-ok ", or [1] to restrict to current file" ""))
5495 (setq c (read-char-exclusive))
5496 (message "")
5497 (when (equal c ?1)
5498 (if restrict-ok
5499 (put 'org-agenda-files 'org-restrict (list bfn))
5500 (error "Cannot restrict agenda to current buffer"))
5501 (message "Press key for agenda command%s"
5502 (if restrict-ok " (restricted to current file)" ""))
5503 (setq c (read-char-exclusive))
5504 (message "")))
5505 (require 'calendar) ; FIXME: can we avoid this for some commands?
5506 ;; For example the todo list should not need it (but does...)
5507 (cond
5508 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
5509 ((equal c ?a) (call-interactively 'org-agenda-list))
5510 ((equal c ?t) (call-interactively 'org-todo-list))
5511 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
5512 ((equal c ?m) (call-interactively 'org-tags-view))
5513 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
5514 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
5515 (setq type (nth 1 entry) string (nth 2 entry))
5516 (cond
5517 ((eq type 'tags)
5518 (org-tags-view current-prefix-arg string))
5519 ((eq type 'tags-todo)
5520 (org-tags-view '(4) string))
5521 ((eq type 'todo)
5522 (org-todo-list string))
5523 ((eq type 'tags-tree)
5524 (org-check-for-org-mode)
5525 (org-tags-sparse-tree current-prefix-arg string))
5526 ((eq type 'todo-tree)
5527 (org-check-for-org-mode)
5528 (org-occur (concat "^" outline-regexp "[ \t]*"
5529 (regexp-quote string) "\\>")))
5530 ((eq type 'occur-tree)
5531 (org-check-for-org-mode)
5532 (org-occur string))
5533 (t (error "Invalid custom agenda command type %s" type))))
5534 (t (error "Invalid key"))))))
5536 (defun org-check-for-org-mode ()
5537 "Make sure current buffer is in org-mode. Error if not."
5538 (or (eq major-mode 'org-mode)
5539 (error "Cannot execute org-mode agenda command on buffer in %s."
5540 major-mode)))
5542 (defun org-fit-agenda-window ()
5543 "Fit the window to the buffer size."
5544 (and org-fit-agenda-window
5545 (fboundp 'fit-window-to-buffer)
5546 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
5547 (/ (frame-height) 2))))
5549 (defun org-agenda-files (&optional unrestricted)
5550 "Get the list of agenda files.
5551 Optional UNRESTRICTED means return the full list even if a restriction
5552 is currently in place."
5553 (cond
5554 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
5555 ((stringp org-agenda-files) (org-read-agenda-file-list))
5556 ((listp org-agenda-files) org-agenda-files)
5557 (t (error "Invalid value of `org-agenda-files'"))))
5559 (defvar org-window-configuration)
5561 (defun org-edit-agenda-file-list ()
5562 "Edit the list of agenda files.
5563 Depending on setup, this either uses customize to edit the variable
5564 `org-agenda-files', or it visits the file that is holding the list. In the
5565 latter case, the buffer is set up in a way that saving it automatically kills
5566 the buffer and restores the previous window configuration."
5567 (interactive)
5568 (if (stringp org-agenda-files)
5569 (let ((cw (current-window-configuration)))
5570 (find-file org-agenda-files)
5571 (set (make-local-variable 'org-window-configuration) cw)
5572 (org-add-hook 'after-save-hook
5573 (lambda ()
5574 (set-window-configuration
5575 (prog1 org-window-configuration
5576 (kill-buffer (current-buffer))))
5577 (org-install-agenda-files-menu)
5578 (message "New agenda file list installed"))
5579 nil 'local)
5580 (message (substitute-command-keys
5581 "Edit list and finish with \\[save-buffer]")))
5582 (customize-variable 'org-agenda-files)))
5584 (defun org-store-new-agenda-file-list (list)
5585 "Set new value for the agenda file list and save it correcly."
5586 (if (stringp org-agenda-files)
5587 (let ((f org-agenda-files) b)
5588 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
5589 (with-temp-file f
5590 (insert (mapconcat 'identity list "\n") "\n")))
5591 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5592 (setq org-agenda-files list)
5593 (customize-save-variable 'org-agenda-files org-agenda-files))))
5595 (defun org-read-agenda-file-list ()
5596 "Read the list of agenda files from a file."
5597 (when (stringp org-agenda-files)
5598 (with-temp-buffer
5599 (insert-file-contents org-agenda-files)
5600 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
5602 (defvar org-agenda-markers nil
5603 "List of all currently active markers created by `org-agenda'.")
5604 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
5605 "Creation time of the last agenda marker.")
5607 (defun org-agenda-new-marker (&optional pos)
5608 "Return a new agenda marker.
5609 Org-mode keeps a list of these markers and resets them when they are
5610 no longer in use."
5611 (let ((m (copy-marker (or pos (point)))))
5612 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
5613 (push m org-agenda-markers)
5616 (defun org-agenda-maybe-reset-markers (&optional force)
5617 "Reset markers created by `org-agenda'. But only if they are old enough."
5618 (if (or force
5619 (> (- (time-to-seconds (current-time))
5620 org-agenda-last-marker-time)
5622 (while org-agenda-markers
5623 (move-marker (pop org-agenda-markers) nil))))
5625 (defvar org-agenda-new-buffers nil
5626 "Buffers created to visit agenda files.")
5628 (defun org-get-agenda-file-buffer (file)
5629 "Get a buffer visiting FILE. If the buffer needs to be created, add
5630 it to the list of buffers which might be released later."
5631 (let ((buf (find-buffer-visiting file)))
5632 (if buf
5633 buf ; just return it
5634 ;; Make a new buffer and remember it
5635 (setq buf (find-file-noselect file))
5636 (if buf (push buf org-agenda-new-buffers))
5637 buf)))
5639 (defun org-release-buffers (blist)
5640 "Release all buffers in list, asking the user for confirmation when needed.
5641 When a buffer is unmodified, it is just killed. When modified, it is saved
5642 \(if the user agrees) and then killed."
5643 (let (buf file)
5644 (while (setq buf (pop blist))
5645 (setq file (buffer-file-name buf))
5646 (when (and (buffer-modified-p buf)
5647 file
5648 (y-or-n-p (format "Save file %s? " file)))
5649 (with-current-buffer buf (save-buffer)))
5650 (kill-buffer buf))))
5652 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
5654 (defun org-timeline (&optional include-all keep-modes)
5655 "Show a time-sorted view of the entries in the current org file.
5656 Only entries with a time stamp of today or later will be listed. With
5657 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
5658 under the current date.
5659 If the buffer contains an active region, only check the region for
5660 dates."
5661 (interactive "P")
5662 (require 'calendar)
5663 (org-agenda-maybe-reset-markers 'force)
5664 (org-compile-prefix-format org-timeline-prefix-format)
5665 (let* ((dopast t)
5666 (dotodo include-all)
5667 (doclosed org-agenda-show-log)
5668 (org-agenda-keep-modes keep-modes)
5669 (entry buffer-file-name)
5670 (org-agenda-files (list buffer-file-name))
5671 (date (calendar-current-date))
5672 (win (selected-window))
5673 (pos1 (point))
5674 (beg (if (org-region-active-p) (region-beginning) (point-min)))
5675 (end (if (org-region-active-p) (region-end) (point-max)))
5676 (day-numbers (org-get-all-dates beg end 'no-ranges
5677 t doclosed ; always include today
5678 org-timeline-show-empty-dates))
5679 (today (time-to-days (current-time)))
5680 (org-respect-restriction t)
5681 (past t)
5682 args
5683 s e rtn d emptyp)
5684 (setq org-agenda-redo-command
5685 (list 'progn
5686 (list 'switch-to-buffer-other-window (current-buffer))
5687 (list 'org-timeline (list 'quote include-all) t)))
5688 (if (not dopast)
5689 ;; Remove past dates from the list of dates.
5690 (setq day-numbers (delq nil (mapcar (lambda(x)
5691 (if (>= x today) x nil))
5692 day-numbers))))
5693 (switch-to-buffer-other-window
5694 (get-buffer-create org-agenda-buffer-name))
5695 (setq buffer-read-only nil)
5696 (erase-buffer)
5697 (org-agenda-mode) (setq buffer-read-only nil)
5698 (set (make-local-variable 'org-agenda-type) 'timeline)
5699 (if doclosed (push :closed args))
5700 (push :timestamp args)
5701 (if dotodo (push :todo args))
5702 (while (setq d (pop day-numbers))
5703 (if (and (listp d) (eq (car d) :omitted))
5704 (progn
5705 (setq s (point))
5706 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
5707 (put-text-property s (1- (point)) 'face 'org-level-3))
5708 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
5709 (if (and (>= d today)
5710 dopast
5711 past)
5712 (progn
5713 (setq past nil)
5714 (insert (make-string 79 ?-) "\n")))
5715 (setq date (calendar-gregorian-from-absolute d))
5716 (setq s (point))
5717 (setq rtn (and (not emptyp)
5718 (apply 'org-agenda-get-day-entries
5719 entry date args)))
5720 (if (or rtn (equal d today) org-timeline-show-empty-dates)
5721 (progn
5722 (insert (calendar-day-name date) " "
5723 (number-to-string (extract-calendar-day date)) " "
5724 (calendar-month-name (extract-calendar-month date)) " "
5725 (number-to-string (extract-calendar-year date)) "\n")
5726 (put-text-property s (1- (point)) 'face
5727 'org-level-3)
5728 (if (equal d today)
5729 (put-text-property s (1- (point)) 'org-today t))
5730 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
5731 (put-text-property s (1- (point)) 'day d)))))
5732 (goto-char (point-min))
5733 (setq buffer-read-only t)
5734 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5735 (point-min)))
5736 (when (not org-select-timeline-window)
5737 (select-window win)
5738 (goto-char pos1))))
5740 ;;;###autoload
5741 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
5742 "Produce a weekly view from all files in variable `org-agenda-files'.
5743 The view will be for the current week, but from the overview buffer you
5744 will be able to go to other weeks.
5745 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
5746 also be shown, under the current date.
5747 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
5748 on the days are also shown. See the variable `org-log-done' for how
5749 to turn on logging.
5750 START-DAY defaults to TODAY, or to the most recent match for the weekday
5751 given in `org-agenda-start-on-weekday'.
5752 NDAYS defaults to `org-agenda-ndays'."
5753 (interactive "P")
5754 (org-agenda-maybe-reset-markers 'force)
5755 (org-compile-prefix-format org-agenda-prefix-format)
5756 (require 'calendar)
5757 (let* ((org-agenda-start-on-weekday
5758 (if (or (equal ndays 1)
5759 (and (null ndays) (equal 1 org-agenda-ndays)))
5760 nil org-agenda-start-on-weekday))
5761 (org-agenda-keep-modes keep-modes)
5762 (thefiles (org-agenda-files))
5763 (files thefiles)
5764 (win (selected-window))
5765 (today (time-to-days (current-time)))
5766 (sd (or start-day today))
5767 (start (if (or (null org-agenda-start-on-weekday)
5768 (< org-agenda-ndays 7))
5770 (let* ((nt (calendar-day-of-week
5771 (calendar-gregorian-from-absolute sd)))
5772 (n1 org-agenda-start-on-weekday)
5773 (d (- nt n1)))
5774 (- sd (+ (if (< d 0) 7 0) d)))))
5775 (day-numbers (list start))
5776 (inhibit-redisplay t)
5777 s e rtn rtnall file date d start-pos end-pos todayp nd)
5778 (setq org-agenda-redo-command
5779 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
5780 ;; Make the list of days
5781 (setq ndays (or ndays org-agenda-ndays)
5782 nd ndays)
5783 (while (> ndays 1)
5784 (push (1+ (car day-numbers)) day-numbers)
5785 (setq ndays (1- ndays)))
5786 (setq day-numbers (nreverse day-numbers))
5787 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
5788 (progn
5789 (delete-other-windows)
5790 (switch-to-buffer-other-window
5791 (get-buffer-create org-agenda-buffer-name))))
5792 (setq buffer-read-only nil)
5793 (erase-buffer)
5794 (org-agenda-mode) (setq buffer-read-only nil)
5795 (set (make-local-variable 'org-agenda-type) 'agenda)
5796 (set (make-local-variable 'starting-day) (car day-numbers))
5797 (set (make-local-variable 'include-all-loc) include-all)
5798 (when (and (or include-all org-agenda-include-all-todo)
5799 (member today day-numbers))
5800 (setq files thefiles
5801 rtnall nil)
5802 (while (setq file (pop files))
5803 (catch 'nextfile
5804 (org-check-agenda-file file)
5805 (setq date (calendar-gregorian-from-absolute today)
5806 rtn (org-agenda-get-day-entries
5807 file date :todo))
5808 (setq rtnall (append rtnall rtn))))
5809 (when rtnall
5810 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
5811 (add-text-properties (point-min) (1- (point))
5812 (list 'face 'org-level-3))
5813 (insert (org-finalize-agenda-entries rtnall) "\n")))
5814 (while (setq d (pop day-numbers))
5815 (setq date (calendar-gregorian-from-absolute d)
5816 s (point))
5817 (if (or (setq todayp (= d today))
5818 (and (not start-pos) (= d sd)))
5819 (setq start-pos (point))
5820 (if (and start-pos (not end-pos))
5821 (setq end-pos (point))))
5822 (setq files thefiles
5823 rtnall nil)
5824 (while (setq file (pop files))
5825 (catch 'nextfile
5826 (org-check-agenda-file file)
5827 (if org-agenda-show-log
5828 (setq rtn (org-agenda-get-day-entries
5829 file date
5830 :deadline :scheduled :timestamp :closed))
5831 (setq rtn (org-agenda-get-day-entries
5832 file date
5833 :deadline :scheduled :timestamp)))
5834 (setq rtnall (append rtnall rtn))))
5835 (if org-agenda-include-diary
5836 (progn
5837 (require 'diary-lib)
5838 (setq rtn (org-get-entries-from-diary date))
5839 (setq rtnall (append rtnall rtn))))
5840 (if (or rtnall org-agenda-show-all-dates)
5841 (progn
5842 (insert (format "%-9s %2d %s %4d\n"
5843 (calendar-day-name date)
5844 (extract-calendar-day date)
5845 (calendar-month-name (extract-calendar-month date))
5846 (extract-calendar-year date)))
5847 (put-text-property s (1- (point)) 'face
5848 'org-level-3)
5849 (if rtnall (insert
5850 (org-finalize-agenda-entries
5851 (org-agenda-add-time-grid-maybe
5852 rtnall nd todayp))
5853 "\n"))
5854 (put-text-property s (1- (point)) 'day d))))
5855 (goto-char (point-min))
5856 (setq buffer-read-only t)
5857 (org-fit-agenda-window)
5858 (unless (and (pos-visible-in-window-p (point-min))
5859 (pos-visible-in-window-p (point-max)))
5860 (goto-char (1- (point-max)))
5861 (recenter -1)
5862 (if (not (pos-visible-in-window-p (or start-pos 1)))
5863 (progn
5864 (goto-char (or start-pos 1))
5865 (recenter 1))))
5866 (goto-char (or start-pos 1))
5867 (if (not org-select-agenda-window) (select-window win))
5868 (message "")))
5870 (defvar org-select-this-todo-keyword nil)
5872 ;;;###autoload
5873 (defun org-todo-list (arg &optional keep-modes)
5874 "Show all TODO entries from all agenda file in a single list.
5875 The prefix arg can be used to select a specific TODO keyword and limit
5876 the list to these. When using \\[universal-argument], you will be prompted
5877 for a keyword. A numeric prefix directly selects the Nth keyword in
5878 `org-todo-keywords'."
5879 (interactive "P")
5880 (org-agenda-maybe-reset-markers 'force)
5881 (org-compile-prefix-format org-agenda-prefix-format)
5882 (let* ((org-agenda-keep-modes keep-modes)
5883 (today (time-to-days (current-time)))
5884 (date (calendar-gregorian-from-absolute today))
5885 (win (selected-window))
5886 (kwds org-todo-keywords)
5887 (completion-ignore-case t)
5888 (org-select-this-todo-keyword
5889 (if (stringp arg) arg
5890 (and arg (integerp arg) (> arg 0)
5891 (nth (1- arg) org-todo-keywords))))
5892 rtn rtnall files file pos)
5893 (when (equal arg '(4))
5894 (setq org-select-this-todo-keyword
5895 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
5896 nil t)))
5897 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
5898 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
5899 (progn
5900 (delete-other-windows)
5901 (switch-to-buffer-other-window
5902 (get-buffer-create org-agenda-buffer-name))))
5903 (setq buffer-read-only nil)
5904 (erase-buffer)
5905 (org-agenda-mode) (setq buffer-read-only nil)
5906 (set (make-local-variable 'org-agenda-type) 'todo)
5907 (set (make-local-variable 'last-arg) arg)
5908 (set (make-local-variable 'org-todo-keywords) kwds)
5909 (set (make-local-variable 'org-agenda-redo-command)
5910 '(org-todo-list (or current-prefix-arg last-arg) t))
5911 (setq files (org-agenda-files)
5912 rtnall nil)
5913 (while (setq file (pop files))
5914 (catch 'nextfile
5915 (org-check-agenda-file file)
5916 (setq rtn (org-agenda-get-day-entries file date :todo))
5917 (setq rtnall (append rtnall rtn))))
5918 (insert "Global list of TODO items of type: ")
5919 (add-text-properties (point-min) (1- (point))
5920 (list 'face 'org-level-3))
5921 (setq pos (point))
5922 (insert (or org-select-this-todo-keyword "ALL") "\n")
5923 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
5924 (setq pos (point))
5925 (insert
5926 "Available with `N r': (0)ALL "
5927 (let ((n 0))
5928 (mapconcat (lambda (x)
5929 (format "(%d)%s" (setq n (1+ n)) x))
5930 org-todo-keywords " "))
5931 "\n")
5932 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
5933 (when rtnall
5934 (insert (org-finalize-agenda-entries rtnall) "\n"))
5935 (goto-char (point-min))
5936 (setq buffer-read-only t)
5937 (org-fit-agenda-window)
5938 (if (not org-select-agenda-window) (select-window win))))
5940 (defun org-check-agenda-file (file)
5941 "Make sure FILE exists. If not, ask user what to do."
5942 (when (not (file-exists-p file))
5943 (message "non-existent file %s. [R]emove from list or [A]bort?"
5944 (abbreviate-file-name file))
5945 (let ((r (downcase (read-char-exclusive))))
5946 (cond
5947 ((equal r ?r)
5948 (org-remove-file file)
5949 (throw 'nextfile t))
5950 (t (error "Abort"))))))
5952 (defun org-agenda-check-type (error &rest types)
5953 "Check if agenda buffer is of allowed type.
5954 If ERROR is non-nil, throw an error, otherwise just return nil."
5955 (if (memq org-agenda-type types)
5957 (if error
5958 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
5959 nil)))
5961 (defun org-agenda-quit ()
5962 "Exit agenda by removing the window or the buffer."
5963 (interactive)
5964 (let ((buf (current-buffer)))
5965 (if (not (one-window-p)) (delete-window))
5966 (kill-buffer buf)
5967 (org-agenda-maybe-reset-markers 'force)))
5969 (defun org-agenda-exit ()
5970 "Exit agenda by removing the window or the buffer.
5971 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
5972 Org-mode buffers visited directly by the user will not be touched."
5973 (interactive)
5974 (org-release-buffers org-agenda-new-buffers)
5975 (setq org-agenda-new-buffers nil)
5976 (org-agenda-quit))
5978 (defun org-agenda-redo ()
5979 "Rebuild Agenda.
5980 When this is the global TODO list, a prefix argument will be interpreted."
5981 (interactive)
5982 (message "Rebuilding agenda buffer...")
5983 (eval org-agenda-redo-command)
5984 (message "Rebuilding agenda buffer...done"))
5986 (defun org-agenda-goto-today ()
5987 "Go to today."
5988 (interactive)
5989 (org-agenda-check-type t 'timeline 'agenda)
5990 (if (boundp 'starting-day)
5991 (let ((cmd (car org-agenda-redo-command))
5992 (iall (nth 1 org-agenda-redo-command))
5993 (nday (nth 3 org-agenda-redo-command))
5994 (keep (nth 4 org-agenda-redo-command)))
5995 (eval (list cmd iall nil nday keep)))
5996 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5997 (point-min)))))
5999 (defun org-agenda-later (arg)
6000 "Go forward in time by `org-agenda-ndays' days.
6001 With prefix ARG, go forward that many times `org-agenda-ndays'."
6002 (interactive "p")
6003 (org-agenda-check-type t 'agenda)
6004 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
6005 (+ starting-day (* arg org-agenda-ndays)) nil t))
6007 (defun org-agenda-earlier (arg)
6008 "Go back in time by `org-agenda-ndays' days.
6009 With prefix ARG, go back that many times `org-agenda-ndays'."
6010 (interactive "p")
6011 (org-agenda-check-type t 'agenda)
6012 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
6013 (- starting-day (* arg org-agenda-ndays)) nil t))
6015 (defun org-agenda-week-view ()
6016 "Switch to weekly view for agenda."
6017 (interactive)
6018 (org-agenda-check-type t 'agenda)
6019 (setq org-agenda-ndays 7)
6020 (org-agenda-list include-all-loc
6021 (or (get-text-property (point) 'day)
6022 starting-day)
6023 nil t)
6024 (org-agenda-set-mode-name)
6025 (message "Switched to week view"))
6027 (defun org-agenda-day-view ()
6028 "Switch to daily view for agenda."
6029 (interactive)
6030 (org-agenda-check-type t 'agenda)
6031 (setq org-agenda-ndays 1)
6032 (org-agenda-list include-all-loc
6033 (or (get-text-property (point) 'day)
6034 starting-day)
6035 nil t)
6036 (org-agenda-set-mode-name)
6037 (message "Switched to day view"))
6039 (defun org-agenda-next-date-line (&optional arg)
6040 "Jump to the next line indicating a date in agenda buffer."
6041 (interactive "p")
6042 (org-agenda-check-type t 'agenda 'timeline)
6043 (beginning-of-line 1)
6044 (if (looking-at "^\\S-") (forward-char 1))
6045 (if (not (re-search-forward "^\\S-" nil t arg))
6046 (progn
6047 (backward-char 1)
6048 (error "No next date after this line in this buffer")))
6049 (goto-char (match-beginning 0)))
6051 (defun org-agenda-previous-date-line (&optional arg)
6052 "Jump to the previous line indicating a date in agenda buffer."
6053 (interactive "p")
6054 (org-agenda-check-type t 'agenda 'timeline)
6055 (beginning-of-line 1)
6056 (if (not (re-search-backward "^\\S-" nil t arg))
6057 (error "No previous date before this line in this buffer")))
6059 ;; Initialize the highlight
6060 (defvar org-hl (org-make-overlay 1 1))
6061 (org-overlay-put org-hl 'face 'highlight)
6063 (defun org-highlight (begin end &optional buffer)
6064 "Highlight a region with overlay."
6065 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
6066 org-hl begin end (or buffer (current-buffer))))
6068 (defun org-unhighlight ()
6069 "Detach overlay INDEX."
6070 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
6073 (defun org-agenda-follow-mode ()
6074 "Toggle follow mode in an agenda buffer."
6075 (interactive)
6076 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
6077 (org-agenda-set-mode-name)
6078 (message "Follow mode is %s"
6079 (if org-agenda-follow-mode "on" "off")))
6081 (defun org-agenda-log-mode ()
6082 "Toggle log mode in an agenda buffer."
6083 (interactive)
6084 (org-agenda-check-type t 'agenda 'timeline)
6085 (setq org-agenda-show-log (not org-agenda-show-log))
6086 (org-agenda-set-mode-name)
6087 (org-agenda-redo)
6088 (message "Log mode is %s"
6089 (if org-agenda-show-log "on" "off")))
6091 (defun org-agenda-toggle-diary ()
6092 "Toggle diary inclusion in an agenda buffer."
6093 (interactive)
6094 (org-agenda-check-type t 'agenda)
6095 (setq org-agenda-include-diary (not org-agenda-include-diary))
6096 (org-agenda-redo)
6097 (org-agenda-set-mode-name)
6098 (message "Diary inclusion turned %s"
6099 (if org-agenda-include-diary "on" "off")))
6101 (defun org-agenda-toggle-time-grid ()
6102 "Toggle time grid in an agenda buffer."
6103 (interactive)
6104 (org-agenda-check-type t 'agenda)
6105 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
6106 (org-agenda-redo)
6107 (org-agenda-set-mode-name)
6108 (message "Time-grid turned %s"
6109 (if org-agenda-use-time-grid "on" "off")))
6111 (defun org-agenda-set-mode-name ()
6112 "Set the mode name to indicate all the small mode settings."
6113 (setq mode-name
6114 (concat "Org-Agenda"
6115 (if (equal org-agenda-ndays 1) " Day" "")
6116 (if (equal org-agenda-ndays 7) " Week" "")
6117 (if org-agenda-follow-mode " Follow" "")
6118 (if org-agenda-include-diary " Diary" "")
6119 (if org-agenda-use-time-grid " Grid" "")
6120 (if org-agenda-show-log " Log" "")))
6121 (force-mode-line-update))
6123 (defun org-agenda-post-command-hook ()
6124 (and (eolp) (not (bolp)) (backward-char 1))
6125 (if (and org-agenda-follow-mode
6126 (get-text-property (point) 'org-marker))
6127 (org-agenda-show)))
6129 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
6131 (defun org-get-entries-from-diary (date)
6132 "Get the (Emacs Calendar) diary entries for DATE."
6133 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
6134 (diary-display-hook '(fancy-diary-display))
6135 (list-diary-entries-hook
6136 (cons 'org-diary-default-entry list-diary-entries-hook))
6137 (diary-file-name-prefix-function nil) ; turn this feature off
6138 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
6139 entries
6140 (org-disable-agenda-to-diary t))
6141 (save-excursion
6142 (save-window-excursion
6143 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
6144 (if (not (get-buffer fancy-diary-buffer))
6145 (setq entries nil)
6146 (with-current-buffer fancy-diary-buffer
6147 (setq buffer-read-only nil)
6148 (if (= (point-max) 1)
6149 ;; No entries
6150 (setq entries nil)
6151 ;; Omit the date and other unnecessary stuff
6152 (org-agenda-cleanup-fancy-diary)
6153 ;; Add prefix to each line and extend the text properties
6154 (if (= (point-max) 1)
6155 (setq entries nil)
6156 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
6157 (set-buffer-modified-p nil)
6158 (kill-buffer fancy-diary-buffer)))
6159 (when entries
6160 (setq entries (org-split-string entries "\n"))
6161 (setq entries
6162 (mapcar
6163 (lambda (x)
6164 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
6165 ;; Extend the text properties to the beginning of the line
6166 (org-add-props x (text-properties-at (1- (length x)) x)))
6167 entries)))))
6169 (defun org-agenda-cleanup-fancy-diary ()
6170 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
6171 This gets rid of the date, the underline under the date, and
6172 the dummy entry installed by `org-mode' to ensure non-empty diary for each
6173 date. It also removes lines that contain only whitespace."
6174 (goto-char (point-min))
6175 (if (looking-at ".*?:[ \t]*")
6176 (progn
6177 (replace-match "")
6178 (re-search-forward "\n=+$" nil t)
6179 (replace-match "")
6180 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
6181 (re-search-forward "\n=+$" nil t)
6182 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
6183 (goto-char (point-min))
6184 (while (re-search-forward "^ +\n" nil t)
6185 (replace-match ""))
6186 (goto-char (point-min))
6187 (if (re-search-forward "^Org-mode dummy\n?" nil t)
6188 (replace-match "")))
6190 ;; Make sure entries from the diary have the right text properties.
6191 (eval-after-load "diary-lib"
6192 '(if (boundp 'diary-modify-entry-list-string-function)
6193 ;; We can rely on the hook, nothing to do
6195 ;; Hook not avaiable, must use advice to make this work
6196 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
6197 "Make the position visible."
6198 (if (and org-disable-agenda-to-diary ;; called from org-agenda
6199 (stringp string)
6200 buffer-file-name)
6201 (setq string (org-modify-diary-entry-string string))))))
6203 (defun org-modify-diary-entry-string (string)
6204 "Add text properties to string, allowing org-mode to act on it."
6205 (org-add-props string nil
6206 'mouse-face 'highlight
6207 'keymap org-agenda-keymap
6208 'help-echo (format "mouse-2 or RET jump to diary file %s"
6209 (abbreviate-file-name buffer-file-name))
6210 'org-agenda-diary-link t
6211 'org-marker (org-agenda-new-marker (point-at-bol))))
6213 (defun org-diary-default-entry ()
6214 "Add a dummy entry to the diary.
6215 Needed to avoid empty dates which mess up holiday display."
6216 ;; Catch the error if dealing with the new add-to-diary-alist
6217 (when org-disable-agenda-to-diary
6218 (condition-case nil
6219 (add-to-diary-list original-date "Org-mode dummy" "")
6220 (error
6221 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
6223 (defun org-cycle-agenda-files ()
6224 "Cycle through the files in `org-agenda-files'.
6225 If the current buffer visits an agenda file, find the next one in the list.
6226 If the current buffer does not, find the first agenda file."
6227 (interactive)
6228 (let* ((fs (org-agenda-files t))
6229 (files (append fs (list (car fs))))
6230 (tcf (if buffer-file-name (file-truename buffer-file-name)))
6231 file)
6232 (unless files (error "No agenda files"))
6233 (catch 'exit
6234 (while (setq file (pop files))
6235 (if (equal (file-truename file) tcf)
6236 (when (car files)
6237 (find-file (car files))
6238 (throw 'exit t))))
6239 (find-file (car fs)))))
6241 (defun org-agenda-file-to-end ()
6242 "Move/add the current file to the end of the agenda file list.
6243 If the file is not present in the list, it is appended to the list. If it is
6244 present, it is moved there."
6245 (interactive)
6246 (org-agenda-file-to-front 'to-end))
6248 (defun org-agenda-file-to-front (&optional to-end)
6249 "Move/add the current file to the top of the agenda file list.
6250 If the file is not present in the list, it is added to the front. If it is
6251 present, it is moved there. With optional argument TO-END, add/move to the
6252 end of the list."
6253 (interactive "P")
6254 (let ((file-alist (mapcar (lambda (x)
6255 (cons (file-truename x) x))
6256 (org-agenda-files t)))
6257 (ctf (file-truename buffer-file-name))
6258 x had)
6259 (setq x (assoc ctf file-alist) had x)
6261 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
6262 (if to-end
6263 (setq file-alist (append (delq x file-alist) (list x)))
6264 (setq file-alist (cons x (delq x file-alist))))
6265 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
6266 (org-install-agenda-files-menu)
6267 (message "File %s to %s of agenda file list"
6268 (if had "moved" "added") (if to-end "end" "front"))))
6270 (defun org-remove-file (&optional file)
6271 "Remove current file from the list of files in variable `org-agenda-files'.
6272 These are the files which are being checked for agenda entries.
6273 Optional argument FILE means, use this file instead of the current."
6274 (interactive)
6275 (let* ((file (or file buffer-file-name))
6276 (true-file (file-truename file))
6277 (afile (abbreviate-file-name file))
6278 (files (delq nil (mapcar
6279 (lambda (x)
6280 (if (equal true-file
6281 (file-truename x))
6282 nil x))
6283 (org-agenda-files t)))))
6284 (if (not (= (length files) (length (org-agenda-files t))))
6285 (progn
6286 (org-store-new-agenda-file-list files)
6287 (org-install-agenda-files-menu)
6288 (message "Removed file: %s" afile))
6289 (message "File was not in list: %s" afile))))
6291 (defun org-file-menu-entry (file)
6292 (vector file (list 'find-file file) t))
6294 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
6295 "Return a list of all relevant day numbers from BEG to END buffer positions.
6296 If NO-RANGES is non-nil, include only the start and end dates of a range,
6297 not every single day in the range. If FORCE-TODAY is non-nil, make
6298 sure that TODAY is included in the list. If INACTIVE is non-nil, also
6299 inactive time stamps (those in square brackets) are included.
6300 When EMPTY is non-nil, also include days without any entries."
6301 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
6302 dates dates1 date day day1 day2 ts1 ts2)
6303 (if force-today
6304 (setq dates (list (time-to-days (current-time)))))
6305 (save-excursion
6306 (goto-char beg)
6307 (while (re-search-forward re end t)
6308 (setq day (time-to-days (org-time-string-to-time
6309 (substring (match-string 1) 0 10))))
6310 (or (memq day dates) (push day dates)))
6311 (unless no-ranges
6312 (goto-char beg)
6313 (while (re-search-forward org-tr-regexp end t)
6314 (setq ts1 (substring (match-string 1) 0 10)
6315 ts2 (substring (match-string 2) 0 10)
6316 day1 (time-to-days (org-time-string-to-time ts1))
6317 day2 (time-to-days (org-time-string-to-time ts2)))
6318 (while (< (setq day1 (1+ day1)) day2)
6319 (or (memq day1 dates) (push day1 dates)))))
6320 (setq dates (sort dates '<))
6321 (when empty
6322 (while (setq day (pop dates))
6323 (setq day2 (car dates))
6324 (push day dates1)
6325 (when (and day2 empty)
6326 (if (or (eq empty t)
6327 (and (numberp empty) (<= (- day2 day) empty)))
6328 (while (< (setq day (1+ day)) day2)
6329 (push (list day) dates1))
6330 (push (cons :omitted (- day2 day)) dates1))))
6331 (setq dates (nreverse dates1)))
6332 dates)))
6334 ;;;###autoload
6335 (defun org-diary (&rest args)
6336 "Return diary information from org-files.
6337 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
6338 It accesses org files and extracts information from those files to be
6339 listed in the diary. The function accepts arguments specifying what
6340 items should be listed. The following arguments are allowed:
6342 :timestamp List the headlines of items containing a date stamp or
6343 date range matching the selected date. Deadlines will
6344 also be listed, on the expiration day.
6346 :deadline List any deadlines past due, or due within
6347 `org-deadline-warning-days'. The listing occurs only
6348 in the diary for *today*, not at any other date. If
6349 an entry is marked DONE, it is no longer listed.
6351 :scheduled List all items which are scheduled for the given date.
6352 The diary for *today* also contains items which were
6353 scheduled earlier and are not yet marked DONE.
6355 :todo List all TODO items from the org-file. This may be a
6356 long list - so this is not turned on by default.
6357 Like deadlines, these entries only show up in the
6358 diary for *today*, not at any other date.
6360 The call in the diary file should look like this:
6362 &%%(org-diary) ~/path/to/some/orgfile.org
6364 Use a separate line for each org file to check. Or, if you omit the file name,
6365 all files listed in `org-agenda-files' will be checked automatically:
6367 &%%(org-diary)
6369 If you don't give any arguments (as in the example above), the default
6370 arguments (:deadline :scheduled :timestamp) are used. So the example above may
6371 also be written as
6373 &%%(org-diary :deadline :timestamp :scheduled)
6375 The function expects the lisp variables `entry' and `date' to be provided
6376 by the caller, because this is how the calendar works. Don't use this
6377 function from a program - use `org-agenda-get-day-entries' instead."
6378 (org-agenda-maybe-reset-markers)
6379 (org-compile-prefix-format org-agenda-prefix-format)
6380 (setq args (or args '(:deadline :scheduled :timestamp)))
6381 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
6382 (list entry)
6383 (org-agenda-files t)))
6384 file rtn results)
6385 ;; If this is called during org-agenda, don't return any entries to
6386 ;; the calendar. Org Agenda will list these entries itself.
6387 (if org-disable-agenda-to-diary (setq files nil))
6388 (while (setq file (pop files))
6389 (setq rtn (apply 'org-agenda-get-day-entries file date args))
6390 (setq results (append results rtn)))
6391 (if results
6392 (concat (org-finalize-agenda-entries results) "\n"))))
6393 (defvar org-category-table nil)
6394 (defun org-get-category-table ()
6395 "Get the table of categories and positions in current buffer."
6396 (let (tbl)
6397 (save-excursion
6398 (goto-char (point-min))
6399 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
6400 (push (cons (point) (org-trim (match-string 2))) tbl)))
6401 tbl))
6402 (defun org-get-category (&optional pos)
6403 "Get the category applying to position POS."
6404 (if (not org-category-table)
6405 (cond
6406 ((null org-category)
6407 (setq org-category
6408 (if buffer-file-name
6409 (file-name-sans-extension
6410 (file-name-nondirectory buffer-file-name))
6411 "???")))
6412 ((symbolp org-category) (symbol-name org-category))
6413 (t org-category))
6414 (let ((tbl org-category-table)
6415 (pos (or pos (point))))
6416 (while (and tbl (> (caar tbl) pos))
6417 (pop tbl))
6418 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
6419 org-category-table))))))
6421 (defun org-agenda-get-day-entries (file date &rest args)
6422 "Does the work for `org-diary' and `org-agenda'.
6423 FILE is the path to a file to be checked for entries. DATE is date like
6424 the one returned by `calendar-current-date'. ARGS are symbols indicating
6425 which kind of entries should be extracted. For details about these, see
6426 the documentation of `org-diary'."
6427 (setq args (or args '(:deadline :scheduled :timestamp)))
6428 (let* ((org-startup-with-deadline-check nil)
6429 (org-startup-folded nil)
6430 (org-startup-align-all-tables nil)
6431 (buffer (if (file-exists-p file)
6432 (org-get-agenda-file-buffer file)
6433 (error "No such file %s" file)))
6434 arg results rtn)
6435 (if (not buffer)
6436 ;; If file does not exist, make sure an error message ends up in diary
6437 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
6438 (with-current-buffer buffer
6439 (unless (eq major-mode 'org-mode)
6440 (error "Agenda file %s is not in `org-mode'" file))
6441 (setq org-category-table (org-get-category-table))
6442 (let ((case-fold-search nil))
6443 (save-excursion
6444 (save-restriction
6445 (if org-respect-restriction
6446 (if (org-region-active-p)
6447 ;; Respect a region to restrict search
6448 (narrow-to-region (region-beginning) (region-end)))
6449 ;; If we work for the calendar or many files,
6450 ;; get rid of any restriction
6451 (widen))
6452 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
6453 (while (setq arg (pop args))
6454 (cond
6455 ((and (eq arg :todo)
6456 (equal date (calendar-current-date)))
6457 (setq rtn (org-agenda-get-todos))
6458 (setq results (append results rtn)))
6459 ((eq arg :timestamp)
6460 (setq rtn (org-agenda-get-blocks))
6461 (setq results (append results rtn))
6462 (setq rtn (org-agenda-get-timestamps))
6463 (setq results (append results rtn)))
6464 ((eq arg :scheduled)
6465 (setq rtn (org-agenda-get-scheduled))
6466 (setq results (append results rtn)))
6467 ((eq arg :closed)
6468 (setq rtn (org-agenda-get-closed))
6469 (setq results (append results rtn)))
6470 ((and (eq arg :deadline)
6471 (equal date (calendar-current-date)))
6472 (setq rtn (org-agenda-get-deadlines))
6473 (setq results (append results rtn))))))))
6474 results))))
6476 (defun org-entry-is-done-p ()
6477 "Is the current entry marked DONE?"
6478 (save-excursion
6479 (and (re-search-backward "[\r\n]\\*" nil t)
6480 (looking-at org-nl-done-regexp))))
6482 (defun org-at-date-range-p ()
6483 "Is the cursor inside a date range?"
6484 (interactive)
6485 (save-excursion
6486 (catch 'exit
6487 (let ((pos (point)))
6488 (skip-chars-backward "^<\r\n")
6489 (skip-chars-backward "<")
6490 (and (looking-at org-tr-regexp)
6491 (>= (match-end 0) pos)
6492 (throw 'exit t))
6493 (skip-chars-backward "^<\r\n")
6494 (skip-chars-backward "<")
6495 (and (looking-at org-tr-regexp)
6496 (>= (match-end 0) pos)
6497 (throw 'exit t)))
6498 nil)))
6500 (defun org-agenda-get-todos ()
6501 "Return the TODO information for agenda display."
6502 (let* ((props (list 'face nil
6503 'done-face 'org-done
6504 'org-not-done-regexp org-not-done-regexp
6505 'mouse-face 'highlight
6506 'keymap org-agenda-keymap
6507 'help-echo
6508 (format "mouse-2 or RET jump to org file %s"
6509 (abbreviate-file-name buffer-file-name))))
6510 (regexp (concat "[\n\r]\\*+ *\\("
6511 (if org-select-this-todo-keyword
6512 (concat "\\<\\(" org-select-this-todo-keyword
6513 "\\)\\>")
6514 org-not-done-regexp)
6515 "[^\n\r]*\\)"))
6516 (sched-re (concat ".*\n?.*?" org-scheduled-time-regexp))
6517 marker priority category tags
6518 ee txt)
6519 (goto-char (point-min))
6520 (while (re-search-forward regexp nil t)
6521 (when (not (and org-agenda-todo-ignore-scheduled
6522 (save-match-data (looking-at sched-re))))
6523 (goto-char (match-beginning 1))
6524 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
6525 category (org-get-category)
6526 tags (org-get-tags-at (point))
6527 txt (org-format-agenda-item "" (match-string 1) category tags)
6528 priority
6529 (+ (org-get-priority txt)
6530 (if org-todo-kwd-priority-p
6531 (- org-todo-kwd-max-priority -2
6532 (length
6533 (member (match-string 2) org-todo-keywords)))
6534 1)))
6535 (org-add-props txt props
6536 'org-marker marker 'org-hd-marker marker
6537 'priority priority 'category category)
6538 (push txt ee))
6539 (if org-agenda-todo-list-sublevels
6540 (goto-char (match-end 1))
6541 (org-end-of-subtree 'invisible)))
6542 (nreverse ee)))
6544 (defconst org-agenda-no-heading-message
6545 "No heading for this item in buffer or region.")
6547 (defun org-agenda-get-timestamps ()
6548 "Return the date stamp information for agenda display."
6549 (let* ((props (list 'face nil
6550 'org-not-done-regexp org-not-done-regexp
6551 'mouse-face 'highlight
6552 'keymap org-agenda-keymap
6553 'help-echo
6554 (format "mouse-2 or RET jump to org file %s"
6555 (abbreviate-file-name buffer-file-name))))
6556 (regexp (regexp-quote
6557 (substring
6558 (format-time-string
6559 (car org-time-stamp-formats)
6560 (apply 'encode-time ; DATE bound by calendar
6561 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
6562 0 11)))
6563 marker hdmarker deadlinep scheduledp donep tmp priority category
6564 ee txt timestr tags)
6565 (goto-char (point-min))
6566 (while (re-search-forward regexp nil t)
6567 (if (not (save-match-data (org-at-date-range-p)))
6568 (progn
6569 (setq marker (org-agenda-new-marker (match-beginning 0))
6570 category (org-get-category (match-beginning 0))
6571 tmp (buffer-substring (max (point-min)
6572 (- (match-beginning 0)
6573 org-ds-keyword-length))
6574 (match-beginning 0))
6575 timestr (buffer-substring (match-beginning 0) (point-at-eol))
6576 deadlinep (string-match org-deadline-regexp tmp)
6577 scheduledp (string-match org-scheduled-regexp tmp)
6578 donep (org-entry-is-done-p))
6579 (if (string-match ">" timestr)
6580 ;; substring should only run to end of time stamp
6581 (setq timestr (substring timestr 0 (match-end 0))))
6582 (save-excursion
6583 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6584 (progn
6585 (goto-char (match-end 1))
6586 (setq hdmarker (org-agenda-new-marker)
6587 tags (org-get-tags-at))
6588 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6589 (setq txt (org-format-agenda-item
6590 (format "%s%s"
6591 (if deadlinep "Deadline: " "")
6592 (if scheduledp "Scheduled: " ""))
6593 (match-string 1) category tags timestr)))
6594 (setq txt org-agenda-no-heading-message))
6595 (setq priority (org-get-priority txt))
6596 (org-add-props txt props
6597 'org-marker marker 'org-hd-marker hdmarker)
6598 (if deadlinep
6599 (org-add-props txt nil
6600 'face (if donep 'org-done 'org-warning)
6601 'undone-face 'org-warning 'done-face 'org-done
6602 'category category 'priority (+ 100 priority))
6603 (if scheduledp
6604 (org-add-props txt nil
6605 'face 'org-scheduled-today
6606 'undone-face 'org-scheduled-today 'done-face 'org-done
6607 'category category 'priority (+ 99 priority))
6608 (org-add-props txt nil 'priority priority 'category category)))
6609 (push txt ee))
6610 (outline-next-heading))))
6611 (nreverse ee)))
6613 (defun org-agenda-get-closed ()
6614 "Return the logged TODO entries for agenda display."
6615 (let* ((props (list 'mouse-face 'highlight
6616 'org-not-done-regexp org-not-done-regexp
6617 'keymap org-agenda-keymap
6618 'help-echo
6619 (format "mouse-2 or RET jump to org file %s"
6620 (abbreviate-file-name buffer-file-name))))
6621 (regexp (concat
6622 "\\<" org-closed-string " *\\["
6623 (regexp-quote
6624 (substring
6625 (format-time-string
6626 (car org-time-stamp-formats)
6627 (apply 'encode-time ; DATE bound by calendar
6628 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
6629 1 11))))
6630 marker hdmarker priority category tags
6631 ee txt timestr)
6632 (goto-char (point-min))
6633 (while (re-search-forward regexp nil t)
6634 (if (not (save-match-data (org-at-date-range-p)))
6635 (progn
6636 (setq marker (org-agenda-new-marker (match-beginning 0))
6637 category (org-get-category (match-beginning 0))
6638 timestr (buffer-substring (match-beginning 0) (point-at-eol))
6639 ;; donep (org-entry-is-done-p)
6641 (if (string-match "\\]" timestr)
6642 ;; substring should only run to end of time stamp
6643 (setq timestr (substring timestr 0 (match-end 0))))
6644 (save-excursion
6645 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6646 (progn
6647 (goto-char (match-end 1))
6648 (setq hdmarker (org-agenda-new-marker)
6649 tags (org-get-tags-at))
6650 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6651 (setq txt (org-format-agenda-item
6652 "Closed: "
6653 (match-string 1) category tags timestr)))
6654 (setq txt org-agenda-no-heading-message))
6655 (setq priority 100000)
6656 (org-add-props txt props
6657 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
6658 'priority priority 'category category
6659 'undone-face 'org-warning 'done-face 'org-done)
6660 (push txt ee))
6661 (outline-next-heading))))
6662 (nreverse ee)))
6664 (defun org-agenda-get-deadlines ()
6665 "Return the deadline information for agenda display."
6666 (let* ((wdays org-deadline-warning-days)
6667 (props (list 'mouse-face 'highlight
6668 'org-not-done-regexp org-not-done-regexp
6669 'keymap org-agenda-keymap
6670 'help-echo
6671 (format "mouse-2 or RET jump to org file %s"
6672 (abbreviate-file-name buffer-file-name))))
6673 (regexp org-deadline-time-regexp)
6674 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
6675 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
6676 d2 diff pos pos1 category tags
6677 ee txt head face)
6678 (goto-char (point-min))
6679 (while (re-search-forward regexp nil t)
6680 (setq pos (1- (match-beginning 1))
6681 d2 (time-to-days
6682 (org-time-string-to-time (match-string 1)))
6683 diff (- d2 d1))
6684 ;; When to show a deadline in the calendar:
6685 ;; If the expiration is within wdays warning time.
6686 ;; Past-due deadlines are only shown on the current date
6687 (if (and (< diff wdays) todayp (not (= diff 0)))
6688 (save-excursion
6689 (setq category (org-get-category))
6690 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
6691 (progn
6692 (goto-char (match-end 0))
6693 (setq pos1 (match-end 1))
6694 (setq tags (org-get-tags-at pos1))
6695 (setq head (buffer-substring-no-properties
6696 (point)
6697 (progn (skip-chars-forward "^\r\n")
6698 (point))))
6699 (if (string-match org-looking-at-done-regexp head)
6700 (setq txt nil)
6701 (setq txt (org-format-agenda-item
6702 (format "In %3d d.: " diff) head category tags))))
6703 (setq txt org-agenda-no-heading-message))
6704 (when txt
6705 (setq face (cond ((<= diff 0) 'org-warning)
6706 ((<= diff 5) 'org-upcoming-deadline)
6707 (t nil)))
6708 (org-add-props txt props
6709 'org-marker (org-agenda-new-marker pos)
6710 'org-hd-marker (org-agenda-new-marker pos1)
6711 'priority (+ (- 10 diff) (org-get-priority txt))
6712 'category category
6713 'face face 'undone-face face 'done-face 'org-done)
6714 (push txt ee)))))
6715 ee))
6717 (defun org-agenda-get-scheduled ()
6718 "Return the scheduled information for agenda display."
6719 (let* ((props (list 'face 'org-scheduled-previously
6720 'org-not-done-regexp org-not-done-regexp
6721 'undone-face 'org-scheduled-previously
6722 'done-face 'org-done
6723 'mouse-face 'highlight
6724 'keymap org-agenda-keymap
6725 'help-echo
6726 (format "mouse-2 or RET jump to org file %s"
6727 (abbreviate-file-name buffer-file-name))))
6728 (regexp org-scheduled-time-regexp)
6729 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
6730 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
6731 d2 diff pos pos1 category tags
6732 ee txt head)
6733 (goto-char (point-min))
6734 (while (re-search-forward regexp nil t)
6735 (setq pos (1- (match-beginning 1))
6736 d2 (time-to-days
6737 (org-time-string-to-time (match-string 1)))
6738 diff (- d2 d1))
6739 ;; When to show a scheduled item in the calendar:
6740 ;; If it is on or past the date.
6741 (if (and (< diff 0) todayp)
6742 (save-excursion
6743 (setq category (org-get-category))
6744 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
6745 (progn
6746 (goto-char (match-end 0))
6747 (setq pos1 (match-end 1))
6748 (setq tags (org-get-tags-at))
6749 (setq head (buffer-substring-no-properties
6750 (point)
6751 (progn (skip-chars-forward "^\r\n") (point))))
6752 (if (string-match org-looking-at-done-regexp head)
6753 (setq txt nil)
6754 (setq txt (org-format-agenda-item
6755 (format "Sched.%2dx: " (- 1 diff)) head
6756 category tags))))
6757 (setq txt org-agenda-no-heading-message))
6758 (when txt
6759 (org-add-props txt props
6760 'org-marker (org-agenda-new-marker pos)
6761 'org-hd-marker (org-agenda-new-marker pos1)
6762 'priority (+ (- 5 diff) (org-get-priority txt))
6763 'category category)
6764 (push txt ee)))))
6765 ee))
6767 (defun org-agenda-get-blocks ()
6768 "Return the date-range information for agenda display."
6769 (let* ((props (list 'face nil
6770 'org-not-done-regexp org-not-done-regexp
6771 'mouse-face 'highlight
6772 'keymap org-agenda-keymap
6773 'help-echo
6774 (format "mouse-2 or RET jump to org file %s"
6775 (abbreviate-file-name buffer-file-name))))
6776 (regexp org-tr-regexp)
6777 (d0 (calendar-absolute-from-gregorian date))
6778 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
6779 (goto-char (point-min))
6780 (while (re-search-forward regexp nil t)
6781 (setq timestr (match-string 0)
6782 s1 (match-string 1)
6783 s2 (match-string 2)
6784 d1 (time-to-days (org-time-string-to-time s1))
6785 d2 (time-to-days (org-time-string-to-time s2)))
6786 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
6787 ;; Only allow days between the limits, because the normal
6788 ;; date stamps will catch the limits.
6789 (save-excursion
6790 (setq marker (org-agenda-new-marker (point)))
6791 (setq category (org-get-category))
6792 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6793 (progn
6794 (setq hdmarker (org-agenda-new-marker (match-end 1)))
6795 (goto-char (match-end 1))
6796 (setq tags (org-get-tags-at))
6797 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6798 (setq txt (org-format-agenda-item
6799 (format (if (= d1 d2) "" "(%d/%d): ")
6800 (1+ (- d0 d1)) (1+ (- d2 d1)))
6801 (match-string 1) category tags
6802 (if (= d0 d1) timestr))))
6803 (setq txt org-agenda-no-heading-message))
6804 (org-add-props txt props
6805 'org-marker marker 'org-hd-marker hdmarker
6806 'priority (org-get-priority txt) 'category category)
6807 (push txt ee)))
6808 (outline-next-heading))
6809 ;; Sort the entries by expiration date.
6810 (nreverse ee)))
6812 (defconst org-plain-time-of-day-regexp
6813 (concat
6814 "\\(\\<[012]?[0-9]"
6815 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
6816 "\\(--?"
6817 "\\(\\<[012]?[0-9]"
6818 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
6819 "\\)?")
6820 "Regular expression to match a plain time or time range.
6821 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
6822 groups carry important information:
6823 0 the full match
6824 1 the first time, range or not
6825 8 the second time, if it is a range.")
6827 (defconst org-stamp-time-of-day-regexp
6828 (concat
6829 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
6830 "\\([012][0-9]:[0-5][0-9]\\)>"
6831 "\\(--?"
6832 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
6833 "Regular expression to match a timestamp time or time range.
6834 After a match, the following groups carry important information:
6835 0 the full match
6836 1 date plus weekday, for backreferencing to make sure both times on same day
6837 2 the first time, range or not
6838 4 the second time, if it is a range.")
6840 (defvar org-prefix-has-time nil
6841 "A flag, set by `org-compile-prefix-format'.
6842 The flag is set if the currently compiled format contains a `%t'.")
6843 (defvar org-prefix-has-tag nil
6844 "A flag, set by `org-compile-prefix-format'.
6845 The flag is set if the currently compiled format contains a `%T'.")
6847 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
6848 "Format TXT to be inserted into the agenda buffer.
6849 In particular, it adds the prefix and corresponding text properties. EXTRA
6850 must be a string and replaces the `%s' specifier in the prefix format.
6851 CATEGORY (string, symbol or nil) may be used to overrule the default
6852 category taken from local variable or file name. It will replace the `%c'
6853 specifier in the format. DOTIME, when non-nil, indicates that a
6854 time-of-day should be extracted from TXT for sorting of this entry, and for
6855 the `%t' specifier in the format. When DOTIME is a string, this string is
6856 searched for a time before TXT is. NOPREFIX is a flag and indicates that
6857 only the correctly processes TXT should be returned - this is used by
6858 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
6859 (save-match-data
6860 ;; Diary entries sometimes have extra whitespace at the beginning
6861 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
6862 (let* ((category (or category
6863 org-category
6864 (if buffer-file-name
6865 (file-name-sans-extension
6866 (file-name-nondirectory buffer-file-name))
6867 "")))
6868 (tag (if tags (nth (1- (length tags)) tags) ""))
6869 time ;; needed for the eval of the prefix format
6870 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
6871 (time-of-day (and dotime (org-get-time-of-day ts)))
6872 stamp plain s0 s1 s2 rtn)
6873 (when (and dotime time-of-day org-prefix-has-time)
6874 ;; Extract starting and ending time and move them to prefix
6875 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
6876 (setq plain (string-match org-plain-time-of-day-regexp ts)))
6877 (setq s0 (match-string 0 ts)
6878 s1 (match-string (if plain 1 2) ts)
6879 s2 (match-string (if plain 8 4) ts))
6881 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
6882 ;; them, we might want to remove them there to avoid duplication.
6883 ;; The user can turn this off with a variable.
6884 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
6885 (string-match (concat (regexp-quote s0) " *") txt)
6886 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
6887 (= (match-beginning 0) 0)
6889 (setq txt (replace-match "" nil nil txt))))
6890 ;; Normalize the time(s) to 24 hour
6891 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
6892 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
6894 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
6895 ;; Tags are in the string
6896 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
6897 (and org-agenda-remove-tags-when-in-prefix
6898 org-prefix-has-tag))
6899 (setq txt (replace-match "" t t txt))
6900 (setq txt (replace-match
6901 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
6902 (match-string 2 txt))
6903 t t txt))))
6905 ;; Create the final string
6906 (if noprefix
6907 (setq rtn txt)
6908 ;; Prepare the variables needed in the eval of the compiled format
6909 (setq time (cond (s2 (concat s1 "-" s2))
6910 (s1 (concat s1 "......"))
6911 (t ""))
6912 extra (or extra "")
6913 category (if (symbolp category) (symbol-name category) category))
6914 ;; Evaluate the compiled format
6915 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
6917 ;; And finally add the text properties
6918 (org-add-props rtn nil
6919 'category (downcase category) 'tags tags
6920 'prefix-length (- (length rtn) (length txt))
6921 'time-of-day time-of-day
6922 'dotime dotime))))
6924 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
6925 (catch 'exit
6926 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
6927 ((and todayp (member 'today (car org-agenda-time-grid))))
6928 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
6929 ((member 'weekly (car org-agenda-time-grid)))
6930 (t (throw 'exit list)))
6931 (let* ((have (delq nil (mapcar
6932 (lambda (x) (get-text-property 1 'time-of-day x))
6933 list)))
6934 (string (nth 1 org-agenda-time-grid))
6935 (gridtimes (nth 2 org-agenda-time-grid))
6936 (req (car org-agenda-time-grid))
6937 (remove (member 'remove-match req))
6938 new time)
6939 (if (and (member 'require-timed req) (not have))
6940 ;; don't show empty grid
6941 (throw 'exit list))
6942 (while (setq time (pop gridtimes))
6943 (unless (and remove (member time have))
6944 (setq time (int-to-string time))
6945 (push (org-format-agenda-item
6946 nil string "" nil
6947 (concat (substring time 0 -2) ":" (substring time -2)))
6948 new)
6949 (put-text-property
6950 1 (length (car new)) 'face 'org-time-grid (car new))))
6951 (if (member 'time-up org-agenda-sorting-strategy)
6952 (append new list)
6953 (append list new)))))
6955 (defun org-compile-prefix-format (format)
6956 "Compile the prefix format into a Lisp form that can be evaluated.
6957 The resulting form is returned and stored in the variable
6958 `org-prefix-format-compiled'."
6959 (setq org-prefix-has-time nil org-prefix-has-tag nil)
6960 (let ((start 0) varform vars var (s format)e c f opt)
6961 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
6962 s start)
6963 (setq var (cdr (assoc (match-string 4 s)
6964 '(("c" . category) ("t" . time) ("s" . extra)
6965 ("T" . tag))))
6966 c (or (match-string 3 s) "")
6967 opt (match-beginning 1)
6968 start (1+ (match-beginning 0)))
6969 (if (equal var 'time) (setq org-prefix-has-time t))
6970 (if (equal var 'tag) (setq org-prefix-has-tag t))
6971 (setq f (concat "%" (match-string 2 s) "s"))
6972 (if opt
6973 (setq varform
6974 `(if (equal "" ,var)
6976 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
6977 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
6978 (setq s (replace-match "%s" t nil s))
6979 (push varform vars))
6980 (setq vars (nreverse vars))
6981 (setq org-prefix-format-compiled `(format ,s ,@vars))))
6983 (defun org-get-time-of-day (s &optional string mod24)
6984 "Check string S for a time of day.
6985 If found, return it as a military time number between 0 and 2400.
6986 If not found, return nil.
6987 The optional STRING argument forces conversion into a 5 character wide string
6988 HH:MM."
6989 (save-match-data
6990 (when
6992 (string-match
6993 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
6994 (string-match
6995 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
6996 (let* ((h (string-to-number (match-string 1 s)))
6997 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
6998 (ampm (if (match-end 4) (downcase (match-string 4 s))))
6999 (am-p (equal ampm "am"))
7000 (h1 (cond ((not ampm) h)
7001 ((= h 12) (if am-p 0 12))
7002 (t (+ h (if am-p 0 12)))))
7003 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
7004 (mod h1 24) h1))
7005 (t0 (+ (* 100 h2) m))
7006 (t1 (concat (if (>= h1 24) "+" " ")
7007 (if (< t0 100) "0" "")
7008 (if (< t0 10) "0" "")
7009 (int-to-string t0))))
7010 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
7012 (defun org-finalize-agenda-entries (list)
7013 "Sort and concatenate the agenda items."
7014 (setq list (mapcar 'org-agenda-highlight-todo list))
7015 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
7017 (defun org-agenda-highlight-todo (x)
7018 (let (re pl)
7019 (if (eq x 'line)
7020 (save-excursion
7021 (beginning-of-line 1)
7022 (setq re (get-text-property (point) 'org-not-done-regexp))
7023 (goto-char (+ (point) (get-text-property (point) 'prefix-length)))
7024 (and (looking-at (concat "[ \t]*" re))
7025 (add-text-properties (match-beginning 0) (match-end 0)
7026 '(face org-todo))))
7027 (setq re (get-text-property 0 'org-not-done-regexp x)
7028 pl (get-text-property 0 'prefix-length x))
7029 (and re (equal (string-match re x pl) pl)
7030 (add-text-properties (match-beginning 0) (match-end 0)
7031 '(face org-todo) x))
7032 x)))
7034 (defsubst org-cmp-priority (a b)
7035 "Compare the priorities of string A and B."
7036 (let ((pa (or (get-text-property 1 'priority a) 0))
7037 (pb (or (get-text-property 1 'priority b) 0)))
7038 (cond ((> pa pb) +1)
7039 ((< pa pb) -1)
7040 (t nil))))
7042 (defsubst org-cmp-category (a b)
7043 "Compare the string values of categories of strings A and B."
7044 (let ((ca (or (get-text-property 1 'category a) ""))
7045 (cb (or (get-text-property 1 'category b) "")))
7046 (cond ((string-lessp ca cb) -1)
7047 ((string-lessp cb ca) +1)
7048 (t nil))))
7050 (defsubst org-cmp-time (a b)
7051 "Compare the time-of-day values of strings A and B."
7052 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
7053 (ta (or (get-text-property 1 'time-of-day a) def))
7054 (tb (or (get-text-property 1 'time-of-day b) def)))
7055 (cond ((< ta tb) -1)
7056 ((< tb ta) +1)
7057 (t nil))))
7059 (defun org-entries-lessp (a b)
7060 "Predicate for sorting agenda entries."
7061 ;; The following variables will be used when the form is evaluated.
7062 (let* ((time-up (org-cmp-time a b))
7063 (time-down (if time-up (- time-up) nil))
7064 (priority-up (org-cmp-priority a b))
7065 (priority-down (if priority-up (- priority-up) nil))
7066 (category-up (org-cmp-category a b))
7067 (category-down (if category-up (- category-up) nil))
7068 (category-keep (if category-up +1 nil)))
7069 (cdr (assoc
7070 (eval (cons 'or org-agenda-sorting-strategy))
7071 '((-1 . t) (1 . nil) (nil . nil))))))
7073 (defun org-agenda-show-priority ()
7074 "Show the priority of the current item.
7075 This priority is composed of the main priority given with the [#A] cookies,
7076 and by additional input from the age of a schedules or deadline entry."
7077 (interactive)
7078 (let* ((pri (get-text-property (point-at-bol) 'priority)))
7079 (message "Priority is %d" (if pri pri -1000))))
7081 (defun org-agenda-show-tags ()
7082 "Show the tags applicable to the current item."
7083 (interactive)
7084 (let* ((tags (get-text-property (point-at-bol) 'tags)))
7085 (if tags
7086 (message "Tags are :%s:"
7087 (org-no-properties (mapconcat 'identity tags ":")))
7088 (message "No tags associated with this line"))))
7090 (defun org-agenda-goto (&optional highlight)
7091 "Go to the Org-mode file which contains the item at point."
7092 (interactive)
7093 (let* ((marker (or (get-text-property (point) 'org-marker)
7094 (org-agenda-error)))
7095 (buffer (marker-buffer marker))
7096 (pos (marker-position marker)))
7097 (switch-to-buffer-other-window buffer)
7098 (widen)
7099 (goto-char pos)
7100 (when (eq major-mode 'org-mode)
7101 (org-show-hidden-entry)
7102 (save-excursion
7103 (and (outline-next-heading)
7104 (org-flag-heading nil)))) ; show the next heading
7105 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
7107 (defun org-agenda-switch-to ()
7108 "Go to the Org-mode file which contains the item at point."
7109 (interactive)
7110 (let* ((marker (or (get-text-property (point) 'org-marker)
7111 (org-agenda-error)))
7112 (buffer (marker-buffer marker))
7113 (pos (marker-position marker)))
7114 (switch-to-buffer buffer)
7115 (delete-other-windows)
7116 (widen)
7117 (goto-char pos)
7118 (when (eq major-mode 'org-mode)
7119 (org-show-hidden-entry)
7120 (save-excursion
7121 (and (outline-next-heading)
7122 (org-flag-heading nil)))))) ; show the next heading
7124 (defun org-agenda-goto-mouse (ev)
7125 "Go to the Org-mode file which contains the item at the mouse click."
7126 (interactive "e")
7127 (mouse-set-point ev)
7128 (org-agenda-goto))
7130 (defun org-agenda-show ()
7131 "Display the Org-mode file which contains the item at point."
7132 (interactive)
7133 (let ((win (selected-window)))
7134 (org-agenda-goto t)
7135 (select-window win)))
7137 (defun org-agenda-recenter (arg)
7138 "Display the Org-mode file which contains the item at point and recenter."
7139 (interactive "P")
7140 (let ((win (selected-window)))
7141 (org-agenda-goto t)
7142 (recenter arg)
7143 (select-window win)))
7145 (defun org-agenda-show-mouse (ev)
7146 "Display the Org-mode file which contains the item at the mouse click."
7147 (interactive "e")
7148 (mouse-set-point ev)
7149 (org-agenda-show))
7151 (defun org-agenda-check-no-diary ()
7152 "Check if the entry is a diary link and abort if yes."
7153 (if (get-text-property (point) 'org-agenda-diary-link)
7154 (org-agenda-error)))
7156 (defun org-agenda-error ()
7157 (error "Command not allowed in this line"))
7159 (defvar org-last-heading-marker (make-marker)
7160 "Marker pointing to the headline that last changed its TODO state
7161 by a remote command from the agenda.")
7163 (defun org-agenda-todo (&optional arg)
7164 "Cycle TODO state of line at point, also in Org-mode file.
7165 This changes the line at point, all other lines in the agenda referring to
7166 the same tree node, and the headline of the tree node in the Org-mode file."
7167 (interactive "P")
7168 (org-agenda-check-no-diary)
7169 (let* ((col (current-column))
7170 (marker (or (get-text-property (point) 'org-marker)
7171 (org-agenda-error)))
7172 (buffer (marker-buffer marker))
7173 (pos (marker-position marker))
7174 (hdmarker (get-text-property (point) 'org-hd-marker))
7175 (buffer-read-only nil)
7176 newhead)
7177 (with-current-buffer buffer
7178 (widen)
7179 (goto-char pos)
7180 (org-show-hidden-entry)
7181 (save-excursion
7182 (and (outline-next-heading)
7183 (org-flag-heading nil))) ; show the next heading
7184 (org-todo arg)
7185 (and (bolp) (forward-char 1))
7186 (setq newhead (org-get-heading))
7187 (save-excursion
7188 (org-back-to-heading)
7189 (move-marker org-last-heading-marker (point))))
7190 (beginning-of-line 1)
7191 (save-excursion
7192 (org-agenda-change-all-lines newhead hdmarker 'fixface))
7193 (move-to-column col)))
7195 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
7196 "Change all lines in the agenda buffer which match HDMARKER.
7197 The new content of the line will be NEWHEAD (as modified by
7198 `org-format-agenda-item'). HDMARKER is checked with
7199 `equal' against all `org-hd-marker' text properties in the file.
7200 If FIXFACE is non-nil, the face of each item is modified acording to
7201 the new TODO state."
7202 (let* (props m pl undone-face done-face finish new dotime cat tags)
7203 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
7204 (save-excursion
7205 (goto-char (point-max))
7206 (beginning-of-line 1)
7207 (while (not finish)
7208 (setq finish (bobp))
7209 (when (and (setq m (get-text-property (point) 'org-hd-marker))
7210 (equal m hdmarker))
7211 (setq props (text-properties-at (point))
7212 dotime (get-text-property (point) 'dotime)
7213 cat (get-text-property (point) 'category)
7214 tags (get-text-property (point) 'tags)
7215 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
7216 pl (get-text-property (point) 'prefix-length)
7217 undone-face (get-text-property (point) 'undone-face)
7218 done-face (get-text-property (point) 'done-face))
7219 (move-to-column pl)
7220 (if (looking-at ".*")
7221 (progn
7222 (replace-match new t t)
7223 (beginning-of-line 1)
7224 (add-text-properties (point-at-bol) (point-at-eol) props)
7225 (when fixface
7226 (add-text-properties
7227 (point-at-bol) (point-at-eol)
7228 (list 'face
7229 (if org-last-todo-state-is-todo
7230 undone-face done-face)))
7231 (org-agenda-highlight-todo 'line))
7232 (beginning-of-line 1))
7233 (error "Line update did not work")))
7234 (beginning-of-line 0)))))
7236 (defun org-agenda-priority-up ()
7237 "Increase the priority of line at point, also in Org-mode file."
7238 (interactive)
7239 (org-agenda-priority 'up))
7241 (defun org-agenda-priority-down ()
7242 "Decrease the priority of line at point, also in Org-mode file."
7243 (interactive)
7244 (org-agenda-priority 'down))
7246 (defun org-agenda-priority (&optional force-direction)
7247 "Set the priority of line at point, also in Org-mode file.
7248 This changes the line at point, all other lines in the agenda referring to
7249 the same tree node, and the headline of the tree node in the Org-mode file."
7250 (interactive)
7251 (org-agenda-check-no-diary)
7252 (let* ((marker (or (get-text-property (point) 'org-marker)
7253 (org-agenda-error)))
7254 (buffer (marker-buffer marker))
7255 (pos (marker-position marker))
7256 (hdmarker (get-text-property (point) 'org-hd-marker))
7257 (buffer-read-only nil)
7258 newhead)
7259 (with-current-buffer buffer
7260 (widen)
7261 (goto-char pos)
7262 (org-show-hidden-entry)
7263 (save-excursion
7264 (and (outline-next-heading)
7265 (org-flag-heading nil))) ; show the next heading
7266 (funcall 'org-priority force-direction)
7267 (end-of-line 1)
7268 (setq newhead (org-get-heading)))
7269 (org-agenda-change-all-lines newhead hdmarker)
7270 (beginning-of-line 1)))
7272 (defun org-get-tags-at (&optional pos)
7273 "Get a list of all headline tags applicable at POS.
7274 POS defaults to point. If tags are inherited, the list contains
7275 the targets in the same sequence as the headlines appear, i.e.
7276 the tags of the current headline come last."
7277 (interactive)
7278 (let (tags)
7279 (save-excursion
7280 (goto-char (or pos (point)))
7281 (save-match-data
7282 (org-back-to-heading t)
7283 (condition-case nil
7284 (while t
7285 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
7286 (setq tags (append (org-split-string
7287 (org-match-string-no-properties 1) ":")
7288 tags)))
7289 (or org-use-tag-inheritance (error ""))
7290 (org-up-heading-all 1))
7291 (error nil))))
7292 (message "%s" tags)
7293 tags))
7295 (defun org-agenda-set-tags ()
7296 "Set tags for the current headline."
7297 (interactive)
7298 (org-agenda-check-no-diary)
7299 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
7300 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
7301 (org-agenda-error)))
7302 (buffer (marker-buffer hdmarker))
7303 (pos (marker-position hdmarker))
7304 (buffer-read-only nil)
7305 newhead)
7306 (with-current-buffer buffer
7307 (widen)
7308 (goto-char pos)
7309 (org-show-hidden-entry)
7310 (save-excursion
7311 (and (outline-next-heading)
7312 (org-flag-heading nil))) ; show the next heading
7313 (call-interactively 'org-set-tags)
7314 (end-of-line 1)
7315 (setq newhead (org-get-heading)))
7316 (org-agenda-change-all-lines newhead hdmarker)
7317 (beginning-of-line 1)))
7319 (defun org-agenda-date-later (arg &optional what)
7320 "Change the date of this item to one day later."
7321 (interactive "p")
7322 (org-agenda-check-type t 'agenda 'timeline)
7323 (org-agenda-check-no-diary)
7324 (let* ((marker (or (get-text-property (point) 'org-marker)
7325 (org-agenda-error)))
7326 (buffer (marker-buffer marker))
7327 (pos (marker-position marker)))
7328 (with-current-buffer buffer
7329 (widen)
7330 (goto-char pos)
7331 (if (not (org-at-timestamp-p))
7332 (error "Cannot find time stamp"))
7333 (org-timestamp-change arg (or what 'day))
7334 (message "Time stamp changed to %s" org-last-changed-timestamp))))
7336 (defun org-agenda-date-earlier (arg &optional what)
7337 "Change the date of this item to one day earlier."
7338 (interactive "p")
7339 (org-agenda-date-later (- arg) what))
7341 (defun org-agenda-date-prompt (arg)
7342 "Change the date of this item. Date is prompted for, with default today.
7343 The prefix ARG is passed to the `org-time-stamp' command and can therefore
7344 be used to request time specification in the time stamp."
7345 (interactive "P")
7346 (org-agenda-check-type t 'agenda 'timeline)
7347 (org-agenda-check-no-diary)
7348 (let* ((marker (or (get-text-property (point) 'org-marker)
7349 (org-agenda-error)))
7350 (buffer (marker-buffer marker))
7351 (pos (marker-position marker)))
7352 (with-current-buffer buffer
7353 (widen)
7354 (goto-char pos)
7355 (if (not (org-at-timestamp-p))
7356 (error "Cannot find time stamp"))
7357 (org-time-stamp arg)
7358 (message "Time stamp changed to %s" org-last-changed-timestamp))))
7360 (defun org-agenda-schedule (arg)
7361 "Schedule the item at point."
7362 (interactive "P")
7363 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
7364 (org-agenda-check-no-diary)
7365 (let* ((marker (or (get-text-property (point) 'org-marker)
7366 (org-agenda-error)))
7367 (buffer (marker-buffer marker))
7368 (pos (marker-position marker))
7369 (org-insert-labeled-timestamps-at-point nil)
7371 (with-current-buffer buffer
7372 (widen)
7373 (goto-char pos)
7374 (setq ts (org-schedule))
7375 (message "Item scheduled for %s" ts))))
7377 (defun org-agenda-deadline (arg)
7378 "Schedule the item at point."
7379 (interactive "P")
7380 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
7381 (org-agenda-check-no-diary)
7382 (let* ((marker (or (get-text-property (point) 'org-marker)
7383 (org-agenda-error)))
7384 (buffer (marker-buffer marker))
7385 (pos (marker-position marker))
7386 (org-insert-labeled-timestamps-at-point nil)
7388 (with-current-buffer buffer
7389 (widen)
7390 (goto-char pos)
7391 (setq ts (org-deadline))
7392 (message "Deadline for this item set to %s" ts))))
7394 (defun org-get-heading ()
7395 "Return the heading of the current entry, without the stars."
7396 (save-excursion
7397 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
7398 (if (and (re-search-backward "[\r\n]\\*" nil t)
7399 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
7400 (match-string 1)
7401 "")))
7403 (defun org-agenda-diary-entry ()
7404 "Make a diary entry, like the `i' command from the calendar.
7405 All the standard commands work: block, weekly etc."
7406 (interactive)
7407 (org-agenda-check-type t 'agenda 'timeline)
7408 (require 'diary-lib)
7409 (let* ((char (progn
7410 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
7411 (read-char-exclusive)))
7412 (cmd (cdr (assoc char
7413 '((?d . insert-diary-entry)
7414 (?w . insert-weekly-diary-entry)
7415 (?m . insert-monthly-diary-entry)
7416 (?y . insert-yearly-diary-entry)
7417 (?a . insert-anniversary-diary-entry)
7418 (?b . insert-block-diary-entry)
7419 (?c . insert-cyclic-diary-entry)))))
7420 (oldf (symbol-function 'calendar-cursor-to-date))
7421 (point (point))
7422 (mark (or (mark t) (point))))
7423 (unless cmd
7424 (error "No command associated with <%c>" char))
7425 (unless (and (get-text-property point 'day)
7426 (or (not (equal ?b char))
7427 (get-text-property mark 'day)))
7428 (error "Don't know which date to use for diary entry"))
7429 ;; We implement this by hacking the `calendar-cursor-to-date' function
7430 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
7431 (let ((calendar-mark-ring
7432 (list (calendar-gregorian-from-absolute
7433 (or (get-text-property mark 'day)
7434 (get-text-property point 'day))))))
7435 (unwind-protect
7436 (progn
7437 (fset 'calendar-cursor-to-date
7438 (lambda (&optional error)
7439 (calendar-gregorian-from-absolute
7440 (get-text-property point 'day))))
7441 (call-interactively cmd))
7442 (fset 'calendar-cursor-to-date oldf)))))
7445 (defun org-agenda-execute-calendar-command (cmd)
7446 "Execute a calendar command from the agenda, with the date associated to
7447 the cursor position."
7448 (org-agenda-check-type t 'agenda 'timeline)
7449 (require 'diary-lib)
7450 (unless (get-text-property (point) 'day)
7451 (error "Don't know which date to use for calendar command"))
7452 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
7453 (point (point))
7454 (date (calendar-gregorian-from-absolute
7455 (get-text-property point 'day)))
7456 (displayed-day (extract-calendar-day date))
7457 (displayed-month (extract-calendar-month date))
7458 (displayed-year (extract-calendar-year date)))
7459 (unwind-protect
7460 (progn
7461 (fset 'calendar-cursor-to-date
7462 (lambda (&optional error)
7463 (calendar-gregorian-from-absolute
7464 (get-text-property point 'day))))
7465 (call-interactively cmd))
7466 (fset 'calendar-cursor-to-date oldf))))
7468 (defun org-agenda-phases-of-moon ()
7469 "Display the phases of the moon for the 3 months around the cursor date."
7470 (interactive)
7471 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
7473 (defun org-agenda-holidays ()
7474 "Display the holidays for the 3 months around the cursor date."
7475 (interactive)
7476 (org-agenda-execute-calendar-command 'list-calendar-holidays))
7478 (defun org-agenda-sunrise-sunset (arg)
7479 "Display sunrise and sunset for the cursor date.
7480 Latitude and longitude can be specified with the variables
7481 `calendar-latitude' and `calendar-longitude'. When called with prefix
7482 argument, latitude and longitude will be prompted for."
7483 (interactive "P")
7484 (let ((calendar-longitude (if arg nil calendar-longitude))
7485 (calendar-latitude (if arg nil calendar-latitude))
7486 (calendar-location-name
7487 (if arg "the given coordinates" calendar-location-name)))
7488 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
7490 (defun org-agenda-goto-calendar ()
7491 "Open the Emacs calendar with the date at the cursor."
7492 (interactive)
7493 (org-agenda-check-type t 'agenda 'timeline)
7494 (let* ((day (or (get-text-property (point) 'day)
7495 (error "Don't know which date to open in calendar")))
7496 (date (calendar-gregorian-from-absolute day))
7497 (calendar-move-hook nil)
7498 (view-calendar-holidays-initially nil)
7499 (view-diary-entries-initially nil))
7500 (calendar)
7501 (calendar-goto-date date)))
7503 (defun org-calendar-goto-agenda ()
7504 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
7505 This is a command that has to be installed in `calendar-mode-map'."
7506 (interactive)
7507 (org-agenda-list nil (calendar-absolute-from-gregorian
7508 (calendar-cursor-to-date))
7509 nil t))
7511 (defun org-agenda-convert-date ()
7512 (interactive)
7513 (org-agenda-check-type t 'agenda 'timeline)
7514 (let ((day (get-text-property (point) 'day))
7515 date s)
7516 (unless day
7517 (error "Don't know which date to convert"))
7518 (setq date (calendar-gregorian-from-absolute day))
7519 (setq s (concat
7520 "Gregorian: " (calendar-date-string date) "\n"
7521 "ISO: " (calendar-iso-date-string date) "\n"
7522 "Day of Yr: " (calendar-day-of-year-string date) "\n"
7523 "Julian: " (calendar-julian-date-string date) "\n"
7524 "Astron. JD: " (calendar-astro-date-string date)
7525 " (Julian date number at noon UTC)\n"
7526 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
7527 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
7528 "French: " (calendar-french-date-string date) "\n"
7529 "Mayan: " (calendar-mayan-date-string date) "\n"
7530 "Coptic: " (calendar-coptic-date-string date) "\n"
7531 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
7532 "Persian: " (calendar-persian-date-string date) "\n"
7533 "Chinese: " (calendar-chinese-date-string date) "\n"))
7534 (with-output-to-temp-buffer "*Dates*"
7535 (princ s))
7536 (if (fboundp 'fit-window-to-buffer)
7537 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
7539 ;;; Tags
7541 (defun org-scan-tags (action matcher &optional todo-only)
7542 "Scan headline tags with inheritance and produce output ACTION.
7543 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
7544 evaluated, testing if a given set of tags qualifies a headline for
7545 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
7546 are included in the output."
7547 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
7548 (mapconcat 'regexp-quote
7549 (nreverse (cdr (reverse org-todo-keywords)))
7550 "\\|")
7551 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
7552 (props (list 'face nil
7553 'done-face 'org-done
7554 'undone-face nil
7555 'mouse-face 'highlight
7556 'keymap org-agenda-keymap
7557 'help-echo
7558 (format "mouse-2 or RET jump to org file %s"
7559 (abbreviate-file-name buffer-file-name))))
7560 lspos
7561 tags tags-list tags-alist (llast 0) rtn level category i txt
7562 todo marker)
7564 (save-excursion
7565 (goto-char (point-min))
7566 (when (eq action 'sparse-tree) (org-overview))
7567 (while (re-search-forward re nil t)
7568 (setq todo (if (match-end 1) (match-string 2))
7569 tags (if (match-end 4) (match-string 4)))
7570 (goto-char (setq lspos (1+ (match-beginning 0))))
7571 (setq level (funcall outline-level)
7572 category (org-get-category))
7573 (setq i llast llast level)
7574 ;; remove tag lists from same and sublevels
7575 (while (>= i level)
7576 (when (setq entry (assoc i tags-alist))
7577 (setq tags-alist (delete entry tags-alist)))
7578 (setq i (1- i)))
7579 ;; add the nex tags
7580 (when tags
7581 (setq tags (mapcar 'downcase (org-split-string tags ":"))
7582 tags-alist
7583 (cons (cons level tags) tags-alist)))
7584 ;; compile tags for current headline
7585 (setq tags-list
7586 (if org-use-tag-inheritance
7587 (apply 'append (mapcar 'cdr tags-alist))
7588 tags))
7589 (when (and (or (not todo-only) todo)
7590 (eval matcher))
7591 ;; list this headline
7592 (if (eq action 'sparse-tree)
7593 (progn
7594 (org-show-hierarchy-above))
7595 (setq txt (org-format-agenda-item
7597 (concat
7598 (if org-tags-match-list-sublevels
7599 (make-string (1- level) ?.) "")
7600 (org-get-heading))
7601 category tags-list))
7602 (goto-char lspos)
7603 (setq marker (org-agenda-new-marker))
7604 (org-add-props txt props
7605 'org-marker marker 'org-hd-marker marker 'category category)
7606 (push txt rtn))
7607 ;; if we are to skip sublevels, jump to end of subtree
7608 (point)
7609 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
7610 (nreverse rtn)))
7612 (defun org-tags-sparse-tree (&optional arg match)
7613 "Create a sparse tree according to tags search string MATCH.
7614 MATCH can contain positive and negative selection of tags, like
7615 \"+WORK+URGENT-WITHBOSS\"."
7616 (interactive "P")
7617 (let ((org-show-following-heading nil)
7618 (org-show-hierarchy-above nil))
7619 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
7621 (defun org-make-tags-matcher (match)
7622 "Create the TAGS matcher form for the tags-selecting string MATCH."
7623 (unless match
7624 ;; Get a new match request, with completion
7625 (setq org-last-tags-completion-table
7626 (or (org-get-buffer-tags)
7627 org-last-tags-completion-table))
7628 (setq match (completing-read
7629 "Tags: " 'org-tags-completion-function nil nil nil
7630 'org-tags-history)))
7631 ;; parse the string and create a lisp form
7632 (let ((match0 match) minus tag mm matcher orterms term orlist)
7633 (setq orterms (org-split-string match "|"))
7634 (while (setq term (pop orterms))
7635 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
7636 (setq minus (and (match-end 1)
7637 (equal (match-string 1 term) "-"))
7638 tag (match-string 2 term)
7639 term (substring term (match-end 0))
7640 mm (list 'member (downcase tag) 'tags-list)
7641 mm (if minus (list 'not mm) mm))
7642 (push mm matcher))
7643 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
7644 orlist)
7645 (setq matcher nil))
7646 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
7647 ;; Return the string and lisp forms of the matcher
7648 (cons match0 matcher)))
7650 ;;;###autoload
7651 (defun org-tags-view (&optional todo-only match keep-modes)
7652 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
7653 The prefix arg TODO-ONLY limits the search to TODO entries."
7654 (interactive "P")
7655 (org-agenda-maybe-reset-markers 'force)
7656 (org-compile-prefix-format org-agenda-prefix-format)
7657 (let* ((org-agenda-keep-modes keep-modes)
7658 (org-tags-match-list-sublevels
7659 (if todo-only t org-tags-match-list-sublevels))
7660 (win (selected-window))
7661 (completion-ignore-case t)
7662 rtn rtnall files file pos matcher
7663 buffer)
7664 (setq matcher (org-make-tags-matcher match)
7665 match (car matcher) matcher (cdr matcher))
7666 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
7667 (progn
7668 (delete-other-windows)
7669 (switch-to-buffer-other-window
7670 (get-buffer-create org-agenda-buffer-name))))
7671 (setq buffer-read-only nil)
7672 (erase-buffer)
7673 (org-agenda-mode) (setq buffer-read-only nil)
7674 (set (make-local-variable 'org-agenda-type) 'tags)
7675 (set (make-local-variable 'org-agenda-redo-command)
7676 (list 'org-tags-view (list 'quote todo-only)
7677 (list 'if 'current-prefix-arg nil match) t))
7678 (setq files (org-agenda-files)
7679 rtnall nil)
7680 (while (setq file (pop files))
7681 (catch 'nextfile
7682 (org-check-agenda-file file)
7683 (setq buffer (if (file-exists-p file)
7684 (org-get-agenda-file-buffer file)
7685 (error "No such file %s" file)))
7686 (if (not buffer)
7687 ;; If file does not exist, merror message to agenda
7688 (setq rtn (list
7689 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
7690 rtnall (append rtnall rtn))
7691 (with-current-buffer buffer
7692 (unless (eq major-mode 'org-mode)
7693 (error "Agenda file %s is not in `org-mode'" file))
7694 (setq org-category-table (org-get-category-table))
7695 (save-excursion
7696 (save-restriction
7697 (if org-respect-restriction
7698 (if (org-region-active-p)
7699 ;; Respect a region to restrict search
7700 (narrow-to-region (region-beginning) (region-end)))
7701 ;; If we work for the calendar or many files,
7702 ;; get rid of any restriction
7703 (widen))
7704 (setq rtn (org-scan-tags 'agenda matcher todo-only))
7705 (setq rtnall (append rtnall rtn))))))))
7706 (insert "Headlines with TAGS match: ")
7707 (add-text-properties (point-min) (1- (point))
7708 (list 'face 'org-level-3))
7709 (setq pos (point))
7710 (insert match "\n")
7711 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
7712 (setq pos (point))
7713 (insert "Press `C-u r' to search again with new search string\n")
7714 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
7715 (when rtnall
7716 (insert (mapconcat 'identity rtnall "\n")))
7717 (goto-char (point-min))
7718 (setq buffer-read-only t)
7719 (org-fit-agenda-window)
7720 (if (not org-select-agenda-window) (select-window win))))
7722 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
7723 (defun org-set-tags (&optional arg just-align)
7724 "Set the tags for the current headline.
7725 With prefix ARG, realign all tags in headings in the current buffer."
7726 (interactive "P")
7727 (let* ((re (concat "^" outline-regexp))
7728 (col (current-column))
7729 (current (org-get-tags))
7730 table current-tags inherited-tags ; computed below when needed
7731 tags hd empty invis)
7732 (if arg
7733 (save-excursion
7734 (goto-char (point-min))
7735 (while (re-search-forward re nil t)
7736 (org-set-tags nil t))
7737 (message "All tags realigned to column %d" org-tags-column))
7738 (if just-align
7739 (setq tags current)
7740 (setq table (or org-tag-alist (org-get-buffer-tags))
7741 org-last-tags-completion-table table
7742 current-tags (org-split-string current ":")
7743 inherited-tags (nreverse
7744 (nthcdr (length current-tags)
7745 (nreverse (org-get-tags-at))))
7746 tags
7747 (if (or (eq t org-use-fast-tag-selection)
7748 (and org-use-fast-tag-selection
7749 (delq nil (mapcar 'cdr table))))
7750 (org-fast-tag-selection current-tags inherited-tags table)
7751 (let ((org-add-colon-after-tag-completion t))
7752 (completing-read "Tags: " 'org-tags-completion-function
7753 nil nil current 'org-tags-history))))
7754 (while (string-match "[-+&]+" tags)
7755 (setq tags (replace-match ":" t t tags))))
7757 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
7758 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
7759 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
7760 (if (equal current "")
7761 (progn
7762 (end-of-line 1)
7763 (or empty (insert-before-markers " ")))
7764 (beginning-of-line 1)
7765 (setq invis (org-invisible-p))
7766 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
7767 (setq hd (match-string 1))
7768 (delete-region (match-beginning 0) (match-end 0))
7769 (insert-before-markers (org-trim hd) (if empty "" " ")))
7770 (unless (equal tags "")
7771 (move-to-column (max (current-column)
7772 (if (> org-tags-column 0)
7773 org-tags-column
7774 (- (- org-tags-column) (length tags))))
7776 (insert-before-markers tags)
7777 (if (and (not invis) (org-invisible-p))
7778 (outline-flag-region (point-at-bol) (point) nil)))
7779 (move-to-column col))))
7781 (defun org-tags-completion-function (string predicate &optional flag)
7782 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
7783 (confirm (lambda (x) (stringp (car x)))))
7784 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
7785 (setq s1 (match-string 1 string)
7786 s2 (match-string 2 string))
7787 (setq s1 "" s2 string))
7788 (cond
7789 ((eq flag nil)
7790 ;; try completion
7791 (setq rtn (try-completion s2 ctable confirm))
7792 (if (stringp rtn)
7793 (concat s1 s2 (substring rtn (length s2))
7794 (if (and org-add-colon-after-tag-completion
7795 (assoc rtn ctable))
7796 ":" "")))
7798 ((eq flag t)
7799 ;; all-completions
7800 (all-completions s2 ctable confirm)
7802 ((eq flag 'lambda)
7803 ;; exact match?
7804 (assoc s2 ctable)))
7807 (defun org-fast-tag-insert (kwd tags face &optional end)
7808 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
7809 (insert (format "%-12s" (concat kwd ":"))
7810 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
7811 (or end "")))
7813 (defun org-fast-tag-selection (current inherited table)
7814 "Fast tag selection with single keys.
7815 CURRENT is the current list of tags in the headline, INHERITED is the
7816 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
7817 possibly with grouping information.
7818 If the keys are nil, a-z are automatically assigned.
7819 Returns the new tags string, or nil to not change the current settings."
7820 (let* ((maxlen (apply 'max (mapcar
7821 (lambda (x)
7822 (if (stringp (car x)) (string-width (car x)) 0))
7823 table)))
7824 (fwidth (+ maxlen 3 1 3))
7825 (ncol (/ (- (window-width) 4) fwidth))
7826 (i-face 'org-done)
7827 (c-face 'org-tag)
7828 tg cnt e c char c1 c2 ntable tbl rtn
7829 groups ingroup)
7830 (save-window-excursion
7831 (delete-other-windows)
7832 (split-window-vertically)
7833 (switch-to-buffer-other-window (get-buffer-create " *Org tags*"))
7834 (erase-buffer)
7835 (org-fast-tag-insert "Inherited" inherited i-face "\n")
7836 (org-fast-tag-insert "Current" current c-face "\n\n")
7837 (setq tbl table char ?a cnt 0)
7838 (while (setq e (pop tbl))
7839 (cond
7840 ((equal e '(:startgroup))
7841 (push '() groups) (setq ingroup t)
7842 (when (not (= cnt 0))
7843 (setq cnt 0)
7844 (insert "\n"))
7845 (insert "{ "))
7846 ((equal e '(:endgroup))
7847 (setq ingroup nil cnt 0)
7848 (insert "}\n"))
7850 (setq tg (car e) c2 nil)
7851 (if (cdr e)
7852 (setq c (cdr e))
7853 ;; automatically assign a character.
7854 (setq c1 (string-to-char
7855 (downcase (substring
7856 tg (if (= (string-to-char tg) ?@) 1 0)))))
7857 (if (or (rassoc c1 ntable) (rassoc c1 table))
7858 (while (or (rassoc char ntable) (rassoc char table))
7859 (setq char (1+ char)))
7860 (setq c2 c1))
7861 (setq c (or c2 char)))
7862 (if ingroup (push tg (car groups)))
7863 (setq tg (org-add-props tg nil 'face
7864 (cond
7865 ((member tg current) c-face)
7866 ((member tg inherited) i-face)
7867 (t nil))))
7868 (if (and (= cnt 0) (not ingroup)) (insert " "))
7869 (insert "[" c "] " tg (make-string
7870 (- fwidth 4 (length tg)) ?\ ))
7871 (push (cons tg c) ntable)
7872 (when (= (setq cnt (1+ cnt)) ncol)
7873 (insert "\n")
7874 (if ingroup (insert " "))
7875 (setq cnt 0)))))
7876 (setq ntable (nreverse ntable))
7877 (insert "\n")
7878 (goto-char (point-min))
7879 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
7880 (setq rtn
7881 (catch 'exit
7882 (while t
7883 (message "[key]:Toggle SPC: clear current RET accept%s"
7884 (if groups " [!] ignore goups" ""))
7885 (setq c (read-char-exclusive))
7886 (cond
7887 ((= c ?\r) (throw 'exit t))
7888 ((= c ?!)
7889 (setq groups nil)
7890 (goto-char (point-min))
7891 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
7892 ((or (= c ?\C-g)
7893 (and (= c ?q) (not (rassoc c ntable))))
7894 (setq quit-flag t))
7895 ((= c ?\ ) (setq current nil))
7896 ((setq e (rassoc c ntable) tg (car e))
7897 (if (member tg current)
7898 (setq current (delete tg current))
7899 (loop for g in groups do
7900 (if (member tg g)
7901 (mapcar (lambda (x)
7902 (setq current (delete x current)))
7903 g)))
7904 (setq current (cons tg current)))))
7905 ;; Create a sorted list
7906 (setq current
7907 (sort current
7908 (lambda (a b)
7909 (assoc b (cdr (memq (assoc a ntable) ntable))))))
7910 (goto-char (point-min))
7911 (beginning-of-line 2)
7912 (delete-region (point) (point-at-eol))
7913 (org-fast-tag-insert "Current" current c-face)
7914 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
7915 (setq tg (match-string 1))
7916 (add-text-properties (match-beginning 1) (match-end 1)
7917 (list 'face
7918 (cond
7919 ((member tg current) c-face)
7920 ((member tg inherited) i-face)
7921 (t nil)))))
7922 (goto-char (point-min)))))
7923 (if rtn
7924 (mapconcat 'identity current ":")
7925 nil))))
7927 (defun org-get-tags ()
7928 "Get the TAGS string in the current headline."
7929 (unless (org-on-heading-p)
7930 (error "Not on a heading"))
7931 (save-excursion
7932 (beginning-of-line 1)
7933 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
7934 (org-match-string-no-properties 1)
7935 "")))
7937 (defun org-get-buffer-tags ()
7938 "Get a table of all tags used in the buffer, for completion."
7939 (let (tags)
7940 (save-excursion
7941 (goto-char (point-min))
7942 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
7943 (mapc (lambda (x) (add-to-list 'tags x))
7944 (org-split-string (org-match-string-no-properties 1) ":"))))
7945 (mapcar 'list tags)))
7947 ;;; Link Stuff
7949 (defvar org-create-file-search-functions nil
7950 "List of functions to construct the right search string for a file link.
7951 These functions are called in turn with point at the location to
7952 which the link should point.
7954 A function in the hook should first test if it would like to
7955 handle this file type, for example by checking the major-mode or
7956 the file extension. If it decides not to handle this file, it
7957 should just return nil to give other functions a chance. If it
7958 does handle the file, it must return the search string to be used
7959 when following the link. The search string will be part of the
7960 file link, given after a double colon, and `org-open-at-point'
7961 will automatically search for it. If special measures must be
7962 taken to make the search successful, another function should be
7963 added to the companion hook `org-execute-file-search-functions',
7964 which see.
7966 A function in this hook may also use `setq' to set the variable
7967 `description' to provide a suggestion for the descriptive text to
7968 be used for this link when it gets inserted into an Org-mode
7969 buffer with \\[org-insert-link].")
7971 (defvar org-execute-file-search-functions nil
7972 "List of functions to execute a file search triggered by a link.
7974 Functions added to this hook must accept a single argument, the
7975 search string that was part of the file link, the part after the
7976 double colon. The function must first check if it would like to
7977 handle this search, for example by checking the major-mode or the
7978 file extension. If it decides not to handle this search, it
7979 should just return nil to give other functions a chance. If it
7980 does handle the search, it must return a non-nil value to keep
7981 other functions from trying.
7983 Each function can access the current prefix argument through the
7984 variable `current-prefix-argument'. Note that a single prefix is
7985 used to force opening a link in Emacs, so it may be good to only
7986 use a numeric or double prefix to guide the search function.
7988 In case this is needed, a function in this hook can also restore
7989 the window configuration before `org-open-at-point' was called using:
7991 (set-window-configuration org-window-config-before-follow-link)")
7993 (defun org-find-file-at-mouse (ev)
7994 "Open file link or URL at mouse."
7995 (interactive "e")
7996 (mouse-set-point ev)
7997 (org-open-at-point 'in-emacs))
7999 (defun org-open-at-mouse (ev)
8000 "Open file link or URL at mouse."
8001 (interactive "e")
8002 (mouse-set-point ev)
8003 (org-open-at-point))
8005 (defvar org-window-config-before-follow-link nil
8006 "The window configuration before following a link.
8007 This is saved in case the need arises to restore it.")
8009 (defun org-open-at-point (&optional in-emacs)
8010 "Open link at or after point.
8011 If there is no link at point, this function will search forward up to
8012 the end of the current subtree.
8013 Normally, files will be opened by an appropriate application. If the
8014 optional argument IN-EMACS is non-nil, Emacs will visit the file."
8015 (interactive "P")
8016 (setq org-window-config-before-follow-link (current-window-configuration))
8017 (org-remove-occur-highlights nil nil t)
8018 (if (org-at-timestamp-p)
8019 (org-agenda-list nil (time-to-days (org-time-string-to-time
8020 (substring (match-string 1) 0 10)))
8022 (let (type path link line search (pos (point)))
8023 (catch 'match
8024 (save-excursion
8025 (skip-chars-forward "^]\n\r")
8026 (when (and (re-search-backward "\\[\\[" nil t)
8027 (looking-at org-bracket-link-regexp)
8028 (<= (match-beginning 0) pos)
8029 (>= (match-end 0) pos))
8030 (setq link (org-link-unescape (org-match-string-no-properties 1)))
8031 (while (string-match " *\n *" link)
8032 (setq link (replace-match " " t t link)))
8033 (if (string-match org-link-re-with-space2 link)
8034 (setq type (match-string 1 link)
8035 path (match-string 2 link))
8036 (setq type "thisfile"
8037 path link))
8038 (throw 'match t)))
8040 (when (get-text-property (point) 'org-linked-text)
8041 (setq type "thisfile"
8042 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8043 (1+ (point)) (point))
8044 path (buffer-substring
8045 (previous-single-property-change pos 'org-linked-text)
8046 (next-single-property-change pos 'org-linked-text)))
8047 (throw 'match t))
8049 (save-excursion
8050 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
8051 (if (equal (char-before) ?<) (backward-char 1))
8052 (when (or (looking-at org-angle-link-re)
8053 (looking-at org-plain-link-re)
8054 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
8055 (re-search-forward org-plain-link-re (point-at-eol) t))
8056 (<= (match-beginning 0) pos)
8057 (>= (match-end 0) pos)))
8058 (setq type (match-string 1)
8059 path (match-string 2))
8060 (throw 'match t)))
8061 (save-excursion
8062 (skip-chars-backward "^ \t\n\r")
8063 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
8064 (setq type "tags"
8065 path (match-string 1))
8066 (while (string-match ":" path)
8067 (setq path (replace-match "+" t t path)))
8068 (throw 'match t)))
8069 (save-excursion
8070 (skip-chars-backward "a-zA-Z_")
8071 (when (and (memq 'camel org-activate-links)
8072 (looking-at org-camel-regexp))
8073 (setq type "camel" path (match-string 0))
8074 (if (equal (char-before) ?*)
8075 (setq path (concat "*" path))))
8076 (throw 'match t)))
8077 (unless path
8078 (error "No link found"))
8079 ;; Remove any trailing spaces in path
8080 (if (string-match " +\\'" path)
8081 (setq path (replace-match "" t t path)))
8083 (cond
8085 ((member type '("http" "https" "ftp" "mailto" "news"))
8086 (browse-url (concat type ":" path)))
8088 ((string= type "tags")
8089 (org-tags-view in-emacs path))
8090 ((or (string= type "camel")
8091 (string= type "thisfile"))
8092 (org-mark-ring-push)
8093 (org-link-search
8094 path
8095 (cond ((equal in-emacs '(4)) 'occur)
8096 ((equal in-emacs '(16)) 'org-occur)
8097 (t nil))))
8099 ((string= type "file")
8100 (if (string-match "::\\([0-9]+\\)\\'" path)
8101 (setq line (string-to-number (match-string 1 path))
8102 path (substring path 0 (match-beginning 0)))
8103 (if (string-match "::\\(.+\\)\\'" path)
8104 (setq search (match-string 1 path)
8105 path (substring path 0 (match-beginning 0)))))
8106 (org-open-file path in-emacs line search))
8108 ((string= type "news")
8109 (org-follow-gnus-link path))
8111 ((string= type "bbdb")
8112 (org-follow-bbdb-link path))
8114 ((string= type "info")
8115 (org-follow-info-link path))
8117 ((string= type "gnus")
8118 (let (group article)
8119 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8120 (error "Error in Gnus link"))
8121 (setq group (match-string 1 path)
8122 article (match-string 3 path))
8123 (org-follow-gnus-link group article)))
8125 ((string= type "vm")
8126 (let (folder article)
8127 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8128 (error "Error in VM link"))
8129 (setq folder (match-string 1 path)
8130 article (match-string 3 path))
8131 ;; in-emacs is the prefix arg, will be interpreted as read-only
8132 (org-follow-vm-link folder article in-emacs)))
8134 ((string= type "wl")
8135 (let (folder article)
8136 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8137 (error "Error in Wanderlust link"))
8138 (setq folder (match-string 1 path)
8139 article (match-string 3 path))
8140 (org-follow-wl-link folder article)))
8142 ((string= type "mhe")
8143 (let (folder article)
8144 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8145 (error "Error in MHE link"))
8146 (setq folder (match-string 1 path)
8147 article (match-string 3 path))
8148 (org-follow-mhe-link folder article)))
8150 ((string= type "rmail")
8151 (let (folder article)
8152 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8153 (error "Error in RMAIL link"))
8154 (setq folder (match-string 1 path)
8155 article (match-string 3 path))
8156 (org-follow-rmail-link folder article)))
8158 ((string= type "shell")
8159 (let ((cmd path))
8160 (while (string-match "@{" cmd)
8161 (setq cmd (replace-match "<" t t cmd)))
8162 (while (string-match "@}" cmd)
8163 (setq cmd (replace-match ">" t t cmd)))
8164 (if (or (not org-confirm-shell-link-function)
8165 (funcall org-confirm-shell-link-function
8166 (format "Execute \"%s\" in shell? "
8167 (org-add-props cmd nil
8168 'face 'org-warning))))
8169 (progn
8170 (message "Executing %s" cmd)
8171 (shell-command cmd))
8172 (error "Abort"))))
8174 ((string= type "elisp")
8175 (let ((cmd path))
8176 (if (or (not org-confirm-elisp-link-function)
8177 (funcall org-confirm-elisp-link-function
8178 (format "Execute \"%s\" as elisp? "
8179 (org-add-props cmd nil
8180 'face 'org-warning))))
8181 (message "%s => %s" cmd (eval (read cmd)))
8182 (error "Abort"))))
8185 (browse-url-at-point))))))
8187 (defun org-link-search (s &optional type)
8188 "Search for a link search option.
8189 When S is a CamelCaseWord, search for a target, or for a sentence containing
8190 the words. If S is surrounded by forward slashes, it is interpreted as a
8191 regular expression. In org-mode files, this will create an `org-occur'
8192 sparse tree. In ordinary files, `occur' will be used to list matches.
8193 If the current buffer is in `dired-mode', grep will be used to search
8194 in all files."
8195 (let ((case-fold-search t)
8196 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8197 (pos (point))
8198 (pre "") (post "")
8199 words re0 re1 re2 re3 re4 re5 re2a reall camel)
8200 (cond
8201 ;; First check if there are any special
8202 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8203 ;; Now try the builtin stuff
8204 ((save-excursion
8205 (goto-char (point-min))
8206 (and
8207 (re-search-forward
8208 (concat "<<" (regexp-quote s0) ">>") nil t)
8209 (setq pos (match-beginning 0))))
8210 ;; There is an exact target for this
8211 (goto-char pos))
8212 ((string-match "^/\\(.*\\)/$" s)
8213 ;; A regular expression
8214 (cond
8215 ((eq major-mode 'org-mode)
8216 (org-occur (match-string 1 s)))
8217 ;;((eq major-mode 'dired-mode)
8218 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8219 (t (org-do-occur (match-string 1 s)))))
8220 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
8222 ;; A camel or a normal search string
8223 (when (equal (string-to-char s) ?*)
8224 ;; Anchor on headlines, post may include tags.
8225 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
8226 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
8227 s (substring s 1)))
8228 (remove-text-properties
8229 0 (length s)
8230 '(face nil mouse-face nil keymap nil fontified nil) s)
8231 ;; Make a series of regular expressions to find a match
8232 (setq words
8233 (if camel
8234 (org-camel-to-words s)
8235 (org-split-string s "[ \n\r\t]+"))
8236 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8237 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
8238 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8239 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8240 re1 (concat pre re2 post)
8241 re3 (concat pre re4 post)
8242 re5 (concat pre ".*" re4)
8243 re2 (concat pre re2)
8244 re2a (concat pre re2a)
8245 re4 (concat pre re4)
8246 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8247 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8248 re5 "\\)"
8250 (cond
8251 ((eq type 'org-occur) (org-occur reall))
8252 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8253 (t (goto-char (point-min))
8254 (if (or (org-search-not-link re0 nil t)
8255 (org-search-not-link re1 nil t)
8256 (org-search-not-link re2 nil t)
8257 (org-search-not-link re2a nil t)
8258 (org-search-not-link re3 nil t)
8259 (org-search-not-link re4 nil t)
8260 (org-search-not-link re5 nil t)
8262 (goto-char (match-beginning 1))
8263 (goto-char pos)
8264 (error "No match")))))
8266 ;; Normal string-search
8267 (goto-char (point-min))
8268 (if (search-forward s nil t)
8269 (goto-char (match-beginning 0))
8270 (error "No match"))))
8271 (and (eq major-mode 'org-mode) (org-show-hierarchy-above))))
8273 (defun org-search-not-link (&rest args)
8274 "Execute `re-search-forward', but only accept matches that are not a link."
8275 (catch 'exit
8276 (let ((pos (point)) p1)
8277 (while (apply 're-search-forward args)
8278 (setq p1 (point))
8279 (if (not (save-match-data
8280 (and (re-search-backward "\\[\\[" nil t)
8281 (looking-at org-bracket-link-regexp)
8282 (<= (match-beginning 0) p1)
8283 (>= (match-end 0) p1))))
8284 (progn (goto-char (match-end 0))
8285 (throw 'exit (point)))
8286 (goto-char (match-end 0)))))))
8288 (defun org-do-occur (regexp &optional cleanup)
8289 "Call the Emacs command `occur'.
8290 If CLEANUP is non-nil, remove the printout of the regular expression
8291 in the *Occur* buffer. This is useful if the regex is long and not useful
8292 to read."
8293 (occur regexp)
8294 (when cleanup
8295 (let ((cwin (selected-window)) win beg end)
8296 (when (setq win (get-buffer-window "*Occur*"))
8297 (select-window win))
8298 (goto-char (point-min))
8299 (when (re-search-forward "match[a-z]+" nil t)
8300 (setq beg (match-end 0))
8301 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8302 (setq end (1- (match-beginning 0)))))
8303 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
8304 (goto-char (point-min))
8305 (select-window cwin))))
8307 (defvar org-mark-ring nil
8308 "Mark ring for positions before jumps in Org-mode.")
8309 (defvar org-mark-ring-last-goto nil
8310 "Last position in the mark ring used to go back.")
8311 ;; Fill and close the ring
8312 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8313 (loop for i from 1 to org-mark-ring-length do
8314 (push (make-marker) org-mark-ring))
8315 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8316 org-mark-ring)
8318 (defun org-mark-ring-push (&optional pos buffer)
8319 "Put the current position or POS into the mark ring and rotate it."
8320 (interactive)
8321 (setq pos (or pos (point)))
8322 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8323 (move-marker (car org-mark-ring)
8324 (or pos (point))
8325 (or buffer (current-buffer)))
8326 (message
8327 (substitute-command-keys
8328 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8330 (defun org-mark-ring-goto (&optional n)
8331 "Jump to the previous position in the mark ring.
8332 With prefix arg N, jump back that many stored positions. When
8333 called several times in succession, walk through the entire ring.
8334 Org-mode commands jumping to a different position in the current file,
8335 or to another Org-mode file, automatically push the old position
8336 onto the ring."
8337 (interactive "p")
8338 (let (p m)
8339 (if (eq last-command this-command)
8340 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8341 (setq p org-mark-ring))
8342 (setq org-mark-ring-last-goto p)
8343 (setq m (car p))
8344 (switch-to-buffer (marker-buffer m))
8345 (goto-char m)
8346 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
8348 (defun org-camel-to-words (s)
8349 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
8350 (let ((case-fold-search nil)
8351 words)
8352 (while (string-match "[a-z][A-Z]" s)
8353 (push (substring s 0 (1+ (match-beginning 0))) words)
8354 (setq s (substring s (1+ (match-beginning 0)))))
8355 (nreverse (cons s words))))
8357 (defun org-remove-angle-brackets (s)
8358 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8359 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8361 (defun org-add-angle-brackets (s)
8362 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8363 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8366 (defun org-follow-bbdb-link (name)
8367 "Follow a BBDB link to NAME."
8368 (require 'bbdb)
8369 (let ((inhibit-redisplay t)
8370 (bbdb-electric-p nil))
8371 (catch 'exit
8372 ;; Exact match on name
8373 (bbdb-name (concat "\\`" name "\\'") nil)
8374 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
8375 ;; Exact match on name
8376 (bbdb-company (concat "\\`" name "\\'") nil)
8377 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
8378 ;; Partial match on name
8379 (bbdb-name name nil)
8380 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
8381 ;; Partial match on company
8382 (bbdb-company name nil)
8383 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
8384 ;; General match including network address and notes
8385 (bbdb name nil)
8386 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
8387 (delete-window (get-buffer-window "*BBDB*"))
8388 (error "No matching BBDB record")))))
8391 (defun org-follow-info-link (name)
8392 "Follow an info file & node link to NAME."
8393 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
8394 (string-match "\\(.*\\)" name))
8395 (progn
8396 (require 'info)
8397 (if (match-string 2 name) ; If there isn't a node, choose "Top"
8398 (Info-find-node (match-string 1 name) (match-string 2 name))
8399 (Info-find-node (match-string 1 name) "Top")))
8400 (message (concat "Could not open: " name))))
8402 (defun org-follow-gnus-link (&optional group article)
8403 "Follow a Gnus link to GROUP and ARTICLE."
8404 (require 'gnus)
8405 (funcall (cdr (assq 'gnus org-link-frame-setup)))
8406 (if group (gnus-fetch-group group))
8407 (if article
8408 (or (gnus-summary-goto-article article nil 'force)
8409 (if (fboundp 'gnus-summary-insert-cached-articles)
8410 (progn
8411 (gnus-summary-insert-cached-articles)
8412 (gnus-summary-goto-article article nil 'force))
8413 (message "Message could not be found.")))))
8415 (defun org-follow-vm-link (&optional folder article readonly)
8416 "Follow a VM link to FOLDER and ARTICLE."
8417 (require 'vm)
8418 (setq article (org-add-angle-brackets article))
8419 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
8420 ;; ange-ftp or efs or tramp access
8421 (let ((user (or (match-string 1 folder) (user-login-name)))
8422 (host (match-string 2 folder))
8423 (file (match-string 3 folder)))
8424 (cond
8425 ((featurep 'tramp)
8426 ;; use tramp to access the file
8427 (if (featurep 'xemacs)
8428 (setq folder (format "[%s@%s]%s" user host file))
8429 (setq folder (format "/%s@%s:%s" user host file))))
8431 ;; use ange-ftp or efs
8432 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
8433 (setq folder (format "/%s@%s:%s" user host file))))))
8434 (when folder
8435 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
8436 (sit-for 0.1)
8437 (when article
8438 (vm-select-folder-buffer)
8439 (widen)
8440 (let ((case-fold-search t))
8441 (goto-char (point-min))
8442 (if (not (re-search-forward
8443 (concat "^" "message-id: *" (regexp-quote article))))
8444 (error "Could not find the specified message in this folder"))
8445 (vm-isearch-update)
8446 (vm-isearch-narrow)
8447 (vm-beginning-of-message)
8448 (vm-summarize)))))
8450 (defun org-follow-wl-link (folder article)
8451 "Follow a Wanderlust link to FOLDER and ARTICLE."
8452 (setq article (org-add-angle-brackets article))
8453 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
8454 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
8455 (wl-summary-redisplay))
8457 (defun org-follow-rmail-link (folder article)
8458 "Follow an RMAIL link to FOLDER and ARTICLE."
8459 (setq article (org-add-angle-brackets article))
8460 (let (message-number)
8461 (save-excursion
8462 (save-window-excursion
8463 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
8464 (setq message-number
8465 (save-restriction
8466 (widen)
8467 (goto-char (point-max))
8468 (if (re-search-backward
8469 (concat "^Message-ID:\\s-+" (regexp-quote
8470 (or article "")))
8471 nil t)
8472 (rmail-what-message))))))
8473 (if message-number
8474 (progn
8475 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
8476 (rmail-show-message message-number)
8477 message-number)
8478 (error "Message not found"))))
8480 ;; mh-e integration based on planner-mode
8481 (defun org-mhe-get-message-real-folder ()
8482 "Return the name of the current message real folder, so if you use
8483 sequences, it will now work."
8484 (save-excursion
8485 (let* ((folder
8486 (if (equal major-mode 'mh-folder-mode)
8487 mh-current-folder
8488 ;; Refer to the show buffer
8489 mh-show-folder-buffer))
8490 (end-index
8491 (if (boundp 'mh-index-folder)
8492 (min (length mh-index-folder) (length folder))))
8494 ;; a simple test on mh-index-data does not work, because
8495 ;; mh-index-data is always nil in a show buffer.
8496 (if (and (boundp 'mh-index-folder)
8497 (string= mh-index-folder (substring folder 0 end-index)))
8498 (if (equal major-mode 'mh-show-mode)
8499 (save-window-excursion
8500 (when (buffer-live-p (get-buffer folder))
8501 (progn
8502 (pop-to-buffer folder)
8503 (org-mhe-get-message-folder-from-index)
8506 (org-mhe-get-message-folder-from-index)
8508 folder
8512 (defun org-mhe-get-message-folder-from-index ()
8513 "Returns the name of the message folder in a index folder buffer."
8514 (save-excursion
8515 (mh-index-previous-folder)
8516 (re-search-forward "^\\(+.*\\)$" nil t)
8517 (message (match-string 1))))
8519 (defun org-mhe-get-message-folder ()
8520 "Return the name of the current message folder. Be careful if you
8521 use sequences."
8522 (save-excursion
8523 (if (equal major-mode 'mh-folder-mode)
8524 mh-current-folder
8525 ;; Refer to the show buffer
8526 mh-show-folder-buffer)))
8528 (defun org-mhe-get-message-num ()
8529 "Return the number of the current message. Be careful if you
8530 use sequences."
8531 (save-excursion
8532 (if (equal major-mode 'mh-folder-mode)
8533 (mh-get-msg-num nil)
8534 ;; Refer to the show buffer
8535 (mh-show-buffer-message-number))))
8537 (defun org-mhe-get-header (header)
8538 "Return a header of the message in folder mode. This will create a
8539 show buffer for the corresponding message. If you have a more clever
8540 idea..."
8541 (let* ((folder (org-mhe-get-message-folder))
8542 (num (org-mhe-get-message-num))
8543 (buffer (get-buffer-create (concat "show-" folder)))
8544 (header-field))
8545 (with-current-buffer buffer
8546 (mh-display-msg num folder)
8547 (if (equal major-mode 'mh-folder-mode)
8548 (mh-header-display)
8549 (mh-show-header-display))
8550 (set-buffer buffer)
8551 (setq header-field (mh-get-header-field header))
8552 (if (equal major-mode 'mh-folder-mode)
8553 (mh-show)
8554 (mh-show-show))
8555 header-field)))
8557 (defun org-follow-mhe-link (folder article)
8558 "Follow an MHE link to FOLDER and ARTICLE.
8559 If ARTICLE is nil FOLDER is shown. If the configuration variable
8560 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
8561 ARTICLE is searched in all folders. Indexed searches (swish++,
8562 namazu, and others supported by MH-E) will always search in all
8563 folders."
8564 (require 'mh-e)
8565 (require 'mh-search)
8566 (require 'mh-utils)
8567 (mh-find-path)
8568 (if (not article)
8569 (mh-visit-folder (mh-normalize-folder-name folder))
8570 (setq article (org-add-angle-brackets article))
8571 (mh-search-choose)
8572 (if (equal mh-searcher 'pick)
8573 (progn
8574 (mh-search folder (list "--message-id" article))
8575 (when (and org-mhe-search-all-folders
8576 (not (org-mhe-get-message-real-folder)))
8577 (kill-this-buffer)
8578 (mh-search "+" (list "--message-id" article))))
8579 (mh-search "+" article))
8580 (if (org-mhe-get-message-real-folder)
8581 (mh-show-msg 1)
8582 (kill-this-buffer)
8583 (error "Message not found"))))
8585 ;; BibTeX links
8587 ;; Use the custom search meachnism to construct and use search strings for
8588 ;; file links to BibTeX database entries.
8590 (defun org-create-file-search-in-bibtex ()
8591 "Create the search string and description for a BibTeX database entry."
8592 (when (eq major-mode 'bibtex-mode)
8593 ;; yes, we want to construct this search string.
8594 ;; Make a good description for this entry, using names, year and the title
8595 ;; Put it into the `description' variable which is dynamically scoped.
8596 (let ((bibtex-autokey-names 1)
8597 (bibtex-autokey-names-stretch 1)
8598 (bibtex-autokey-name-case-convert-function 'identity)
8599 (bibtex-autokey-name-separator " & ")
8600 (bibtex-autokey-additional-names " et al.")
8601 (bibtex-autokey-year-length 4)
8602 (bibtex-autokey-name-year-separator " ")
8603 (bibtex-autokey-titlewords 3)
8604 (bibtex-autokey-titleword-separator " ")
8605 (bibtex-autokey-titleword-case-convert-function 'identity)
8606 (bibtex-autokey-titleword-length 'infty)
8607 (bibtex-autokey-year-title-separator ": "))
8608 (setq description (bibtex-generate-autokey)))
8609 ;; Now parse the entry, get the key and return it.
8610 (save-excursion
8611 (bibtex-beginning-of-entry)
8612 (cdr (assoc "=key=" (bibtex-parse-entry))))))
8614 (defun org-execute-file-search-in-bibtex (s)
8615 "Find the link search string S as a key for a database entry."
8616 (when (eq major-mode 'bibtex-mode)
8617 ;; Yes, we want to do the search in this file.
8618 ;; We construct a regexp that searches for "@entrytype{" followed by the key
8619 (goto-char (point-min))
8620 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
8621 (regexp-quote s) "[ \t\n]*,") nil t)
8622 (goto-char (match-beginning 0)))
8623 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
8624 ;; Use double prefix to indicate that any web link should be browsed
8625 (let ((b (current-buffer)) (p (point)))
8626 ;; Restore the window configuration because we just use the web link
8627 (set-window-configuration org-window-config-before-follow-link)
8628 (save-excursion (set-buffer b) (goto-char p)
8629 (bibtex-url)))
8630 (recenter 0)) ; Move entry start to beginning of window
8631 ;; return t to indicate that the search is done.
8634 ;; Finally add the functions to the right hooks.
8635 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
8636 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
8638 ;; end of Bibtex link setup
8640 (defun org-upgrade-old-links (&optional query-description)
8641 "Transfer old <...> style links to new [[...]] style links.
8642 With arg query-description, ask at each match for a description text to use
8643 for this link."
8644 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
8645 (save-excursion
8646 (goto-char (point-min))
8647 (let ((re (concat "\\([^[]\\)<\\("
8648 "\\(" (mapconcat 'identity org-link-types "\\|")
8649 "\\):"
8650 "[^" org-non-link-chars "]+\\)>"))
8651 l1 l2 (cnt 0))
8652 (while (re-search-forward re nil t)
8653 (setq cnt (1+ cnt)
8654 l1 (org-match-string-no-properties 2)
8655 l2 (save-match-data (org-link-escape l1)))
8656 (when query-description (setq l1 (read-string "Desc: " l1)))
8657 (if (equal l1 l2)
8658 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
8659 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
8660 (message "%d matches have beed treated" cnt))))
8662 (defun org-open-file (path &optional in-emacs line search)
8663 "Open the file at PATH.
8664 First, this expands any special file name abbreviations. Then the
8665 configuration variable `org-file-apps' is checked if it contains an
8666 entry for this file type, and if yes, the corresponding command is launched.
8667 If no application is found, Emacs simply visits the file.
8668 With optional argument IN-EMACS, Emacs will visit the file.
8669 Optional LINE specifies a line to go to, optional SEARCH a string to
8670 search for. If LINE or SEARCH is given, the file will always be
8671 opened in Emacs.
8672 If the file does not exist, an error is thrown."
8673 (setq in-emacs (or in-emacs line search))
8674 (let* ((file (if (equal path "")
8675 buffer-file-name
8676 (convert-standard-filename (org-expand-file-name path))))
8677 (dirp (file-directory-p file))
8678 (dfile (downcase file))
8679 (old-buffer (current-buffer))
8680 (old-pos (point))
8681 (old-mode major-mode)
8682 ext cmd apps)
8683 (if (and (not (file-exists-p file))
8684 (not org-open-non-existing-files))
8685 (error "No such file: %s" file))
8686 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8687 (setq ext (match-string 1 dfile))
8688 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8689 (setq ext (match-string 1 dfile))))
8690 (setq apps (append org-file-apps (org-default-apps)))
8691 (if in-emacs
8692 (setq cmd 'emacs)
8693 (setq cmd (or (and dirp (cdr (assoc 'directory apps)))
8694 (cdr (assoc ext apps))
8695 (cdr (assoc t apps)))))
8696 (when (eq cmd 'mailcap)
8697 (require 'mailcap)
8698 (mailcap-parse-mailcaps)
8699 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8700 (command (mailcap-mime-info mime-type)))
8701 (if (stringp command)
8702 (setq cmd command)
8703 (setq cmd 'emacs))))
8704 (cond
8705 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8706 ;; Normalize use of quote, this can vary.
8707 (if (string-match "['\"]%s['\"]" cmd)
8708 (setq cmd (replace-match "'%s'" t t cmd)))
8709 (setq cmd (format cmd file))
8710 (save-window-excursion
8711 (shell-command (concat cmd " &"))))
8712 ((or (stringp cmd)
8713 (eq cmd 'emacs))
8714 (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
8715 (funcall (cdr (assq 'file org-link-frame-setup)) file))
8716 (if line (goto-line line)
8717 (if search (org-link-search search))))
8718 ((consp cmd)
8719 (eval cmd))
8720 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8721 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
8722 (or (not (equal old-buffer (current-buffer)))
8723 (not (equal old-pos (point))))
8724 (org-mark-ring-push old-pos old-buffer))))
8726 (defun org-default-apps ()
8727 "Return the default applications for this operating system."
8728 (cond
8729 ((eq system-type 'darwin)
8730 org-file-apps-defaults-macosx)
8731 ((eq system-type 'windows-nt)
8732 org-file-apps-defaults-windowsnt)
8733 (t org-file-apps-defaults-gnu)))
8735 (defun org-expand-file-name (path)
8736 "Replace special path abbreviations and expand the file name."
8737 (expand-file-name path))
8740 (defvar org-insert-link-history nil
8741 "Minibuffer history for links inserted with `org-insert-link'.")
8743 (defvar org-stored-links nil
8744 "Contains the links stored with `org-store-link'.")
8746 ;;;###autoload
8747 (defun org-store-link (arg)
8748 "\\<org-mode-map>Store an org-link to the current location.
8749 This link can later be inserted into an org-buffer with
8750 \\[org-insert-link].
8751 For some link types, a prefix arg is interpreted:
8752 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
8753 For file links, arg negates `org-context-in-file-links'."
8754 (interactive "P")
8755 (let (link cpltxt desc description search txt (pos (point)))
8756 (cond
8758 ((eq major-mode 'bbdb-mode)
8759 (setq cpltxt (concat
8760 "bbdb:"
8761 (or (bbdb-record-name (bbdb-current-record))
8762 (bbdb-record-company (bbdb-current-record))))
8763 link (org-make-link cpltxt)))
8765 ((eq major-mode 'Info-mode)
8766 (setq link (org-make-link "info:"
8767 (file-name-nondirectory Info-current-file)
8768 ":" Info-current-node))
8769 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
8770 ":" Info-current-node)))
8772 ((eq major-mode 'calendar-mode)
8773 (let ((cd (calendar-cursor-to-date)))
8774 (setq link
8775 (format-time-string
8776 (car org-time-stamp-formats)
8777 (apply 'encode-time
8778 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8779 nil nil nil))))))
8781 ((or (eq major-mode 'vm-summary-mode)
8782 (eq major-mode 'vm-presentation-mode))
8783 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
8784 (vm-follow-summary-cursor)
8785 (save-excursion
8786 (vm-select-folder-buffer)
8787 (let* ((message (car vm-message-pointer))
8788 (folder buffer-file-name)
8789 (subject (vm-su-subject message))
8790 (author (vm-su-full-name message))
8791 (message-id (vm-su-message-id message)))
8792 (setq message-id (org-remove-angle-brackets message-id))
8793 (setq folder (abbreviate-file-name folder))
8794 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
8795 folder)
8796 (setq folder (replace-match "" t t folder)))
8797 (setq cpltxt (concat author " on: " subject))
8798 (setq link (org-make-link "vm:" folder "#" message-id)))))
8800 ((eq major-mode 'wl-summary-mode)
8801 (let* ((msgnum (wl-summary-message-number))
8802 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
8803 msgnum 'message-id))
8804 (wl-message-entity (elmo-msgdb-overview-get-entity
8805 msgnum (wl-summary-buffer-msgdb)))
8806 (author (wl-summary-line-from)) ; FIXME: correct?
8807 (subject "???")) ; FIXME:
8808 (setq message-id (org-remove-angle-brackets message-id))
8809 (setq cpltxt (concat author " on: " subject))
8810 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
8811 "#" message-id))))
8813 ((or (equal major-mode 'mh-folder-mode)
8814 (equal major-mode 'mh-show-mode))
8815 (let ((from-header (org-mhe-get-header "From:"))
8816 (to-header (org-mhe-get-header "To:"))
8817 (subject (org-mhe-get-header "Subject:")))
8818 (setq cpltxt (concat from-header " on: " subject))
8819 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
8820 (org-remove-angle-brackets
8821 (org-mhe-get-header "Message-Id:"))))))
8823 ((eq major-mode 'rmail-mode)
8824 (save-excursion
8825 (save-restriction
8826 (rmail-narrow-to-non-pruned-header)
8827 (let ((folder buffer-file-name)
8828 (message-id (mail-fetch-field "message-id"))
8829 (author (mail-fetch-field "from"))
8830 (subject (mail-fetch-field "subject")))
8831 (setq message-id (org-remove-angle-brackets message-id))
8832 (setq cpltxt (concat author " on: " subject))
8833 (setq link (org-make-link "rmail:" folder "#" message-id))))))
8835 ((eq major-mode 'gnus-group-mode)
8836 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
8837 (gnus-group-group-name)) ; version
8838 ((fboundp 'gnus-group-name)
8839 (gnus-group-name))
8840 (t "???"))))
8841 (setq cpltxt (concat
8842 (if (org-xor arg org-usenet-links-prefer-google)
8843 "http://groups.google.com/groups?group="
8844 "gnus:")
8845 group)
8846 link (org-make-link cpltxt))))
8848 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
8849 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
8850 (gnus-summary-beginning-of-article)
8851 (let* ((group (car gnus-article-current))
8852 (article (cdr gnus-article-current))
8853 (header (gnus-summary-article-header article))
8854 (author (mail-header-from header))
8855 (message-id (mail-header-id header))
8856 (date (mail-header-date header))
8857 (subject (gnus-summary-subject-string)))
8858 (setq cpltxt (concat author " on: " subject))
8859 (if (org-xor arg org-usenet-links-prefer-google)
8860 (setq link
8861 (concat
8862 cpltxt "\n "
8863 (format "http://groups.google.com/groups?as_umsgid=%s"
8864 (org-fixup-message-id-for-http message-id))))
8865 (setq link (org-make-link "gnus:" group
8866 "#" (number-to-string article))))))
8868 ((eq major-mode 'w3-mode)
8869 (setq cpltxt (url-view-url t)
8870 link (org-make-link cpltxt)))
8871 ((eq major-mode 'w3m-mode)
8872 (setq cpltxt w3m-current-url
8873 link (org-make-link cpltxt)))
8875 ((setq search (run-hook-with-args-until-success
8876 'org-create-file-search-functions))
8877 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8878 "::" search))
8879 (setq cpltxt (or description link)))
8881 ((eq major-mode 'org-mode)
8882 ;; Just link to current headline
8883 (setq cpltxt (concat "file:"
8884 (abbreviate-file-name buffer-file-name)))
8885 ;; Add a context search string
8886 (when (org-xor org-context-in-file-links arg)
8887 ;; Check if we are on a target
8888 (if (save-excursion
8889 (skip-chars-forward "^>\n\r")
8890 (and (re-search-backward "<<" nil t)
8891 (looking-at "<<\\(.*?\\)>>")
8892 (<= (match-beginning 0) pos)
8893 (>= (match-end 0) pos)))
8894 (setq cpltxt (concat cpltxt "::" (match-string 1)))
8895 (setq txt (cond
8896 ((org-on-heading-p) nil)
8897 ((org-region-active-p)
8898 (buffer-substring (region-beginning) (region-end)))
8899 (t (buffer-substring (point-at-bol) (point-at-eol)))))
8900 (when (or (null txt) (string-match "\\S-" txt))
8901 (setq cpltxt
8902 (concat cpltxt "::"
8903 (if org-file-link-context-use-camel-case
8904 (org-make-org-heading-camel txt)
8905 (org-make-org-heading-search-string txt)))
8906 desc "NONE"))))
8907 (if (string-match "::\\'" cpltxt)
8908 (setq cpltxt (substring cpltxt 0 -2)))
8909 (setq link (org-make-link cpltxt)))
8911 (buffer-file-name
8912 ;; Just link to this file here.
8913 (setq cpltxt (concat "file:"
8914 (abbreviate-file-name buffer-file-name)))
8915 ;; Add a context string
8916 (when (org-xor org-context-in-file-links arg)
8917 (setq txt (if (org-region-active-p)
8918 (buffer-substring (region-beginning) (region-end))
8919 (buffer-substring (point-at-bol) (point-at-eol))))
8920 ;; Only use search option if there is some text.
8921 (when (string-match "\\S-" txt)
8922 (setq cpltxt
8923 (concat cpltxt "::"
8924 (if org-file-link-context-use-camel-case
8925 (org-make-org-heading-camel txt)
8926 (org-make-org-heading-search-string txt)))
8927 desc "NONE")))
8928 (setq link (org-make-link cpltxt)))
8930 ((interactive-p)
8931 (error "Cannot link to a buffer which is not visiting a file"))
8933 (t (setq link nil)))
8935 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8936 (setq link (or link cpltxt)
8937 desc (or desc cpltxt))
8938 (if (equal desc "NONE") (setq desc nil))
8940 (if (and (interactive-p) link)
8941 (progn
8942 (setq org-stored-links
8943 (cons (list cpltxt link desc) org-stored-links))
8944 (message "Stored: %s" (or cpltxt link)))
8945 (org-make-link-string link desc))))
8947 (defun org-make-org-heading-search-string (&optional string heading)
8948 "Make search string for STRING or current headline."
8949 (interactive)
8950 (let ((s (or string (org-get-heading))))
8951 (unless (and string (not heading))
8952 ;; We are using a headline, clean up garbage in there.
8953 (if (string-match org-todo-regexp s)
8954 (setq s (replace-match "" t t s)))
8955 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
8956 (setq s (replace-match "" t t s)))
8957 (setq s (org-trim s))
8958 (if (string-match (concat "^\\(" org-quote-string "\\|"
8959 org-comment-string "\\)") s)
8960 (setq s (replace-match "" t t s)))
8961 (while (string-match org-ts-regexp s)
8962 (setq s (replace-match "" t t s))))
8963 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
8964 (setq s (replace-match " " t t s)))
8965 (or string (setq s (concat "*" s))) ; Add * for headlines
8966 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8968 (defun org-make-org-heading-camel (&optional string heading)
8969 "Make a CamelCase string for STRING or the current headline."
8970 (interactive)
8971 (let ((s (or string (org-get-heading))))
8972 (unless (and string (not heading))
8973 ;; We are using a headline, clean up garbage in there.
8974 (if (string-match org-todo-regexp s)
8975 (setq s (replace-match "" t t s)))
8976 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
8977 (setq s (replace-match "" t t s)))
8978 (setq s (org-trim s))
8979 (if (string-match (concat "^\\(" org-quote-string "\\|"
8980 org-comment-string "\\)") s)
8981 (setq s (replace-match "" t t s)))
8982 (while (string-match org-ts-regexp s)
8983 (setq s (replace-match "" t t s))))
8984 (while (string-match "[^a-zA-Z_ \t]+" s)
8985 (setq s (replace-match " " t t s)))
8986 (or string (setq s (concat "*" s))) ; Add * for headlines
8987 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
8989 (defun org-make-link (&rest strings)
8990 "Concatenate STRINGS, format resulting string with `org-link-format'."
8991 (format org-link-format (apply 'concat strings)))
8993 (defun org-make-link-string (link &optional description)
8994 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8995 (if (eq org-link-style 'plain)
8996 (if (equal description link)
8997 link
8998 (concat description "\n" link))
8999 (when (stringp description)
9000 ;; Remove brackets from the description, they are fatal.
9001 (while (string-match "\\[\\|\\]" description)
9002 (setq description (replace-match "" t t description))))
9003 (when (equal (org-link-escape link) description)
9004 ;; No description needed, it is identical
9005 (setq description nil))
9006 (when (and (not description)
9007 (not (equal link (org-link-escape link))))
9008 (setq description link))
9009 (concat "[[" (org-link-escape link) "]"
9010 (if description (concat "[" description "]") "")
9011 "]")))
9013 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
9014 "Association list of escapes for some characters problematic in links.")
9016 (defun org-link-escape (text)
9017 "Escape charaters in TEXT that are problematic for links."
9018 (when text
9019 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
9020 org-link-escape-chars "\\|")))
9021 (while (string-match re text)
9022 (setq text
9023 (replace-match
9024 (cdr (assoc (match-string 0 text) org-link-escape-chars))
9025 t t text)))
9026 text)))
9028 (defun org-link-unescape (text)
9029 "Reverse the action of `org-link-escape'."
9030 (when text
9031 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
9032 org-link-escape-chars "\\|")))
9033 (while (string-match re text)
9034 (setq text
9035 (replace-match
9036 (car (rassoc (match-string 0 text) org-link-escape-chars))
9037 t t text)))
9038 text)))
9040 (defun org-xor (a b)
9041 "Exclusive or."
9042 (if a (not b) b))
9044 (defun org-get-header (header)
9045 "Find a header field in the current buffer."
9046 (save-excursion
9047 (goto-char (point-min))
9048 (let ((case-fold-search t) s)
9049 (cond
9050 ((eq header 'from)
9051 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
9052 (setq s (match-string 1)))
9053 (while (string-match "\"" s)
9054 (setq s (replace-match "" t t s)))
9055 (if (string-match "[<(].*" s)
9056 (setq s (replace-match "" t t s))))
9057 ((eq header 'message-id)
9058 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
9059 (setq s (match-string 1))))
9060 ((eq header 'subject)
9061 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
9062 (setq s (match-string 1)))))
9063 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
9064 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
9065 s)))
9068 (defun org-fixup-message-id-for-http (s)
9069 "Replace special characters in a message id, so it can be used in an http query."
9070 (while (string-match "<" s)
9071 (setq s (replace-match "%3C" t t s)))
9072 (while (string-match ">" s)
9073 (setq s (replace-match "%3E" t t s)))
9074 (while (string-match "@" s)
9075 (setq s (replace-match "%40" t t s)))
9078 (defun org-insert-link (&optional complete-file)
9079 "Insert a link. At the prompt, enter the link.
9081 Completion can be used to select a link previously stored with
9082 `org-store-link'. When the empty string is entered (i.e. if you just
9083 press RET at the prompt), the link defaults to the most recently
9084 stored link. As SPC triggers completion in the minibuffer, you need to
9085 use M-SPC or C-q SPC to force the insertion of a space character.
9087 You will also be prompted for a description, and if one is given, it will
9088 be displayed in the buffer instead of the link.
9090 If there is already a link at point, this command will allow you to edit link
9091 and description parts.
9093 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
9094 selected using completion. The path to the file will be relative to
9095 the current directory if the file is in the current directory or a
9096 subdirectory. Otherwise, the link will be the absolute path as
9097 completed in the minibuffer (i.e. normally ~/path/to/file).
9099 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
9100 is in the current directory or below."
9101 (interactive "P")
9102 (let (link desc entry remove file (pos (point)))
9103 (cond
9104 ((save-excursion
9105 (skip-chars-forward "^]\n\r")
9106 (and (re-search-backward "\\[\\[" nil t)
9107 (looking-at org-bracket-link-regexp)
9108 (<= (match-beginning 0) pos)
9109 (>= (match-end 0) pos)))
9110 ;; We do have a link at point, and we are going to edit it.
9111 (setq remove (list (match-beginning 0) (match-end 0)))
9112 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9113 (setq link (read-string "Link: "
9114 (org-link-unescape
9115 (org-match-string-no-properties 1)))))
9116 (complete-file
9117 ;; Completing read for file names.
9118 (setq file (read-file-name "File: "))
9119 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9120 (pwd1 (file-name-as-directory (abbreviate-file-name
9121 (expand-file-name ".")))))
9122 (cond
9123 ((equal complete-file '(16))
9124 (setq link (org-make-link
9125 "file:"
9126 (abbreviate-file-name (expand-file-name file)))))
9127 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9128 (setq link (org-make-link "file:" (match-string 1 file))))
9129 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9130 (expand-file-name file))
9131 (setq link (org-make-link
9132 "file:" (match-string 1 (expand-file-name file)))))
9133 (t (setq link (org-make-link "file:" file))))))
9135 ;; Read link, with completion for stored links.
9136 (setq link (org-completing-read
9137 "Link: " org-stored-links nil nil nil
9138 org-insert-link-history
9139 (or (car (car org-stored-links)))))
9140 (setq entry (assoc link org-stored-links))
9141 (if (not org-keep-stored-link-after-insertion)
9142 (setq org-stored-links (delq (assoc link org-stored-links)
9143 org-stored-links)))
9144 (setq link (if entry (nth 1 entry) link)
9145 desc (or desc (nth 2 entry)))))
9147 (if (string-match org-plain-link-re link)
9148 ;; URL-like link, normalize the use of angular brackets.
9149 (setq link (org-make-link (org-remove-angle-brackets link))))
9151 ;; Check if we are linking to the current file with a search option
9152 ;; If yes, simplify the link by using only the search option.
9153 (when (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link)
9154 (let* ((path (match-string 1 link))
9155 (case-fold-search nil)
9156 (search (match-string 2 link)))
9157 (save-match-data
9158 (if (equal (file-truename buffer-file-name) (file-truename path))
9159 ;; We are linking to this same file, with a search option
9160 (setq link search)))))
9162 ;; Check if we can/should use a relative path. If yes, simplify the link
9163 (when (string-match "\\<file:\\(.*\\)" link)
9164 (let* ((path (match-string 1 link))
9165 (case-fold-search nil))
9166 (cond
9167 ((eq org-link-file-path-type 'absolute)
9168 (setq path (abbreviate-file-name (expand-file-name path))))
9169 ((eq org-link-file-path-type 'noabbrev)
9170 (setq path (expand-file-name path)))
9171 ((eq org-link-file-path-type 'relative)
9172 (setq path (file-relative-name path)))
9174 (save-match-data
9175 (if (string-match (concat "^" (regexp-quote
9176 (file-name-as-directory
9177 (expand-file-name "."))))
9178 (expand-file-name path))
9179 ;; We are linking a file with relative path name.
9180 (setq path (substring (expand-file-name path)
9181 (match-end 0)))))))
9182 (setq link (concat "file:" path))))
9184 (setq desc (read-string "Description: " desc))
9185 (unless (string-match "\\S-" desc) (setq desc nil))
9186 (if remove (apply 'delete-region remove))
9187 (insert (org-make-link-string link desc))))
9189 (defun org-completing-read (&rest args)
9190 (let ((minibuffer-local-completion-map
9191 (copy-keymap minibuffer-local-completion-map)))
9192 (define-key minibuffer-local-completion-map " " 'self-insert-command)
9193 (apply 'completing-read args)))
9195 ;;; Hooks for remember.el
9197 (defvar org-finish-function nil)
9199 ;;;###autoload
9200 (defun org-remember-annotation ()
9201 "Return a link to the current location as an annotation for remember.el.
9202 If you are using Org-mode files as target for data storage with
9203 remember.el, then the annotations should include a link compatible with the
9204 conventions in Org-mode. This function returns such a link."
9205 (org-store-link nil))
9207 (defconst org-remember-help
9208 "Select a destination location for the note.
9209 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
9210 RET at beg-of-buf -> Append to file as level 2 headline
9211 RET on headline -> Store as sublevel entry to current headline
9212 <left>/<right> -> before/after current headline, same headings level")
9214 ;;;###autoload
9215 (defun org-remember-apply-template ()
9216 "Initialize *remember* buffer with template, invoke `org-mode'.
9217 This function should be placed into `remember-mode-hook' and in fact requires
9218 to be run from that hook to fucntion properly."
9219 (if org-remember-templates
9221 (let* ((entry (if (= (length org-remember-templates) 1)
9222 (cdar org-remember-templates)
9223 (message "Select template: %s"
9224 (mapconcat
9225 (lambda (x) (char-to-string (car x)))
9226 org-remember-templates " "))
9227 (cdr (assoc (read-char-exclusive) org-remember-templates))))
9228 (tpl (car entry))
9229 (file (if (consp (cdr entry)) (nth 1 entry)))
9230 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
9231 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
9232 (v-u (concat "[" (substring v-t 1 -1) "]"))
9233 (v-U (concat "[" (substring v-T 1 -1) "]"))
9234 (v-a annotation) ; defined in `remember-mode'
9235 (v-i initial) ; defined in `remember-mode'
9236 (v-n user-full-name)
9238 (unless tpl (setq tpl "") (message "No template") (ding))
9239 (insert tpl) (goto-char (point-min))
9240 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
9241 (when (and initial (equal (match-string 0) "%i"))
9242 (save-match-data
9243 (let* ((lead (buffer-substring
9244 (point-at-bol) (match-beginning 0))))
9245 (setq v-i (mapconcat 'identity
9246 (org-split-string initial "\n")
9247 (concat "\n" lead))))))
9248 (replace-match
9249 (or (eval (intern (concat "v-" (match-string 1)))) "")
9250 t t))
9251 (let ((org-startup-folded nil)
9252 (org-startup-with-deadline-check nil))
9253 (org-mode))
9254 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
9255 (set (make-local-variable 'org-default-notes-file) file))
9256 (goto-char (point-min))
9257 (if (re-search-forward "%\\?" nil t) (replace-match "")))
9258 (let ((org-startup-folded nil)
9259 (org-startup-with-deadline-check nil))
9260 (org-mode)))
9261 (set (make-local-variable 'org-finish-function) 'remember-buffer))
9263 ;;;###autoload
9264 (defun org-remember-handler ()
9265 "Store stuff from remember.el into an org file.
9266 First prompts for an org file. If the user just presses return, the value
9267 of `org-default-notes-file' is used.
9268 Then the command offers the headings tree of the selected file in order to
9269 file the text at a specific location.
9270 You can either immediately press RET to get the note appended to the
9271 file, or you can use vertical cursor motion and visibility cycling (TAB) to
9272 find a better place. Then press RET or <left> or <right> in insert the note.
9274 Key Cursor position Note gets inserted
9275 -----------------------------------------------------------------------------
9276 RET buffer-start as level 2 heading at end of file
9277 RET on headline as sublevel of the heading at cursor
9278 RET no heading at cursor position, level taken from context.
9279 Or use prefix arg to specify level manually.
9280 <left> on headline as same level, before current heading
9281 <right> on headline as same level, after current heading
9283 So the fastest way to store the note is to press RET RET to append it to
9284 the default file. This way your current train of thought is not
9285 interrupted, in accordance with the principles of remember.el. But with
9286 little extra effort, you can push it directly to the correct location.
9288 Before being stored away, the function ensures that the text has a
9289 headline, i.e. a first line that starts with a \"*\". If not, a headline
9290 is constructed from the current date and some additional data.
9292 If the variable `org-adapt-indentation' is non-nil, the entire text is
9293 also indented so that it starts in the same column as the headline
9294 \(i.e. after the stars).
9296 See also the variable `org-reverse-note-order'."
9297 (catch 'quit
9298 (let* ((txt (buffer-substring (point-min) (point-max)))
9299 (fastp current-prefix-arg)
9300 (file (if fastp org-default-notes-file (org-get-org-file)))
9301 (visiting (find-buffer-visiting file))
9302 (org-startup-with-deadline-check nil)
9303 (org-startup-folded nil)
9304 (org-startup-align-all-tables nil)
9305 spos level indent reversed)
9306 ;; Modify text so that it becomes a nice subtree which can be inserted
9307 ;; into an org tree.
9308 (let* ((lines (split-string txt "\n"))
9309 first)
9310 ;; remove empty lines at the beginning
9311 (while (and lines (string-match "^[ \t]*\n" (car lines)))
9312 (setq lines (cdr lines)))
9313 (setq first (car lines) lines (cdr lines))
9314 (if (string-match "^\\*+" first)
9315 ;; Is already a headline
9316 (setq indent nil)
9317 ;; We need to add a headline: Use time and first buffer line
9318 (setq lines (cons first lines)
9319 first (concat "* " (current-time-string)
9320 " (" (remember-buffer-desc) ")")
9321 indent " "))
9322 (if (and org-adapt-indentation indent)
9323 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
9324 (setq txt (concat first "\n"
9325 (mapconcat 'identity lines "\n"))))
9326 ;; Find the file
9327 (if (not visiting)
9328 (find-file-noselect file))
9329 (with-current-buffer (get-file-buffer file)
9330 (save-excursion (and (goto-char (point-min))
9331 (not (re-search-forward "^\\* " nil t))
9332 (insert "\n* Notes\n")))
9333 (setq reversed (org-notes-order-reversed-p))
9334 (save-excursion
9335 (save-restriction
9336 (widen)
9337 ;; Ask the User for a location
9338 (setq spos (if fastp 1 (org-get-location
9339 (current-buffer)
9340 org-remember-help)))
9341 (if (not spos) (throw 'quit nil)) ; return nil to show we did
9342 ; not handle this note
9343 (goto-char spos)
9344 (cond ((bobp)
9345 ;; Put it at the start or end, as level 2
9346 (save-restriction
9347 (widen)
9348 (goto-char (if reversed (point-min) (point-max)))
9349 (if (not (bolp)) (newline))
9350 (org-paste-subtree 2 txt)))
9351 ((and (org-on-heading-p nil) (not current-prefix-arg))
9352 ;; Put it below this entry, at the beg/end of the subtree
9353 (org-back-to-heading)
9354 (setq level (funcall outline-level))
9355 (if reversed
9356 (outline-end-of-heading)
9357 (outline-end-of-subtree))
9358 (if (not (bolp)) (newline))
9359 (beginning-of-line 1)
9360 (org-paste-subtree (1+ level) txt))
9362 ;; Put it right there, with automatic level determined by
9363 ;; org-paste-subtree or from prefix arg
9364 (org-paste-subtree current-prefix-arg txt)))
9365 (when remember-save-after-remembering
9366 (save-buffer)
9367 (if (not visiting) (kill-buffer (current-buffer)))))))))
9368 t) ;; return t to indicate that we took care of this note.
9370 (defun org-get-org-file ()
9371 "Read a filename, with default directory `org-directory'."
9372 (let ((default (or org-default-notes-file remember-data-file)))
9373 (read-file-name (format "File name [%s]: " default)
9374 (file-name-as-directory org-directory)
9375 default)))
9377 (defun org-notes-order-reversed-p ()
9378 "Check if the current file should receive notes in reversed order."
9379 (cond
9380 ((not org-reverse-note-order) nil)
9381 ((eq t org-reverse-note-order) t)
9382 ((not (listp org-reverse-note-order)) nil)
9383 (t (catch 'exit
9384 (let ((all org-reverse-note-order)
9385 entry)
9386 (while (setq entry (pop all))
9387 (if (string-match (car entry) buffer-file-name)
9388 (throw 'exit (cdr entry))))
9389 nil)))))
9391 ;;; Tables
9393 ;; Watch out: Here we are talking about two different kind of tables.
9394 ;; Most of the code is for the tables created with the Org-mode table editor.
9395 ;; Sometimes, we talk about tables created and edited with the table.el
9396 ;; Emacs package. We call the former org-type tables, and the latter
9397 ;; table.el-type tables.
9400 (defun org-before-change-function (beg end)
9401 "Every change indicates that a table might need an update."
9402 (setq org-table-may-need-update t))
9404 (defconst org-table-line-regexp "^[ \t]*|"
9405 "Detects an org-type table line.")
9406 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
9407 "Detects an org-type table line.")
9408 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
9409 "Detects a table line marked for automatic recalculation.")
9410 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
9411 "Detects a table line marked for automatic recalculation.")
9412 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
9413 "Detects a table line marked for automatic recalculation.")
9414 (defconst org-table-hline-regexp "^[ \t]*|-"
9415 "Detects an org-type table hline.")
9416 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
9417 "Detects a table-type table hline.")
9418 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
9419 "Detects an org-type or table-type table.")
9420 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
9421 "Searching from within a table (any type) this finds the first line
9422 outside the table.")
9423 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
9424 "Searching from within a table (any type) this finds the first line
9425 outside the table.")
9427 (defun org-table-create-with-table.el ()
9428 "Use the table.el package to insert a new table.
9429 If there is already a table at point, convert between Org-mode tables
9430 and table.el tables."
9431 (interactive)
9432 (require 'table)
9433 (cond
9434 ((org-at-table.el-p)
9435 (if (y-or-n-p "Convert table to Org-mode table? ")
9436 (org-table-convert)))
9437 ((org-at-table-p)
9438 (if (y-or-n-p "Convert table to table.el table? ")
9439 (org-table-convert)))
9440 (t (call-interactively 'table-insert))))
9442 (defun org-table-create-or-convert-from-region (arg)
9443 "Convert region to table, or create an empty table.
9444 If there is an active region, convert it to a table. If there is no such
9445 region, create an empty table."
9446 (interactive "P")
9447 (if (org-region-active-p)
9448 (org-table-convert-region (region-beginning) (region-end) arg)
9449 (org-table-create arg)))
9451 (defun org-table-create (&optional size)
9452 "Query for a size and insert a table skeleton.
9453 SIZE is a string Columns x Rows like for example \"3x2\"."
9454 (interactive "P")
9455 (unless size
9456 (setq size (read-string
9457 (concat "Table size Columns x Rows [e.g. "
9458 org-table-default-size "]: ")
9459 "" nil org-table-default-size)))
9461 (let* ((pos (point))
9462 (indent (make-string (current-column) ?\ ))
9463 (split (org-split-string size " *x *"))
9464 (rows (string-to-number (nth 1 split)))
9465 (columns (string-to-number (car split)))
9466 (line (concat (apply 'concat indent "|" (make-list columns " |"))
9467 "\n")))
9468 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
9469 (point-at-bol) (point)))
9470 (beginning-of-line 1)
9471 (newline))
9472 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
9473 (dotimes (i rows) (insert line))
9474 (goto-char pos)
9475 (if (> rows 1)
9476 ;; Insert a hline after the first row.
9477 (progn
9478 (end-of-line 1)
9479 (insert "\n|-")
9480 (goto-char pos)))
9481 (org-table-align)))
9483 (defun org-table-convert-region (beg0 end0 &optional nspace)
9484 "Convert region to a table.
9485 The region goes from BEG0 to END0, but these borders will be moved
9486 slightly, to make sure a beginning of line in the first line is included.
9487 When NSPACE is non-nil, it indicates the minimum number of spaces that
9488 separate columns (default: just one space)."
9489 (interactive "rP")
9490 (let* ((beg (min beg0 end0))
9491 (end (max beg0 end0))
9492 (tabsep t)
9494 (goto-char beg)
9495 (beginning-of-line 1)
9496 (setq beg (move-marker (make-marker) (point)))
9497 (goto-char end)
9498 (if (bolp) (backward-char 1) (end-of-line 1))
9499 (setq end (move-marker (make-marker) (point)))
9500 ;; Lets see if this is tab-separated material. If every nonempty line
9501 ;; contains a tab, we will assume that it is tab-separated material
9502 (if nspace
9503 (setq tabsep nil)
9504 (goto-char beg)
9505 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
9506 (if nspace (setq tabsep nil))
9507 (if tabsep
9508 (setq re "^\\|\t")
9509 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
9510 (max 1 (prefix-numeric-value nspace)))))
9511 (goto-char beg)
9512 (while (re-search-forward re end t)
9513 (replace-match "|" t t))
9514 (goto-char beg)
9515 (insert " ")
9516 (org-table-align)))
9518 (defun org-table-import (file arg)
9519 "Import FILE as a table.
9520 The file is assumed to be tab-separated. Such files can be produced by most
9521 spreadsheet and database applications. If no tabs (at least one per line)
9522 are found, lines will be split on whitespace into fields."
9523 (interactive "f\nP")
9524 (or (bolp) (newline))
9525 (let ((beg (point))
9526 (pm (point-max)))
9527 (insert-file-contents file)
9528 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
9530 (defun org-table-export ()
9531 "Export table as a tab-separated file.
9532 Such a file can be imported into a spreadsheet program like Excel."
9533 (interactive)
9534 (let* ((beg (org-table-begin))
9535 (end (org-table-end))
9536 (table (buffer-substring beg end))
9537 (file (read-file-name "Export table to: "))
9538 buf)
9539 (unless (or (not (file-exists-p file))
9540 (y-or-n-p (format "Overwrite file %s? " file)))
9541 (error "Abort"))
9542 (with-current-buffer (find-file-noselect file)
9543 (setq buf (current-buffer))
9544 (erase-buffer)
9545 (fundamental-mode)
9546 (insert table)
9547 (goto-char (point-min))
9548 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
9549 (replace-match "" t t)
9550 (end-of-line 1))
9551 (goto-char (point-min))
9552 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
9553 (replace-match "" t t)
9554 (goto-char (min (1+ (point)) (point-max))))
9555 (goto-char (point-min))
9556 (while (re-search-forward "^-[-+]*$" nil t)
9557 (replace-match "")
9558 (if (looking-at "\n")
9559 (delete-char 1)))
9560 (goto-char (point-min))
9561 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
9562 (replace-match "\t" t t))
9563 (save-buffer))
9564 (kill-buffer buf)))
9566 (defvar org-table-aligned-begin-marker (make-marker)
9567 "Marker at the beginning of the table last aligned.
9568 Used to check if cursor still is in that table, to minimize realignment.")
9569 (defvar org-table-aligned-end-marker (make-marker)
9570 "Marker at the end of the table last aligned.
9571 Used to check if cursor still is in that table, to minimize realignment.")
9572 (defvar org-table-last-alignment nil
9573 "List of flags for flushright alignment, from the last re-alignment.
9574 This is being used to correctly align a single field after TAB or RET.")
9575 (defvar org-table-last-column-widths nil
9576 "List of max width of fields in each column.
9577 This is being used to correctly align a single field after TAB or RET.")
9579 (defvar org-last-recalc-line nil)
9580 (defconst org-narrow-column-arrow "=>"
9581 "Used as display property in narrowed table columns.")
9583 (defun org-table-align ()
9584 "Align the table at point by aligning all vertical bars."
9585 (interactive)
9586 (let* (
9587 ;; Limits of table
9588 (beg (org-table-begin))
9589 (end (org-table-end))
9590 ;; Current cursor position
9591 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9592 (colpos (org-table-current-column))
9593 (winstart (window-start))
9594 text lines (new "") lengths l typenums ty fields maxfields i
9595 column
9596 (indent "") cnt frac
9597 rfmt hfmt
9598 (spaces '(1 . 1))
9599 (sp1 (car spaces))
9600 (sp2 (cdr spaces))
9601 (rfmt1 (concat
9602 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
9603 (hfmt1 (concat
9604 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
9605 emptystrings xx links narrow fmax fmin f1 len c e)
9606 (untabify beg end)
9607 (remove-text-properties beg end '(org-cwidth t display t))
9608 ;; Check if we have links
9609 (goto-char beg)
9610 (setq links (re-search-forward org-bracket-link-regexp end t))
9611 ;; Make sure the link properties are right
9612 (when links (goto-char beg) (while (org-activate-bracket-links end)))
9613 ;; Check if we are narrowing any columns
9614 (goto-char beg)
9615 (setq narrow (and org-format-transports-properties-p
9616 (re-search-forward "<[0-9]+>" end t)))
9617 ;; Get the rows
9618 (setq lines (org-split-string
9619 (buffer-substring beg end) "\n"))
9620 ;; Store the indentation of the first line
9621 (if (string-match "^ *" (car lines))
9622 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
9623 ;; Mark the hlines by setting the corresponding element to nil
9624 ;; At the same time, we remove trailing space.
9625 (setq lines (mapcar (lambda (l)
9626 (if (string-match "^ *|-" l)
9628 (if (string-match "[ \t]+$" l)
9629 (substring l 0 (match-beginning 0))
9630 l)))
9631 lines))
9632 ;; Get the data fields by splitting the lines.
9633 (setq fields (mapcar
9634 (lambda (l)
9635 (org-split-string l " *| *"))
9636 (delq nil (copy-sequence lines))))
9637 ;; How many fields in the longest line?
9638 (condition-case nil
9639 (setq maxfields (apply 'max (mapcar 'length fields)))
9640 (error
9641 (kill-region beg end)
9642 (org-table-create org-table-default-size)
9643 (error "Empty table - created default table")))
9644 ;; A list of empty string to fill any short rows on output
9645 (setq emptystrings (make-list maxfields ""))
9646 ;; Check for special formatting.
9647 (setq i -1)
9648 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
9649 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
9650 ;; Check if there is an explicit width specified
9651 (when (and org-table-limit-column-width narrow)
9652 (setq c column fmax nil)
9653 (while c
9654 (setq e (pop c))
9655 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
9656 (setq fmax (string-to-number (match-string 1 e)) c nil)))
9657 ;; Find fields that are wider than fmax, and shorten them
9658 (when fmax
9659 (loop for xx in column do
9660 (when (and (stringp xx)
9661 (> (org-string-width xx) fmax))
9662 (org-add-props xx nil
9663 'help-echo
9664 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
9665 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
9666 (unless (> f1 1)
9667 (error "Cannot narrow field starting with wide link \"%s\""
9668 (match-string 0 xx)))
9669 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
9670 (add-text-properties (- f1 2) f1
9671 (list 'display org-narrow-column-arrow)
9672 xx)))))
9673 ;; Get the maximum width for each column
9674 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
9675 ;; Get the fraction of numbers, to decide about alignment of the column
9676 (setq cnt 0 frac 0.0)
9677 (loop for x in column do
9678 (if (equal x "")
9680 (setq frac ( / (+ (* frac cnt)
9681 (if (string-match org-table-number-regexp x) 1 0))
9682 (setq cnt (1+ cnt))))))
9683 (push (>= frac org-table-number-fraction) typenums))
9684 (setq lengths (nreverse lengths) typenums (nreverse typenums))
9686 ;; Store the alignment of this table, for later editing of single fields
9687 (setq org-table-last-alignment typenums
9688 org-table-last-column-widths lengths)
9690 ;; With invisible characters, `format' does not get the field width right
9691 ;; So we need to make these fields wide by hand.
9692 (when links
9693 (loop for i from 0 upto (1- maxfields) do
9694 (setq len (nth i lengths))
9695 (loop for j from 0 upto (1- (length fields)) do
9696 (setq c (nthcdr i (car (nthcdr j fields))))
9697 (if (and (stringp (car c))
9698 (string-match org-bracket-link-regexp (car c))
9699 (< (org-string-width (car c)) len))
9700 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
9702 ;; Compute the formats needed for output of the table
9703 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
9704 (while (setq l (pop lengths))
9705 (setq ty (if (pop typenums) "" "-")) ; number types flushright
9706 (setq rfmt (concat rfmt (format rfmt1 ty l))
9707 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
9708 (setq rfmt (concat rfmt "\n")
9709 hfmt (concat (substring hfmt 0 -1) "|\n"))
9711 (setq new (mapconcat
9712 (lambda (l)
9713 (if l (apply 'format rfmt
9714 (append (pop fields) emptystrings))
9715 hfmt))
9716 lines ""))
9717 ;; Replace the old one
9718 (delete-region beg end)
9719 (move-marker end nil)
9720 (move-marker org-table-aligned-begin-marker (point))
9721 (insert new)
9722 (move-marker org-table-aligned-end-marker (point))
9723 (when (and orgtbl-mode (not (eq major-mode 'org-mode)))
9724 (goto-char org-table-aligned-begin-marker)
9725 (while (org-hide-wide-columns org-table-aligned-end-marker)))
9726 ;; Try to move to the old location (approximately)
9727 (goto-line linepos)
9728 (set-window-start (selected-window) winstart 'noforce)
9729 (org-table-goto-column colpos)
9730 (setq org-table-may-need-update nil)
9733 (defun org-string-width (s)
9734 "Compute width of string, ignoring invisible characters.
9735 This ignores character with invisibility property `org-link', and also
9736 characters with property `org-cwidth', because these will become invisible
9737 upon the next fontification round."
9738 (let (b)
9739 (when (or (eq t buffer-invisibility-spec)
9740 (assq 'org-link buffer-invisibility-spec))
9741 (while (setq b (text-property-any 0 (length s)
9742 'invisible 'org-link s))
9743 (setq s (concat (substring s 0 b)
9744 (substring s (or (next-single-property-change
9745 b 'invisible s) (length s)))))))
9746 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
9747 (setq s (concat (substring s 0 b)
9748 (substring s (or (next-single-property-change
9749 b 'org-cwidth s) (length s))))))
9750 (string-width s)))
9752 (defun org-table-begin (&optional table-type)
9753 "Find the beginning of the table and return its position.
9754 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
9755 (save-excursion
9756 (if (not (re-search-backward
9757 (if table-type org-table-any-border-regexp
9758 org-table-border-regexp)
9759 nil t))
9760 (progn (goto-char (point-min)) (point))
9761 (goto-char (match-beginning 0))
9762 (beginning-of-line 2)
9763 (point))))
9765 (defun org-table-end (&optional table-type)
9766 "Find the end of the table and return its position.
9767 With argument TABLE-TYPE, go to the end of a table.el-type table."
9768 (save-excursion
9769 (if (not (re-search-forward
9770 (if table-type org-table-any-border-regexp
9771 org-table-border-regexp)
9772 nil t))
9773 (goto-char (point-max))
9774 (goto-char (match-beginning 0)))
9775 (point-marker)))
9777 (defun org-table-justify-field-maybe (&optional new)
9778 "Justify the current field, text to left, number to right.
9779 Optional argument NEW may specify text to replace the current field content."
9780 (cond
9781 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
9782 ((org-at-table-hline-p))
9783 ((and (not new)
9784 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
9785 (current-buffer)))
9786 (< (point) org-table-aligned-begin-marker)
9787 (>= (point) org-table-aligned-end-marker)))
9788 ;; This is not the same table, force a full re-align
9789 (setq org-table-may-need-update t))
9790 (t ;; realign the current field, based on previous full realign
9791 (let* ((pos (point)) s
9792 (col (org-table-current-column))
9793 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
9794 l f n o e)
9795 (when (> col 0)
9796 (skip-chars-backward "^|\n")
9797 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
9798 (progn
9799 (setq s (match-string 1)
9800 o (match-string 0)
9801 l (max 1 (- (match-end 0) (match-beginning 0) 3))
9802 e (not (= (match-beginning 2) (match-end 2))))
9803 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
9804 l (if e "|" (setq org-table-may-need-update t) ""))
9805 n (format f s))
9806 (if new
9807 (if (<= (length new) l) ;; FIXME: length -> str-width?
9808 (setq n (format f new))
9809 (setq n (concat new "|") org-table-may-need-update t)))
9810 (or (equal n o)
9811 (let (org-table-may-need-update)
9812 (replace-match n))))
9813 (setq org-table-may-need-update t))
9814 (goto-char pos))))))
9816 (defun org-table-next-field ()
9817 "Go to the next field in the current table, creating new lines as needed.
9818 Before doing so, re-align the table if necessary."
9819 (interactive)
9820 (org-table-maybe-eval-formula)
9821 (org-table-maybe-recalculate-line)
9822 (if (and org-table-automatic-realign
9823 org-table-may-need-update)
9824 (org-table-align))
9825 (let ((end (org-table-end)))
9826 (if (org-at-table-hline-p)
9827 (end-of-line 1))
9828 (condition-case nil
9829 (progn
9830 (re-search-forward "|" end)
9831 (if (looking-at "[ \t]*$")
9832 (re-search-forward "|" end))
9833 (if (and (looking-at "-")
9834 org-table-tab-jumps-over-hlines
9835 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
9836 (goto-char (match-beginning 1)))
9837 (if (looking-at "-")
9838 (progn
9839 (beginning-of-line 0)
9840 (org-table-insert-row 'below))
9841 (if (looking-at " ") (forward-char 1))))
9842 (error
9843 (org-table-insert-row 'below)))))
9845 (defun org-table-previous-field ()
9846 "Go to the previous field in the table.
9847 Before doing so, re-align the table if necessary."
9848 (interactive)
9849 (org-table-justify-field-maybe)
9850 (org-table-maybe-recalculate-line)
9851 (if (and org-table-automatic-realign
9852 org-table-may-need-update)
9853 (org-table-align))
9854 (if (org-at-table-hline-p)
9855 (end-of-line 1))
9856 (re-search-backward "|" (org-table-begin))
9857 (re-search-backward "|" (org-table-begin))
9858 (while (looking-at "|\\(-\\|[ \t]*$\\)")
9859 (re-search-backward "|" (org-table-begin)))
9860 (if (looking-at "| ?")
9861 (goto-char (match-end 0))))
9863 (defun org-table-next-row ()
9864 "Go to the next row (same column) in the current table.
9865 Before doing so, re-align the table if necessary."
9866 (interactive)
9867 (org-table-maybe-eval-formula)
9868 (org-table-maybe-recalculate-line)
9869 (if (or (looking-at "[ \t]*$")
9870 (save-excursion (skip-chars-backward " \t") (bolp)))
9871 (newline)
9872 (if (and org-table-automatic-realign
9873 org-table-may-need-update)
9874 (org-table-align))
9875 (let ((col (org-table-current-column)))
9876 (beginning-of-line 2)
9877 (if (or (not (org-at-table-p))
9878 (org-at-table-hline-p))
9879 (progn
9880 (beginning-of-line 0)
9881 (org-table-insert-row 'below)))
9882 (org-table-goto-column col)
9883 (skip-chars-backward "^|\n\r")
9884 (if (looking-at " ") (forward-char 1)))))
9886 (defun org-table-copy-down (n)
9887 "Copy a field down in the current column.
9888 If the field at the cursor is empty, copy into it the content of the nearest
9889 non-empty field above. With argument N, use the Nth non-empty field.
9890 If the current field is not empty, it is copied down to the next row, and
9891 the cursor is moved with it. Therefore, repeating this command causes the
9892 column to be filled row-by-row.
9893 If the variable `org-table-copy-increment' is non-nil and the field is an
9894 integer, it will be incremented while copying."
9895 (interactive "p")
9896 (let* ((colpos (org-table-current-column))
9897 (field (org-table-get-field))
9898 (non-empty (string-match "[^ \t]" field))
9899 (beg (org-table-begin))
9900 txt)
9901 (org-table-check-inside-data-field)
9902 (if non-empty
9903 (progn
9904 (setq txt (org-trim field))
9905 (org-table-next-row)
9906 (org-table-blank-field))
9907 (save-excursion
9908 (setq txt
9909 (catch 'exit
9910 (while (progn (beginning-of-line 1)
9911 (re-search-backward org-table-dataline-regexp
9912 beg t))
9913 (org-table-goto-column colpos t)
9914 (if (and (looking-at
9915 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
9916 (= (setq n (1- n)) 0))
9917 (throw 'exit (match-string 1))))))))
9918 (if txt
9919 (progn
9920 (if (and org-table-copy-increment
9921 (string-match "^[0-9]+$" txt))
9922 (setq txt (format "%d" (+ (string-to-number txt) 1))))
9923 (insert txt)
9924 (org-table-maybe-recalculate-line)
9925 (org-table-align))
9926 (error "No non-empty field found"))))
9928 (defun org-table-check-inside-data-field ()
9929 "Is point inside a table data field?
9930 I.e. not on a hline or before the first or after the last column?
9931 This actually throws an error, so it aborts the current command."
9932 (if (or (not (org-at-table-p))
9933 (= (org-table-current-column) 0)
9934 (org-at-table-hline-p)
9935 (looking-at "[ \t]*$"))
9936 (error "Not in table data field")))
9938 (defvar org-table-clip nil
9939 "Clipboard for table regions.")
9941 (defun org-table-blank-field ()
9942 "Blank the current table field or active region."
9943 (interactive)
9944 (org-table-check-inside-data-field)
9945 (if (and (interactive-p) (org-region-active-p))
9946 (let (org-table-clip)
9947 (org-table-cut-region (region-beginning) (region-end)))
9948 (skip-chars-backward "^|")
9949 (backward-char 1)
9950 (if (looking-at "|[^|\n]+")
9951 (let* ((pos (match-beginning 0))
9952 (match (match-string 0))
9953 (len (org-string-width match)))
9954 (replace-match (concat "|" (make-string (1- len) ?\ )))
9955 (goto-char (+ 2 pos))
9956 (substring match 1)))))
9958 (defun org-table-get-field (&optional n replace)
9959 "Return the value of the field in column N of current row.
9960 N defaults to current field.
9961 If REPLACE is a string, replace field with this value. The return value
9962 is always the old value."
9963 (and n (org-table-goto-column n))
9964 (skip-chars-backward "^|\n")
9965 (backward-char 1)
9966 (if (looking-at "|[^|\r\n]*")
9967 (let* ((pos (match-beginning 0))
9968 (val (buffer-substring (1+ pos) (match-end 0))))
9969 (if replace
9970 (replace-match (concat "|" replace)))
9971 (goto-char (min (point-at-eol) (+ 2 pos)))
9972 val)
9973 (forward-char 1) ""))
9975 (defun org-table-current-column ()
9976 "Find out which column we are in.
9977 When called interactively, column is also displayed in echo area."
9978 (interactive)
9979 (if (interactive-p) (org-table-check-inside-data-field))
9980 (save-excursion
9981 (let ((cnt 0) (pos (point)))
9982 (beginning-of-line 1)
9983 (while (search-forward "|" pos t)
9984 (setq cnt (1+ cnt)))
9985 (if (interactive-p) (message "This is table column %d" cnt))
9986 cnt)))
9988 (defun org-table-goto-column (n &optional on-delim force)
9989 "Move the cursor to the Nth column in the current table line.
9990 With optional argument ON-DELIM, stop with point before the left delimiter
9991 of the field.
9992 If there are less than N fields, just go to after the last delimiter.
9993 However, when FORCE is non-nil, create new columns if necessary."
9994 (interactive "p")
9995 (let ((pos (point-at-eol)))
9996 (beginning-of-line 1)
9997 (when (> n 0)
9998 (while (and (> (setq n (1- n)) -1)
9999 (or (search-forward "|" pos t)
10000 (and force
10001 (progn (end-of-line 1)
10002 (skip-chars-backward "^|")
10003 (insert " | "))))))
10004 ; (backward-char 2) t)))))
10005 (when (and force (not (looking-at ".*|")))
10006 (save-excursion (end-of-line 1) (insert " | ")))
10007 (if on-delim
10008 (backward-char 1)
10009 (if (looking-at " ") (forward-char 1))))))
10011 (defun org-at-table-p (&optional table-type)
10012 "Return t if the cursor is inside an org-type table.
10013 If TABLE-TYPE is non-nil, also check for table.el-type tables."
10014 (if org-enable-table-editor
10015 (save-excursion
10016 (beginning-of-line 1)
10017 (looking-at (if table-type org-table-any-line-regexp
10018 org-table-line-regexp)))
10019 nil))
10021 (defun org-at-table.el-p ()
10022 "Return t if and only if we are at a table.el table."
10023 (and (org-at-table-p 'any)
10024 (save-excursion
10025 (goto-char (org-table-begin 'any))
10026 (looking-at org-table1-hline-regexp))))
10028 (defun org-table-recognize-table.el ()
10029 "If there is a table.el table nearby, recognize it and move into it."
10030 (if org-table-tab-recognizes-table.el
10031 (if (org-at-table.el-p)
10032 (progn
10033 (beginning-of-line 1)
10034 (if (looking-at org-table-dataline-regexp)
10036 (if (looking-at org-table1-hline-regexp)
10037 (progn
10038 (beginning-of-line 2)
10039 (if (looking-at org-table-any-border-regexp)
10040 (beginning-of-line -1)))))
10041 (if (re-search-forward "|" (org-table-end t) t)
10042 (progn
10043 (require 'table)
10044 (if (table--at-cell-p (point))
10046 (message "recognizing table.el table...")
10047 (table-recognize-table)
10048 (message "recognizing table.el table...done")))
10049 (error "This should not happen..."))
10051 nil)
10052 nil))
10054 (defun org-at-table-hline-p ()
10055 "Return t if the cursor is inside a hline in a table."
10056 (if org-enable-table-editor
10057 (save-excursion
10058 (beginning-of-line 1)
10059 (looking-at org-table-hline-regexp))
10060 nil))
10062 (defun org-table-insert-column ()
10063 "Insert a new column into the table."
10064 (interactive)
10065 (if (not (org-at-table-p))
10066 (error "Not at a table"))
10067 (org-table-find-dataline)
10068 (let* ((col (max 1 (org-table-current-column)))
10069 (beg (org-table-begin))
10070 (end (org-table-end))
10071 ;; Current cursor position
10072 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10073 (colpos col))
10074 (goto-char beg)
10075 (while (< (point) end)
10076 (if (org-at-table-hline-p)
10078 (org-table-goto-column col t)
10079 (insert "| "))
10080 (beginning-of-line 2))
10081 (move-marker end nil)
10082 (goto-line linepos)
10083 (org-table-goto-column colpos)
10084 (org-table-align)
10085 (org-table-modify-formulas 'insert col)))
10087 (defun org-table-find-dataline ()
10088 "Find a dataline in the current table, which is needed for column commands."
10089 (if (and (org-at-table-p)
10090 (not (org-at-table-hline-p)))
10092 (let ((col (current-column))
10093 (end (org-table-end)))
10094 (move-to-column col)
10095 (while (and (< (point) end)
10096 (or (not (= (current-column) col))
10097 (org-at-table-hline-p)))
10098 (beginning-of-line 2)
10099 (move-to-column col))
10100 (if (and (org-at-table-p)
10101 (not (org-at-table-hline-p)))
10103 (error
10104 "Please position cursor in a data line for column operations")))))
10106 (defun org-table-delete-column ()
10107 "Delete a column from the table."
10108 (interactive)
10109 (if (not (org-at-table-p))
10110 (error "Not at a table"))
10111 (org-table-find-dataline)
10112 (org-table-check-inside-data-field)
10113 (let* ((col (org-table-current-column))
10114 (beg (org-table-begin))
10115 (end (org-table-end))
10116 ;; Current cursor position
10117 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10118 (colpos col))
10119 (goto-char beg)
10120 (while (< (point) end)
10121 (if (org-at-table-hline-p)
10123 (org-table-goto-column col t)
10124 (and (looking-at "|[^|\n]+|")
10125 (replace-match "|")))
10126 (beginning-of-line 2))
10127 (move-marker end nil)
10128 (goto-line linepos)
10129 (org-table-goto-column colpos)
10130 (org-table-align)
10131 (org-table-modify-formulas 'remove col)))
10133 (defun org-table-move-column-right ()
10134 "Move column to the right."
10135 (interactive)
10136 (org-table-move-column nil))
10137 (defun org-table-move-column-left ()
10138 "Move column to the left."
10139 (interactive)
10140 (org-table-move-column 'left))
10142 (defun org-table-move-column (&optional left)
10143 "Move the current column to the right. With arg LEFT, move to the left."
10144 (interactive "P")
10145 (if (not (org-at-table-p))
10146 (error "Not at a table"))
10147 (org-table-find-dataline)
10148 (org-table-check-inside-data-field)
10149 (let* ((col (org-table-current-column))
10150 (col1 (if left (1- col) col))
10151 (beg (org-table-begin))
10152 (end (org-table-end))
10153 ;; Current cursor position
10154 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10155 (colpos (if left (1- col) (1+ col))))
10156 (if (and left (= col 1))
10157 (error "Cannot move column further left"))
10158 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
10159 (error "Cannot move column further right"))
10160 (goto-char beg)
10161 (while (< (point) end)
10162 (if (org-at-table-hline-p)
10164 (org-table-goto-column col1 t)
10165 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
10166 (replace-match "|\\2|\\1|")))
10167 (beginning-of-line 2))
10168 (move-marker end nil)
10169 (goto-line linepos)
10170 (org-table-goto-column colpos)
10171 (org-table-align)
10172 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
10174 (defun org-table-move-row-down ()
10175 "Move table row down."
10176 (interactive)
10177 (org-table-move-row nil))
10178 (defun org-table-move-row-up ()
10179 "Move table row up."
10180 (interactive)
10181 (org-table-move-row 'up))
10183 (defun org-table-move-row (&optional up)
10184 "Move the current table line down. With arg UP, move it up."
10185 (interactive "P")
10186 (let ((col (current-column))
10187 (pos (point))
10188 (tonew (if up 0 2))
10189 txt)
10190 (beginning-of-line tonew)
10191 (if (not (org-at-table-p))
10192 (progn
10193 (goto-char pos)
10194 (error "Cannot move row further")))
10195 (goto-char pos)
10196 (beginning-of-line 1)
10197 (setq pos (point))
10198 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
10199 (delete-region (point) (1+ (point-at-eol)))
10200 (beginning-of-line tonew)
10201 (insert txt)
10202 (beginning-of-line 0)
10203 (move-to-column col)))
10205 (defun org-table-insert-row (&optional arg)
10206 "Insert a new row above the current line into the table.
10207 With prefix ARG, insert below the current line."
10208 (interactive "P")
10209 (if (not (org-at-table-p))
10210 (error "Not at a table"))
10211 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
10212 (new (org-table-clean-line line)))
10213 ;; Fix the first field if necessary
10214 (if (string-match "^[ \t]*| *[#$] *|" line)
10215 (setq new (replace-match (match-string 0 line) t t new)))
10216 (beginning-of-line (if arg 2 1))
10217 (let (org-table-may-need-update) (insert-before-markers new "\n"))
10218 (beginning-of-line 0)
10219 (re-search-forward "| ?" (point-at-eol) t)
10220 (and org-table-may-need-update (org-table-align))))
10222 (defun org-table-insert-hline (&optional arg)
10223 "Insert a horizontal-line below the current line into the table.
10224 With prefix ARG, insert above the current line."
10225 (interactive "P")
10226 (if (not (org-at-table-p))
10227 (error "Not at a table"))
10228 (let ((line (org-table-clean-line
10229 (buffer-substring (point-at-bol) (point-at-eol))))
10230 (col (current-column)))
10231 (while (string-match "|\\( +\\)|" line)
10232 (setq line (replace-match
10233 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
10234 ?-) "|") t t line)))
10235 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
10236 (beginning-of-line (if arg 1 2))
10237 (insert line "\n")
10238 (beginning-of-line (if arg 1 -1))
10239 (move-to-column col)))
10241 (defun org-table-clean-line (s)
10242 "Convert a table line S into a string with only \"|\" and space.
10243 In particular, this does handle wide and invisible characters."
10244 (if (string-match "^[ \t]*|-" s)
10245 ;; It's a hline, just map the characters
10246 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
10247 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
10248 (setq s (replace-match
10249 (concat "|" (make-string (org-string-width (match-string 1 s))
10250 ?\ ) "|")
10251 t t s)))
10254 (defun org-table-kill-row ()
10255 "Delete the current row or horizontal line from the table."
10256 (interactive)
10257 (if (not (org-at-table-p))
10258 (error "Not at a table"))
10259 (let ((col (current-column)))
10260 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
10261 (if (not (org-at-table-p)) (beginning-of-line 0))
10262 (move-to-column col)))
10264 (defun org-table-sort-lines (beg end numericp)
10265 "Sort table lines in region.
10266 Point and mark define the first and last line to include. Both point and
10267 mark should be in the column that is used for sorting. For example, to
10268 sort according to column 3, put the mark in the first line to sort, in
10269 table column 3. Put point into the last line to be included in the sorting,
10270 also in table column 3. The command will prompt for the sorting method
10271 \(n for numerical, a for alphanumeric)."
10272 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
10273 (setq numericp (string-match "[nN]" numericp))
10274 (org-table-align) ;; Just to be safe
10275 (let* (bcol ecol cmp column lns)
10276 (goto-char beg)
10277 (org-table-check-inside-data-field)
10278 (setq column (org-table-current-column)
10279 beg (move-marker (make-marker) (point-at-bol)))
10280 (goto-char end)
10281 (org-table-check-inside-data-field)
10282 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
10283 (untabify beg end)
10284 (goto-char beg)
10285 (org-table-goto-column column)
10286 (skip-chars-backward "^|")
10287 (setq bcol (current-column))
10288 (org-table-goto-column (1+ column))
10289 (skip-chars-backward "^|")
10290 (setq ecol (1- (current-column)))
10291 (setq cmp (if numericp
10292 (lambda (a b) (< (car a) (car b)))
10293 (lambda (a b) (string< (car a) (car b)))))
10294 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
10295 (org-split-string (buffer-substring beg end) "\n")))
10296 (if numericp
10297 (setq lns (mapcar (lambda(x)
10298 (cons (string-to-number (car x)) (cdr x)))
10299 lns)))
10300 (delete-region beg end)
10301 (move-marker beg nil)
10302 (move-marker end nil)
10303 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
10304 (message "%d lines sorted %s based on column %d"
10305 (length lns)
10306 (if numericp "numerically" "alphabetically") column)))
10308 (defun org-table-cut-region (beg end)
10309 "Copy region in table to the clipboard and blank all relevant fields."
10310 (interactive "r")
10311 (org-table-copy-region beg end 'cut))
10313 (defun org-table-copy-region (beg end &optional cut)
10314 "Copy rectangular region in table to clipboard.
10315 A special clipboard is used which can only be accessed
10316 with `org-table-paste-rectangle'."
10317 (interactive "rP")
10318 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
10319 region cols
10320 (rpl (if cut " " nil)))
10321 (goto-char beg)
10322 (org-table-check-inside-data-field)
10323 (setq l01 (count-lines (point-min) (point))
10324 c01 (org-table-current-column))
10325 (goto-char end)
10326 (org-table-check-inside-data-field)
10327 (setq l02 (count-lines (point-min) (point))
10328 c02 (org-table-current-column))
10329 (setq l1 (min l01 l02) l2 (max l01 l02)
10330 c1 (min c01 c02) c2 (max c01 c02))
10331 (catch 'exit
10332 (while t
10333 (catch 'nextline
10334 (if (> l1 l2) (throw 'exit t))
10335 (goto-line l1)
10336 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
10337 (setq cols nil ic1 c1 ic2 c2)
10338 (while (< ic1 (1+ ic2))
10339 (push (org-table-get-field ic1 rpl) cols)
10340 (setq ic1 (1+ ic1)))
10341 (push (nreverse cols) region)
10342 (setq l1 (1+ l1)))))
10343 (setq org-table-clip (nreverse region))
10344 (if cut (org-table-align))
10345 org-table-clip))
10347 (defun org-table-paste-rectangle ()
10348 "Paste a rectangular region into a table.
10349 The upper right corner ends up in the current field. All involved fields
10350 will be overwritten. If the rectangle does not fit into the present table,
10351 the table is enlarged as needed. The process ignores horizontal separator
10352 lines."
10353 (interactive)
10354 (unless (and org-table-clip (listp org-table-clip))
10355 (error "First cut/copy a region to paste!"))
10356 (org-table-check-inside-data-field)
10357 (let* ((clip org-table-clip)
10358 (line (count-lines (point-min) (point)))
10359 (col (org-table-current-column))
10360 (org-enable-table-editor t)
10361 (org-table-automatic-realign nil)
10362 c cols field)
10363 (while (setq cols (pop clip))
10364 (while (org-at-table-hline-p) (beginning-of-line 2))
10365 (if (not (org-at-table-p))
10366 (progn (end-of-line 0) (org-table-next-field)))
10367 (setq c col)
10368 (while (setq field (pop cols))
10369 (org-table-goto-column c nil 'force)
10370 (org-table-get-field nil field)
10371 (setq c (1+ c)))
10372 (beginning-of-line 2))
10373 (goto-line line)
10374 (org-table-goto-column col)
10375 (org-table-align)))
10377 (defun org-table-convert ()
10378 "Convert from `org-mode' table to table.el and back.
10379 Obviously, this only works within limits. When an Org-mode table is
10380 converted to table.el, all horizontal separator lines get lost, because
10381 table.el uses these as cell boundaries and has no notion of horizontal lines.
10382 A table.el table can be converted to an Org-mode table only if it does not
10383 do row or column spanning. Multiline cells will become multiple cells.
10384 Beware, Org-mode does not test if the table can be successfully converted - it
10385 blindly applies a recipe that works for simple tables."
10386 (interactive)
10387 (require 'table)
10388 (if (org-at-table.el-p)
10389 ;; convert to Org-mode table
10390 (let ((beg (move-marker (make-marker) (org-table-begin t)))
10391 (end (move-marker (make-marker) (org-table-end t))))
10392 (table-unrecognize-region beg end)
10393 (goto-char beg)
10394 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
10395 (replace-match ""))
10396 (goto-char beg))
10397 (if (org-at-table-p)
10398 ;; convert to table.el table
10399 (let ((beg (move-marker (make-marker) (org-table-begin)))
10400 (end (move-marker (make-marker) (org-table-end))))
10401 ;; first, get rid of all horizontal lines
10402 (goto-char beg)
10403 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
10404 (replace-match ""))
10405 ;; insert a hline before first
10406 (goto-char beg)
10407 (org-table-insert-hline 'above)
10408 (beginning-of-line -1)
10409 ;; insert a hline after each line
10410 (while (progn (beginning-of-line 3) (< (point) end))
10411 (org-table-insert-hline))
10412 (goto-char beg)
10413 (setq end (move-marker end (org-table-end)))
10414 ;; replace "+" at beginning and ending of hlines
10415 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
10416 (replace-match "\\1+-"))
10417 (goto-char beg)
10418 (while (re-search-forward "-|[ \t]*$" end t)
10419 (replace-match "-+"))
10420 (goto-char beg)))))
10422 (defun org-table-wrap-region (arg)
10423 "Wrap several fields in a column like a paragraph.
10424 This is useful if you'd like to spread the contents of a field over several
10425 lines, in order to keep the table compact.
10427 If there is an active region, and both point and mark are in the same column,
10428 the text in the column is wrapped to minimum width for the given number of
10429 lines. Generally, this makes the table more compact. A prefix ARG may be
10430 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
10431 formats the selected text to two lines. If the region was longer than two
10432 lines, the remaining lines remain empty. A negative prefix argument reduces
10433 the current number of lines by that amount. The wrapped text is pasted back
10434 into the table. If you formatted it to more lines than it was before, fields
10435 further down in the table get overwritten - so you might need to make space in
10436 the table first.
10438 If there is no region, the current field is split at the cursor position and
10439 the text fragment to the right of the cursor is prepended to the field one
10440 line down.
10442 If there is no region, but you specify a prefix ARG, the current field gets
10443 blank, and the content is appended to the field above."
10444 (interactive "P")
10445 (org-table-check-inside-data-field)
10446 (if (org-region-active-p)
10447 ;; There is a region: fill as a paragraph
10448 (let ((beg (region-beginning))
10449 nlines)
10450 (org-table-cut-region (region-beginning) (region-end))
10451 (if (> (length (car org-table-clip)) 1)
10452 (error "Region must be limited to single column"))
10453 (setq nlines (if arg
10454 (if (< arg 1)
10455 (+ (length org-table-clip) arg)
10456 arg)
10457 (length org-table-clip)))
10458 (setq org-table-clip
10459 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
10460 nil nlines)))
10461 (goto-char beg)
10462 (org-table-paste-rectangle))
10463 ;; No region, split the current field at point
10464 (if arg
10465 ;; combine with field above
10466 (let ((s (org-table-blank-field))
10467 (col (org-table-current-column)))
10468 (beginning-of-line 0)
10469 (while (org-at-table-hline-p) (beginning-of-line 0))
10470 (org-table-goto-column col)
10471 (skip-chars-forward "^|")
10472 (skip-chars-backward " ")
10473 (insert " " (org-trim s))
10474 (org-table-align))
10475 ;; split field
10476 (when (looking-at "\\([^|]+\\)+|")
10477 (let ((s (match-string 1)))
10478 (replace-match " |")
10479 (goto-char (match-beginning 0))
10480 (org-table-next-row)
10481 (insert (org-trim s) " ")
10482 (org-table-align))))))
10484 (defvar org-field-marker nil)
10486 (defun org-table-edit-field (arg)
10487 "Edit table field in a different window.
10488 This is mainly useful for fields that contain hidden parts.
10489 When called with a \\[universal-argument] prefix, just make the full field visible so that
10490 it can be edited in place."
10491 (interactive "P")
10492 (if arg
10493 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
10494 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
10495 (remove-text-properties b e '(org-cwidth t invisible t
10496 display t intangible t))
10497 (if (and (boundp 'font-lock-mode) font-lock-mode)
10498 (font-lock-fontify-block)))
10499 (let ((pos (move-marker (make-marker) (point)))
10500 (field (org-table-get-field))
10501 (cw (current-window-configuration))
10503 (switch-to-buffer-other-window "*Org tmp*")
10504 (erase-buffer)
10505 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
10506 (org-mode)
10507 (goto-char (setq p (point-max)))
10508 (insert (org-trim field))
10509 (remove-text-properties p (point-max)
10510 '(invisible t org-cwidth t display t
10511 intangible t))
10512 (goto-char p)
10513 (set (make-local-variable 'org-finish-function)
10514 'org-table-finish-edit-field)
10515 (set (make-local-variable 'org-window-configuration) cw)
10516 (set (make-local-variable 'org-field-marker) pos)
10517 (message "Edit and finish with C-c C-c"))))
10519 (defun org-table-finish-edit-field ()
10520 "Finish editing a table data field.
10521 Remove all newline characters, insert the result into the table, realign
10522 the table and kill the editing buffer."
10523 (let ((pos org-field-marker)
10524 (cw org-window-configuration)
10525 (cb (current-buffer))
10526 text)
10527 (goto-char (point-min))
10528 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
10529 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
10530 (replace-match " "))
10531 (setq text (org-trim (buffer-string)))
10532 (set-window-configuration cw)
10533 (kill-buffer cb)
10534 (select-window (get-buffer-window (marker-buffer pos)))
10535 (goto-char pos)
10536 (move-marker pos nil)
10537 (org-table-check-inside-data-field)
10538 (org-table-get-field nil text)
10539 (org-table-align)
10540 (message "New field value inserted")))
10542 (defun org-trim (s)
10543 "Remove whitespace at beginning and end of string."
10544 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
10545 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
10548 (defun org-wrap (string &optional width lines)
10549 "Wrap string to either a number of lines, or a width in characters.
10550 If WIDTH is non-nil, the string is wrapped to that width, however many lines
10551 that costs. If there is a word longer than WIDTH, the text is actually
10552 wrapped to the length of that word.
10553 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
10554 many lines, whatever width that takes.
10555 The return value is a list of lines, without newlines at the end."
10556 (let* ((words (org-split-string string "[ \t\n]+"))
10557 (maxword (apply 'max (mapcar 'org-string-width words)))
10558 w ll)
10559 (cond (width
10560 (org-do-wrap words (max maxword width)))
10561 (lines
10562 (setq w maxword)
10563 (setq ll (org-do-wrap words maxword))
10564 (if (<= (length ll) lines)
10566 (setq ll words)
10567 (while (> (length ll) lines)
10568 (setq w (1+ w))
10569 (setq ll (org-do-wrap words w)))
10570 ll))
10571 (t (error "Cannot wrap this")))))
10574 (defun org-do-wrap (words width)
10575 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
10576 (let (lines line)
10577 (while words
10578 (setq line (pop words))
10579 (while (and words (< (+ (length line) (length (car words))) width))
10580 (setq line (concat line " " (pop words))))
10581 (setq lines (push line lines)))
10582 (nreverse lines)))
10584 (defun org-split-string (string &optional separators)
10585 "Splits STRING into substrings at SEPARATORS.
10586 No empty strings are returned if there are matches at the beginning
10587 and end of string."
10588 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
10589 (start 0)
10590 notfirst
10591 (list nil))
10592 (while (and (string-match rexp string
10593 (if (and notfirst
10594 (= start (match-beginning 0))
10595 (< start (length string)))
10596 (1+ start) start))
10597 (< (match-beginning 0) (length string)))
10598 (setq notfirst t)
10599 (or (eq (match-beginning 0) 0)
10600 (and (eq (match-beginning 0) (match-end 0))
10601 (eq (match-beginning 0) start))
10602 (setq list
10603 (cons (substring string start (match-beginning 0))
10604 list)))
10605 (setq start (match-end 0)))
10606 (or (eq start (length string))
10607 (setq list
10608 (cons (substring string start)
10609 list)))
10610 (nreverse list)))
10612 (defun org-table-map-tables (function)
10613 "Apply FUNCTION to the start of all tables in the buffer."
10614 (save-excursion
10615 (save-restriction
10616 (widen)
10617 (goto-char (point-min))
10618 (while (re-search-forward org-table-any-line-regexp nil t)
10619 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
10620 (beginning-of-line 1)
10621 (if (looking-at org-table-line-regexp)
10622 (save-excursion (funcall function)))
10623 (re-search-forward org-table-any-border-regexp nil 1))))
10624 (message "Mapping tables: done"))
10626 (defun org-table-sum (&optional beg end nlast)
10627 "Sum numbers in region of current table column.
10628 The result will be displayed in the echo area, and will be available
10629 as kill to be inserted with \\[yank].
10631 If there is an active region, it is interpreted as a rectangle and all
10632 numbers in that rectangle will be summed. If there is no active
10633 region and point is located in a table column, sum all numbers in that
10634 column.
10636 If at least one number looks like a time HH:MM or HH:MM:SS, all other
10637 numbers are assumed to be times as well (in decimal hours) and the
10638 numbers are added as such.
10640 If NLAST is a number, only the NLAST fields will actually be summed."
10641 (interactive)
10642 (save-excursion
10643 (let (col (timecnt 0) diff h m s org-table-clip)
10644 (cond
10645 ((and beg end)) ; beg and end given explicitly
10646 ((org-region-active-p)
10647 (setq beg (region-beginning) end (region-end)))
10649 (setq col (org-table-current-column))
10650 (goto-char (org-table-begin))
10651 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
10652 (error "No table data"))
10653 (org-table-goto-column col)
10654 ;not needed? (skip-chars-backward "^|")
10655 (setq beg (point))
10656 (goto-char (org-table-end))
10657 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
10658 (error "No table data"))
10659 (org-table-goto-column col)
10660 ;not needed? (skip-chars-forward "^|")
10661 (setq end (point))))
10662 (let* ((items (apply 'append (org-table-copy-region beg end)))
10663 (items1 (cond ((not nlast) items)
10664 ((>= nlast (length items)) items)
10665 (t (setq items (reverse items))
10666 (setcdr (nthcdr (1- nlast) items) nil)
10667 (nreverse items))))
10668 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
10669 items1)))
10670 (res (apply '+ numbers))
10671 (sres (if (= timecnt 0)
10672 (format "%g" res)
10673 (setq diff (* 3600 res)
10674 h (floor (/ diff 3600)) diff (mod diff 3600)
10675 m (floor (/ diff 60)) diff (mod diff 60)
10676 s diff)
10677 (format "%d:%02d:%02d" h m s))))
10678 (kill-new sres)
10679 (if (interactive-p)
10680 (message "%s"
10681 (substitute-command-keys
10682 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
10683 (length numbers) sres))))
10684 sres))))
10686 (defun org-table-get-number-for-summing (s)
10687 (let (n)
10688 (if (string-match "^ *|? *" s)
10689 (setq s (replace-match "" nil nil s)))
10690 (if (string-match " *|? *$" s)
10691 (setq s (replace-match "" nil nil s)))
10692 (setq n (string-to-number s))
10693 (cond
10694 ((and (string-match "0" s)
10695 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
10696 ((string-match "\\`[ \t]+\\'" s) nil)
10697 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
10698 (let ((h (string-to-number (or (match-string 1 s) "0")))
10699 (m (string-to-number (or (match-string 2 s) "0")))
10700 (s (string-to-number (or (match-string 4 s) "0"))))
10701 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
10702 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
10703 ((equal n 0) nil)
10704 (t n))))
10706 (defun org-table-get-vertical-vector (desc &optional tbeg col)
10707 "Get a calc vector from a column, accorting to descriptor DESC.
10708 Optional arguments TBEG and COL can give the beginning of the table and
10709 the current column, to avoid unnecessary parsing."
10710 (save-excursion
10711 (or tbeg (setq tbeg (org-table-begin)))
10712 (or col (setq col (org-table-current-column)))
10713 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
10714 (cond
10715 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
10716 (setq n1 (- (match-end 1) (match-beginning 1)))
10717 (if (match-beginning 3)
10718 (setq n2 (- (match-end 2) (match-beginning 3))))
10719 (setq n (if n2 (max n1 n2) n1))
10720 (setq n1 (if n2 (min n1 n2)))
10721 (setq nn n)
10722 (while (and (> nn 0)
10723 (re-search-backward org-table-hline-regexp tbeg t))
10724 (push (org-current-line) hline-list)
10725 (setq nn (1- nn)))
10726 (setq hline-list (nreverse hline-list))
10727 (goto-line (nth (1- n) hline-list))
10728 (when (re-search-forward org-table-dataline-regexp)
10729 (org-table-goto-column col)
10730 (setq beg (point)))
10731 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
10732 (when (re-search-backward org-table-dataline-regexp)
10733 (org-table-goto-column col)
10734 (setq end (point)))
10735 (setq l (apply 'append (org-table-copy-region beg end)))
10736 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
10737 (if (equal x "") "0" x))
10738 l ",") "]"))
10739 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
10740 (setq n1 (string-to-number (match-string 1 desc))
10741 n2 (string-to-number (match-string 2 desc)))
10742 (beginning-of-line 1)
10743 (save-excursion
10744 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
10745 (org-table-goto-column col)
10746 (setq beg (point))))
10747 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
10748 (org-table-goto-column col)
10749 (setq end (point)))
10750 (setq l (apply 'append (org-table-copy-region beg end)))
10751 (concat "[" (mapconcat
10752 (lambda (x) (setq x (org-trim x))
10753 (if (equal x "") "0" x))
10754 l ",") "]"))
10755 ((string-match "\\([0-9]+\\)" desc)
10756 (beginning-of-line 1)
10757 (when (re-search-backward org-table-dataline-regexp tbeg t
10758 (string-to-number (match-string 0 desc)))
10759 (org-table-goto-column col)
10760 (org-trim (org-table-get-field))))))))
10762 (defvar org-table-formula-history nil)
10764 (defvar org-table-column-names nil
10765 "Alist with column names, derived from the `!' line.")
10766 (defvar org-table-column-name-regexp nil
10767 "Regular expression matching the current column names.")
10768 (defvar org-table-local-parameters nil
10769 "Alist with parameter names, derived from the `$' line.")
10770 (defvar org-table-named-field-locations nil
10771 "Alist with locations of named fields.")
10773 (defun org-table-get-formula (&optional equation named)
10774 "Read a formula from the minibuffer, offer stored formula as default."
10775 (let* ((name (car (rassoc (list (org-current-line)
10776 (org-table-current-column))
10777 org-table-named-field-locations)))
10778 (scol (if named
10779 (if name name
10780 (error "Not in a named field"))
10781 (int-to-string (org-table-current-column))))
10782 (dummy (and name (not named)
10783 (not (y-or-n-p "Replace named-field formula with column equation? " ))
10784 (error "Abort")))
10785 (org-table-may-need-update nil)
10786 (stored-list (org-table-get-stored-formulas))
10787 (stored (cdr (assoc scol stored-list)))
10788 (eq (cond
10789 ((and stored equation (string-match "^ *=? *$" equation))
10790 stored)
10791 ((stringp equation)
10792 equation)
10793 (t (read-string
10794 (format "%s formula $%s=" (if named "Field" "Column") scol)
10795 (or stored "") 'org-table-formula-history
10796 ;stored
10797 ))))
10798 mustsave)
10799 (when (not (string-match "\\S-" eq))
10800 ;; remove formula
10801 (setq stored-list (delq (assoc scol stored-list) stored-list))
10802 (org-table-store-formulas stored-list)
10803 (error "Formula removed"))
10804 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
10805 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
10806 (if (and name (not named))
10807 ;; We set the column equation, delete the named one.
10808 (setq stored-list (delq (assoc name stored-list) stored-list)
10809 mustsave t))
10810 (if stored
10811 (setcdr (assoc scol stored-list) eq)
10812 (setq stored-list (cons (cons scol eq) stored-list)))
10813 (if (or mustsave (not (equal stored eq)))
10814 (org-table-store-formulas stored-list))
10815 eq))
10817 (defun org-table-store-formulas (alist)
10818 "Store the list of formulas below the current table."
10819 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
10820 (save-excursion
10821 (goto-char (org-table-end))
10822 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
10823 (delete-region (point) (match-end 0)))
10824 (insert "#+TBLFM: "
10825 (mapconcat (lambda (x)
10826 (concat "$" (car x) "=" (cdr x)))
10827 alist "::")
10828 "\n")))
10830 (defun org-table-get-stored-formulas ()
10831 "Return an alist with the stored formulas directly after current table."
10832 (interactive)
10833 (let (scol eq eq-alist strings string seen)
10834 (save-excursion
10835 (goto-char (org-table-end))
10836 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
10837 (setq strings (org-split-string (match-string 2) " *:: *"))
10838 (while (setq string (pop strings))
10839 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
10840 (setq scol (match-string 1 string)
10841 eq (match-string 2 string)
10842 eq-alist (cons (cons scol eq) eq-alist))
10843 (if (member scol seen)
10844 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
10845 (push scol seen))))))
10846 (nreverse eq-alist)))
10848 (defun org-table-modify-formulas (action &rest columns)
10849 "Modify the formulas stored below the current table.
10850 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
10851 expected, for the other actions only a single column number is needed."
10852 (let ((list (org-table-get-stored-formulas))
10853 (nmax (length (org-split-string
10854 (buffer-substring (point-at-bol) (point-at-eol))
10855 "|")))
10856 col col1 col2 scol si sc1 sc2)
10857 (cond
10858 ((null list)) ; No action needed if there are no stored formulas
10859 ((eq action 'remove)
10860 (setq col (car columns)
10861 scol (int-to-string col))
10862 (org-table-replace-in-formulas list scol "INVALID")
10863 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
10864 (loop for i from (1+ col) upto nmax by 1 do
10865 (setq si (int-to-string i))
10866 (org-table-replace-in-formulas list si (int-to-string (1- i)))
10867 (if (assoc si list) (setcar (assoc si list)
10868 (int-to-string (1- i))))))
10869 ((eq action 'insert)
10870 (setq col (car columns))
10871 (loop for i from nmax downto col by 1 do
10872 (setq si (int-to-string i))
10873 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
10874 (if (assoc si list) (setcar (assoc si list)
10875 (int-to-string (1+ i))))))
10876 ((eq action 'swap)
10877 (setq col1 (car columns) col2 (nth 1 columns)
10878 sc1 (int-to-string col1) sc2 (int-to-string col2))
10879 ;; Hopefully, ZqZtZ will never be a name in a table
10880 (org-table-replace-in-formulas list sc1 "ZqZtZ")
10881 (org-table-replace-in-formulas list sc2 sc1)
10882 (org-table-replace-in-formulas list "ZqZtZ" sc2)
10883 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
10884 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
10885 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
10886 (t (error "Invalid action in `org-table-modify-formulas'")))
10887 (if list (org-table-store-formulas list))))
10889 (defun org-table-replace-in-formulas (list s1 s2)
10890 (let (elt re s)
10891 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
10892 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
10893 re (concat (regexp-quote s1) "\\>"))
10894 (while (setq elt (pop list))
10895 (setq s (cdr elt))
10896 (while (string-match re s)
10897 (setq s (replace-match s2 t t s)))
10898 (setcdr elt s))))
10900 (defun org-table-get-specials ()
10901 "Get the column names and local parameters for this table."
10902 (save-excursion
10903 (let ((beg (org-table-begin)) (end (org-table-end))
10904 names name fields fields1 field cnt c v line col)
10905 (setq org-table-column-names nil
10906 org-table-local-parameters nil
10907 org-table-named-field-locations nil)
10908 (goto-char beg)
10909 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
10910 (setq names (org-split-string (match-string 1) " *| *")
10911 cnt 1)
10912 (while (setq name (pop names))
10913 (setq cnt (1+ cnt))
10914 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
10915 (push (cons name (int-to-string cnt)) org-table-column-names))))
10916 (setq org-table-column-names (nreverse org-table-column-names))
10917 (setq org-table-column-name-regexp
10918 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
10919 (goto-char beg)
10920 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
10921 (setq fields (org-split-string (match-string 1) " *| *"))
10922 (while (setq field (pop fields))
10923 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
10924 (push (cons (match-string 1 field) (match-string 2 field))
10925 org-table-local-parameters))))
10926 (goto-char beg)
10927 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10928 (setq c (match-string 1)
10929 fields (org-split-string (match-string 2) " *| *"))
10930 (save-excursion
10931 (beginning-of-line (if (equal c "_") 2 0))
10932 (setq line (org-current-line) col 1)
10933 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10934 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10935 (while (and fields1 (setq field (pop fields)))
10936 (setq v (pop fields1) col (1+ col))
10937 (when (and (stringp field) (stringp v)
10938 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10939 (push (cons field v) org-table-local-parameters)
10940 (push (list field line col) org-table-named-field-locations)))))))
10942 (defun org-this-word ()
10943 ;; Get the current word
10944 (save-excursion
10945 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
10946 (end (progn (skip-chars-forward "^ \t\n") (point))))
10947 (buffer-substring-no-properties beg end))))
10949 (defun org-table-maybe-eval-formula ()
10950 "Check if the current field starts with \"=\" or \":=\".
10951 If yes, store the formula and apply it."
10952 ;; We already know we are in a table. Get field will only return a formula
10953 ;; when appropriate. It might return a separator line, but no problem.
10954 (when org-table-formula-evaluate-inline
10955 (let* ((field (org-trim (or (org-table-get-field) "")))
10956 named eq)
10957 (when (string-match "^:?=\\(.*\\)" field)
10958 (setq named (equal (string-to-char field) ?:)
10959 eq (match-string 1 field))
10960 (if (fboundp 'calc-eval)
10961 (org-table-eval-formula (if named '(4) nil) eq))))))
10963 (defvar org-recalc-commands nil
10964 "List of commands triggering the recalculation of a line.
10965 Will be filled automatically during use.")
10967 (defvar org-recalc-marks
10968 '((" " . "Unmarked: no special line, no automatic recalculation")
10969 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10970 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10971 ("!" . "Column name definition line. Reference in formula as $name.")
10972 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10973 ("_" . "Names for values in row below this one.")
10974 ("^" . "Names for values in row above this one.")))
10976 (defun org-table-rotate-recalc-marks (&optional newchar)
10977 "Rotate the recalculation mark in the first column.
10978 If in any row, the first field is not consistent with a mark,
10979 insert a new column for the markers.
10980 When there is an active region, change all the lines in the region,
10981 after prompting for the marking character.
10982 After each change, a message will be displayed indicating the meaning
10983 of the new mark."
10984 (interactive)
10985 (unless (org-at-table-p) (error "Not at a table"))
10986 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10987 (beg (org-table-begin))
10988 (end (org-table-end))
10989 (l (org-current-line))
10990 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10991 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10992 (have-col
10993 (save-excursion
10994 (goto-char beg)
10995 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10996 (col (org-table-current-column))
10997 (forcenew (car (assoc newchar org-recalc-marks)))
10998 epos new)
10999 (when l1
11000 (message "Change region to what mark? Type # * ! $ or SPC: ")
11001 (setq newchar (char-to-string (read-char-exclusive))
11002 forcenew (car (assoc newchar org-recalc-marks))))
11003 (if (and newchar (not forcenew))
11004 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
11005 newchar))
11006 (if l1 (goto-line l1))
11007 (save-excursion
11008 (beginning-of-line 1)
11009 (unless (looking-at org-table-dataline-regexp)
11010 (error "Not at a table data line")))
11011 (unless have-col
11012 (org-table-goto-column 1)
11013 (org-table-insert-column)
11014 (org-table-goto-column (1+ col)))
11015 (setq epos (point-at-eol))
11016 (save-excursion
11017 (beginning-of-line 1)
11018 (org-table-get-field
11019 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
11020 (concat " "
11021 (setq new (or forcenew
11022 (cadr (member (match-string 1) marks))))
11023 " ")
11024 " # ")))
11025 (if (and l1 l2)
11026 (progn
11027 (goto-line l1)
11028 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
11029 (and (looking-at org-table-dataline-regexp)
11030 (org-table-get-field 1 (concat " " new " "))))
11031 (goto-line l1)))
11032 (if (not (= epos (point-at-eol))) (org-table-align))
11033 (goto-line l)
11034 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
11036 (defun org-table-maybe-recalculate-line ()
11037 "Recompute the current line if marked for it, and if we haven't just done it."
11038 (interactive)
11039 (and org-table-allow-automatic-line-recalculation
11040 (not (and (memq last-command org-recalc-commands)
11041 (equal org-last-recalc-line (org-current-line))))
11042 (save-excursion (beginning-of-line 1)
11043 (looking-at org-table-auto-recalculate-regexp))
11044 (fboundp 'calc-eval)
11045 (org-table-recalculate) t))
11047 (defvar org-table-formula-debug nil
11048 "Non-nil means, debug table formulas.
11049 When nil, simply write \"#ERROR\" in corrupted fields.")
11051 (defvar modes)
11052 (defsubst org-set-calc-mode (var &optional value)
11053 (if (stringp var)
11054 (setq var (assoc var '(("D" calc-angle-mode deg)
11055 ("R" calc-angle-mode rad)
11056 ("F" calc-prefer-frac t)
11057 ("S" calc-symbolic-mode t)))
11058 value (nth 2 var) var (nth 1 var)))
11059 (if (memq var modes)
11060 (setcar (cdr (memq var modes)) value)
11061 (cons var (cons value modes)))
11062 modes)
11064 (defun org-table-eval-formula (&optional arg equation
11065 suppress-align suppress-const
11066 suppress-store)
11067 "Replace the table field value at the cursor by the result of a calculation.
11069 This function makes use of Dave Gillespie's Calc package, in my view the
11070 most exciting program ever written for GNU Emacs. So you need to have Calc
11071 installed in order to use this function.
11073 In a table, this command replaces the value in the current field with the
11074 result of a formula. It also installs the formula as the \"current\" column
11075 formula, by storing it in a special line below the table. When called
11076 with a `C-u' prefix, the current field must ba a named field, and the
11077 formula is installed as valid in only this specific field.
11079 When called, the command first prompts for a formula, which is read in
11080 the minibuffer. Previously entered formulas are available through the
11081 history list, and the last used formula is offered as a default.
11082 These stored formulas are adapted correctly when moving, inserting, or
11083 deleting columns with the corresponding commands.
11085 The formula can be any algebraic expression understood by the Calc package.
11086 For details, see the Org-mode manual.
11088 This function can also be called from Lisp programs and offers
11089 additional arguments: EQUATION can be the formula to apply. If this
11090 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
11091 used to speed-up recursive calls by by-passing unnecessary aligns.
11092 SUPPRESS-CONST suppresses the interpretation of constants in the
11093 formula, assuming that this has been done already outside the function.
11094 SUPPRESS-STORE means the formula should not be stored, either because
11095 it is already stored, or because it is a modified equation that should
11096 not overwrite the stored one."
11097 (interactive "P")
11098 (require 'calc)
11099 (org-table-check-inside-data-field)
11100 (org-table-get-specials)
11101 (let* (fields
11102 (ndown (if (integerp arg) arg 1))
11103 (org-table-automatic-realign nil)
11104 (case-fold-search nil)
11105 (down (> ndown 1))
11106 (formula (if (and equation suppress-store)
11107 equation
11108 (org-table-get-formula equation (equal arg '(4)))))
11109 (n0 (org-table-current-column))
11110 (modes (copy-sequence org-calc-default-modes))
11111 n form fmt x ev orig c lispp)
11112 ;; Parse the format string. Since we have a lot of modes, this is
11113 ;; a lot of work. However, I think calc still uses most of the time.
11114 (if (string-match ";" formula)
11115 (let ((tmp (org-split-string formula ";")))
11116 (setq formula (car tmp)
11117 fmt (concat (cdr (assoc "%" org-table-local-parameters))
11118 (nth 1 tmp)))
11119 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
11120 (setq c (string-to-char (match-string 1 fmt))
11121 n (string-to-number (or (match-string 1 fmt) "")))
11122 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
11123 (setq modes (org-set-calc-mode
11124 'calc-float-format
11125 (list (cdr (assoc c '((?n . float) (?f . fix)
11126 (?s . sci) (?e . eng))))
11127 n))))
11128 (setq fmt (replace-match "" t t fmt)))
11129 (while (string-match "[DRFS]" fmt)
11130 (setq modes (org-set-calc-mode (match-string 0 fmt)))
11131 (setq fmt (replace-match "" t t fmt)))
11132 (unless (string-match "\\S-" fmt)
11133 (setq fmt nil))))
11134 (if (and (not suppress-const) org-table-formula-use-constants)
11135 (setq formula (org-table-formula-substitute-names formula)))
11136 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
11137 (while (> ndown 0)
11138 (setq fields (org-split-string
11139 (buffer-substring
11140 (point-at-bol) (point-at-eol)) " *| *"))
11141 (if org-table-formula-numbers-only
11142 (setq fields (mapcar
11143 (lambda (x) (number-to-string (string-to-number x)))
11144 fields)))
11145 (setq ndown (1- ndown))
11146 (setq form (copy-sequence formula)
11147 lispp (equal (substring form 0 2) "'("))
11148 ;; Insert the references to fields in same row
11149 (while (string-match "\\$\\([0-9]+\\)?" form)
11150 (setq n (if (match-beginning 1)
11151 (string-to-number (match-string 1 form))
11153 x (nth (1- n) fields))
11154 (unless x (error "Invalid field specifier \"%s\""
11155 (match-string 0 form)))
11156 (if (equal x "") (setq x "0"))
11157 (setq form (replace-match
11158 (if lispp x (concat "(" x ")"))
11159 t t form)))
11160 ;; Insert ranges in current column
11161 (while (string-match "\\&[-I0-9]+" form)
11162 (setq form (replace-match
11163 (save-match-data
11164 (org-table-get-vertical-vector (match-string 0 form)
11165 nil n0))
11166 t t form)))
11167 (if lispp
11168 (setq ev (eval (eval (read form)))
11169 ev (if (numberp ev) (number-to-string ev) ev))
11170 (setq ev (calc-eval (cons form modes)
11171 (if org-table-formula-numbers-only 'num))))
11173 (when org-table-formula-debug
11174 (with-output-to-temp-buffer "*Help*"
11175 (princ (format "Substitution history of formula
11176 Orig: %s
11177 $xyz-> %s
11178 $1-> %s\n" orig formula form))
11179 (if (listp ev)
11180 (princ (format " %s^\nError: %s"
11181 (make-string (car ev) ?\-) (nth 1 ev)))
11182 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
11183 ev (or fmt "NONE")
11184 (if fmt (format fmt (string-to-number ev)) ev)))))
11185 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
11186 (unless (and (interactive-p) (not ndown))
11187 (unless (let (inhibit-redisplay)
11188 (y-or-n-p "Debugging Formula. Continue to next? "))
11189 (org-table-align)
11190 (error "Abort"))
11191 (delete-window (get-buffer-window "*Help*"))
11192 (message "")))
11193 (if (listp ev) (setq fmt nil ev "#ERROR"))
11194 (org-table-justify-field-maybe
11195 (if fmt (format fmt (string-to-number ev)) ev))
11196 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
11197 (call-interactively 'org-return)
11198 (setq ndown 0)))
11199 (and down (org-table-maybe-recalculate-line))
11200 (or suppress-align (and org-table-may-need-update
11201 (org-table-align)))))
11203 (defun org-table-recalculate (&optional all noalign)
11204 "Recalculate the current table line by applying all stored formulas.
11205 With prefix arg ALL, do this for all lines in the table."
11206 (interactive "P")
11207 (or (memq this-command org-recalc-commands)
11208 (setq org-recalc-commands (cons this-command org-recalc-commands)))
11209 (unless (org-at-table-p) (error "Not at a table"))
11210 (org-table-get-specials)
11211 (let* ((eqlist (sort (org-table-get-stored-formulas)
11212 (lambda (a b) (string< (car a) (car b)))))
11213 (inhibit-redisplay t)
11214 (line-re org-table-dataline-regexp)
11215 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11216 (thiscol (org-table-current-column))
11217 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
11218 ;; Insert constants in all formulas
11219 (setq eqlist
11220 (mapcar (lambda (x)
11221 (setcdr x (org-table-formula-substitute-names (cdr x)))
11223 eqlist))
11224 ;; Split the equation list
11225 (while (setq eq (pop eqlist))
11226 (if (<= (string-to-char (car eq)) ?9)
11227 (push eq eqlnum)
11228 (push eq eqlname)))
11229 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
11230 (if all
11231 (progn
11232 (setq end (move-marker (make-marker) (1+ (org-table-end))))
11233 (goto-char (setq beg (org-table-begin)))
11234 (if (re-search-forward org-table-calculate-mark-regexp end t)
11235 ;; This is a table with marked lines, only compute selected lines
11236 (setq line-re org-table-recalculate-regexp)
11237 ;; Move forward to the first non-header line
11238 (if (and (re-search-forward org-table-dataline-regexp end t)
11239 (re-search-forward org-table-hline-regexp end t)
11240 (re-search-forward org-table-dataline-regexp end t))
11241 (setq beg (match-beginning 0))
11242 nil))) ;; just leave beg where it is
11243 (setq beg (point-at-bol)
11244 end (move-marker (make-marker) (1+ (point-at-eol)))))
11245 (goto-char beg)
11246 (and all (message "Re-applying formulas to full table..."))
11247 (while (re-search-forward line-re end t)
11248 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
11249 ;; Unprotected line, recalculate
11250 (and all (message "Re-applying formulas to full table...(line %d)"
11251 (setq cnt (1+ cnt))))
11252 (setq org-last-recalc-line (org-current-line))
11253 (setq eql eqlnum)
11254 (while (setq entry (pop eql))
11255 (goto-line org-last-recalc-line)
11256 (org-table-goto-column (string-to-number (car entry)) nil 'force)
11257 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
11258 (goto-line thisline)
11259 (org-table-goto-column thiscol)
11260 (or noalign (and org-table-may-need-update (org-table-align))
11261 (and all (message "Re-applying formulas to %d lines...done" cnt)))
11262 ;; Now do the names fields
11263 (while (setq eq (pop eqlname))
11264 (setq name (car eq)
11265 a (assoc name org-table-named-field-locations))
11266 (when a
11267 (message "Re-applying formula to named field: %s" name)
11268 (goto-line (nth 1 a))
11269 (org-table-goto-column (nth 2 a))
11270 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
11271 ;; back to initial position
11272 (goto-line thisline)
11273 (org-table-goto-column thiscol)
11274 (or noalign (and org-table-may-need-update (org-table-align))
11275 (and all (message "Re-applying formulas...done")))))
11277 (defun org-table-formula-substitute-names (f)
11278 "Replace $const with values in string F."
11279 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
11280 ;; First, check for column names
11281 (while (setq start (string-match org-table-column-name-regexp f start))
11282 (setq start (1+ start))
11283 (setq a (assoc (match-string 1 f) org-table-column-names))
11284 (setq f (replace-match (concat "$" (cdr a)) t t f)))
11285 ;; Expand ranges to vectors
11286 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
11287 (setq n1 (string-to-number (match-string 1 f))
11288 n2 (string-to-number (match-string 2 f))
11289 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
11290 s (concat "[($" (number-to-string (1- nn1)) ")"))
11291 (loop for i from nn1 upto nn2 do
11292 (setq s (concat s ",($" (int-to-string i) ")")))
11293 (setq s (concat s "]"))
11294 (if (< n2 n1) (setq s (concat "rev(" s ")")))
11295 (setq f (replace-match s t t f)))
11296 ;; Parameters and constants
11297 (setq start 0)
11298 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
11299 (setq start (1+ start))
11300 (if (setq a (save-match-data
11301 (org-table-get-constant (match-string 1 f))))
11302 (setq f (replace-match (concat "(" a ")") t t f))))
11303 (if org-table-formula-debug
11304 (put-text-property 0 (length f) :orig-formula f1 f))
11307 (defun org-table-get-constant (const)
11308 "Find the value for a parameter or constant in a formula.
11309 Parameters get priority."
11310 (or (cdr (assoc const org-table-local-parameters))
11311 (cdr (assoc const org-table-formula-constants))
11312 (and (fboundp 'constants-get) (constants-get const))
11313 "#UNDEFINED_NAME"))
11315 (defvar org-edit-formulas-map (make-sparse-keymap))
11316 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
11317 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
11318 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
11320 (defvar org-pos)
11322 (defun org-table-edit-formulas ()
11323 "Edit the formulas of the current table in a separate buffer."
11324 (interactive)
11325 (unless (org-at-table-p)
11326 (error "Not at a table"))
11327 (org-table-get-specials)
11328 (let ((eql (org-table-get-stored-formulas))
11329 (pos (move-marker (make-marker) (point)))
11330 (wc (current-window-configuration))
11331 entry loc s)
11332 (switch-to-buffer-other-window "*Edit Formulas*")
11333 (erase-buffer)
11334 (fundamental-mode)
11335 (set (make-local-variable 'org-pos) pos)
11336 (set (make-local-variable 'org-window-configuration) wc)
11337 (use-local-map org-edit-formulas-map)
11338 (setq s "# Edit formulas and finish with `C-c C-c'.
11339 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
11340 # Use `C-c ?' to get information about $name at point.
11341 # To cancel editing, press `C-c C-q'.\n")
11342 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
11343 (insert s)
11344 (while (setq entry (pop eql))
11345 (when (setq loc (assoc (car entry) org-table-named-field-locations))
11346 (setq s (format "# Named formula, referring to column %d in line %d\n"
11347 (nth 2 loc) (nth 1 loc)))
11348 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
11349 (insert s))
11350 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
11351 (remove-text-properties 0 (length s) '(face nil) s)
11352 (insert s))
11353 (goto-char (point-min))
11354 (message "Edit formulas and finish with `C-c C-c'.")))
11356 (defun org-show-variable ()
11357 "Show the location/value of the $ expression at point."
11358 (interactive)
11359 (let (var (pos org-pos) (win (selected-window)) e)
11360 (save-excursion
11361 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
11362 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
11363 (setq var (match-string 1))
11364 (error "No variable at point")))
11365 (cond
11366 ((setq e (assoc var org-table-named-field-locations))
11367 (switch-to-buffer-other-window (marker-buffer pos))
11368 (goto-line (nth 1 e))
11369 (org-table-goto-column (nth 2 e))
11370 (select-window win)
11371 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11372 ((setq e (assoc var org-table-column-names))
11373 (switch-to-buffer-other-window (marker-buffer pos))
11374 (goto-char pos)
11375 (goto-char (org-table-begin))
11376 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11377 (org-table-end) t)
11378 (progn
11379 (goto-char (match-beginning 1))
11380 (message "Named column (column %s)" (cdr e)))
11381 (error "Column name not found"))
11382 (select-window win))
11383 ((string-match "^[0-9]$" var)
11384 ;; column number
11385 (switch-to-buffer-other-window (marker-buffer pos))
11386 (goto-char pos)
11387 (goto-char (org-table-begin))
11388 (recenter 1)
11389 (if (re-search-forward org-table-dataline-regexp
11390 (org-table-end) t)
11391 (progn
11392 (goto-char (match-beginning 0))
11393 (org-table-goto-column (string-to-number var))
11394 (message "Column %s" var))
11395 (error "Column name not found"))
11396 (select-window win))
11397 ((setq e (assoc var org-table-local-parameters))
11398 (switch-to-buffer-other-window (marker-buffer pos))
11399 (goto-char pos)
11400 (goto-char (org-table-begin))
11401 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11402 (progn
11403 (goto-char (match-beginning 1))
11404 (message "Local parameter."))
11405 (error "Parameter not found"))
11406 (select-window win))
11408 (cond
11409 ((setq e (assoc var org-table-formula-constants))
11410 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
11411 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11412 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
11413 (t (error "Undefined name $%s" var)))))))
11415 (defun org-finish-edit-formulas (&optional arg)
11416 "Parse the buffer for formula definitions and install them.
11417 With prefix ARG, apply the new formulas to the table."
11418 (interactive "P")
11419 (let ((pos org-pos) eql)
11420 (goto-char (point-min))
11421 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
11422 (push (cons (match-string 1) (match-string 2)) eql))
11423 (set-window-configuration org-window-configuration)
11424 (select-window (get-buffer-window (marker-buffer pos)))
11425 (goto-char pos)
11426 (unless (org-at-table-p)
11427 (error "Lost table position - cannot install formulae"))
11428 (org-table-store-formulas eql)
11429 (move-marker pos nil)
11430 (kill-buffer "*Edit Formulas*")
11431 (if arg
11432 (org-table-recalculate 'all)
11433 (message "New formulas installed - press C-u C-c C-c to apply."))))
11435 (defun org-abort-edit-formulas ()
11436 "Abort editing formulas, without installing the changes."
11437 (interactive)
11438 (let ((pos org-pos))
11439 (set-window-configuration org-window-configuration)
11440 (select-window (get-buffer-window (marker-buffer pos)))
11441 (goto-char pos)
11442 (message "Formula editing aborted without installing changes")))
11444 ;;; The orgtbl minor mode
11446 ;; Define a minor mode which can be used in other modes in order to
11447 ;; integrate the org-mode table editor.
11449 ;; This is really a hack, because the org-mode table editor uses several
11450 ;; keys which normally belong to the major mode, for example the TAB and
11451 ;; RET keys. Here is how it works: The minor mode defines all the keys
11452 ;; necessary to operate the table editor, but wraps the commands into a
11453 ;; function which tests if the cursor is currently inside a table. If that
11454 ;; is the case, the table editor command is executed. However, when any of
11455 ;; those keys is used outside a table, the function uses `key-binding' to
11456 ;; look up if the key has an associated command in another currently active
11457 ;; keymap (minor modes, major mode, global), and executes that command.
11458 ;; There might be problems if any of the keys used by the table editor is
11459 ;; otherwise used as a prefix key.
11461 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11462 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11463 ;; addresses this by checking explicitly for both bindings.
11465 ;; The optimized version (see variable `orgtbl-optimized') takes over
11466 ;; all keys which are bound to `self-insert-command' in the *global map*.
11467 ;; Some modes bind other commands to simple characters, for example
11468 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11469 ;; active, this binding is ignored inside tables and replaced with a
11470 ;; modified self-insert.
11472 (defvar orgtbl-mode nil
11473 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11474 table editor in arbitrary modes.")
11475 (make-variable-buffer-local 'orgtbl-mode)
11477 (defvar orgtbl-mode-map (make-keymap)
11478 "Keymap for `orgtbl-mode'.")
11480 ;;;###autoload
11481 (defun turn-on-orgtbl ()
11482 "Unconditionally turn on `orgtbl-mode'."
11483 (orgtbl-mode 1))
11485 ;;;###autoload
11486 (defun orgtbl-mode (&optional arg)
11487 "The `org-mode' table editor as a minor mode for use in other modes."
11488 (interactive)
11489 (if (eq major-mode 'org-mode)
11490 ;; Exit without error, in case some hook functions calls this
11491 ;; by accident in org-mode.
11492 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11493 (setq orgtbl-mode
11494 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11495 (if orgtbl-mode
11496 (progn
11497 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11498 ;; Make sure we are first in minor-mode-map-alist
11499 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11500 (and c (setq minor-mode-map-alist
11501 (cons c (delq c minor-mode-map-alist)))))
11502 (set (make-local-variable (quote org-table-may-need-update)) t)
11503 (org-add-hook 'before-change-functions 'org-before-change-function
11504 nil 'local)
11505 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
11506 auto-fill-inhibit-regexp)
11507 (set (make-local-variable 'auto-fill-inhibit-regexp)
11508 (if auto-fill-inhibit-regexp
11509 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
11510 "[ \t]*|"))
11511 (org-add-to-invisibility-spec '(org-cwidth))
11512 (easy-menu-add orgtbl-mode-menu)
11513 (run-hooks 'orgtbl-mode-hook))
11514 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11515 (org-cleanup-narrow-column-properties)
11516 (org-remove-from-invisibility-spec '(org-cwidth))
11517 (remove-hook 'before-change-functions 'org-before-change-function t)
11518 (easy-menu-remove orgtbl-mode-menu)
11519 (force-mode-line-update 'all))))
11521 (defun org-cleanup-narrow-column-properties ()
11522 "Remove all properties related to narrow-column invisibility."
11523 (let ((s 1))
11524 (while (setq s (text-property-any s (point-max)
11525 'display org-narrow-column-arrow))
11526 (remove-text-properties s (1+ s) '(display t)))
11527 (setq s 1)
11528 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11529 (remove-text-properties s (1+ s) '(org-cwidth t)))
11530 (setq s 1)
11531 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11532 (remove-text-properties s (1+ s) '(invisible t)))))
11534 ;; Install it as a minor mode.
11535 (put 'orgtbl-mode :included t)
11536 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11537 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11539 (defun orgtbl-make-binding (fun n &rest keys)
11540 "Create a function for binding in the table minor mode.
11541 FUN is the command to call inside a table. N is used to create a unique
11542 command name. KEYS are keys that should be checked in for a command
11543 to execute outside of tables."
11544 (eval
11545 (list 'defun
11546 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11547 '(arg)
11548 (concat "In tables, run `" (symbol-name fun) "'.\n"
11549 "Outside of tables, run the binding of `"
11550 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11551 "'.")
11552 '(interactive "p")
11553 (list 'if
11554 '(org-at-table-p)
11555 (list 'call-interactively (list 'quote fun))
11556 (list 'let '(orgtbl-mode)
11557 (list 'call-interactively
11558 (append '(or)
11559 (mapcar (lambda (k)
11560 (list 'key-binding k))
11561 keys)
11562 '('orgtbl-error))))))))
11564 (defun orgtbl-error ()
11565 "Error when there is no default binding for a table key."
11566 (interactive)
11567 (error "This key is has no function outside tables"))
11569 (defun orgtbl-setup ()
11570 "Setup orgtbl keymaps."
11571 (let ((nfunc 0)
11572 (bindings
11573 (list
11574 '([(meta shift left)] org-table-delete-column)
11575 '([(meta left)] org-table-move-column-left)
11576 '([(meta right)] org-table-move-column-right)
11577 '([(meta shift right)] org-table-insert-column)
11578 '([(meta shift up)] org-table-kill-row)
11579 '([(meta shift down)] org-table-insert-row)
11580 '([(meta up)] org-table-move-row-up)
11581 '([(meta down)] org-table-move-row-down)
11582 '("\C-c\C-w" org-table-cut-region)
11583 '("\C-c\M-w" org-table-copy-region)
11584 '("\C-c\C-y" org-table-paste-rectangle)
11585 '("\C-c-" org-table-insert-hline)
11586 ; '([(shift tab)] org-table-previous-field)
11587 '("\C-m" org-table-next-row)
11588 (list (org-key 'S-return) 'org-table-copy-down)
11589 '([(meta return)] org-table-wrap-region)
11590 '("\C-c\C-q" org-table-wrap-region)
11591 '("\C-c?" org-table-current-column)
11592 '("\C-c " org-table-blank-field)
11593 '("\C-c+" org-table-sum)
11594 '("\C-c=" org-table-eval-formula)
11595 '("\C-c'" org-table-edit-formulas)
11596 '("\C-c`" org-table-edit-field)
11597 '("\C-c*" org-table-recalculate)
11598 '("\C-c|" org-table-create-or-convert-from-region)
11599 '("\C-c^" org-table-sort-lines)
11600 '([(control ?#)] org-table-rotate-recalc-marks)))
11601 elt key fun cmd)
11602 (while (setq elt (pop bindings))
11603 (setq nfunc (1+ nfunc))
11604 (setq key (car elt)
11605 fun (nth 1 elt)
11606 cmd (orgtbl-make-binding fun nfunc key))
11607 (define-key orgtbl-mode-map key cmd))
11608 ;; Special treatment needed for TAB and RET
11609 (define-key orgtbl-mode-map [(return)]
11610 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11611 (define-key orgtbl-mode-map "\C-m"
11612 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11613 (define-key orgtbl-mode-map [(tab)]
11614 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11615 (define-key orgtbl-mode-map "\C-i"
11616 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
11617 (define-key orgtbl-mode-map "\C-i"
11618 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
11619 (define-key orgtbl-mode-map "\C-c\C-c"
11620 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
11621 (when orgtbl-optimized
11622 ;; If the user wants maximum table support, we need to hijack
11623 ;; some standard editing functions
11624 (org-remap orgtbl-mode-map
11625 'self-insert-command 'orgtbl-self-insert-command
11626 'delete-char 'org-delete-char
11627 'delete-backward-char 'org-delete-backward-char)
11628 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
11629 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11630 '("OrgTbl"
11631 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11632 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11633 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11634 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11635 "--"
11636 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11637 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11638 ["Copy Field from Above"
11639 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11640 "--"
11641 ("Column"
11642 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11643 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11644 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11645 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
11646 "--"
11647 ["Enable Narrowing" (setq org-table-limit-column-width (not org-table-limit-column-width)) :active (org-at-table-p) :selected org-table-limit-column-width :style toggle])
11648 ("Row"
11649 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11650 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11651 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11652 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11653 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
11654 "--"
11655 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11656 ("Rectangle"
11657 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11658 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11659 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11660 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11661 "--"
11662 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11663 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11664 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11665 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11666 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11667 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11668 ["Sum Column/Rectangle" org-table-sum
11669 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11670 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11671 ["Debug Formulas"
11672 (setq org-table-formula-debug (not org-table-formula-debug))
11673 :style toggle :selected org-table-formula-debug]
11677 (defun orgtbl-tab (arg)
11678 "Justification and field motion for `orgtbl-mode'."
11679 (interactive "P")
11680 (if arg (org-table-edit-field t)
11681 (org-table-justify-field-maybe)
11682 (org-table-next-field)))
11684 (defun orgtbl-ret ()
11685 "Justification and field motion for `orgtbl-mode'."
11686 (interactive)
11687 (org-table-justify-field-maybe)
11688 (org-table-next-row))
11690 (defun orgtbl-self-insert-command (N)
11691 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11692 If the cursor is in a table looking at whitespace, the whitespace is
11693 overwritten, and the table is not marked as requiring realignment."
11694 (interactive "p")
11695 (if (and (org-at-table-p)
11697 (and org-table-auto-blank-field
11698 (member last-command
11699 '(orgtbl-hijacker-command-100
11700 orgtbl-hijacker-command-101
11701 orgtbl-hijacker-command-102
11702 orgtbl-hijacker-command-103
11703 orgtbl-hijacker-command-104
11704 orgtbl-hijacker-command-105))
11705 (org-table-blank-field))
11707 (eq N 1)
11708 (looking-at "[^|\n]* +|"))
11709 (let (org-table-may-need-update)
11710 (goto-char (1- (match-end 0)))
11711 (delete-backward-char 1)
11712 (goto-char (match-beginning 0))
11713 (self-insert-command N))
11714 (setq org-table-may-need-update t)
11715 (let (orgtbl-mode)
11716 (call-interactively (key-binding (vector last-input-event))))))
11718 (defun org-force-self-insert (N)
11719 "Needed to enforce self-insert under remapping."
11720 (interactive "p")
11721 (self-insert-command N))
11723 ;;; Exporting
11725 (defconst org-level-max 20)
11727 (defvar org-export-html-preamble nil
11728 "Preamble, to be inserted just after <body>. Set by publishing functions.")
11729 (defvar org-export-html-postamble nil
11730 "Preamble, to be inserted just before </body>. Set by publishing functions.")
11731 (defvar org-export-html-auto-preamble t
11732 "Should default preamble be inserted? Set by publishing functions.")
11733 (defvar org-export-html-auto-postamble t
11734 "Should default postamble be inserted? Set by publishing functions.")
11736 (defconst org-export-plist-vars
11737 '((:language . org-export-default-language)
11738 (:headline-levels . org-export-headline-levels)
11739 (:section-numbers . org-export-with-section-numbers)
11740 (:table-of-contents . org-export-with-toc)
11741 (:emphasize . org-export-with-emphasize)
11742 (:sub-superscript . org-export-with-sub-superscripts)
11743 (:TeX-macros . org-export-with-TeX-macros)
11744 (:fixed-width . org-export-with-fixed-width)
11745 (:timestamps . org-export-with-timestamps)
11746 (:tables . org-export-with-tables)
11747 (:table-auto-headline . org-export-highlight-first-table-line)
11748 (:style . org-export-html-style)
11749 (:convert-org-links . org-export-html-link-org-files-as-html)
11750 (:inline-images . org-export-html-inline-images)
11751 (:expand-quoted-html . org-export-html-expand)
11752 (:timestamp . org-export-html-with-timestamp)
11753 (:publishing-directory . org-export-publishing-directory)
11754 (:preamble . org-export-html-preamble)
11755 (:postamble . org-export-html-postamble)
11756 (:auto-preamble . org-export-html-auto-preamble)
11757 (:auto-postamble . org-export-html-auto-postamble)
11758 (:author . user-full-name)
11759 (:email . user-mail-address)))
11761 (defun org-default-export-plist ()
11762 "Return the property list with default settings for the export variables."
11763 (let ((l org-export-plist-vars) rtn e)
11764 (while (setq e (pop l))
11765 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
11766 rtn))
11768 (defun org-infile-export-plist ()
11769 "Return the property list with file-local settings for export."
11770 (save-excursion
11771 (goto-char 0)
11772 (let ((re (org-make-options-regexp
11773 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
11774 (text nil)
11775 p key val text options)
11776 (while (re-search-forward re nil t)
11777 (setq key (org-match-string-no-properties 1)
11778 val (org-match-string-no-properties 2))
11779 (cond
11780 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
11781 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
11782 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
11783 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
11784 ((string-equal key "TEXT")
11785 (setq text (if text (concat text "\n" val) val)))
11786 ((string-equal key "OPTIONS") (setq options val))))
11787 (setq p (plist-put p :text text))
11788 (when options
11789 (let ((op '(("H" . :headline-levels)
11790 ("num" . :section-numbers)
11791 ("toc" . :table-of-contents)
11792 ("\\n" . :preserve-breaks)
11793 ("@" . :expand-quoted-html)
11794 (":" . :fixed-width)
11795 ("|" . :tables)
11796 ("^" . :sub-superscript)
11797 ("*" . :emphasize)
11798 ("TeX" . :TeX-macros)))
11800 (while (setq o (pop op))
11801 (if (string-match (concat (regexp-quote (car o))
11802 ":\\([^ \t\n\r;,.]*\\)")
11803 options)
11804 (setq p (plist-put p (cdr o)
11805 (car (read-from-string
11806 (match-string 1 options)))))))))
11807 p)))
11809 (defun org-combine-plists (&rest plists)
11810 "Create a single property list from all plists in PLISTS.
11811 The process starts by copying the last list, and then setting properties
11812 from the other lists. Settings in the first list are the most significant
11813 ones and overrule settings in the other lists."
11814 (let ((rtn (copy-sequence (pop plists)))
11815 p v ls)
11816 (while plists
11817 (setq ls (pop plists))
11818 (while ls
11819 (setq p (pop ls) v (pop ls))
11820 (setq rtn (plist-put rtn p v))))
11821 rtn))
11823 (defun org-export-directory (type plist)
11824 (let* ((val (plist-get plist :publishing-directory))
11825 (dir (if (listp val)
11826 (or (cdr (assoc type val)) ".")
11827 val)))
11828 dir))
11830 (defun org-export-find-first-heading-line (list)
11831 "Remove all lines from LIST which are before the first headline."
11832 (let ((orig-list list)
11833 (re (concat "^" outline-regexp)))
11834 (while (and list
11835 (not (string-match re (car list))))
11836 (pop list))
11837 (or list orig-list)))
11839 (defun org-skip-comments (lines)
11840 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
11841 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
11842 (re2 "^\\(\\*+\\)[ \t\n\r]")
11843 rtn line level)
11844 (while (setq line (pop lines))
11845 (cond
11846 ((and (string-match re1 line)
11847 (setq level (- (match-end 1) (match-beginning 1))))
11848 ;; Beginning of a COMMENT subtree. Skip it.
11849 (while (and (setq line (pop lines))
11850 (or (not (string-match re2 line))
11851 (> (- (match-end 1) (match-beginning 1)) level))))
11852 (setq lines (cons line lines)))
11853 ((string-match "^#" line)
11854 ;; an ordinary comment line
11856 ((and org-export-table-remove-special-lines
11857 (string-match "^[ \t]*|" line)
11858 (or (string-match "^[ \t]*| *[!_^] *|" line)
11859 (and (string-match "| *<[0-9]+> *|" line)
11860 (not (string-match "| *[^ <|]" line)))))
11861 ;; a special table line that should be removed
11863 (t (setq rtn (cons line rtn)))))
11864 (nreverse rtn)))
11866 ;; ASCII
11868 (defconst org-html-entities
11869 '(("nbsp")
11870 ("iexcl")
11871 ("cent")
11872 ("pound")
11873 ("curren")
11874 ("yen")
11875 ("brvbar")
11876 ("sect")
11877 ("uml")
11878 ("copy")
11879 ("ordf")
11880 ("laquo")
11881 ("not")
11882 ("shy")
11883 ("reg")
11884 ("macr")
11885 ("deg")
11886 ("plusmn")
11887 ("sup2")
11888 ("sup3")
11889 ("acute")
11890 ("micro")
11891 ("para")
11892 ("middot")
11893 ("odot"."o")
11894 ("star"."*")
11895 ("cedil")
11896 ("sup1")
11897 ("ordm")
11898 ("raquo")
11899 ("frac14")
11900 ("frac12")
11901 ("frac34")
11902 ("iquest")
11903 ("Agrave")
11904 ("Aacute")
11905 ("Acirc")
11906 ("Atilde")
11907 ("Auml")
11908 ("Aring") ("AA"."&Aring;")
11909 ("AElig")
11910 ("Ccedil")
11911 ("Egrave")
11912 ("Eacute")
11913 ("Ecirc")
11914 ("Euml")
11915 ("Igrave")
11916 ("Iacute")
11917 ("Icirc")
11918 ("Iuml")
11919 ("ETH")
11920 ("Ntilde")
11921 ("Ograve")
11922 ("Oacute")
11923 ("Ocirc")
11924 ("Otilde")
11925 ("Ouml")
11926 ("times")
11927 ("Oslash")
11928 ("Ugrave")
11929 ("Uacute")
11930 ("Ucirc")
11931 ("Uuml")
11932 ("Yacute")
11933 ("THORN")
11934 ("szlig")
11935 ("agrave")
11936 ("aacute")
11937 ("acirc")
11938 ("atilde")
11939 ("auml")
11940 ("aring")
11941 ("aelig")
11942 ("ccedil")
11943 ("egrave")
11944 ("eacute")
11945 ("ecirc")
11946 ("euml")
11947 ("igrave")
11948 ("iacute")
11949 ("icirc")
11950 ("iuml")
11951 ("eth")
11952 ("ntilde")
11953 ("ograve")
11954 ("oacute")
11955 ("ocirc")
11956 ("otilde")
11957 ("ouml")
11958 ("divide")
11959 ("oslash")
11960 ("ugrave")
11961 ("uacute")
11962 ("ucirc")
11963 ("uuml")
11964 ("yacute")
11965 ("thorn")
11966 ("yuml")
11967 ("fnof")
11968 ("Alpha")
11969 ("Beta")
11970 ("Gamma")
11971 ("Delta")
11972 ("Epsilon")
11973 ("Zeta")
11974 ("Eta")
11975 ("Theta")
11976 ("Iota")
11977 ("Kappa")
11978 ("Lambda")
11979 ("Mu")
11980 ("Nu")
11981 ("Xi")
11982 ("Omicron")
11983 ("Pi")
11984 ("Rho")
11985 ("Sigma")
11986 ("Tau")
11987 ("Upsilon")
11988 ("Phi")
11989 ("Chi")
11990 ("Psi")
11991 ("Omega")
11992 ("alpha")
11993 ("beta")
11994 ("gamma")
11995 ("delta")
11996 ("epsilon")
11997 ("varepsilon"."&epsilon;")
11998 ("zeta")
11999 ("eta")
12000 ("theta")
12001 ("iota")
12002 ("kappa")
12003 ("lambda")
12004 ("mu")
12005 ("nu")
12006 ("xi")
12007 ("omicron")
12008 ("pi")
12009 ("rho")
12010 ("sigmaf") ("varsigma"."&sigmaf;")
12011 ("sigma")
12012 ("tau")
12013 ("upsilon")
12014 ("phi")
12015 ("chi")
12016 ("psi")
12017 ("omega")
12018 ("thetasym") ("vartheta"."&thetasym;")
12019 ("upsih")
12020 ("piv")
12021 ("bull") ("bullet"."&bull;")
12022 ("hellip") ("dots"."&hellip;")
12023 ("prime")
12024 ("Prime")
12025 ("oline")
12026 ("frasl")
12027 ("weierp")
12028 ("image")
12029 ("real")
12030 ("trade")
12031 ("alefsym")
12032 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
12033 ("uarr") ("uparrow"."&uarr;")
12034 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
12035 ("darr")("downarrow"."&darr;")
12036 ("harr") ("leftrightarrow"."&harr;")
12037 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
12038 ("lArr") ("Leftarrow"."&lArr;")
12039 ("uArr") ("Uparrow"."&uArr;")
12040 ("rArr") ("Rightarrow"."&rArr;")
12041 ("dArr") ("Downarrow"."&dArr;")
12042 ("hArr") ("Leftrightarrow"."&hArr;")
12043 ("forall")
12044 ("part") ("partial"."&part;")
12045 ("exist") ("exists"."&exist;")
12046 ("empty") ("emptyset"."&empty;")
12047 ("nabla")
12048 ("isin") ("in"."&isin;")
12049 ("notin")
12050 ("ni")
12051 ("prod")
12052 ("sum")
12053 ("minus")
12054 ("lowast") ("ast"."&lowast;")
12055 ("radic")
12056 ("prop") ("proptp"."&prop;")
12057 ("infin") ("infty"."&infin;")
12058 ("ang") ("angle"."&ang;")
12059 ("and") ("vee"."&and;")
12060 ("or") ("wedge"."&or;")
12061 ("cap")
12062 ("cup")
12063 ("int")
12064 ("there4")
12065 ("sim")
12066 ("cong") ("simeq"."&cong;")
12067 ("asymp")("approx"."&asymp;")
12068 ("ne") ("neq"."&ne;")
12069 ("equiv")
12070 ("le")
12071 ("ge")
12072 ("sub") ("subset"."&sub;")
12073 ("sup") ("supset"."&sup;")
12074 ("nsub")
12075 ("sube")
12076 ("supe")
12077 ("oplus")
12078 ("otimes")
12079 ("perp")
12080 ("sdot") ("cdot"."&sdot;")
12081 ("lceil")
12082 ("rceil")
12083 ("lfloor")
12084 ("rfloor")
12085 ("lang")
12086 ("rang")
12087 ("loz") ("Diamond"."&loz;")
12088 ("spades") ("spadesuit"."&spades;")
12089 ("clubs") ("clubsuit"."&clubs;")
12090 ("hearts") ("diamondsuit"."&hearts;")
12091 ("diams") ("diamondsuit"."&diams;")
12092 ("quot")
12093 ("amp")
12094 ("lt")
12095 ("gt")
12096 ("OElig")
12097 ("oelig")
12098 ("Scaron")
12099 ("scaron")
12100 ("Yuml")
12101 ("circ")
12102 ("tilde")
12103 ("ensp")
12104 ("emsp")
12105 ("thinsp")
12106 ("zwnj")
12107 ("zwj")
12108 ("lrm")
12109 ("rlm")
12110 ("ndash")
12111 ("mdash")
12112 ("lsquo")
12113 ("rsquo")
12114 ("sbquo")
12115 ("ldquo")
12116 ("rdquo")
12117 ("bdquo")
12118 ("dagger")
12119 ("Dagger")
12120 ("permil")
12121 ("lsaquo")
12122 ("rsaquo")
12123 ("euro")
12125 ("arccos"."arccos")
12126 ("arcsin"."arcsin")
12127 ("arctan"."arctan")
12128 ("arg"."arg")
12129 ("cos"."cos")
12130 ("cosh"."cosh")
12131 ("cot"."cot")
12132 ("coth"."coth")
12133 ("csc"."csc")
12134 ("deg"."deg")
12135 ("det"."det")
12136 ("dim"."dim")
12137 ("exp"."exp")
12138 ("gcd"."gcd")
12139 ("hom"."hom")
12140 ("inf"."inf")
12141 ("ker"."ker")
12142 ("lg"."lg")
12143 ("lim"."lim")
12144 ("liminf"."liminf")
12145 ("limsup"."limsup")
12146 ("ln"."ln")
12147 ("log"."log")
12148 ("max"."max")
12149 ("min"."min")
12150 ("Pr"."Pr")
12151 ("sec"."sec")
12152 ("sin"."sin")
12153 ("sinh"."sinh")
12154 ("sup"."sup")
12155 ("tan"."tan")
12156 ("tanh"."tanh")
12158 "Entities for TeX->HTML translation.
12159 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
12160 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
12161 In that case, \"\\ent\" will be translated to \"&other;\".
12162 The list contains HTML entities for Latin-1, Greek and other symbols.
12163 It is supplemented by a number of commonly used TeX macros with appropriate
12164 translations. There is currently no way for users to extend this.")
12166 (defun org-cleaned-string-for-export (string)
12167 "Cleanup a buffer substring so that links can be created safely."
12168 (interactive)
12169 (let* ((cb (current-buffer))
12170 (re-radio (and org-target-link-regexp
12171 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
12172 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
12173 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
12174 rtn)
12175 (save-excursion
12176 (set-buffer (get-buffer-create " org-mode-tmp"))
12177 (erase-buffer)
12178 (insert string)
12179 (org-mode)
12180 ;; Find targets in comments and move them out of comments,
12181 ;; but mark them as targets that should be invisible
12182 (goto-char (point-min))
12183 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
12184 (replace-match "\\1(INVISIBLE)"))
12185 ;; Find matches for radio targets and turn them into internal links
12186 (goto-char (point-min))
12187 (when re-radio
12188 (while (re-search-forward re-radio nil t)
12189 (replace-match "\\1[[\\2]]")))
12190 ;; Find all links that contain a newline and put them into a single line
12191 (goto-char (point-min))
12192 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
12193 (replace-match "\\1 \\3")
12194 (goto-char (match-beginning 0)))
12195 ;; Normalize links: Convert angle and plain links into bracket links
12196 (goto-char (point-min))
12197 (while (re-search-forward re-plain-link nil t)
12198 (replace-match
12199 (concat
12200 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
12201 t t))
12202 (goto-char (point-min))
12203 (while (re-search-forward re-angle-link nil t)
12204 (replace-match
12205 (concat
12206 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
12207 t t))
12209 ;; Remove comments
12210 (goto-char (point-min))
12211 (while (re-search-forward "^#.*\n?" nil t)
12212 (replace-match ""))
12213 (setq rtn (buffer-string)))
12214 (kill-buffer " org-mode-tmp")
12215 rtn))
12217 (defun org-solidify-link-text (s &optional alist)
12218 "Take link text and make a safe target out of it."
12219 (save-match-data
12220 (let* ((rtn
12221 (mapconcat
12222 'identity
12223 (org-split-string s "[ \t\r\n]+") "--"))
12224 (a (assoc rtn alist)))
12225 (or (cdr a) rtn))))
12227 (defun org-convert-to-odd-levels ()
12228 "Convert an org-mode file with all levels allowed to one with odd levels.
12229 This will leave level 1 alone, convert level 2 to level 3, level 3 to
12230 level 5 etc."
12231 (interactive)
12232 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
12233 (let ((org-odd-levels-only nil) n)
12234 (save-excursion
12235 (goto-char (point-min))
12236 (while (re-search-forward "^\\*\\*+" nil t)
12237 (setq n (1- (length (match-string 0))))
12238 (while (>= (setq n (1- n)) 0)
12239 (org-demote))
12240 (end-of-line 1))))))
12243 (defun org-convert-to-oddeven-levels ()
12244 "Convert an org-mode file with only odd levels to one with odd and even levels.
12245 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
12246 section with an even level, conversion would destroy the structure of the file. An error
12247 is signaled in this case."
12248 (interactive)
12249 (goto-char (point-min))
12250 ;; First check if there are no even levels
12251 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
12252 (org-show-hierarchy-above)
12253 (error "Not all levels are odd in this file. Conversion not possible."))
12254 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
12255 (let ((org-odd-levels-only nil) n)
12256 (save-excursion
12257 (goto-char (point-min))
12258 (while (re-search-forward "^\\*\\*+" nil t)
12259 (setq n (/ (length (match-string 0)) 2))
12260 (while (>= (setq n (1- n)) 0)
12261 (org-promote))
12262 (end-of-line 1))))))
12264 (defun org-tr-level (n)
12265 "Make N odd if required."
12266 (if org-odd-levels-only (1+ (/ n 2)) n))
12268 (defvar org-last-level nil) ; dynamically scoped variable
12269 (defvar org-ascii-current-indentation nil) ; For communication
12271 (defun org-export-as-ascii (arg)
12272 "Export the outline as a pretty ASCII file.
12273 If there is an active region, export only the region.
12274 The prefix ARG specifies how many levels of the outline should become
12275 underlined headlines. The default is 3."
12276 (interactive "P")
12277 (setq-default org-todo-line-regexp org-todo-line-regexp)
12278 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
12279 (org-infile-export-plist)))
12280 (region
12281 (buffer-substring
12282 (if (org-region-active-p) (region-beginning) (point-min))
12283 (if (org-region-active-p) (region-end) (point-max))))
12284 (lines (org-export-find-first-heading-line
12285 (org-skip-comments
12286 (org-split-string
12287 (org-cleaned-string-for-export region)
12288 "[\r\n]"))))
12289 (org-ascii-current-indentation '(0 . 0))
12290 (org-startup-with-deadline-check nil)
12291 (level 0) line txt
12292 (umax nil)
12293 (case-fold-search nil)
12294 (filename (concat (file-name-as-directory
12295 (org-export-directory :ascii opt-plist))
12296 (file-name-sans-extension
12297 (file-name-nondirectory buffer-file-name))
12298 ".txt"))
12299 (buffer (find-file-noselect filename))
12300 (levels-open (make-vector org-level-max nil))
12301 (odd org-odd-levels-only)
12302 (date (format-time-string "%Y/%m/%d" (current-time)))
12303 (time (format-time-string "%X" (org-current-time)))
12304 (author (plist-get opt-plist :author))
12305 (title (or (plist-get opt-plist :title)
12306 (file-name-sans-extension
12307 (file-name-nondirectory buffer-file-name))))
12308 (options nil)
12309 (email (plist-get opt-plist :email))
12310 (language (plist-get opt-plist :language))
12311 (text nil)
12312 (todo nil)
12313 (lang-words nil))
12315 (setq org-last-level 1)
12316 (org-init-section-numbers)
12318 (find-file-noselect filename)
12320 (setq lang-words (or (assoc language org-export-language-setup)
12321 (assoc "en" org-export-language-setup)))
12322 (if org-export-ascii-show-new-buffer
12323 (switch-to-buffer-other-window buffer)
12324 (set-buffer buffer))
12325 (erase-buffer)
12326 (fundamental-mode)
12327 ;; create local variables for all options, to make sure all called
12328 ;; functions get the correct information
12329 (mapcar (lambda (x)
12330 (set (make-local-variable (cdr x))
12331 (plist-get opt-plist (car x))))
12332 org-export-plist-vars)
12333 (set (make-local-variable 'org-odd-levels-only) odd)
12334 (setq umax (if arg (prefix-numeric-value arg)
12335 org-export-headline-levels))
12337 ;; File header
12338 (if title (org-insert-centered title ?=))
12339 (insert "\n")
12340 (if (or author email)
12341 (insert (concat (nth 1 lang-words) ": " (or author "")
12342 (if email (concat " <" email ">") "")
12343 "\n")))
12344 (if (and date time)
12345 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
12346 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
12348 (insert "\n\n")
12350 (if org-export-with-toc
12351 (progn
12352 (insert (nth 3 lang-words) "\n"
12353 (make-string (length (nth 3 lang-words)) ?=) "\n")
12354 (mapcar '(lambda (line)
12355 (if (string-match org-todo-line-regexp
12356 line)
12357 ;; This is a headline
12358 (progn
12359 (setq level (- (match-end 1) (match-beginning 1))
12360 level (org-tr-level level)
12361 txt (match-string 3 line)
12362 todo
12363 (or (and org-export-mark-todo-in-toc
12364 (match-beginning 2)
12365 (not (equal (match-string 2 line)
12366 org-done-string)))
12367 ; TODO, not DONE
12368 (and org-export-mark-todo-in-toc
12369 (= level umax)
12370 (org-search-todo-below
12371 line lines level))))
12372 (setq txt (org-html-expand-for-ascii txt))
12374 (if org-export-with-section-numbers
12375 (setq txt (concat (org-section-number level)
12376 " " txt)))
12377 (if (<= level umax)
12378 (progn
12379 (insert
12380 (make-string (* (1- level) 4) ?\ )
12381 (format (if todo "%s (*)\n" "%s\n") txt))
12382 (setq org-last-level level))
12383 ))))
12384 lines)))
12386 (org-init-section-numbers)
12387 (while (setq line (pop lines))
12388 ;; Remove the quoted HTML tags.
12389 (setq line (org-html-expand-for-ascii line))
12390 ;; Remove targets
12391 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
12392 (setq line (replace-match "" t t line)))
12393 ;; Replace internal links
12394 (while (string-match org-bracket-link-regexp line)
12395 (setq line (replace-match
12396 (if (match-end 3) "[\\3]" "[\\1]")
12397 t nil line)))
12398 (cond
12399 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
12400 ;; a Headline
12401 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
12402 txt (match-string 2 line))
12403 (org-ascii-level-start level txt umax lines))
12405 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
12406 (normal-mode)
12407 (save-buffer)
12408 ;; remove display and invisible chars
12409 (let (beg end s)
12410 (goto-char (point-min))
12411 (while (setq beg (next-single-property-change (point) 'display))
12412 (setq end (next-single-property-change beg 'display))
12413 (delete-region beg end)
12414 (goto-char beg)
12415 (insert "=>"))
12416 (goto-char (point-min))
12417 (while (setq beg (next-single-property-change (point) 'org-cwidth))
12418 (setq end (next-single-property-change beg 'org-cwidth))
12419 (delete-region beg end)
12420 (goto-char beg)))
12421 (goto-char (point-min))))
12423 (defun org-search-todo-below (line lines level)
12424 "Search the subtree below LINE for any TODO entries."
12425 (let ((rest (cdr (memq line lines)))
12426 (re org-todo-line-regexp)
12427 line lv todo)
12428 (catch 'exit
12429 (while (setq line (pop rest))
12430 (if (string-match re line)
12431 (progn
12432 (setq lv (- (match-end 1) (match-beginning 1))
12433 todo (and (match-beginning 2)
12434 (not (equal (match-string 2 line)
12435 org-done-string))))
12436 ; TODO, not DONE
12437 (if (<= lv level) (throw 'exit nil))
12438 (if todo (throw 'exit t))))))))
12440 (defun org-html-expand-for-ascii (line)
12441 "Handle quoted HTML for ASCII export."
12442 (if org-export-html-expand
12443 (while (string-match "@<[^<>\n]*>" line)
12444 ;; We just remove the tags for now.
12445 (setq line (replace-match "" nil nil line))))
12446 line)
12448 (defun org-insert-centered (s &optional underline)
12449 "Insert the string S centered and underline it with character UNDERLINE."
12450 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
12451 (insert (make-string ind ?\ ) s "\n")
12452 (if underline
12453 (insert (make-string ind ?\ )
12454 (make-string (string-width s) underline)
12455 "\n"))))
12457 (defun org-ascii-level-start (level title umax &optional lines)
12458 "Insert a new level in ASCII export."
12459 (let (char (n (- level umax 1)) (ind 0))
12460 (if (> level umax)
12461 (progn
12462 (insert (make-string (* 2 n) ?\ )
12463 (char-to-string (nth (% n (length org-export-ascii-bullets))
12464 org-export-ascii-bullets))
12465 " " title "\n")
12466 ;; find the indentation of the next non-empty line
12467 (catch 'stop
12468 (while lines
12469 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
12470 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
12471 (throw 'stop (setq ind (org-get-indentation (car lines)))))
12472 (pop lines)))
12473 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
12474 (if (or (not (equal (char-before) ?\n))
12475 (not (equal (char-before (1- (point))) ?\n)))
12476 (insert "\n"))
12477 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
12478 (if org-export-with-section-numbers
12479 (setq title (concat (org-section-number level) " " title)))
12480 (insert title "\n" (make-string (string-width title) char) "\n")
12481 (setq org-ascii-current-indentation '(0 . 0)))))
12483 (defun org-export-visible (type arg)
12484 "Create a copy of the visible part of the current buffer, and export it.
12485 The copy is created in a temporary buffer and removed after use.
12486 TYPE is the final key (as a string) of the `C-c C-x' key sequence that will
12487 run the export command - in interactive use, the command prompts for this
12488 key. As a special case, if the you type SPC at the prompt, the temporary
12489 org-mode file will not be removed but presented to you so that you can
12490 continue to use it. The prefix arg ARG is passed through to the exporting
12491 command."
12492 (interactive
12493 (list (progn
12494 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
12495 (char-to-string (read-char-exclusive)))
12496 current-prefix-arg))
12497 (if (not (member type '("a" "\C-a" "b" "\C-b" "h" "x" " ")))
12498 (error "Invalid export key"))
12499 (let* ((binding (key-binding (concat "\C-c\C-x" type)))
12500 (keepp (equal type " "))
12501 (file buffer-file-name)
12502 (buffer (get-buffer-create "*Org Export Visible*"))
12503 s e)
12504 (with-current-buffer buffer (erase-buffer))
12505 (save-excursion
12506 (setq s (goto-char (point-min)))
12507 (while (not (= (point) (point-max)))
12508 (goto-char (org-find-invisible))
12509 (append-to-buffer buffer s (point))
12510 (setq s (goto-char (org-find-visible))))
12511 (goto-char (point-min))
12512 (unless keepp
12513 ;; Copy all comment lines to the end, to make sure #+ settings are
12514 ;; still available for the second export step. Kind of a hack, but
12515 ;; does do the trick.
12516 (if (looking-at "#[^\r\n]*")
12517 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
12518 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
12519 (append-to-buffer buffer (1+ (match-beginning 0))
12520 (min (point-max) (1+ (match-end 0))))))
12521 (set-buffer buffer)
12522 (let ((buffer-file-name file)
12523 (org-inhibit-startup t))
12524 (org-mode)
12525 (show-all)
12526 (unless keepp (funcall binding arg))))
12527 (if (not keepp)
12528 (kill-buffer buffer)
12529 (switch-to-buffer-other-window buffer)
12530 (goto-char (point-min)))))
12532 (defun org-find-visible ()
12533 (if (featurep 'noutline)
12534 (let ((s (point)))
12535 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
12536 (get-char-property s 'invisible)))
12538 (skip-chars-forward "^\n")
12539 (point)))
12540 (defun org-find-invisible ()
12541 (if (featurep 'noutline)
12542 (let ((s (point)))
12543 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
12544 (not (get-char-property s 'invisible))))
12546 (skip-chars-forward "^\r")
12547 (point)))
12550 ;; HTML
12552 (defun org-get-current-options ()
12553 "Return a string with current options as keyword options.
12554 Does include HTML export options as well as TODO and CATEGORY stuff."
12555 (format
12556 "#+TITLE: %s
12557 #+AUTHOR: %s
12558 #+EMAIL: %s
12559 #+LANGUAGE: %s
12560 #+TEXT: Some descriptive text to be emitted. Several lines OK.
12561 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
12562 #+CATEGORY: %s
12563 #+SEQ_TODO: %s
12564 #+TYP_TODO: %s
12565 #+STARTUP: %s %s %s %s %s %s
12566 #+TAGS: %s
12567 #+ARCHIVE: %s
12569 (buffer-name) (user-full-name) user-mail-address org-export-default-language
12570 org-export-headline-levels
12571 org-export-with-section-numbers
12572 org-export-with-toc
12573 org-export-preserve-breaks
12574 org-export-html-expand
12575 org-export-with-fixed-width
12576 org-export-with-tables
12577 org-export-with-sub-superscripts
12578 org-export-with-emphasize
12579 org-export-with-TeX-macros
12580 (file-name-nondirectory buffer-file-name)
12581 (if (equal org-todo-interpretation 'sequence)
12582 (mapconcat 'identity org-todo-keywords " ")
12583 "TODO FEEDBACK VERIFY DONE")
12584 (if (equal org-todo-interpretation 'type)
12585 (mapconcat 'identity org-todo-keywords " ")
12586 "Me Jason Marie DONE")
12587 (cdr (assoc org-startup-folded
12588 '((nil . "showall") (t . "overview") (content . "content"))))
12589 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
12590 (if org-odd-levels-only "odd" "oddeven")
12591 (if org-hide-leading-stars "hidestars" "showstars")
12592 (if org-startup-align-all-tables "align" "noalign")
12593 (if org-log-done "logging" "nologging")
12594 (if org-tag-alist (mapconcat 'car org-tag-alist " ") "")
12595 org-archive-location
12598 (defun org-insert-export-options-template ()
12599 "Insert into the buffer a template with information for exporting."
12600 (interactive)
12601 (if (not (bolp)) (newline))
12602 (let ((s (org-get-current-options)))
12603 (and (string-match "#\\+CATEGORY" s)
12604 (setq s (substring s 0 (match-beginning 0))))
12605 (insert s)))
12607 (defun org-toggle-fixed-width-section (arg)
12608 "Toggle the fixed-width export.
12609 If there is no active region, the QUOTE keyword at the current headline is
12610 inserted or removed. When present, it causes the text between this headline
12611 and the next to be exported as fixed-width text, and unmodified.
12612 If there is an active region, this command adds or removes a colon as the
12613 first character of this line. If the first character of a line is a colon,
12614 this line is also exported in fixed-width font."
12615 (interactive "P")
12616 (let* ((cc 0)
12617 (regionp (org-region-active-p))
12618 (beg (if regionp (region-beginning) (point)))
12619 (end (if regionp (region-end)))
12620 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
12621 (re "[ \t]*\\(:\\)")
12622 off)
12623 (if regionp
12624 (save-excursion
12625 (goto-char beg)
12626 (setq cc (current-column))
12627 (beginning-of-line 1)
12628 (setq off (looking-at re))
12629 (while (> nlines 0)
12630 (setq nlines (1- nlines))
12631 (beginning-of-line 1)
12632 (cond
12633 (arg
12634 (move-to-column cc t)
12635 (insert ":\n")
12636 (forward-line -1))
12637 ((and off (looking-at re))
12638 (replace-match "" t t nil 1))
12639 ((not off) (move-to-column cc t) (insert ":")))
12640 (forward-line 1)))
12641 (save-excursion
12642 (org-back-to-heading)
12643 (if (looking-at (concat outline-regexp
12644 "\\( +\\<" org-quote-string "\\>\\)"))
12645 (replace-match "" t t nil 1)
12646 (if (looking-at outline-regexp)
12647 (progn
12648 (goto-char (match-end 0))
12649 (insert " " org-quote-string))))))))
12651 (defun org-export-as-html-and-open (arg)
12652 "Export the outline as HTML and immediately open it with a browser.
12653 If there is an active region, export only the region.
12654 The prefix ARG specifies how many levels of the outline should become
12655 headlines. The default is 3. Lower levels will become bulleted lists."
12656 (interactive "P")
12657 (org-export-as-html arg 'hidden)
12658 (org-open-file buffer-file-name))
12660 (defun org-export-as-html-batch ()
12661 "Call `org-export-as-html', may be used in batch processing as
12662 emacs --batch
12663 --load=$HOME/lib/emacs/org.el
12664 --eval \"(setq org-export-headline-levels 2)\"
12665 --visit=MyFile --funcall org-export-as-html-batch"
12666 (org-export-as-html org-export-headline-levels 'hidden))
12668 (defun org-export-as-html (arg &optional hidden ext-plist)
12669 "Export the outline as a pretty HTML file.
12670 If there is an active region, export only the region.
12671 The prefix ARG specifies how many levels of the outline should become
12672 headlines. The default is 3. Lower levels will become bulleted lists.
12673 When HIDDEN is non-nil, don't display the HTML buffer.
12674 EXT-PLIST is a property list with external parameters overriding
12675 org-mode's default settings, but still inferior to file-local settings."
12676 (interactive "P")
12677 (setq-default org-todo-line-regexp org-todo-line-regexp)
12678 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
12679 (setq-default org-done-string org-done-string)
12680 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
12681 ext-plist
12682 (org-infile-export-plist)))
12684 (style (plist-get opt-plist :style))
12685 (odd org-odd-levels-only)
12686 (region-p (org-region-active-p))
12687 (region
12688 (buffer-substring
12689 (if region-p (region-beginning) (point-min))
12690 (if region-p (region-end) (point-max))))
12691 (all_lines
12692 (org-skip-comments (org-split-string
12693 (org-cleaned-string-for-export region)
12694 "[\r\n]")))
12695 (lines (org-export-find-first-heading-line all_lines))
12696 (level 0) (line "") (origline "") txt todo
12697 (umax nil)
12698 (filename (concat (file-name-as-directory
12699 (org-export-directory :html opt-plist))
12700 (file-name-sans-extension
12701 (file-name-nondirectory buffer-file-name))
12702 ".html"))
12703 (buffer (find-file-noselect filename))
12704 (levels-open (make-vector org-level-max nil))
12705 (date (format-time-string "%Y/%m/%d" (current-time)))
12706 (time (format-time-string "%X" (org-current-time)))
12707 (author (plist-get opt-plist :author))
12708 (title (or (plist-get opt-plist :title)
12709 (file-name-sans-extension
12710 (file-name-nondirectory buffer-file-name))))
12711 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
12712 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
12713 (inquote nil)
12714 (infixed nil)
12715 (in-local-list nil)
12716 (local-list-num nil)
12717 (local-list-indent nil)
12718 (llt org-plain-list-ordered-item-terminator)
12719 (email (plist-get opt-plist :email))
12720 (language (plist-get opt-plist :language))
12721 (text (plist-get opt-plist :text))
12722 (lang-words nil)
12723 (target-alist nil) tg
12724 (head-count 0) cnt
12725 (start 0)
12726 (coding-system (and (fboundp 'coding-system-get)
12727 (boundp 'buffer-file-coding-system)
12728 buffer-file-coding-system))
12729 (coding-system-for-write (or coding-system coding-system-for-write))
12730 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
12731 (charset (and coding-system
12732 (coding-system-get coding-system 'mime-charset)))
12733 table-open type
12734 table-buffer table-orig-buffer
12735 ind start-is-num starter
12736 rpl path desc descp desc1 desc2 link
12738 (message "Exporting...")
12740 (setq org-last-level 1)
12741 (org-init-section-numbers)
12743 ;; Get the language-dependent settings
12744 (setq lang-words (or (assoc language org-export-language-setup)
12745 (assoc "en" org-export-language-setup)))
12747 ;; Switch to the output buffer
12748 (if (or hidden (not org-export-html-show-new-buffer))
12749 (set-buffer buffer)
12750 (switch-to-buffer-other-window buffer))
12751 (erase-buffer)
12752 (fundamental-mode)
12753 (let ((case-fold-search nil)
12754 (org-odd-levels-only odd))
12755 ;; create local variables for all options, to make sure all called
12756 ;; functions get the correct information
12757 (mapcar (lambda (x)
12758 (set (make-local-variable (cdr x))
12759 (plist-get opt-plist (car x))))
12760 org-export-plist-vars)
12761 (setq umax (if arg (prefix-numeric-value arg)
12762 org-export-headline-levels))
12764 ;; File header
12765 (insert (format
12766 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
12767 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
12768 <html xmlns=\"http://www.w3.org/1999/xhtml\"
12769 lang=\"%s\" xml:lang=\"%s\">
12770 <head>
12771 <title>%s</title>
12772 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
12773 <meta name=\"generator\" content=\"Org-mode\"/>
12774 <meta name=\"generated\" content=\"%s %s\"/>
12775 <meta name=\"author\" content=\"%s\"/>
12777 </head><body>
12779 language language (org-html-expand title) (or charset "iso-8859-1")
12780 date time author style))
12783 (insert (or (plist-get opt-plist :preamble) ""))
12785 (when (plist-get opt-plist :auto-preamble)
12786 (if title (insert (concat "<h1 class=\"title\">"
12787 (org-html-expand title) "</h1>\n")))
12789 (if text (insert "<p>\n" (org-html-expand text) "</p>")))
12791 (if org-export-with-toc
12792 (progn
12793 (insert (format "<h2>%s</h2>\n" (nth 3 lang-words)))
12794 (insert "<ul>\n<li>")
12795 (setq lines
12796 (mapcar '(lambda (line)
12797 (if (string-match org-todo-line-regexp line)
12798 ;; This is a headline
12799 (progn
12800 (setq level (- (match-end 1) (match-beginning 1))
12801 level (org-tr-level level)
12802 txt (save-match-data
12803 (org-html-expand
12804 (org-html-cleanup-toc-line
12805 (match-string 3 line))))
12806 todo
12807 (or (and org-export-mark-todo-in-toc
12808 (match-beginning 2)
12809 (not (equal (match-string 2 line)
12810 org-done-string)))
12811 ; TODO, not DONE
12812 (and org-export-mark-todo-in-toc
12813 (= level umax)
12814 (org-search-todo-below
12815 line lines level))))
12816 (if org-export-with-section-numbers
12817 (setq txt (concat (org-section-number level)
12818 " " txt)))
12819 (if (<= level umax)
12820 (progn
12821 (setq head-count (+ head-count 1))
12822 (if (> level org-last-level)
12823 (progn
12824 (setq cnt (- level org-last-level))
12825 (while (>= (setq cnt (1- cnt)) 0)
12826 (insert "\n<ul>\n<li>"))
12827 (insert "\n")))
12828 (if (< level org-last-level)
12829 (progn
12830 (setq cnt (- org-last-level level))
12831 (while (>= (setq cnt (1- cnt)) 0)
12832 (insert "</li>\n</ul>"))
12833 (insert "\n")))
12834 ;; Check for targets
12835 (while (string-match org-target-regexp line)
12836 (setq tg (match-string 1 line)
12837 line (replace-match
12838 (concat "@<span class=\"target\">" tg "@</span> ")
12839 t t line))
12840 (push (cons (org-solidify-link-text tg)
12841 (format "sec-%d" head-count))
12842 target-alist))
12843 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
12844 (setq txt (replace-match "" t t txt)))
12845 (insert
12846 (format
12847 (if todo
12848 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
12849 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
12850 head-count txt))
12852 (setq org-last-level level))
12854 line)
12855 lines))
12856 (while (> org-last-level 0)
12857 (setq org-last-level (1- org-last-level))
12858 (insert "</li>\n</ul>\n"))
12860 (setq head-count 0)
12861 (org-init-section-numbers)
12863 (while (setq line (pop lines) origline line)
12864 (catch 'nextline
12866 ;; end of quote section?
12867 (when (and inquote (string-match "^\\*+" line))
12868 (insert "</pre>\n")
12869 (setq inquote nil))
12870 ;; inside a quote section?
12871 (when inquote
12872 (insert (org-html-protect line) "\n")
12873 (throw 'nextline nil))
12875 ;; verbatim lines
12876 (when (and org-export-with-fixed-width
12877 (string-match "^[ \t]*:\\(.*\\)" line))
12878 (when (not infixed)
12879 (setq infixed t)
12880 (insert "<pre>\n"))
12881 (insert (org-html-protect (match-string 1 line)) "\n")
12882 (when (and lines
12883 (not (string-match "^[ \t]*\\(:.*\\)"
12884 (car lines))))
12885 (setq infixed nil)
12886 (insert "</pre>\n"))
12887 (throw 'nextline nil))
12890 ;; make targets to anchors
12891 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
12892 (cond
12893 ((match-end 2)
12894 (setq line (replace-match
12895 (concat "@<a name=\""
12896 (org-solidify-link-text (match-string 1 line))
12897 "\">\\nbsp@</a>")
12898 t t line)))
12899 ((and org-export-with-toc (equal (string-to-char line) ?*))
12900 (setq line (replace-match
12901 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
12902 ; (concat "@<i>" (match-string 1 line) "@</i> ")
12903 t t line)))
12905 (setq line (replace-match
12906 (concat "@<a name=\""
12907 (org-solidify-link-text (match-string 1 line))
12908 "\" class=\"target\">" (match-string 1 line) "@</a> ")
12909 t t line)))))
12911 (setq line (org-html-handle-time-stamps line))
12913 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
12914 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
12915 ;; Also handle sub_superscripts and checkboxes
12916 (setq line (org-html-expand line))
12918 ;; Format the links
12919 (setq start 0)
12920 (while (string-match org-bracket-link-analytic-regexp line start)
12921 (setq start (match-beginning 0))
12922 (setq type (if (match-end 2) (match-string 2 line) "internal"))
12923 (setq path (match-string 3 line))
12924 (setq desc1 (if (match-end 5) (match-string 5 line))
12925 desc2 (if (match-end 2) (concat type ":" path) path)
12926 descp (and desc1 (not (equal desc1 desc2)))
12927 desc (or desc1 desc2))
12928 ;; FIXME: do we need to unescape here somewhere?
12929 (cond
12930 ((equal type "internal")
12931 (setq rpl
12932 (concat
12933 "<a href=\"#"
12934 (org-solidify-link-text path target-alist)
12935 "\">" desc "</a>")))
12936 ((member type '("http" "https" "ftp" "mailto" "news"))
12937 ;; standard URL
12938 (setq link (concat type ":" path))
12939 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
12940 ((string= type "file")
12941 ;; FILE link
12942 (let* ((filename path)
12943 (abs-p (file-name-absolute-p filename))
12944 thefile file-is-image-p search)
12945 (save-match-data
12946 (if (string-match "::\\(.*\\)" filename)
12947 (setq search (match-string 1 filename)
12948 filename (replace-match "" t nil filename)))
12949 (setq file-is-image-p
12950 (string-match (org-image-file-name-regexp) filename))
12951 (setq thefile (if abs-p (expand-file-name filename) filename))
12952 (when (and org-export-html-link-org-files-as-html
12953 (string-match "\\.org$" thefile))
12954 (setq thefile (concat (substring thefile 0
12955 (match-beginning 0))
12956 ".html"))
12957 (if (and search
12958 ;; make sure this is can be used as target search
12959 (not (string-match "^[0-9]*$" search))
12960 (not (string-match "^\\*" search))
12961 (not (string-match "^/.*/$" search)))
12962 (setq thefile (concat thefile "#"
12963 (org-solidify-link-text
12964 (org-link-unescape search)))))
12965 (when (string-match "^file:" desc)
12966 (setq desc (replace-match "" t t desc))
12967 (if (string-match "\\.org$" desc)
12968 (setq desc (replace-match "" t t desc))))))
12969 (setq rpl (if (and file-is-image-p
12970 (or (eq t org-export-html-inline-images)
12971 (and org-export-html-inline-images
12972 (not descp))))
12973 (concat "<img src=\"" thefile "\"/>")
12974 (concat "<a href=\"" thefile "\">" desc "</a>")))))
12975 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
12976 (setq rpl (concat "<i>&lt;" type ":"
12977 (save-match-data (org-link-unescape path))
12978 "&gt;</i>"))))
12979 (setq line (replace-match rpl t t line)
12980 start (+ start (length rpl))))
12981 ;; TODO items
12982 (if (and (string-match org-todo-line-regexp line)
12983 (match-beginning 2))
12984 (if (equal (match-string 2 line) org-done-string)
12985 (setq line (replace-match
12986 "<span class=\"done\">\\2</span>"
12987 t nil line 2))
12988 (setq line (replace-match "<span class=\"todo\">\\2</span>"
12989 t nil line 2))))
12991 (cond
12992 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
12993 ;; This is a headline
12994 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
12995 txt (match-string 2 line))
12996 (if (string-match quote-re0 txt)
12997 (setq txt (replace-match "" t t txt)))
12998 (if (<= level umax) (setq head-count (+ head-count 1)))
12999 (when in-local-list
13000 ;; Close any local lists before inserting a new header line
13001 (while local-list-num
13002 (org-close-li)
13003 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
13004 (pop local-list-num))
13005 (setq local-list-indent nil
13006 in-local-list nil))
13007 (org-html-level-start level txt umax
13008 (and org-export-with-toc (<= level umax))
13009 head-count)
13010 ;; QUOTES
13011 (when (string-match quote-re line)
13012 (insert "<pre>")
13013 (setq inquote t)))
13015 ((and org-export-with-tables
13016 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
13017 (if (not table-open)
13018 ;; New table starts
13019 (setq table-open t table-buffer nil table-orig-buffer nil))
13020 ;; Accumulate lines
13021 (setq table-buffer (cons line table-buffer)
13022 table-orig-buffer (cons origline table-orig-buffer))
13023 (when (or (not lines)
13024 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
13025 (car lines))))
13026 (setq table-open nil
13027 table-buffer (nreverse table-buffer)
13028 table-orig-buffer (nreverse table-orig-buffer))
13029 (org-close-par-maybe)
13030 (insert (org-format-table-html table-buffer table-orig-buffer))))
13032 ;; Normal lines
13033 (when (string-match
13034 (cond
13035 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
13036 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
13037 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
13038 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
13039 line)
13040 (setq ind (org-get-string-indentation line)
13041 start-is-num (match-beginning 4)
13042 starter (if (match-beginning 2)
13043 (substring (match-string 2 line) 0 -1))
13044 line (substring line (match-beginning 5)))
13045 (unless (string-match "[^ \t]" line)
13046 ;; empty line. Pretend indentation is large.
13047 (setq ind (1+ (or (car local-list-indent) 1))))
13048 (while (and in-local-list
13049 (or (and (= ind (car local-list-indent))
13050 (not starter))
13051 (< ind (car local-list-indent))))
13052 (org-close-li)
13053 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
13054 (pop local-list-num) (pop local-list-indent)
13055 (setq in-local-list local-list-indent))
13056 (cond
13057 ((and starter
13058 (or (not in-local-list)
13059 (> ind (car local-list-indent))))
13060 ;; Start new (level of ) list
13061 (org-close-par-maybe)
13062 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
13063 (push start-is-num local-list-num)
13064 (push ind local-list-indent)
13065 (setq in-local-list t))
13066 (starter
13067 ;; continue current list
13068 (org-close-li)
13069 (insert "<li>\n")))
13070 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
13071 (setq line
13072 (replace-match
13073 (if (equal (match-string 1 line) "X")
13074 "<b>[X]</b>"
13075 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
13076 t t line))))
13078 ;; Empty lines start a new paragraph. If hand-formatted lists
13079 ;; are not fully interpreted, lines starting with "-", "+", "*"
13080 ;; also start a new paragraph.
13081 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
13083 ;; Check if the line break needs to be conserved
13084 (cond
13085 ((string-match "\\\\\\\\[ \t]*$" line)
13086 (setq line (replace-match "<br/>" t t line)))
13087 (org-export-preserve-breaks
13088 (setq line (concat line "<br/>"))))
13090 (insert line "\n")))))
13092 ;; Properly close all local lists and other lists
13093 (when inquote (insert "</pre>\n"))
13094 (when in-local-list
13095 ;; Close any local lists before inserting a new header line
13096 (while local-list-num
13097 (org-close-li)
13098 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
13099 (pop local-list-num))
13100 (setq local-list-indent nil
13101 in-local-list nil))
13102 (org-html-level-start 1 nil umax
13103 (and org-export-with-toc (<= level umax))
13104 head-count)
13106 (when (plist-get opt-plist :auto-postamble)
13107 (when author
13108 (insert "<p class=\"author\"> "
13109 (nth 1 lang-words) ": " author "\n")
13110 (when email
13111 (insert "<a href=\"mailto:" email "\">&lt;"
13112 email "&gt;</a>\n"))
13113 (insert "</p>\n"))
13114 (when (and date time)
13115 (insert "<p class=\"date\"> "
13116 (nth 2 lang-words) ": "
13117 date " " time "</p>\n")))
13119 (if org-export-html-with-timestamp
13120 (insert org-export-html-html-helper-timestamp))
13121 (insert (or (plist-get opt-plist :postamble) ""))
13122 (insert "</body>\n</html>\n")
13123 (normal-mode)
13124 ;; remove empty paragraphs and lists
13125 (goto-char (point-min))
13126 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
13127 (replace-match ""))
13128 (goto-char (point-min))
13129 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
13130 (replace-match ""))
13131 (save-buffer)
13132 (goto-char (point-min)))))
13134 (defun org-format-table-html (lines olines)
13135 "Find out which HTML converter to use and return the HTML code."
13136 (if (string-match "^[ \t]*|" (car lines))
13137 ;; A normal org table
13138 (org-format-org-table-html lines)
13139 ;; Table made by table.el - test for spanning
13140 (let* ((hlines (delq nil (mapcar
13141 (lambda (x)
13142 (if (string-match "^[ \t]*\\+-" x) x
13143 nil))
13144 lines)))
13145 (first (car hlines))
13146 (ll (and (string-match "\\S-+" first)
13147 (match-string 0 first)))
13148 (re (concat "^[ \t]*" (regexp-quote ll)))
13149 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
13150 hlines))))
13151 (if (and (not spanning)
13152 (not org-export-prefer-native-exporter-for-tables))
13153 ;; We can use my own converter with HTML conversions
13154 (org-format-table-table-html lines)
13155 ;; Need to use the code generator in table.el, with the original text.
13156 (org-format-table-table-html-using-table-generate-source olines)))))
13158 (defun org-format-org-table-html (lines)
13159 "Format a table into HTML."
13160 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
13161 (setq lines (nreverse lines))
13162 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
13163 (setq lines (nreverse lines))
13164 (when org-export-table-remove-special-lines
13165 ;; Check if the table has a marking column. If yes remove the
13166 ;; column and the special lines
13167 (let* ((special
13168 (not
13169 (memq nil
13170 (mapcar
13171 (lambda (x)
13172 (or (string-match "^[ \t]*|-" x)
13173 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
13174 lines)))))
13175 (if special
13176 (setq lines
13177 (delq nil
13178 (mapcar
13179 (lambda (x)
13180 (if (string-match "^[ \t]*| *[!_^] *|" x)
13181 nil ; ignore this line
13182 (and (or (string-match "^[ \t]*|-+\\+" x)
13183 (string-match "^[ \t]*|[^|]*|" x))
13184 (replace-match "|" t t x))))
13185 lines))))))
13187 (let ((head (and org-export-highlight-first-table-line
13188 (delq nil (mapcar
13189 (lambda (x) (string-match "^[ \t]*|-" x))
13190 (cdr lines)))))
13191 line fields html)
13192 (setq html (concat org-export-html-table-tag "\n"))
13193 (while (setq line (pop lines))
13194 (catch 'next-line
13195 (if (string-match "^[ \t]*|-" line)
13196 (progn
13197 (setq head nil) ;; head ends here, first time around
13198 ;; ignore this line
13199 (throw 'next-line t)))
13200 ;; Break the line into fields
13201 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
13202 (setq html (concat
13203 html
13204 "<tr>"
13205 (mapconcat (lambda (x)
13206 (if head
13207 (concat "<th>" x "</th>")
13208 (concat "<td>" x "</td>")))
13209 fields "")
13210 "</tr>\n"))))
13211 (setq html (concat html "</table>\n"))
13212 html))
13214 (defun org-fake-empty-table-line (line)
13215 "Replace everything except \"|\" with spaces."
13216 (let ((i (length line))
13217 (newstr (copy-sequence line)))
13218 (while (> i 0)
13219 (setq i (1- i))
13220 (if (not (eq (aref newstr i) ?|))
13221 (aset newstr i ?\ )))
13222 newstr))
13224 (defun org-format-table-table-html (lines)
13225 "Format a table generated by table.el into HTML.
13226 This conversion does *not* use `table-generate-source' from table.el.
13227 This has the advantage that Org-mode's HTML conversions can be used.
13228 But it has the disadvantage, that no cell- or row-spanning is allowed."
13229 (let (line field-buffer
13230 (head org-export-highlight-first-table-line)
13231 fields html empty)
13232 (setq html (concat org-export-html-table-tag "\n"))
13233 (while (setq line (pop lines))
13234 (setq empty "&nbsp;")
13235 (catch 'next-line
13236 (if (string-match "^[ \t]*\\+-" line)
13237 (progn
13238 (if field-buffer
13239 (progn
13240 (setq html (concat
13241 html
13242 "<tr>"
13243 (mapconcat
13244 (lambda (x)
13245 (if (equal x "") (setq x empty))
13246 (if head
13247 (concat "<th>" x "</th>\n")
13248 (concat "<td>" x "</td>\n")))
13249 field-buffer "\n")
13250 "</tr>\n"))
13251 (setq head nil)
13252 (setq field-buffer nil)))
13253 ;; Ignore this line
13254 (throw 'next-line t)))
13255 ;; Break the line into fields and store the fields
13256 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
13257 (if field-buffer
13258 (setq field-buffer (mapcar
13259 (lambda (x)
13260 (concat x "<br/>" (pop fields)))
13261 field-buffer))
13262 (setq field-buffer fields))))
13263 (setq html (concat html "</table>\n"))
13264 html))
13266 (defun org-format-table-table-html-using-table-generate-source (lines)
13267 "Format a table into html, using `table-generate-source' from table.el.
13268 This has the advantage that cell- or row-spanning is allowed.
13269 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
13270 (require 'table)
13271 (with-current-buffer (get-buffer-create " org-tmp1 ")
13272 (erase-buffer)
13273 (insert (mapconcat 'identity lines "\n"))
13274 (goto-char (point-min))
13275 (if (not (re-search-forward "|[^+]" nil t))
13276 (error "Error processing table"))
13277 (table-recognize-table)
13278 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
13279 (table-generate-source 'html " org-tmp2 ")
13280 (set-buffer " org-tmp2 ")
13281 (buffer-substring (point-min) (point-max))))
13283 (defun org-html-handle-time-stamps (s)
13284 "Format time stamps in string S, or remove them."
13285 (let (r b)
13286 (while (string-match org-maybe-keyword-time-regexp s)
13287 (or b (setq b (substring s 0 (match-beginning 0))))
13288 (if (not org-export-with-timestamps)
13289 (setq r (concat r (substring s 0 (match-beginning 0)))
13290 s (substring s (match-end 0)))
13291 (setq r (concat
13292 r (substring s 0 (match-beginning 0))
13293 (if (match-end 1)
13294 (format "@<span class=\"timestamp-kwd\">%s @</span>"
13295 (match-string 1 s)))
13296 (format " @<span class=\"timestamp\">%s@</span>"
13297 (substring (match-string 3 s) 1 -1)))
13298 s (substring s (match-end 0)))))
13299 ;; Line break of line started and ended with time stamp stuff
13300 (if (not r)
13302 (setq r (concat r s))
13303 (unless (string-match "\\S-" (concat b s))
13304 (setq r (concat r "@<br/>")))
13305 r)))
13307 (defun org-html-protect (s)
13308 ;; convert & to &amp;, < to &lt; and > to &gt;
13309 (let ((start 0))
13310 (while (string-match "&" s start)
13311 (setq s (replace-match "&amp;" t t s)
13312 start (1+ (match-beginning 0))))
13313 (while (string-match "<" s)
13314 (setq s (replace-match "&lt;" t t s)))
13315 (while (string-match ">" s)
13316 (setq s (replace-match "&gt;" t t s))))
13319 (defun org-html-cleanup-toc-line (s)
13320 "Remove tags and time staps from lines going into the toc."
13321 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
13322 (setq s (replace-match "" t t s)))
13323 (while (string-match org-maybe-keyword-time-regexp s)
13324 (setq s (replace-match "" t t s)))
13327 (defun org-html-expand (string)
13328 "Prepare STRING for HTML export. Applies all active conversions.
13329 If there are links in the string, don't modify these."
13330 (let* (m s l res)
13331 (while (setq m (string-match org-bracket-link-regexp string))
13332 (setq s (substring string 0 m)
13333 l (match-string 0 string)
13334 string (substring string (match-end 0)))
13335 (push (org-html-do-expand s) res)
13336 (push l res))
13337 (push (org-html-do-expand string) res)
13338 (apply 'concat (nreverse res))))
13340 (defun org-html-do-expand (s)
13341 "Apply all active conversions to translate special ASCII to HTML."
13342 (setq s (org-html-protect s))
13343 (if org-export-html-expand
13344 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
13345 (setq s (replace-match "<\\1>" t nil s))))
13346 (if org-export-with-emphasize
13347 (setq s (org-export-html-convert-emphasize s)))
13348 (if org-export-with-sub-superscripts
13349 (setq s (org-export-html-convert-sub-super s)))
13350 (if org-export-with-TeX-macros
13351 (let ((start 0) wd ass)
13352 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
13353 (setq wd (match-string 1 s))
13354 (if (setq ass (assoc wd org-html-entities))
13355 (setq s (replace-match (or (cdr ass)
13356 (concat "&" (car ass) ";"))
13357 t t s))
13358 (setq start (+ start (length wd)))))))
13361 (defun org-create-multibrace-regexp (left right n)
13362 "Create a regular expression which will match a balanced sexp.
13363 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
13364 as single character strings.
13365 The regexp returned will match the entire expression including the
13366 delimiters. It will also define a single group which contains the
13367 match except for the outermost delimiters. The maximum depth of
13368 stacked delimiters is N. Escaping delimiters is not possible."
13369 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
13370 (or "\\|")
13371 (re nothing)
13372 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
13373 (while (> n 1)
13374 (setq n (1- n)
13375 re (concat re or next)
13376 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
13377 (concat left "\\(" re "\\)" right)))
13379 (defvar org-match-substring-regexp
13380 (concat
13381 "\\([^\\]\\)\\([_^]\\)\\("
13382 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
13383 "\\|"
13384 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
13385 "\\|"
13386 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
13387 "The regular expression matching a sub- or superscript.")
13389 (defun org-export-html-convert-sub-super (string)
13390 "Convert sub- and superscripts in STRING to HTML."
13391 (let (key c)
13392 (while (string-match org-match-substring-regexp string)
13393 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
13394 (setq c (or (match-string 8 string)
13395 (match-string 6 string)
13396 (match-string 5 string)))
13397 (setq string (replace-match
13398 (concat (match-string 1 string)
13399 "<" key ">" c "</" key ">")
13400 t t string)))
13401 (while (string-match "\\\\\\([_^]\\)" string)
13402 (setq string (replace-match (match-string 1 string) t t string))))
13403 string)
13405 (defun org-export-html-convert-emphasize (string)
13406 (while (string-match org-italic-re string)
13407 (setq string (replace-match "\\1<i>\\3</i>\\4" t nil string)))
13408 (while (string-match org-bold-re string)
13409 (setq string (replace-match "\\1<b>\\3</b>\\4" t nil string)))
13410 (while (string-match org-underline-re string)
13411 (setq string (replace-match "\\1<u>\\3</u>\\4" t nil string)))
13412 string)
13414 (defvar org-par-open nil)
13415 (defun org-open-par ()
13416 "Insert <p>, but first close previous paragraph if any."
13417 (org-close-par-maybe)
13418 (insert "\n<p>")
13419 (setq org-par-open t))
13420 (defun org-close-par-maybe ()
13421 "Close paragraph if there is one open."
13422 (when org-par-open
13423 (insert "</p>")
13424 (setq org-par-open nil)))
13425 (defun org-close-li ()
13426 "Close <li> if necessary."
13427 (org-close-par-maybe)
13428 (insert "</li>\n"))
13429 ; (when (save-excursion
13430 ; (re-search-backward "</?\\(ul\\|ol\\|li\\|[hH][0-9]\\)>" nil t))
13431 ; (if (member (match-string 0) '("</ul>" "</ol>" "<li>"))
13432 ; (insert "</li>"))))
13434 (defun org-html-level-start (level title umax with-toc head-count)
13435 "Insert a new level in HTML export.
13436 When TITLE is nil, just close all open levels."
13437 (org-close-par-maybe)
13438 (let ((l (1+ (max level umax))))
13439 (while (<= l org-level-max)
13440 (if (aref levels-open (1- l))
13441 (progn
13442 (org-html-level-close l)
13443 (aset levels-open (1- l) nil)))
13444 (setq l (1+ l)))
13445 (when title
13446 ;; If title is nil, this means this function is called to close
13447 ;; all levels, so the rest is done only if title is given
13448 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
13449 (setq title (replace-match
13450 (if org-export-with-tags
13451 (save-match-data
13452 (concat
13453 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
13454 (mapconcat 'identity (org-split-string
13455 (match-string 1 title) ":")
13456 "&nbsp;")
13457 "</span>"))
13459 t t title)))
13460 (if (> level umax)
13461 (progn
13462 (if (aref levels-open (1- level))
13463 (progn
13464 (org-close-li)
13465 (insert "<li>" title "<br/>\n"))
13466 (aset levels-open (1- level) t)
13467 (org-close-par-maybe)
13468 (insert "<ul>\n<li>" title "<br/>\n")))
13469 (if org-export-with-section-numbers
13470 (setq title (concat (org-section-number level) " " title)))
13471 (setq level (+ level 1))
13472 (if with-toc
13473 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
13474 level head-count title level))
13475 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
13476 (org-open-par)))))
13478 (defun org-html-level-close (&rest args)
13479 "Terminate one level in HTML export."
13480 (org-close-li)
13481 (insert "</ul>"))
13483 ;; Variable holding the vector with section numbers
13484 (defvar org-section-numbers (make-vector org-level-max 0))
13486 (defun org-init-section-numbers ()
13487 "Initialize the vector for the section numbers."
13488 (let* ((level -1)
13489 (numbers (nreverse (org-split-string "" "\\.")))
13490 (depth (1- (length org-section-numbers)))
13491 (i depth) number-string)
13492 (while (>= i 0)
13493 (if (> i level)
13494 (aset org-section-numbers i 0)
13495 (setq number-string (or (car numbers) "0"))
13496 (if (string-match "\\`[A-Z]\\'" number-string)
13497 (aset org-section-numbers i
13498 (- (string-to-char number-string) ?A -1))
13499 (aset org-section-numbers i (string-to-number number-string)))
13500 (pop numbers))
13501 (setq i (1- i)))))
13503 (defun org-section-number (&optional level)
13504 "Return a string with the current section number.
13505 When LEVEL is non-nil, increase section numbers on that level."
13506 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
13507 (when level
13508 (when (> level -1)
13509 (aset org-section-numbers
13510 level (1+ (aref org-section-numbers level))))
13511 (setq idx (1+ level))
13512 (while (<= idx depth)
13513 (if (not (= idx 1))
13514 (aset org-section-numbers idx 0))
13515 (setq idx (1+ idx))))
13516 (setq idx 0)
13517 (while (<= idx depth)
13518 (setq n (aref org-section-numbers idx))
13519 (setq string (concat string (if (not (string= string "")) "." "")
13520 (int-to-string n)))
13521 (setq idx (1+ idx)))
13522 (save-match-data
13523 (if (string-match "\\`\\([@0]\\.\\)+" string)
13524 (setq string (replace-match "" t nil string)))
13525 (if (string-match "\\(\\.0\\)+\\'" string)
13526 (setq string (replace-match "" t nil string))))
13527 string))
13530 (defun org-export-icalendar-this-file ()
13531 "Export current file as an iCalendar file.
13532 The iCalendar file will be located in the same directory as the Org-mode
13533 file, but with extension `.ics'."
13534 (interactive)
13535 (org-export-icalendar nil buffer-file-name))
13537 (defun org-export-as-xoxo-insert-into (buffer &rest output)
13538 (with-current-buffer buffer
13539 (apply 'insert output)))
13541 (defun org-export-as-xoxo (&optional buffer)
13542 "Export the org buffer as XOXO.
13543 The XOXO buffer is named *xoxo-<source buffer name>*"
13544 (interactive (list (current-buffer)))
13545 ;; A quickie abstraction
13547 ;; Output everything as XOXO
13548 (with-current-buffer (get-buffer buffer)
13549 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
13550 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
13551 (org-infile-export-plist)))
13552 (filename (concat (file-name-as-directory
13553 (org-export-directory :xoxo opt-plist))
13554 (file-name-sans-extension
13555 (file-name-nondirectory buffer-file-name))
13556 ".html"))
13557 (out (find-file-noselect filename))
13558 (last-level 1)
13559 (hanging-li nil))
13560 ;; Check the output buffer is empty.
13561 (with-current-buffer out (erase-buffer))
13562 ;; Kick off the output
13563 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
13564 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
13565 (let* ((hd (match-string-no-properties 1))
13566 (level (length hd))
13567 (text (concat
13568 (match-string-no-properties 2)
13569 (save-excursion
13570 (goto-char (match-end 0))
13571 (let ((str ""))
13572 (catch 'loop
13573 (while 't
13574 (forward-line)
13575 (if (looking-at "^[ \t]\\(.*\\)")
13576 (setq str (concat str (match-string-no-properties 1)))
13577 (throw 'loop str)))))))))
13579 ;; Handle level rendering
13580 (cond
13581 ((> level last-level)
13582 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
13584 ((< level last-level)
13585 (dotimes (- (- last-level level) 1)
13586 (if hanging-li
13587 (org-export-as-xoxo-insert-into out "</li>\n"))
13588 (org-export-as-xoxo-insert-into out "</ol>\n"))
13589 (when hanging-li
13590 (org-export-as-xoxo-insert-into out "</li>\n")
13591 (setq hanging-li nil)))
13593 ((equal level last-level)
13594 (if hanging-li
13595 (org-export-as-xoxo-insert-into out "</li>\n")))
13598 (setq last-level level)
13600 ;; And output the new li
13601 (setq hanging-li 't)
13602 (if (equal ?+ (elt text 0))
13603 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
13604 (org-export-as-xoxo-insert-into out "<li>" text))))
13606 ;; Finally finish off the ol
13607 (dotimes (- last-level 1)
13608 (if hanging-li
13609 (org-export-as-xoxo-insert-into out "</li>\n"))
13610 (org-export-as-xoxo-insert-into out "</ol>\n"))
13612 ;; Finish the buffer off and clean it up.
13613 (switch-to-buffer-other-window out)
13614 (indent-region (point-min) (point-max) nil)
13615 (save-buffer)
13616 (goto-char (point-min))
13619 ;;;###autoload
13620 (defun org-export-icalendar-all-agenda-files ()
13621 "Export all files in `org-agenda-files' to iCalendar .ics files.
13622 Each iCalendar file will be located in the same directory as the Org-mode
13623 file, but with extension `.ics'."
13624 (interactive)
13625 (apply 'org-export-icalendar nil (org-agenda-files t)))
13627 ;;;###autoload
13628 (defun org-export-icalendar-combine-agenda-files ()
13629 "Export all files in `org-agenda-files' to a single combined iCalendar file.
13630 The file is stored under the name `org-combined-agenda-icalendar-file'."
13631 (interactive)
13632 (apply 'org-export-icalendar t (org-agenda-files t)))
13634 (defun org-export-icalendar (combine &rest files)
13635 "Create iCalendar files for all elements of FILES.
13636 If COMBINE is non-nil, combine all calendar entries into a single large
13637 file and store it under the name `org-combined-agenda-icalendar-file'."
13638 (save-excursion
13639 (let* ((dir (org-export-directory
13640 :ical (list :publishing-directory
13641 org-export-publishing-directory)))
13642 file ical-file ical-buffer category started org-agenda-new-buffers)
13644 (when combine
13645 (setq ical-file
13646 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
13647 org-combined-agenda-icalendar-file
13648 (expand-file-name org-combined-agenda-icalendar-file dir))
13649 ical-buffer (org-get-agenda-file-buffer ical-file))
13650 (set-buffer ical-buffer) (erase-buffer))
13651 (while (setq file (pop files))
13652 (catch 'nextfile
13653 (org-check-agenda-file file)
13654 (set-buffer (org-get-agenda-file-buffer file))
13655 (unless combine
13656 (setq ical-file (concat (file-name-as-directory dir)
13657 (file-name-sans-extension
13658 (file-name-nondirectory buffer-file-name))
13659 ".ics"))
13660 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
13661 (with-current-buffer ical-buffer (erase-buffer)))
13662 (setq category (or org-category
13663 (file-name-sans-extension
13664 (file-name-nondirectory buffer-file-name))))
13665 (if (symbolp category) (setq category (symbol-name category)))
13666 (let ((standard-output ical-buffer))
13667 (if combine
13668 (and (not started) (setq started t)
13669 (org-start-icalendar-file org-icalendar-combined-name))
13670 (org-start-icalendar-file category))
13671 (org-print-icalendar-entries combine category)
13672 (when (or (and combine (not files)) (not combine))
13673 (org-finish-icalendar-file)
13674 (set-buffer ical-buffer)
13675 (save-buffer)
13676 (run-hooks 'org-after-save-iCalendar-file-hook)))))
13677 (org-release-buffers org-agenda-new-buffers))))
13679 (defvar org-after-save-iCalendar-file-hook nil
13680 "Hook run after an iCalendar file has been saved.
13681 The iCalendar buffer is still current when this hook is run.
13682 A good way to use this is to tell a desktop calenndar application to re-read
13683 the iCalendar file.")
13685 (defun org-print-icalendar-entries (&optional combine category)
13686 "Print iCalendar entries for the current Org-mode file to `standard-output'.
13687 When COMBINE is non nil, add the category to each line."
13688 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
13689 (dts (org-ical-ts-to-string
13690 (format-time-string (cdr org-time-stamp-formats) (current-time))
13691 "DTSTART"))
13692 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
13693 (save-excursion
13694 (goto-char (point-min))
13695 (while (re-search-forward org-ts-regexp nil t)
13696 (setq pos (match-beginning 0)
13697 ts (match-string 0)
13698 inc t
13699 hd (org-get-heading))
13700 (if (looking-at re2)
13701 (progn
13702 (goto-char (match-end 0))
13703 (setq ts2 (match-string 1) inc nil))
13704 (setq ts2 ts
13705 tmp (buffer-substring (max (point-min)
13706 (- pos org-ds-keyword-length))
13707 pos)
13708 deadlinep (string-match org-deadline-regexp tmp)
13709 scheduledp (string-match org-scheduled-regexp tmp)
13710 ;; donep (org-entry-is-done-p)
13712 (if (or (string-match org-tr-regexp hd)
13713 (string-match org-ts-regexp hd))
13714 (setq hd (replace-match "" t t hd)))
13715 (if combine
13716 (setq hd (concat hd " (category " category ")")))
13717 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
13718 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
13719 (princ (format "BEGIN:VEVENT
13722 SUMMARY:%s
13723 END:VEVENT\n"
13724 (org-ical-ts-to-string ts "DTSTART")
13725 (org-ical-ts-to-string ts2 "DTEND" inc)
13726 hd)))
13727 (when org-icalendar-include-todo
13728 (goto-char (point-min))
13729 (while (re-search-forward org-todo-line-regexp nil t)
13730 (setq state (match-string 1))
13731 (unless (equal state org-done-string)
13732 (setq hd (match-string 3))
13733 (if (string-match org-priority-regexp hd)
13734 (setq pri (string-to-char (match-string 2 hd))
13735 hd (concat (substring hd 0 (match-beginning 1))
13736 (substring hd (- (match-end 1)))))
13737 (setq pri org-default-priority))
13738 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
13739 (- org-lowest-priority ?A))))))
13741 (princ (format "BEGIN:VTODO
13743 SUMMARY:%s
13744 SEQUENCE:1
13745 PRIORITY:%d
13746 END:VTODO\n"
13747 dts hd pri))))))))
13749 (defun org-start-icalendar-file (name)
13750 "Start an iCalendar file by inserting the header."
13751 (let ((user user-full-name)
13752 (name (or name "unknown"))
13753 (timezone (cadr (current-time-zone))))
13754 (princ
13755 (format "BEGIN:VCALENDAR
13756 VERSION:2.0
13757 X-WR-CALNAME:%s
13758 PRODID:-//%s//Emacs with Org-mode//EN
13759 X-WR-TIMEZONE:%s
13760 CALSCALE:GREGORIAN\n" name user timezone))))
13762 (defun org-finish-icalendar-file ()
13763 "Finish an iCalendar file by inserting the END statement."
13764 (princ "END:VCALENDAR\n"))
13766 (defun org-ical-ts-to-string (s keyword &optional inc)
13767 "Take a time string S and convert it to iCalendar format.
13768 KEYWORD is added in front, to make a complete line like DTSTART....
13769 When INC is non-nil, increase the hour by two (if time string contains
13770 a time), or the day by one (if it does not contain a time)."
13771 (let ((t1 (org-parse-time-string s 'nodefault))
13772 t2 fmt have-time time)
13773 (if (and (car t1) (nth 1 t1) (nth 2 t1))
13774 (setq t2 t1 have-time t)
13775 (setq t2 (org-parse-time-string s)))
13776 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
13777 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
13778 (when inc
13779 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
13780 (setq time (encode-time s mi h d m y)))
13781 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
13782 (concat keyword (format-time-string fmt time))))
13785 ;;; Key bindings
13787 ;; - Bindings in Org-mode map are currently
13788 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
13789 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
13790 ;; e (?) useful from outline-mode
13791 ;; i k @ expendable from outline-mode
13792 ;; 0123456789 % & ()_{} " ` free
13794 ;; Make `C-c C-x' a prefix key
13795 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
13796 (define-key org-mode-map "\C-c\C-e" (make-sparse-keymap))
13798 ;; TAB key with modifiers
13799 (define-key org-mode-map "\C-i" 'org-cycle)
13800 (define-key org-mode-map [(tab)] 'org-cycle)
13801 (define-key org-mode-map [(meta tab)] 'org-complete)
13802 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
13803 ;; The following line is necessary under Suse GNU/Linux
13804 (unless (featurep 'xemacs)
13805 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
13806 (define-key org-mode-map [(shift tab)] 'org-shifttab)
13808 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
13809 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
13810 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13811 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
13812 (define-key org-mode-map [(meta return)] 'org-meta-return)
13813 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
13814 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
13816 ;; Cursor keys with modifiers
13817 (define-key org-mode-map [(meta left)] 'org-metaleft)
13818 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
13819 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
13820 (define-key org-mode-map [(meta right)] 'org-metaright)
13821 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
13822 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
13823 (define-key org-mode-map [(meta up)] 'org-metaup)
13824 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
13825 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
13826 (define-key org-mode-map [(meta down)] 'org-metadown)
13827 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
13828 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
13830 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13831 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
13832 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
13833 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
13834 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
13835 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
13836 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
13837 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
13838 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
13839 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
13840 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
13841 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
13842 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
13843 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
13844 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
13845 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
13847 ;; All the other keys
13849 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13850 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
13851 (define-key org-mode-map "\C-c\C-j" 'org-goto)
13852 (define-key org-mode-map "\C-c\C-t" 'org-todo)
13853 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
13854 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
13855 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
13856 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13857 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
13858 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
13859 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
13860 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
13861 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
13862 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
13863 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
13864 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
13865 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
13866 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
13867 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13868 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13869 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13870 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13871 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
13872 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
13873 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13874 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
13875 (define-key org-mode-map "\C-c]" 'org-remove-file)
13876 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
13877 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
13878 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
13879 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13880 (define-key org-mode-map "\C-m" 'org-return)
13881 (define-key org-mode-map "\C-c?" 'org-table-current-column)
13882 (define-key org-mode-map "\C-c " 'org-table-blank-field)
13883 (define-key org-mode-map "\C-c+" 'org-table-sum)
13884 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
13885 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
13886 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
13887 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13888 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
13889 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13890 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
13891 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
13892 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
13893 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
13894 (define-key org-mode-map "\C-c\C-xv" 'org-export-visible)
13895 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-visible)
13896 ;; OPML support is only an option for the future
13897 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
13898 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
13899 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
13900 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
13901 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
13902 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
13903 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
13904 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13905 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
13906 (define-key org-mode-map "\C-c\C-xx" 'org-export-as-xoxo)
13907 (define-key org-mode-map "\C-c\C-x\C-x" 'org-export-as-xoxo)
13908 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
13909 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
13911 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
13912 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13913 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13914 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13916 (define-key org-mode-map "\C-c\C-ef" 'org-publish-current-file)
13917 (define-key org-mode-map "\C-c\C-ep" 'org-publish-current-project)
13918 (define-key org-mode-map "\C-c\C-ec" 'org-publish)
13919 (define-key org-mode-map "\C-c\C-ea" 'org-publish-all)
13920 (define-key org-mode-map "\C-c\C-e\C-f" 'org-publish-current-file)
13921 (define-key org-mode-map "\C-c\C-e\C-p" 'org-publish-current-project)
13922 (define-key org-mode-map "\C-c\C-e\C-c" 'org-publish)
13923 (define-key org-mode-map "\C-c\C-e\C-a" 'org-publish-all)
13925 (when (featurep 'xemacs)
13926 (define-key org-mode-map 'button3 'popup-mode-menu))
13928 (defsubst org-table-p () (org-at-table-p))
13930 (defun org-self-insert-command (N)
13931 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13932 If the cursor is in a table looking at whitespace, the whitespace is
13933 overwritten, and the table is not marked as requiring realignment."
13934 (interactive "p")
13935 (if (and (org-table-p)
13936 (progn
13937 ;; check if we blank the field, and if that triggers align
13938 (and org-table-auto-blank-field
13939 (member last-command
13940 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13941 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13942 ;; got extra space, this field does not determine column width
13943 (let (org-table-may-need-update) (org-table-blank-field))
13944 ;; no extra space, this field may determine column width
13945 (org-table-blank-field)))
13947 (eq N 1)
13948 (looking-at "[^|\n]* |"))
13949 (let (org-table-may-need-update)
13950 (goto-char (1- (match-end 0)))
13951 (delete-backward-char 1)
13952 (goto-char (match-beginning 0))
13953 (self-insert-command N))
13954 (setq org-table-may-need-update t)
13955 (self-insert-command N)))
13957 (defun org-delete-backward-char (N)
13958 "Like `delete-backward-char', insert whitespace at field end in tables.
13959 When deleting backwards, in tables this function will insert whitespace in
13960 front of the next \"|\" separator, to keep the table aligned. The table will
13961 still be marked for re-alignment if the field did fill the entire column,
13962 because, in this case the deletion might narrow the column."
13963 (interactive "p")
13964 (if (and (org-table-p)
13965 (eq N 1)
13966 (string-match "|" (buffer-substring (point-at-bol) (point)))
13967 (looking-at ".*?|"))
13968 (let ((pos (point))
13969 (noalign (looking-at "[^|\n\r]* |"))
13970 (c org-table-may-need-update))
13971 (backward-delete-char N)
13972 (skip-chars-forward "^|")
13973 (insert " ")
13974 (goto-char (1- pos))
13975 ;; noalign: if there were two spaces at the end, this field
13976 ;; does not determine the width of the column.
13977 (if noalign (setq org-table-may-need-update c)))
13978 (backward-delete-char N)))
13980 (defun org-delete-char (N)
13981 "Like `delete-char', but insert whitespace at field end in tables.
13982 When deleting characters, in tables this function will insert whitespace in
13983 front of the next \"|\" separator, to keep the table aligned. The table will
13984 still be marked for re-alignment if the field did fill the entire column,
13985 because, in this case the deletion might narrow the column."
13986 (interactive "p")
13987 (if (and (org-table-p)
13988 (not (bolp))
13989 (not (= (char-after) ?|))
13990 (eq N 1))
13991 (if (looking-at ".*?|")
13992 (let ((pos (point))
13993 (noalign (looking-at "[^|\n\r]* |"))
13994 (c org-table-may-need-update))
13995 (replace-match (concat
13996 (substring (match-string 0) 1 -1)
13997 " |"))
13998 (goto-char pos)
13999 ;; noalign: if there were two spaces at the end, this field
14000 ;; does not determine the width of the column.
14001 (if noalign (setq org-table-may-need-update c)))
14002 (delete-char N))
14003 (delete-char N)))
14005 ;; How to do this: Measure non-white length of current string
14006 ;; If equal to column width, we should realign.
14008 (defun org-remap (map &rest commands)
14009 "In MAP, remap the functions given in COMMANDS.
14010 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14011 (let (new old)
14012 (while commands
14013 (setq old (pop commands) new (pop commands))
14014 (if (fboundp 'command-remapping)
14015 (define-key map (vector 'remap old) new)
14016 (substitute-key-definition old new map global-map)))))
14018 (when (eq org-enable-table-editor 'optimized)
14019 ;; If the user wants maximum table support, we need to hijack
14020 ;; some standard editing functions
14021 (org-remap org-mode-map
14022 'self-insert-command 'org-self-insert-command
14023 'delete-char 'org-delete-char
14024 'delete-backward-char 'org-delete-backward-char)
14025 (define-key org-mode-map "|" 'org-force-self-insert))
14027 (defun org-shiftcursor-error ()
14028 "Throw an error because Shift-Cursor command was applied in wrong context."
14029 (error "This command is active in special context like tables, headlines or timestamps"))
14031 (defun org-shifttab ()
14032 "Global visibility cycling or move to previous table field.
14033 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14034 on context.
14035 See the individual commands for more information."
14036 (interactive)
14037 (cond
14038 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14039 (t (call-interactively 'org-global-cycle))))
14041 (defun org-shiftmetaleft ()
14042 "Promote subtree or delete table column.
14043 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
14044 See the individual commands for more information."
14045 (interactive)
14046 (cond
14047 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14048 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14049 ((org-at-item-p) (call-interactively 'org-outdent-item))
14050 (t (org-shiftcursor-error))))
14052 (defun org-shiftmetaright ()
14053 "Demote subtree or insert table column.
14054 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
14055 See the individual commands for more information."
14056 (interactive)
14057 (cond
14058 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14059 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14060 ((org-at-item-p) (call-interactively 'org-indent-item))
14061 (t (org-shiftcursor-error))))
14063 (defun org-shiftmetaup (&optional arg)
14064 "Move subtree up or kill table row.
14065 Calls `org-move-subtree-up' or `org-table-kill-row' or
14066 `org-move-item-up' depending on context. See the individual commands
14067 for more information."
14068 (interactive "P")
14069 (cond
14070 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14071 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14072 ((org-at-item-p) (call-interactively 'org-move-item-up))
14073 (t (org-shiftcursor-error))))
14074 (defun org-shiftmetadown (&optional arg)
14075 "Move subtree down or insert table row.
14076 Calls `org-move-subtree-down' or `org-table-insert-row' or
14077 `org-move-item-down', depending on context. See the individual
14078 commands for more information."
14079 (interactive "P")
14080 (cond
14081 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14082 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14083 ((org-at-item-p) (call-interactively 'org-move-item-down))
14084 (t (org-shiftcursor-error))))
14086 (defun org-metaleft (&optional arg)
14087 "Promote heading or move table column to left.
14088 Calls `org-do-promote' or `org-table-move-column', depending on context.
14089 With no specific context, calls the Emacs default `backward-word'.
14090 See the individual commands for more information."
14091 (interactive "P")
14092 (cond
14093 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14094 ((or (org-on-heading-p) (org-region-active-p))
14095 (call-interactively 'org-do-promote))
14096 (t (call-interactively 'backward-word))))
14098 (defun org-metaright (&optional arg)
14099 "Demote subtree or move table column to right.
14100 Calls `org-do-demote' or `org-table-move-column', depending on context.
14101 With no specific context, calls the Emacs default `forward-word'.
14102 See the individual commands for more information."
14103 (interactive "P")
14104 (cond
14105 ((org-at-table-p) (call-interactively 'org-table-move-column))
14106 ((or (org-on-heading-p) (org-region-active-p))
14107 (call-interactively 'org-do-demote))
14108 (t (call-interactively 'forward-word))))
14110 (defun org-metaup (&optional arg)
14111 "Move subtree up or move table row up.
14112 Calls `org-move-subtree-up' or `org-table-move-row' or
14113 `org-move-item-up', depending on context. See the individual commands
14114 for more information."
14115 (interactive "P")
14116 (cond
14117 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14118 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14119 ((org-at-item-p) (call-interactively 'org-move-item-up))
14120 (t (org-shiftcursor-error))))
14122 (defun org-metadown (&optional arg)
14123 "Move subtree down or move table row down.
14124 Calls `org-move-subtree-down' or `org-table-move-row' or
14125 `org-move-item-down', depending on context. See the individual
14126 commands for more information."
14127 (interactive "P")
14128 (cond
14129 ((org-at-table-p) (call-interactively 'org-table-move-row))
14130 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14131 ((org-at-item-p) (call-interactively 'org-move-item-down))
14132 (t (org-shiftcursor-error))))
14134 (defun org-shiftup (&optional arg)
14135 "Increase item in timestamp or increase priority of current headline.
14136 Calls `org-timestamp-up' or `org-priority-up', depending on context.
14137 See the individual commands for more information."
14138 (interactive "P")
14139 (cond
14140 ((org-at-timestamp-p) (call-interactively 'org-timestamp-up))
14141 ((org-on-heading-p) (call-interactively 'org-priority-up))
14142 ((org-at-item-p) (call-interactively 'org-previous-item))
14143 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
14145 (defun org-shiftdown (&optional arg)
14146 "Decrease item in timestamp or decrease priority of current headline.
14147 Calls `org-timestamp-down' or `org-priority-down', depending on context.
14148 See the individual commands for more information."
14149 (interactive "P")
14150 (cond
14151 ((org-at-timestamp-p) (call-interactively 'org-timestamp-down))
14152 ((org-on-heading-p) (call-interactively 'org-priority-down))
14153 (t (call-interactively 'org-next-item))))
14155 (defun org-shiftright ()
14156 "Next TODO keyword or timestamp one day later, depending on context."
14157 (interactive)
14158 (cond
14159 ((org-at-timestamp-p) (call-interactively 'org-timestamp-up-day))
14160 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
14161 (t (org-shiftcursor-error))))
14163 (defun org-shiftleft ()
14164 "Previous TODO keyword or timestamp one day earlier, depending on context."
14165 (interactive)
14166 (cond
14167 ((org-at-timestamp-p) (call-interactively 'org-timestamp-down-day))
14168 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
14169 (t (org-shiftcursor-error))))
14171 (defun org-copy-special ()
14172 "Copy region in table or copy current subtree.
14173 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14174 See the individual commands for more information."
14175 (interactive)
14176 (call-interactively
14177 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14179 (defun org-cut-special ()
14180 "Cut region in table or cut current subtree.
14181 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14182 See the individual commands for more information."
14183 (interactive)
14184 (call-interactively
14185 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14187 (defun org-paste-special (arg)
14188 "Paste rectangular region into table, or past subtree relative to level.
14189 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14190 See the individual commands for more information."
14191 (interactive "P")
14192 (if (org-at-table-p)
14193 (org-table-paste-rectangle)
14194 (org-paste-subtree arg)))
14196 (defun org-ctrl-c-ctrl-c (&optional arg)
14197 "Set tags in headline, or update according to changed information at point.
14199 This command does many different things, depending on context:
14201 - If the cursor is in a headline, prompt for tags and insert them
14202 into the current line, aligned to `org-tags-column'. When called
14203 with prefix arg, realign all tags in the current buffer.
14205 - If the cursor is in one of the special #+KEYWORD lines, this
14206 triggers scanning the buffer for these lines and updating the
14207 information.
14209 - If the cursor is inside a table, realign the table. This command
14210 works even if the automatic table editor has been turned off.
14212 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14213 the entire table.
14215 - If the cursor is inside a table created by the table.el package,
14216 activate that table.
14218 - If the current buffer is a remember buffer, close note and file it.
14219 with a prefix argument, file it without further interaction to the default
14220 location.
14222 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14223 links in this buffer.
14225 - If the cursor is on a numbered item in a plain list, renumber the
14226 ordered list."
14227 (interactive "P")
14228 (let ((org-enable-table-editor t))
14229 (cond
14230 ((and (local-variable-p 'org-finish-function (current-buffer))
14231 (fboundp org-finish-function))
14232 (funcall org-finish-function))
14233 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14234 ((org-on-heading-p) (call-interactively 'org-set-tags))
14235 ((org-at-table.el-p)
14236 (require 'table)
14237 (beginning-of-line 1)
14238 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14239 (call-interactively 'table-recognize-table))
14240 ((org-at-table-p)
14241 (org-table-maybe-eval-formula)
14242 (if arg
14243 (call-interactively 'org-table-recalculate)
14244 (org-table-maybe-recalculate-line))
14245 (call-interactively 'org-table-align))
14246 ((org-at-item-checkbox-p)
14247 (call-interactively 'org-toggle-checkbox))
14248 ((org-at-item-p)
14249 (call-interactively 'org-renumber-ordered-list))
14250 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
14251 (cond
14252 ((equal (match-string 1) "TBLFM")
14253 ;; Recalculate the table before this line
14254 (save-excursion
14255 (beginning-of-line 1)
14256 (skip-chars-backward " \r\n\t")
14257 (if (org-at-table-p)
14258 (org-call-with-arg 'org-table-recalculate t))))
14260 (call-interactively 'org-mode-restart))))
14261 (t (error "C-c C-c can do nothing useful at this location.")))))
14263 (defun org-mode-restart ()
14264 "Restart Org-mode, to scan again for special lines.
14265 Also updates the keyword regular expressions."
14266 (interactive)
14267 (let ((org-inhibit-startup t)) (org-mode))
14268 (message "Org-mode restarted to refresh keyword and special line setup"))
14270 (defun org-return ()
14271 "Goto next table row or insert a newline.
14272 Calls `org-table-next-row' or `newline', depending on context.
14273 See the individual commands for more information."
14274 (interactive)
14275 (cond
14276 ((org-at-table-p)
14277 (org-table-justify-field-maybe)
14278 (call-interactively 'org-table-next-row))
14279 (t (newline))))
14281 (defun org-meta-return (&optional arg)
14282 "Insert a new heading or wrap a region in a table.
14283 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14284 See the individual commands for more information."
14285 (interactive "P")
14286 (cond
14287 ((org-at-table-p)
14288 (call-interactively 'org-table-wrap-region))
14289 (t (call-interactively 'org-insert-heading))))
14291 ;;; Menu entries
14293 ;; Define the Org-mode menus
14294 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14295 '("Tbl"
14296 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
14297 ["Next Field" org-cycle (org-at-table-p)]
14298 ["Previous Field" org-shifttab (org-at-table-p)]
14299 ["Next Row" org-return (org-at-table-p)]
14300 "--"
14301 ["Blank Field" org-table-blank-field (org-at-table-p)]
14302 ["Edit Field" org-table-edit-field (org-at-table-p)]
14303 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14304 "--"
14305 ("Column"
14306 ["Move Column Left" org-metaleft (org-at-table-p)]
14307 ["Move Column Right" org-metaright (org-at-table-p)]
14308 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14309 ["Insert Column" org-shiftmetaright (org-at-table-p)]
14310 "--"
14311 ["Enable Narrowing" (setq org-table-limit-column-width (not org-table-limit-column-width)) :active (org-at-table-p) :selected org-table-limit-column-width :style toggle])
14312 ("Row"
14313 ["Move Row Up" org-metaup (org-at-table-p)]
14314 ["Move Row Down" org-metadown (org-at-table-p)]
14315 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14316 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14317 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14318 "--"
14319 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
14320 ("Rectangle"
14321 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14322 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14323 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14324 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14325 "--"
14326 ("Calculate"
14327 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14328 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14329 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
14330 "--"
14331 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14332 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14333 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14334 "--"
14335 ["Sum Column/Rectangle" org-table-sum
14336 (or (org-at-table-p) (org-region-active-p))]
14337 ["Which Column?" org-table-current-column (org-at-table-p)])
14338 ["Debug Formulas"
14339 (setq org-table-formula-debug (not org-table-formula-debug))
14340 :style toggle :selected org-table-formula-debug]
14341 "--"
14342 ["Create" org-table-create (and (not (org-at-table-p))
14343 org-enable-table-editor)]
14344 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14345 ["Import from File" org-table-import (not (org-at-table-p))]
14346 ["Export to File" org-table-export (org-at-table-p)]
14347 "--"
14348 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14350 (easy-menu-define org-org-menu org-mode-map "Org menu"
14351 '("Org"
14352 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
14353 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
14354 ["Sparse Tree" org-occur t]
14355 ["Show All" show-all t]
14356 "--"
14357 ["New Heading" org-insert-heading t]
14358 ("Navigate Headings"
14359 ["Up" outline-up-heading t]
14360 ["Next" outline-next-visible-heading t]
14361 ["Previous" outline-previous-visible-heading t]
14362 ["Next Same Level" outline-forward-same-level t]
14363 ["Previous Same Level" outline-backward-same-level t]
14364 "--"
14365 ["Jump" org-goto t])
14366 ("Edit Structure"
14367 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14368 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14369 "--"
14370 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14371 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14372 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14373 "--"
14374 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14375 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14376 ["Demote Heading" org-metaright (not (org-at-table-p))]
14377 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14378 "--"
14379 ["Archive Subtree" org-archive-subtree t]
14380 "--"
14381 ["Convert to odd levels" org-convert-to-odd-levels t]
14382 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14383 "--"
14384 ("TODO Lists"
14385 ["TODO/DONE/-" org-todo t]
14386 ["Show TODO Tree" org-show-todo-tree t]
14387 ["Global TODO list" org-todo-list t]
14388 "--"
14389 ["Set Priority" org-priority t]
14390 ["Priority Up" org-shiftup t]
14391 ["Priority Down" org-shiftdown t])
14392 ("Dates and Scheduling"
14393 ["Timestamp" org-time-stamp t]
14394 ["Timestamp (inactive)" org-time-stamp-inactive t]
14395 ("Change Date"
14396 ["1 Day Later" org-timestamp-up-day t]
14397 ["1 Day Earlier" org-timestamp-down-day t]
14398 ["1 ... Later" org-shiftup t]
14399 ["1 ... Earlier" org-shiftdown t])
14400 ["Compute Time Range" org-evaluate-time-range t]
14401 ["Schedule Item" org-schedule t]
14402 ["Deadline" org-deadline t]
14403 "--"
14404 ["Goto Calendar" org-goto-calendar t]
14405 ["Date from Calendar" org-date-from-calendar t])
14406 "--"
14407 ["Agenda Command" org-agenda t]
14408 ("File List for Agenda")
14409 ("Special views current file"
14410 ["TODO Tree" org-show-todo-tree t]
14411 ["Check Deadlines" org-check-deadlines t]
14412 ["Timeline" org-timeline t]
14413 ["Tags Tree" org-tags-sparse-tree t])
14414 "--"
14415 ("Hyperlinks"
14416 ["Store Link (Global)" org-store-link t]
14417 ["Insert Link" org-insert-link t]
14418 ["Follow Link" org-open-at-point t]
14419 "--"
14420 ["Descriptive Links"
14421 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14422 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
14423 ["Literal Links"
14424 (progn
14425 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14426 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
14427 "--"
14428 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
14429 (save-excursion (goto-char (point-min))
14430 (re-search-forward "<[a-z]+:" nil t))])
14431 "--"
14432 ("Export"
14433 ["ASCII" org-export-as-ascii t]
14434 ["Export visible part..." org-export-visible t]
14435 ["HTML" org-export-as-html t]
14436 ["HTML and Open" org-export-as-html-and-open t]
14437 ["XOXO" org-export-as-xoxo t]
14438 "--"
14439 ["iCalendar this file" org-export-icalendar-this-file t]
14440 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
14441 :active t :keys "C-c C-x C-i"]
14442 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
14443 "--"
14444 ["Option Template" org-insert-export-options-template t]
14445 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
14446 ("Publish"
14447 ["Current File" org-publish-current-file t]
14448 ["Current Project" org-publish-current-project t]
14449 ["Project..." org-publish t]
14450 ["All Projects" org-publish-all t])
14451 "--"
14452 ("Documentation"
14453 ["Show Version" org-version t]
14454 ["Info Documentation" org-info t])
14455 ("Customize"
14456 ["Browse Org Group" org-customize t]
14457 "--"
14458 ["Expand This Menu" org-create-customize-menu
14459 (fboundp 'customize-menu-create)])
14460 "--"
14461 ["Refresh setup" org-mode-restart t]
14464 (defun org-info (&optional node)
14465 "Read documentation for Org-mode in the info system.
14466 With optional NODE, go directly to that node."
14467 (interactive)
14468 (require 'info)
14469 (Info-goto-node (format "(org)%s" (or node ""))))
14471 (defun org-install-agenda-files-menu ()
14472 (let ((bl (buffer-list)))
14473 (save-excursion
14474 (while bl
14475 (set-buffer (pop bl))
14476 (if (eq major-mode 'org-mode) (setq bl nil)))
14477 (when (eq major-mode 'org-mode)
14478 (easy-menu-change
14479 '("Org") "File List for Agenda"
14480 (append
14481 (list
14482 ["Edit File List" (org-edit-agenda-file-list) t]
14483 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14484 ["Remove Current File from List" org-remove-file t]
14485 ["Cycle through agenda files" org-cycle-agenda-files t]
14486 "--")
14487 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14489 ;;; Documentation
14491 (defun org-customize ()
14492 "Call the customize function with org as argument."
14493 (interactive)
14494 (customize-browse 'org))
14496 (defun org-create-customize-menu ()
14497 "Create a full customization menu for Org-mode, insert it into the menu."
14498 (interactive)
14499 (if (fboundp 'customize-menu-create)
14500 (progn
14501 (easy-menu-change
14502 '("Org") "Customize"
14503 `(["Browse Org group" org-customize t]
14504 "--"
14505 ,(customize-menu-create 'org)
14506 ["Set" Custom-set t]
14507 ["Save" Custom-save t]
14508 ["Reset to Current" Custom-reset-current t]
14509 ["Reset to Saved" Custom-reset-saved t]
14510 ["Reset to Standard Settings" Custom-reset-standard t]))
14511 (message "\"Org\"-menu now contains full customization menu"))
14512 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14514 ;;; Miscellaneous stuff
14516 (defun org-context ()
14517 "Return a list of contexts of the current cursor position.
14518 If several contexts apply, all are returned.
14519 Each context entry is a list with a symbol naming the context, and
14520 two positions indicating start and end of the context. Possible
14521 contexts are:
14523 :headline anywhere in a headline
14524 :headline-stars on the leading stars in a headline
14525 :todo-keyword on a TODO keyword (including DONE) in a headline
14526 :tags on the TAGS in a headline
14527 :priority on the priority cookie in a headline
14528 :item on the first line of a plain list item
14529 :checkbox on the checkbox in a plain list item
14530 :table in an org-mode table
14531 :table-special on a special filed in a table
14532 :table-table in a table.el table
14533 :link on a hyperline
14534 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14535 :target on a <<target>>
14536 :radio-target on a <<<radio-target>>>
14538 This function expects the position to be visible because it uses font-lock
14539 faces as a help to recognize the following contexts: :table-special, :link,
14540 and :keyword."
14541 (let* ((f (get-text-property (point) 'face))
14542 (faces (if (listp f) f (list f)))
14543 (p (point)) clist)
14544 ;; First the large context
14545 (cond
14546 ((org-on-heading-p)
14547 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14548 (when (progn
14549 (beginning-of-line 1)
14550 (looking-at org-todo-line-tags-regexp))
14551 (push (org-point-in-group p 1 :headline-stars) clist)
14552 (push (org-point-in-group p 2 :todo-keyword) clist)
14553 (push (org-point-in-group p 4 :tags) clist))
14554 (goto-char p)
14555 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14556 (if (looking-at "\\[#[A-Z]\\]")
14557 (push (org-point-in-group p 0 :priority) clist)))
14559 ((org-at-item-p)
14560 (push (list :item (point-at-bol)
14561 (save-excursion (org-end-of-item) (point)))
14562 clist)
14563 (and (org-at-item-checkbox-p)
14564 (push (org-point-in-group p 0 :checkbox) clist)))
14566 ((org-at-table-p)
14567 (push (list :table (org-table-begin) (org-table-end)) clist)
14568 (if (memq 'org-formula faces)
14569 (push (list :table-special
14570 (previous-single-property-change p 'face)
14571 (next-single-property-change p 'face)) clist)))
14572 ((org-at-table-p 'any)
14573 (push (list :table-table) clist)))
14574 (goto-char p)
14576 ;; Now the small context
14577 (cond
14578 ((org-at-timestamp-p)
14579 (push (org-point-in-group p 0 :timestamp) clist))
14580 ((memq 'org-link faces)
14581 (push (list :link
14582 (previous-single-property-change p 'face)
14583 (next-single-property-change p 'face)) clist))
14584 ((memq 'org-special-keyword faces)
14585 (push (list :keyword
14586 (previous-single-property-change p 'face)
14587 (next-single-property-change p 'face)) clist))
14588 ((org-on-target-p)
14589 (push (org-point-in-group p 0 :target) clist)
14590 (goto-char (1- (match-beginning 0)))
14591 (if (looking-at org-radio-target-regexp)
14592 (push (org-point-in-group p 0 :radio-target) clist))
14593 (goto-char p)))
14595 (setq clist (nreverse (delq nil clist)))
14596 clist))
14598 (defun org-point-in-group (point group &optional context)
14599 "Check if POINT is in match-group GROUP.
14600 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14601 match. If the match group does ot exist or point is not inside it,
14602 return nil."
14603 (and (match-beginning group)
14604 (>= point (match-beginning group))
14605 (<= point (match-end group))
14606 (if context
14607 (list context (match-beginning group) (match-end group))
14608 t)))
14610 (defun org-move-line-down (arg)
14611 "Move the current line down. With prefix argument, move it past ARG lines."
14612 (interactive "p")
14613 (let ((col (current-column))
14614 beg end pos)
14615 (beginning-of-line 1) (setq beg (point))
14616 (beginning-of-line 2) (setq end (point))
14617 (beginning-of-line (+ 1 arg))
14618 (setq pos (move-marker (make-marker) (point)))
14619 (insert (delete-and-extract-region beg end))
14620 (goto-char pos)
14621 (move-to-column col)))
14623 (defun org-move-line-up (arg)
14624 "Move the current line up. With prefix argument, move it past ARG lines."
14625 (interactive "p")
14626 (let ((col (current-column))
14627 beg end pos)
14628 (beginning-of-line 1) (setq beg (point))
14629 (beginning-of-line 2) (setq end (point))
14630 (beginning-of-line (- arg))
14631 (setq pos (move-marker (make-marker) (point)))
14632 (insert (delete-and-extract-region beg end))
14633 (goto-char pos)
14634 (move-to-column col)))
14636 ;; Paragraph filling stuff.
14637 ;; We want this to be just right, so use the full arsenal.
14639 (defun org-set-autofill-regexps ()
14640 (interactive)
14641 ;; In the paragraph separator we include headlines, because filling
14642 ;; text in a line directly attached to a headline would otherwise
14643 ;; fill the headline as well.
14644 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
14645 ;; The paragraph starter includes hand-formatted lists.
14646 (set (make-local-variable 'paragraph-start)
14647 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14648 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14649 ;; But only if the user has not turned off tables or fixed-width regions
14650 (set (make-local-variable 'auto-fill-inhibit-regexp)
14651 (concat "\\*\\|#"
14652 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14653 (concat
14654 "\\|[ \t]*["
14655 (if org-enable-table-editor "|" "")
14656 (if org-enable-fixed-width-editor ":" "")
14657 "]"))))
14658 ;; We use our own fill-paragraph function, to make sure that tables
14659 ;; and fixed-width regions are not wrapped. That function will pass
14660 ;; through to `fill-paragraph' when appropriate.
14661 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
14662 ;; Adaptive filling: To get full control, first make sure that
14663 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14664 (set (make-local-variable 'adaptive-fill-regexp) "\000")
14665 (set (make-local-variable 'adaptive-fill-function)
14666 'org-adaptive-fill-function))
14668 (defun org-fill-paragraph (&optional justify)
14669 "Re-align a table, pass through to fill-paragraph if no table."
14670 (let ((table-p (org-at-table-p))
14671 (table.el-p (org-at-table.el-p)))
14672 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
14673 (table.el-p t) ; skip table.el tables
14674 (table-p (org-table-align) t) ; align org-mode tables
14675 (t nil)))) ; call paragraph-fill
14677 ;; For reference, this is the default value of adaptive-fill-regexp
14678 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14680 (defun org-adaptive-fill-function ()
14681 "Return a fill prefix for org-mode files.
14682 In particular, this makes sure hanging paragraphs for hand-formatted lists
14683 work correctly."
14684 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
14685 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
14687 ;; Functions needed for Emacs/XEmacs region compatibility
14689 (defun org-add-hook (hook function &optional append local)
14690 "Add-hook, compatible with both Emacsen."
14691 (if (and local (featurep 'xemacs))
14692 (add-local-hook hook function append)
14693 (add-hook hook function append local)))
14695 (defun org-region-active-p ()
14696 "Is `transient-mark-mode' on and the region active?
14697 Works on both Emacs and XEmacs."
14698 (if org-ignore-region
14700 (if (featurep 'xemacs)
14701 (and zmacs-regions (region-active-p))
14702 (and transient-mark-mode mark-active))))
14704 (defun org-add-to-invisibility-spec (arg)
14705 "Add elements to `buffer-invisibility-spec'.
14706 See documentation for `buffer-invisibility-spec' for the kind of elements
14707 that can be added."
14708 (cond
14709 ((fboundp 'add-to-invisibility-spec)
14710 (add-to-invisibility-spec arg))
14711 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
14712 (setq buffer-invisibility-spec (list arg)))
14714 (setq buffer-invisibility-spec
14715 (cons arg buffer-invisibility-spec)))))
14717 (defun org-remove-from-invisibility-spec (arg)
14718 "Remove elements from `buffer-invisibility-spec'."
14719 (if (fboundp 'remove-from-invisibility-spec)
14720 (remove-from-invisibility-spec arg)
14721 (if (consp buffer-invisibility-spec)
14722 (setq buffer-invisibility-spec
14723 (delete arg buffer-invisibility-spec)))))
14725 (defun org-in-invisibility-spec-p (arg)
14726 "Is ARG a member of `buffer-invisibility-spec'?"
14727 (if (consp buffer-invisibility-spec)
14728 (member arg buffer-invisibility-spec)
14729 nil))
14731 (defun org-image-file-name-regexp ()
14732 "Return regexp matching the file names of images."
14733 (if (fboundp 'image-file-name-regexp)
14734 (image-file-name-regexp)
14735 (let ((image-file-name-extensions
14736 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14737 "xbm" "xpm" "pbm" "pgm" "ppm")))
14738 (concat "\\."
14739 (regexp-opt (nconc (mapcar 'upcase
14740 image-file-name-extensions)
14741 image-file-name-extensions)
14743 "\\'"))))
14745 ;; Functions needed for compatibility with old outline.el.
14747 ;; Programming for the old outline.el (that uses selective display
14748 ;; instead of `invisible' text properties) is a nightmare, mostly
14749 ;; because regular expressions can no longer be anchored at
14750 ;; beginning/end of line. Therefore a number of function need special
14751 ;; treatment when the old outline.el is being used.
14753 ;; The following functions capture almost the entire compatibility code
14754 ;; between the different versions of outline-mode. The only other
14755 ;; places where this is important are the font-lock-keywords, and in
14756 ;; `org-export-visible'. Search for `org-noutline-p' to find them.
14758 ;; C-a should go to the beginning of a *visible* line, also in the
14759 ;; new outline.el. I guess this should be patched into Emacs?
14760 (defun org-beginning-of-line ()
14761 "Go to the beginning of the current line. If that is invisible, continue
14762 to a visible line beginning. This makes the function of C-a more intuitive."
14763 (interactive)
14764 (beginning-of-line 1)
14765 (if (bobp)
14767 (backward-char 1)
14768 (if (org-invisible-p)
14769 (while (and (not (bobp)) (org-invisible-p))
14770 (backward-char 1)
14771 (beginning-of-line 1))
14772 (forward-char 1))))
14774 (when org-noutline-p
14775 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
14777 (defun org-invisible-p ()
14778 "Check if point is at a character currently not visible."
14779 (if org-noutline-p
14780 ;; Early versions of noutline don't have `outline-invisible-p'.
14781 (if (fboundp 'outline-invisible-p)
14782 (outline-invisible-p)
14783 (get-char-property (point) 'invisible))
14784 (save-excursion
14785 (skip-chars-backward "^\r\n")
14786 (equal (char-before) ?\r))))
14788 (defun org-invisible-p2 ()
14789 "Check if point is at a character currently not visible."
14790 (save-excursion
14791 (if org-noutline-p
14792 (progn
14793 (if (and (eolp) (not (bobp))) (backward-char 1))
14794 ;; Early versions of noutline don't have `outline-invisible-p'.
14795 (if (fboundp 'outline-invisible-p)
14796 (outline-invisible-p)
14797 (get-char-property (point) 'invisible)))
14798 (skip-chars-backward "^\r\n")
14799 (equal (char-before) ?\r))))
14801 (defun org-back-to-heading (&optional invisible-ok)
14802 "Move to previous heading line, or beg of this line if it's a heading.
14803 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
14804 (if org-noutline-p
14805 (outline-back-to-heading invisible-ok)
14806 (if (and (or (bobp) (memq (char-before) '(?\n ?\r)))
14807 (looking-at outline-regexp))
14809 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
14810 outline-regexp)
14811 nil t)
14812 (if invisible-ok
14813 (progn (goto-char (or (match-end 1) (match-beginning 0)))
14814 (looking-at outline-regexp)))
14815 (error "Before first heading")))))
14817 (defun org-on-heading-p (&optional invisible-ok)
14818 "Return t if point is on a (visible) heading line.
14819 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
14820 (if org-noutline-p
14821 (outline-on-heading-p 'invisible-ok)
14822 (save-excursion
14823 (skip-chars-backward "^\n\r")
14824 (and (looking-at outline-regexp)
14825 (or invisible-ok
14826 (bobp)
14827 (equal (char-before) ?\n))))))
14829 (defun org-on-target-p ()
14830 (let ((pos (point)))
14831 (save-excursion
14832 (skip-chars-forward "<")
14833 (and (re-search-backward "<<" nil t)
14834 (or (looking-at org-radio-target-regexp)
14835 (looking-at org-target-regexp))
14836 (<= (match-beginning 0) pos)
14837 (>= (1+ (match-end 0)) pos)))))
14839 (defun org-up-heading-all (arg)
14840 "Move to the heading line of which the present line is a subheading.
14841 This function considers both visible and invisible heading lines.
14842 With argument, move up ARG levels."
14843 (if org-noutline-p
14844 (if (fboundp 'outline-up-heading-all)
14845 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14846 (outline-up-heading arg t)) ; emacs 22 version of outline.el
14847 (org-back-to-heading t)
14848 (looking-at outline-regexp)
14849 (if (<= (- (match-end 0) (match-beginning 0)) arg)
14850 (error "Cannot move up %d levels" arg)
14851 (re-search-backward
14852 (concat "[\n\r]" (regexp-quote
14853 (make-string (- (match-end 0) (match-beginning 0) arg)
14854 ?*))
14855 "[^*]"))
14856 (forward-char 1))))
14858 (defun org-show-hidden-entry ()
14859 "Show an entry where even the heading is hidden."
14860 (save-excursion
14861 (if (not org-noutline-p)
14862 (progn
14863 (org-back-to-heading t)
14864 (org-flag-heading nil)))
14865 (org-show-entry)))
14867 (defun org-check-occur-regexp (regexp)
14868 "If REGEXP starts with \"^\", modify it to check for \\r as well.
14869 Of course, only for the old outline mode."
14870 (if org-noutline-p
14871 regexp
14872 (if (string-match "^\\^" regexp)
14873 (concat "[\n\r]" (substring regexp 1))
14874 regexp)))
14876 (defun org-flag-heading (flag &optional entry)
14877 "Flag the current heading. FLAG non-nil means make invisible.
14878 When ENTRY is non-nil, show the entire entry."
14879 (save-excursion
14880 (org-back-to-heading t)
14881 (if (not org-noutline-p)
14882 ;; Make the current headline visible
14883 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
14884 ;; Check if we should show the entire entry
14885 (if entry
14886 (progn
14887 (org-show-entry)
14888 (save-excursion
14889 (and (outline-next-heading)
14890 (org-flag-heading nil))))
14891 (outline-flag-region (max 1 (1- (point)))
14892 (save-excursion (outline-end-of-heading) (point))
14893 (if org-noutline-p
14894 flag
14895 (if flag ?\r ?\n))))))
14897 (defun org-end-of-subtree (&optional invisible-OK)
14898 ;; This is an exact copy of the original function, but it uses
14899 ;; `org-back-to-heading', to make it work also in invisible
14900 ;; trees. And is uses an invisible-OK argument.
14901 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14902 (org-back-to-heading invisible-OK)
14903 (let ((first t)
14904 (level (funcall outline-level)))
14905 (while (and (not (eobp))
14906 (or first (> (funcall outline-level) level)))
14907 (setq first nil)
14908 (outline-next-heading))
14909 (if (memq (preceding-char) '(?\n ?\^M))
14910 (progn
14911 ;; Go to end of line before heading
14912 (forward-char -1)
14913 (if (memq (preceding-char) '(?\n ?\^M))
14914 ;; leave blank line before heading
14915 (forward-char -1))))))
14917 (defun org-show-subtree ()
14918 "Show everything after this heading at deeper levels."
14919 (outline-flag-region
14920 (point)
14921 (save-excursion
14922 (outline-end-of-subtree) (outline-next-heading) (point))
14923 (if org-noutline-p nil ?\n)))
14925 (defun org-show-entry ()
14926 "Show the body directly following this heading.
14927 Show the heading too, if it is currently invisible."
14928 (interactive)
14929 (save-excursion
14930 (org-back-to-heading t)
14931 (outline-flag-region
14932 (max 1 (1- (point)))
14933 (save-excursion
14934 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14935 (or (match-beginning 1) (point-max)))
14936 (if org-noutline-p nil ?\n))))
14938 (defun org-make-options-regexp (kwds)
14939 "Make a regular expression for keyword lines."
14940 (concat
14941 (if org-noutline-p "^" "[\n\r]")
14942 "#?[ \t]*\\+\\("
14943 (mapconcat 'regexp-quote kwds "\\|")
14944 "\\):[ \t]*"
14945 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
14947 ;; Make `bookmark-jump' show the jump location if it was hidden.
14948 (eval-after-load "bookmark"
14949 '(if (boundp 'bookmark-after-jump-hook)
14950 ;; We can use the hook
14951 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14952 ;; Hook not available, use advice
14953 (defadvice bookmark-jump (after org-make-visible activate)
14954 "Make the position visible."
14955 (org-bookmark-jump-unhide))))
14957 (defun org-bookmark-jump-unhide ()
14958 "Unhide the current position, to show the bookmark location."
14959 (and (eq major-mode 'org-mode)
14960 (or (org-invisible-p)
14961 (save-excursion (goto-char (max (point-min) (1- (point))))
14962 (org-invisible-p)))
14963 (org-show-hierarchy-above)))
14965 ;;; Finish up
14967 (provide 'org)
14969 (run-hooks 'org-load-hook)
14972 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14973 ;;; org.el ends here