Release 4.51
[org-mode.git] / org.el
blobbff45011941a01a412cfca6a6a7f4ea010651bf8
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.51
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.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://staff.science.uva.nl/~dominik/Tools/org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org-mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org-mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the etc/ directory of Emacs 22.
62 ;; Recent changes
63 ;; --------------
64 ;; Version 4.51
65 ;; - Link abbreviations (manual section 4.5).
66 ;; - More control over how agenda is displayed. See the new variables
67 ;; `org-agenda-window-setup', `org-agenda-restore-windows-after-quit'.
68 ;; - Bug fixes.
69 ;;
70 ;; Version 4.50
71 ;; - Closing a TODO item can record an additional note.
72 ;; See variables `org-log-done' and `org-log-note-headings'.
73 ;; - Inserting headlines and bullets can leave an extra blank line.
74 ;; See variable `org-blank-before-new-entry'. (Ed Hirgelt patch)
75 ;; - [[bracket links]] in the agenda are active just as in org-mode buffers.
76 ;; - C-c C-o on a date range displays the agenda for exactly this range.
77 ;; - The default for `org-cycle-include-plain-lists' is back to nil.
78 ;; - Calls to `org-occur' can be stacked by using a prefix argument.
79 ;; - The options `org-show-hierarchy-above' and `org-show-following-heading'
80 ;; now always default to `t', but can be customized differently for
81 ;; different types of sparse trees or jump commands.
82 ;; - Bug fixes.
84 ;; Version 4.49
85 ;; - Agenda views can be made in batch mode from the command line.
86 ;; - `org-store-link' does the right thing in dired-mode.
87 ;; - File links can contain environment variables.
88 ;; - Full Emacs 21 compatibility has been restored.
89 ;; - Bug fixes.
91 ;; Version 4.47
92 ;; - Custom commands may produce an agenda which contains several blocks,
93 ;; each block created by a different agenda command.
94 ;; - Agenda commands can be restricted to the current file, region, subtree.
95 ;; - The timeline command must now be called through the agenda
96 ;; dispatcher (C-c a L). `C-c C-r' no longer works.
97 ;; - Agenda items can be sorted by tag. The *last* tag is used for this.
98 ;; - The prefix and the sorting strategy for agenda items can depend
99 ;; upon the agenda type.
100 ;; - The handling of `mailto:' links can be customized, see the new
101 ;; variable `org-link-mailto-program'.
102 ;; - `mailto' links can specify a subject after a double colon,
103 ;; like [[mailto:carsten@orgmode.org::Org-mode is buggy]].
104 ;; - In the #+STARTUP line, M-TAB completes valid keywords.
105 ;; - In the #+TAGS: line, M-TAB after ":" inserts all currently used tags.
106 ;; - Again full Emacs 21 support: Checkboxes and publishing are fixed.
107 ;; - More minor bug fixes.
109 ;; Version 4.45
110 ;; - Checkbox lists can show statistics about checked items.
111 ;; - C-TAB will cycle the visibility of archived subtrees.
112 ;;; - Documentation about checkboxes has been moved to chapter 5.
113 ;; - Bux fixes.
115 ;; Version 4.44
116 ;; - Clock table can be done for a limited time interval.
117 ;; - Obsolete support for the old outline mode has been removed.
118 ;; - Bug fixes and code cleaning.
120 ;; Version 4.43
121 ;; - Bug fixes
122 ;; - `s' key in the agenda saves all org-mode buffers.
124 ;; Version 4.41
125 ;; - Shift-curser keys can modify inactive time stamps (inactive time
126 ;; stamps are the ones in [...] brackets.
127 ;; - Toggle all checkboxes in a region/below a headline.
128 ;; - Bug fixes.
130 ;;; Code:
132 (eval-when-compile
133 (require 'cl)
134 (require 'calendar))
135 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
136 ;; the file noutline.el being loaded.
137 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
138 ;; We require noutline, which might be provided in outline.el
139 (require 'outline) (require 'noutline)
140 ;; Other stuff we need.
141 (require 'time-date)
142 (require 'easymenu)
144 ;;; Customization variables
146 (defvar org-version "4.51"
147 "The version number of the file org.el.")
148 (defun org-version ()
149 (interactive)
150 (message "Org-mode version %s" org-version))
152 ;; Compatibility constants
153 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
154 (defconst org-format-transports-properties-p
155 (let ((x "a"))
156 (add-text-properties 0 1 '(test t) x)
157 (get-text-property 0 'test (format "%s" x)))
158 "Does format transport text properties?")
160 (defgroup org nil
161 "Outline-based notes management and organizer."
162 :tag "Org"
163 :group 'outlines
164 :group 'hypermedia
165 :group 'calendar)
167 (defgroup org-startup nil
168 "Options concerning startup of Org-mode."
169 :tag "Org Startup"
170 :group 'org)
172 (defcustom org-startup-folded t
173 "Non-nil means, entering Org-mode will switch to OVERVIEW.
174 This can also be configured on a per-file basis by adding one of
175 the following lines anywhere in the buffer:
177 #+STARTUP: fold
178 #+STARTUP: nofold
179 #+STARTUP: content"
180 :group 'org-startup
181 :type '(choice
182 (const :tag "nofold: show all" nil)
183 (const :tag "fold: overview" t)
184 (const :tag "content: all headlines" content)))
186 (defcustom org-startup-truncated t
187 "Non-nil means, entering Org-mode will set `truncate-lines'.
188 This is useful since some lines containing links can be very long and
189 uninteresting. Also tables look terrible when wrapped."
190 :group 'org-startup
191 :type 'boolean)
193 (defcustom org-startup-align-all-tables nil
194 "Non-nil means, align all tables when visiting a file.
195 This is useful when the column width in tables is forced with <N> cookies
196 in table fields. Such tables will look correct only after the first re-align.
197 This can also be configured on a per-file basis by adding one of
198 the following lines anywhere in the buffer:
199 #+STARTUP: align
200 #+STARTUP: noalign"
201 :group 'org-startup
202 :type 'boolean)
204 (defcustom org-startup-with-deadline-check nil
205 "Non-nil means, entering Org-mode will run the deadline check.
206 This means, if you start editing an org file, you will get an
207 immediate reminder of any due deadlines.
208 This can also be configured on a per-file basis by adding one of
209 the following lines anywhere in the buffer:
210 #+STARTUP: dlcheck
211 #+STARTUP: nodlcheck"
212 :group 'org-startup
213 :type 'boolean)
215 (defcustom org-insert-mode-line-in-empty-file nil
216 "Non-nil means insert the first line setting Org-mode in empty files.
217 When the function `org-mode' is called interactively in an empty file, this
218 normally means that the file name does not automatically trigger Org-mode.
219 To ensure that the file will always be in Org-mode in the future, a
220 line enforcing Org-mode will be inserted into the buffer, if this option
221 has been set."
222 :group 'org-startup
223 :type 'boolean)
225 (defcustom org-CUA-compatible nil
226 "Non-nil means use alternative key bindings for S-<cursor movement>.
227 Org-mode used S-<cursor movement> for changing timestamps and priorities.
228 S-<cursor movement> is also used for example by `CUA-mode' to select text.
229 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
230 alternative bindings. Setting this variable to t will replace the following
231 keys both in Org-mode and in the Org-agenda buffer.
233 S-RET -> C-S-RET
234 S-up -> M-p
235 S-down -> M-n
236 S-left -> M--
237 S-right -> M-+
239 If you do not like the alternative keys, take a look at the variable
240 `org-disputed-keys'.
242 This option is only relevant at load-time of Org-mode. Changing it requires
243 a restart of Emacs to become effective."
244 :group 'org-startup
245 :type 'boolean)
247 (defvar org-disputed-keys
248 '((S-up [(shift up)] [(meta ?p)])
249 (S-down [(shift down)] [(meta ?n)])
250 (S-left [(shift left)] [(meta ?-)])
251 (S-right [(shift right)] [(meta ?+)])
252 (S-return [(shift return)] [(control shift return)]))
253 "Keys for which Org-mode and other modes compete.
254 This is an alist, cars are symbols for lookup, 1st element is the default key,
255 second element will be used when `org-CUA-compatible' is t.")
257 (defun org-key (key)
258 "Select a key according to `org-CUA-compatible'."
259 (nth (if org-CUA-compatible 2 1)
260 (or (assq key org-disputed-keys)
261 (error "Invalid Key %s in `org-key'" key))))
263 (defcustom org-ellipsis nil
264 "The ellipsis to use in the Org-mode outline.
265 When nil, just use the standard three dots. When a string, use that instead,
266 and just in Org-mode (which will then use its own display table).
267 Changing this requires executing `M-x org-mode' in a buffer to become
268 effective."
269 :group 'org-startup
270 :type '(choice (const :tag "Default" nil)
271 (string :tag "String" :value "...#")))
273 (defvar org-display-table nil
274 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
276 (defgroup org-keywords nil
277 "Keywords in Org-mode."
278 :tag "Org Keywords"
279 :group 'org)
281 (defcustom org-deadline-string "DEADLINE:"
282 "String to mark deadline entries.
283 A deadline is this string, followed by a time stamp. Should be a word,
284 terminated by a colon. You can insert a schedule keyword and
285 a timestamp with \\[org-deadline].
286 Changes become only effective after restarting Emacs."
287 :group 'org-keywords
288 :type 'string)
290 (defcustom org-scheduled-string "SCHEDULED:"
291 "String to mark scheduled TODO entries.
292 A schedule is this string, followed by a time stamp. Should be a word,
293 terminated by a colon. You can insert a schedule keyword and
294 a timestamp with \\[org-schedule].
295 Changes become only effective after restarting Emacs."
296 :group 'org-keywords
297 :type 'string)
299 (defcustom org-closed-string "CLOSED:"
300 "String used as the prefix for timestamps logging closing a TODO entry."
301 :group 'org-keywords
302 :type 'string)
304 (defcustom org-clock-string "CLOCK:"
305 "String used as prefix for timestamps clocking work hours on an item."
306 :group 'org-keywords
307 :type 'string)
309 (defcustom org-comment-string "COMMENT"
310 "Entries starting with this keyword will never be exported.
311 An entry can be toggled between COMMENT and normal with
312 \\[org-toggle-comment].
313 Changes become only effective after restarting Emacs."
314 :group 'org-keywords
315 :type 'string)
317 (defcustom org-quote-string "QUOTE"
318 "Entries starting with this keyword will be exported in fixed-width font.
319 Quoting applies only to the text in the entry following the headline, and does
320 not extend beyond the next headline, even if that is lower level.
321 An entry can be toggled between QUOTE and normal with
322 \\[org-toggle-fixed-width-section]."
323 :group 'org-keywords
324 :type 'string)
326 (defgroup org-structure nil
327 "Options concerning the general structure of Org-mode files."
328 :tag "Org Structure"
329 :group 'org)
331 (defgroup org-cycle nil
332 "Options concerning visibility cycling in Org-mode."
333 :tag "Org Cycle"
334 :group 'org-structure)
336 (defcustom org-cycle-global-at-bob t
337 "Cycle globally if cursor is at beginning of buffer and not at a headline.
338 This makes it possible to do global cycling without having to use S-TAB or
339 C-u TAB. For this special case to work, the first line of the buffer
340 must not be a headline - it may be empty ot some other text. When used in
341 this way, `org-cycle-hook' is disables temporarily, to make sure the
342 cursor stays at the beginning of the buffer.
343 When this option is nil, don't do anything special at the beginning
344 of the buffer."
345 :group 'org-cycle
346 :type 'boolean)
348 (defcustom org-cycle-emulate-tab t
349 "Where should `org-cycle' emulate TAB.
350 nil Never
351 white Only in completely white lines
352 whitestart Only at the beginning of lines, before the first non-white char.
353 t Everywhere except in headlines
354 If TAB is used in a place where it does not emulate TAB, the current subtree
355 visibility is cycled."
356 :group 'org-cycle
357 :type '(choice (const :tag "Never" nil)
358 (const :tag "Only in completely white lines" white)
359 (const :tag "Before first char in a line" whitestart)
360 (const :tag "Everywhere except in headlines" t)
363 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
364 org-optimize-window-after-visibility-change)
365 "Hook that is run after `org-cycle' has changed the buffer visibility.
366 The function(s) in this hook must accept a single argument which indicates
367 the new state that was set by the most recent `org-cycle' command. The
368 argument is a symbol. After a global state change, it can have the values
369 `overview', `content', or `all'. After a local state change, it can have
370 the values `folded', `children', or `subtree'."
371 :group 'org-cycle
372 :type 'hook)
374 (defgroup org-edit-structure nil
375 "Options concerning structure editing in Org-mode."
376 :tag "Org Edit Structure"
377 :group 'org-structure)
379 (defcustom org-odd-levels-only nil
380 "Non-nil means, skip even levels and only use odd levels for the outline.
381 This has the effect that two stars are being added/taken away in
382 promotion/demotion commands. It also influences how levels are
383 handled by the exporters.
384 Changing it requires restart of `font-lock-mode' to become effective
385 for fontification also in regions already fontified.
386 You may also set this on a per-file basis by adding one of the following
387 lines to the buffer:
389 #+STARTUP: odd
390 #+STARTUP: oddeven"
391 :group 'org-edit-structure
392 :group 'org-font-lock
393 :type 'boolean)
395 (defcustom org-adapt-indentation t
396 "Non-nil means, adapt indentation when promoting and demoting.
397 When this is set and the *entire* text in an entry is indented, the
398 indentation is increased by one space in a demotion command, and
399 decreased by one in a promotion command. If any line in the entry
400 body starts at column 0, indentation is not changed at all."
401 :group 'org-edit-structure
402 :type 'boolean)
404 (defcustom org-blank-before-new-entry '((heading . nil)
405 (plain-list-item . nil))
406 "Should `org-insert-heading' leave a blank line before new heading/item?
407 The value is an alist, with `heading' and `plain-list-item' as car,
408 and a boolean flag as cdr."
409 :group 'org-edit-structure
410 :type '(list
411 (cons (const heading) (boolean))
412 (cons (const plain-list-item) (boolean))))
414 (defcustom org-insert-heading-hook nil
415 "Hook being run after inserting a new heading."
416 :group 'org-edit-structure
417 :type 'boolean)
419 (defcustom org-enable-fixed-width-editor t
420 "Non-nil means, lines starting with \":\" are treated as fixed-width.
421 This currently only means, they are never auto-wrapped.
422 When nil, such lines will be treated like ordinary lines.
423 See also the QUOTE keyword."
424 :group 'org-edit-structure
425 :type 'boolean)
427 (defgroup org-sparse-trees nil
428 "Options concerning sparse trees in Org-mode."
429 :tag "Org Sparse Trees"
430 :group 'org-structure)
432 (defcustom org-highlight-sparse-tree-matches t
433 "Non-nil means, highlight all matches that define a sparse tree.
434 The highlights will automatically disappear the next time the buffer is
435 changed by an edit command."
436 :group 'org-sparse-trees
437 :type 'boolean)
439 (defcustom org-remove-highlights-with-change t
440 "Non-nil means, any change to the buffer will remove temporary highlights.
441 Such highlights are created by `org-occur' and `org-clock-display'.
442 When nil, `C-c C-c needs to be used to get rid of the highlights.
443 The highlights created by `org-preview-latex-fragment' always need
444 `C-c C-c' to be removed."
445 :group 'org-sparse-trees
446 :group 'org-time
447 :type 'boolean)
449 (defcustom org-show-hierarchy-above '((default t))
450 "Non-nil means, show full hierarchy when showing a spot in the tree.
451 Turning this off makes sparse trees more compact, but also less clear.
452 Instead of t, this can also be an alist specifying this option for different
453 contexts. Valid contexts are
454 agenda when exposing an entry from the agenda
455 org-goto when using the command `org-goto' on key C-c C-j
456 occur-tree when using the command `org-occur' on key C-c /
457 tags-tree when constructing a sparse tree based on tags matches
458 link-search when exposing search matches associated with a link
459 mark-goto when exposing the jump goal of a mark
460 bookmark-jump when exposing a bookmark location
461 default default for all contexts not set explicitly"
462 :group 'org-sparse-trees
463 :type '(choice
464 (const :tag "Always" t)
465 (const :tag "Never" nil)
466 (repeat :greedy t :tag "Individual contexts"
467 (cons
468 (choice :tag "Context"
469 (const agenda)
470 (const org-goto)
471 (const occur-tree)
472 (const tags-tree)
473 (const link-search)
474 (const mark-goto)
475 (const bookmark-jump)
476 (const default))
477 (boolean)))))
479 (defcustom org-show-following-heading '((default t))
480 "Non-nil means, show heading following match in `org-occur'.
481 When doing an `org-occur' it is useful to show the headline which
482 follows the match, even if they do not match the regexp. This makes it
483 easier to edit directly inside the sparse tree. However, if you use
484 `org-occur' mainly as an overview, the following headlines are
485 unnecessary clutter.
486 Instead of t, this can also be an alist specifying this option for different
487 contexts. See `org-show-hierarchy-above' for valid contexts."
488 :group 'org-sparse-trees
489 :type '(choice
490 (const :tag "Always" t)
491 (const :tag "Never" nil)
492 (repeat :greedy t :tag "Individual contexts"
493 (cons
494 (choice :tag "Context"
495 (const agenda)
496 (const org-goto)
497 (const occur-tree)
498 (const tags-tree)
499 (const link-search)
500 (const mark-goto)
501 (const bookmark-jump)
502 (const default))
503 (boolean)))))
505 (defcustom org-occur-hook '(org-first-headline-recenter)
506 "Hook that is run after `org-occur' has constructed a sparse tree.
507 This can be used to recenter the window to show as much of the structure
508 as possible."
509 :group 'org-sparse-trees
510 :type 'hook)
512 (defgroup org-plain-lists nil
513 "Options concerning plain lists in Org-mode."
514 :tag "Org Plain lists"
515 :group 'org-structure)
517 (defcustom org-cycle-include-plain-lists nil
518 "Non-nil means, include plain lists into visibility cycling.
519 This means that during cycling, plain list items will *temporarily* be
520 interpreted as outline headlines with a level given by 1000+i where i is the
521 indentation of the bullet. In all other operations, plain list items are
522 not seen as headlines. For example, you cannot assign a TODO keyword to
523 such an item."
524 :group 'org-plain-lists
525 :type 'boolean)
527 (defcustom org-plain-list-ordered-item-terminator t
528 "The character that makes a line with leading number an ordered list item.
529 Valid values are ?. and ?\). To get both terminators, use t. While
530 ?. may look nicer, it creates the danger that a line with leading
531 number may be incorrectly interpreted as an item. ?\) therefore is
532 the safe choice."
533 :group 'org-plain-lists
534 :type '(choice (const :tag "dot like in \"2.\"" ?.)
535 (const :tag "paren like in \"2)\"" ?\))
536 (const :tab "both" t)))
538 (defcustom org-auto-renumber-ordered-lists t
539 "Non-nil means, automatically renumber ordered plain lists.
540 Renumbering happens when the sequence have been changed with
541 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
542 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
543 :group 'org-plain-lists
544 :type 'boolean)
546 (defcustom org-provide-checkbox-statistics t
547 "Non-nil means, update checkbox statistics after insert and toggle.
548 When this is set, checkbox statistics is updated each time you either insert
549 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
550 with \\[org-ctrl-c-ctrl-c\\]."
551 :group 'org
552 :type 'boolean)
554 (defgroup org-archive nil
555 "Options concerning archiving in Org-mode."
556 :tag "Org Archive"
557 :group 'org-structure)
559 (defcustom org-archive-tag "ARCHIVE"
560 "The tag that marks a subtree as archived.
561 An archived subtree does not open during visibility cycling, and does
562 not contribute to the agenda listings."
563 :group 'org-archive
564 :group 'org-keywords
565 :type 'string)
567 (defcustom org-agenda-skip-archived-trees t
568 "Non-nil means, the agenda will skip any items located in archived trees.
569 An archived tree is a tree marked with the tag ARCHIVE."
570 :group 'org-archive
571 :group 'org-agenda-display
572 :type 'boolean)
574 (defcustom org-cycle-open-archived-trees nil
575 "Non-nil means, `org-cycle' will open archived trees.
576 An archived tree is a tree marked with the tag ARCHIVE.
577 When nil, archived trees will stay folded. You can still open them with
578 normal outline commands like `show-all', but not with the cycling commands."
579 :group 'org-archive
580 :group 'org-cycle
581 :type 'boolean)
583 (defcustom org-sparse-tree-open-archived-trees nil
584 "Non-nil means sparse tree construction shows matches in archived trees.
585 When nil, matches in these trees are highlighted, but the trees are kept in
586 collapsed state."
587 :group 'org-archive
588 :group 'org-sparse-trees
589 :type 'boolean)
591 (defcustom org-archive-location "%s_archive::"
592 "The location where subtrees should be archived.
593 This string consists of two parts, separated by a double-colon.
595 The first part is a file name - when omitted, archiving happens in the same
596 file. %s will be replaced by the current file name (without directory part).
597 Archiving to a different file is useful to keep archived entries from
598 contributing to the Org-mode Agenda.
600 The part after the double colon is a headline. The archived entries will be
601 filed under that headline. When omitted, the subtrees are simply filed away
602 at the end of the file, as top-level entries.
604 Here are a few examples:
605 \"%s_archive::\"
606 If the current file is Projects.org, archive in file
607 Projects.org_archive, as top-level trees. This is the default.
609 \"::* Archived Tasks\"
610 Archive in the current file, under the top-level headline
611 \"* Archived Tasks\".
613 \"~/org/archive.org::\"
614 Archive in file ~/org/archive.org (absolute path), as top-level trees.
616 \"basement::** Finished Tasks\"
617 Archive in file ./basement (relative path), as level 3 trees
618 below the level 2 heading \"** Finished Tasks\".
620 You may set this option on a per-file basis by adding to the buffer a
621 line like
623 #+ARCHIVE: basement::** Finished Tasks"
624 :group 'org-archive
625 :type 'string)
627 (defcustom org-archive-mark-done t
628 "Non-nil means, mark entries as DONE when they are moved to the archive file."
629 :group 'org-archive
630 :type 'boolean)
632 (defcustom org-archive-stamp-time t
633 "Non-nil means, add a time stamp to entries moved to an archive file.
634 The time stamp will be added directly after the TODO state keyword in the
635 first line, so it is probably best to use this in combinations with
636 `org-archive-mark-done'."
637 :group 'org-archive
638 :type 'boolean)
640 (defgroup org-table nil
641 "Options concerning tables in Org-mode."
642 :tag "Org Table"
643 :group 'org)
645 (defcustom org-enable-table-editor 'optimized
646 "Non-nil means, lines starting with \"|\" are handled by the table editor.
647 When nil, such lines will be treated like ordinary lines.
649 When equal to the symbol `optimized', the table editor will be optimized to
650 do the following:
651 - Automatic overwrite mode in front of whitespace in table fields.
652 This makes the structure of the table stay in tact as long as the edited
653 field does not exceed the column width.
654 - Minimize the number of realigns. Normally, the table is aligned each time
655 TAB or RET are pressed to move to another field. With optimization this
656 happens only if changes to a field might have changed the column width.
657 Optimization requires replacing the functions `self-insert-command',
658 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
659 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
660 very good at guessing when a re-align will be necessary, but you can always
661 force one with \\[org-ctrl-c-ctrl-c].
663 If you would like to use the optimized version in Org-mode, but the
664 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
666 This variable can be used to turn on and off the table editor during a session,
667 but in order to toggle optimization, a restart is required.
669 See also the variable `org-table-auto-blank-field'."
670 :group 'org-table
671 :type '(choice
672 (const :tag "off" nil)
673 (const :tag "on" t)
674 (const :tag "on, optimized" optimized)))
676 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
677 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
678 In the optimized version, the table editor takes over all simple keys that
679 normally just insert a character. In tables, the characters are inserted
680 in a way to minimize disturbing the table structure (i.e. in overwrite mode
681 for empty fields). Outside tables, the correct binding of the keys is
682 restored.
684 The default for this option is t if the optimized version is also used in
685 Org-mode. See the variable `org-enable-table-editor' for details. Changing
686 this variable requires a restart of Emacs to become effective."
687 :group 'org-table
688 :type 'boolean)
690 (defgroup org-table-settings nil
691 "Settings for tables in Org-mode."
692 :tag "Org Table Settings"
693 :group 'org-table)
695 (defcustom org-table-default-size "5x2"
696 "The default size for newly created tables, Columns x Rows."
697 :group 'org-table-settings
698 :type 'string)
700 (defcustom org-table-number-regexp
701 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)?[0-9a-fA-F]+\\)$"
702 "Regular expression for recognizing numbers in table columns.
703 If a table column contains mostly numbers, it will be aligned to the
704 right. If not, it will be aligned to the left.
706 The default value of this option is a regular expression which allows
707 anything which looks remotely like a number as used in scientific
708 context. For example, all of the following will be considered a
709 number:
710 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
712 Other options offered by the customize interface are more restrictive."
713 :group 'org-table-settings
714 :type '(choice
715 (const :tag "Positive Integers"
716 "^[0-9]+$")
717 (const :tag "Integers"
718 "^[-+]?[0-9]+$")
719 (const :tag "Floating Point Numbers"
720 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
721 (const :tag "Floating Point Number or Integer"
722 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
723 (const :tag "Exponential, Floating point, Integer"
724 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
725 (const :tag "Very General Number-Like, including hex"
726 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)?[0-9a-fA-F]+\\)$")
727 (string :tag "Regexp:")))
729 (defcustom org-table-number-fraction 0.5
730 "Fraction of numbers in a column required to make the column align right.
731 In a column all non-white fields are considered. If at least this
732 fraction of fields is matched by `org-table-number-fraction',
733 alignment to the right border applies."
734 :group 'org-table-settings
735 :type 'number)
737 (defgroup org-table-editing nil
738 "Bahavior of tables during editing in Org-mode."
739 :tag "Org Table Editing"
740 :group 'org-table)
742 (defcustom org-table-automatic-realign t
743 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
744 When nil, aligning is only done with \\[org-table-align], or after column
745 removal/insertion."
746 :group 'org-table-editing
747 :type 'boolean)
749 (defcustom org-table-limit-column-width t ;kw
750 "Non-nil means, allow to limit the width of table columns with <N> fields."
751 :group 'org-table-editing
752 :type 'boolean)
754 (defcustom org-table-auto-blank-field t
755 "Non-nil means, automatically blank table field when starting to type into it.
756 This only happens when typing immediately after a field motion
757 command (TAB, S-TAB or RET).
758 Only relevant when `org-enable-table-editor' is equal to `optimized'."
759 :group 'org-table-editing
760 :type 'boolean)
762 (defcustom org-table-tab-jumps-over-hlines t
763 "Non-nil means, tab in the last column of a table with jump over a hline.
764 If a horizontal separator line is following the current line,
765 `org-table-next-field' can either create a new row before that line, or jump
766 over the line. When this option is nil, a new line will be created before
767 this line."
768 :group 'org-table-editing
769 :type 'boolean)
771 (defcustom org-table-tab-recognizes-table.el t
772 "Non-nil means, TAB will automatically notice a table.el table.
773 When it sees such a table, it moves point into it and - if necessary -
774 calls `table-recognize-table'."
775 :group 'org-table-editing
776 :type 'boolean)
778 (defgroup org-table-calculation nil
779 "Options concerning tables in Org-mode."
780 :tag "Org Table Calculation"
781 :group 'org-table)
783 (defcustom org-table-copy-increment t
784 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
785 :group 'org-table-calculation
786 :type 'boolean)
788 (defcustom org-calc-default-modes
789 '(calc-internal-prec 12
790 calc-float-format (float 5)
791 calc-angle-mode deg
792 calc-prefer-frac nil
793 calc-symbolic-mode nil
794 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
795 calc-display-working-message t
797 "List with Calc mode settings for use in calc-eval for table formulas.
798 The list must contain alternating symbols (Calc modes variables and values).
799 Don't remove any of the default settings, just change the values. Org-mode
800 relies on the variables to be present in the list."
801 :group 'org-table-calculation
802 :type 'plist)
804 (defcustom org-table-formula-evaluate-inline t
805 "Non-nil means, TAB and RET evaluate a formula in current table field.
806 If the current field starts with an equal sign, it is assumed to be a formula
807 which should be evaluated as described in the manual and in the documentation
808 string of the command `org-table-eval-formula'. This feature requires the
809 Emacs calc package.
810 When this variable is nil, formula calculation is only available through
811 the command \\[org-table-eval-formula]."
812 :group 'org-table-calculation
813 :type 'boolean)
816 (defcustom org-table-formula-use-constants t
817 "Non-nil means, interpret constants in formulas in tables.
818 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
819 by the value given in `org-table-formula-constants', or by a value obtained
820 from the `constants.el' package."
821 :group 'org-table-calculation
822 :type 'boolean)
824 (defcustom org-table-formula-constants nil
825 "Alist with constant names and values, for use in table formulas.
826 The car of each element is a name of a constant, without the `$' before it.
827 The cdr is the value as a string. For example, if you'd like to use the
828 speed of light in a formula, you would configure
830 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
832 and then use it in an equation like `$1*$c'."
833 :group 'org-table-calculation
834 :type '(repeat
835 (cons (string :tag "name")
836 (string :tag "value"))))
838 (defcustom org-table-formula-numbers-only nil
839 "Non-nil means, calculate only with numbers in table formulas.
840 Then all input fields will be converted to a number, and the result
841 must also be a number. When nil, calc's full potential is available
842 in table calculations, including symbolics etc."
843 :group 'org-table-calculation
844 :type 'boolean)
846 (defcustom org-table-allow-automatic-line-recalculation t
847 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
848 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
849 :group 'org-table-calculation
850 :type 'boolean)
852 (defgroup org-link nil
853 "Options concerning links in Org-mode."
854 :tag "Org Link"
855 :group 'org)
857 (defvar org-link-abbrev-alist-local nil
858 "buffer-local version of `org-link-abbrev-alist', which see.
859 The value of this is taken from the #+LINK lines.")
860 (make-variable-buffer-local 'org-link-abbrev-alist-local)
862 (defcustom org-link-abbrev-alist nil
863 "Alist of link abbreviations.
864 The car of each element is a string, to be replaced at the start of a link.
865 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
866 links in Org-mode buffers can have an optional tag after a double colon, e.g.
868 [[linkkey::tag][description]]
870 If REPLACE is a string, the tag will simply be appended to create the link.
871 If the string contains \"%s\", the tag will be inserted there. REPLACE may
872 also be a function that will be called with the tag as the only argument to
873 create the link. See the manual for examples."
874 :group 'org-link
875 :type 'alist)
877 (defcustom org-descriptive-links t
878 "Non-nil means, hide link part and only show description of bracket links.
879 Bracket links are like [[link][descritpion]]. This variable sets the initial
880 state in new org-mode buffers. The setting can then be toggled on a
881 per-buffer basis from the Org->Hyperlinks menu."
882 :group 'org-link
883 :type 'boolean)
885 (defcustom org-link-style 'bracket
886 "The style of links to be inserted with \\[org-insert-link].
887 Possible values are:
888 bracket [[link][description]]. This is recommended
889 plain Description \\n link. The old way, no longer recommended."
890 :group 'org-link
891 :type '(choice
892 (const :tag "Bracket (recommended)" bracket)
893 (const :tag "Plain (no longer recommended)" plain)))
895 (defcustom org-link-format "%s"
896 "Default format for external, URL-like linkes in the buffer.
897 This is a format string for printf, %s will be replaced by the link text.
898 The recommended value is just \"%s\", since links will be protected by
899 enclosing them in double brackets. If you prefer plain links (see variable
900 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
901 additional URL: prefix, so the format would be \"<URL:%s>\"."
902 :group 'org-link
903 :type '(choice
904 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
905 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
906 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
907 (string :tag "Other" :value "<%s>")))
909 (defcustom org-link-file-path-type 'adaptive
910 "How the path name in file links should be stored.
911 Valid values are:
913 relative relative to the current directory, i.e. the directory of the file
914 into which the link is being inserted.
915 absolute absolute path, if possible with ~ for home directory.
916 noabbrev absolute path, no abbreviation of home directory.
917 adaptive Use relative path for files in the current directory and sub-
918 directories of it. For other files, use an absolute path."
919 :group 'org-link
920 :type '(choice
921 (const relative)
922 (const absolute)
923 (const noabbrev)
924 (const adaptive)))
926 (defcustom org-activate-links '(bracket angle plain radio tag date)
927 "Types of links that should be activated in Org-mode files.
928 This is a list of symbols, each leading to the activation of a certain link
929 type. In principle, it does not hurt to turn on most link types - there may
930 be a small gain when turning off unused link types. The types are:
932 bracket The recommended [[link][description]] or [[link]] links with hiding.
933 angular Links in angular brackes that may contain whitespace like
934 <bbdb:Carsten Dominik>.
935 plain Plain links in normal text, no whitespace, like http://google.com.
936 radio Text that is matched by a radio target, see manual for details.
937 tag Tag settings in a headline (link to tag search).
938 date Time stamps (link to calendar).
939 camel CamelCase words defining text searches.
941 Changing this variable requires a restart of Emacs to become effective."
942 :group 'org-link
943 :type '(set (const :tag "Double bracket links (new style)" bracket)
944 (const :tag "Angular bracket links (old style)" angular)
945 (const :tag "plain text links" plain)
946 (const :tag "Radio target matches" radio)
947 (const :tag "Tags" tag)
948 (const :tag "Timestamps" date)
949 (const :tag "CamelCase words" camel)))
951 (defgroup org-link-store nil
952 "Options concerning storing links in Org-mode"
953 :tag "Org Store Link"
954 :group 'org-link)
956 (defcustom org-context-in-file-links t
957 "Non-nil means, file links from `org-store-link' contain context.
958 A search string will be added to the file name with :: as separator and
959 used to find the context when the link is activated by the command
960 `org-open-at-point'.
961 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
962 negates this setting for the duration of the command."
963 :group 'org-link-store
964 :type 'boolean)
966 (defcustom org-file-link-context-use-camel-case nil
967 "Non-nil means, use CamelCase to store a search context in a file link.
968 When nil, the search string simply consists of the words of the string.
969 CamelCase is deprecated, and support for it may be dropped in the future."
970 :group 'org-link-store
971 :type 'boolean)
973 (defcustom org-keep-stored-link-after-insertion nil
974 "Non-nil means, keep link in list for entire session.
976 The command `org-store-link' adds a link pointing to the current
977 location to an internal list. These links accumulate during a session.
978 The command `org-insert-link' can be used to insert links into any
979 Org-mode file (offering completion for all stored links). When this
980 option is nil, every link which has been inserted once using \\[org-insert-link]
981 will be removed from the list, to make completing the unused links
982 more efficient."
983 :group 'org-link-store
984 :type 'boolean)
986 (defcustom org-usenet-links-prefer-google nil
987 "Non-nil means, `org-store-link' will create web links to Google groups.
988 When nil, Gnus will be used for such links.
989 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
990 negates this setting for the duration of the command."
991 :group 'org-link-store
992 :type 'boolean)
994 (defgroup org-link-follow nil
995 "Options concerning following links in Org-mode"
996 :tag "Org Follow Link"
997 :group 'org-link)
999 (defcustom org-tab-follows-link nil
1000 "Non-nil means, on links TAB will follow the link.
1001 Needs to be set before org.el is loaded."
1002 :group 'org-link-follow
1003 :type 'boolean)
1005 (defcustom org-return-follows-link nil
1006 "Non-nil means, on links RET will follow the link.
1007 Needs to be set before org.el is loaded."
1008 :group 'org-link-follow
1009 :type 'boolean)
1011 (defcustom org-mouse-1-follows-link t
1012 "Non-nil means, mouse-1 on a link will follow the link.
1013 A longer mouse click will still set point. Does not wortk on XEmacs.
1014 Needs to be set before org.el is loaded."
1015 :group 'org-link-follow
1016 :type 'boolean)
1018 (defcustom org-mark-ring-length 4
1019 "Number of different positions to be recorded in the ring
1020 Changing this requires a restart of Emacs to work correctly."
1021 :group 'org-link-follow
1022 :type 'interger)
1024 (defcustom org-link-frame-setup
1025 '((vm . vm-visit-folder-other-frame)
1026 (gnus . gnus-other-frame)
1027 (file . find-file-other-window))
1028 "Setup the frame configuration for following links.
1029 When following a link with Emacs, it may often be useful to display
1030 this link in another window or frame. This variable can be used to
1031 set this up for the different types of links.
1032 For VM, use any of
1033 `vm-visit-folder'
1034 `vm-visit-folder-other-frame'
1035 For Gnus, use any of
1036 `gnus'
1037 `gnus-other-frame'
1038 For FILE, use any of
1039 `find-file'
1040 `find-file-other-window'
1041 `find-file-other-frame'
1042 For the calendar, use the variable `calendar-setup'.
1043 For BBDB, it is currently only possible to display the matches in
1044 another window."
1045 :group 'org-link-follow
1046 :type '(list
1047 (cons (const vm)
1048 (choice
1049 (const vm-visit-folder)
1050 (const vm-visit-folder-other-window)
1051 (const vm-visit-folder-other-frame)))
1052 (cons (const gnus)
1053 (choice
1054 (const gnus)
1055 (const gnus-other-frame)))
1056 (cons (const file)
1057 (choice
1058 (const find-file)
1059 (const find-file-other-window)
1060 (const find-file-other-frame)))))
1062 (defcustom org-display-internal-link-with-indirect-buffer nil
1063 "Non-nil means, use indirect buffer to display infile links.
1064 Activating internal links (from one location in a file to another location
1065 in the same file) normally just jumps to the location. When the link is
1066 activated with a C-u prefix (or with mouse-3), the link is displayed in
1067 another window. When this option is set, the other window actually displays
1068 an indirect buffer clone of the current buffer, to avoid any visibility
1069 changes to the current buffer."
1070 :group 'org-link-follow
1071 :type 'boolean)
1074 (defcustom org-open-non-existing-files nil
1075 "Non-nil means, `org-open-file' will open non-existing file.
1076 When nil, an error will be generated."
1077 :group 'org-link-follow
1078 :type 'boolean)
1080 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1081 "Function and arguments to call for following mailto links.
1082 This is a list with the first element being a lisp function, and the
1083 remaining elements being arguments to the function. In string arguments,
1084 %a will be replaced by the address, and %s will be replaced by the subject
1085 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1086 :group 'org-link-follow
1087 :type '(choice
1088 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1089 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1090 (const :tag "message-mail" (message-mail "%a" "%s"))
1091 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1093 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1094 "Non-nil means, ask for confirmation before executing shell links.
1095 Shell links can be dangerous, just thing about a link
1097 [[shell:rm -rf ~/*][Google Search]]
1099 This link would show up in your Org-mode document as \"Google Search\"
1100 but really it would remove your entire home directory.
1101 Therefore I *definitely* advise against setting this variable to nil.
1102 Just change it to `y-or-n-p' of you want to confirm with a single key press
1103 rather than having to type \"yes\"."
1104 :group 'org-link-follow
1105 :type '(choice
1106 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1107 (const :tag "with y-or-n (faster)" y-or-n-p)
1108 (const :tag "no confirmation (dangerous)" nil)))
1110 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1111 "Non-nil means, ask for confirmation before executing elisp links.
1112 Elisp links can be dangerous, just thing about a link
1114 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1116 This link would show up in your Org-mode document as \"Google Search\"
1117 but really it would remove your entire home directory.
1118 Therefore I *definitely* advise against setting this variable to nil.
1119 Just change it to `y-or-n-p' of you want to confirm with a single key press
1120 rather than having to type \"yes\"."
1121 :group 'org-link-follow
1122 :type '(choice
1123 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1124 (const :tag "with y-or-n (faster)" y-or-n-p)
1125 (const :tag "no confirmation (dangerous)" nil)))
1127 (defconst org-file-apps-defaults-gnu
1128 '((remote . emacs)
1129 (t . mailcap))
1130 "Default file applications on a UNIX or GNU/Linux system.
1131 See `org-file-apps'.")
1133 (defconst org-file-apps-defaults-macosx
1134 '((remote . emacs)
1135 (t . "open %s")
1136 ("ps" . "gv %s")
1137 ("ps.gz" . "gv %s")
1138 ("eps" . "gv %s")
1139 ("eps.gz" . "gv %s")
1140 ("dvi" . "xdvi %s")
1141 ("fig" . "xfig %s"))
1142 "Default file applications on a MacOS X system.
1143 The system \"open\" is known as a default, but we use X11 applications
1144 for some files for which the OS does not have a good default.
1145 See `org-file-apps'.")
1147 (defconst org-file-apps-defaults-windowsnt
1148 (list
1149 '(remote . emacs)
1150 (cons t
1151 (list (if (featurep 'xemacs)
1152 'mswindows-shell-execute
1153 'w32-shell-execute)
1154 "open" 'file)))
1155 "Default file applications on a Windows NT system.
1156 The system \"open\" is used for most files.
1157 See `org-file-apps'.")
1159 (defcustom org-file-apps
1161 ("txt" . emacs)
1162 ("tex" . emacs)
1163 ("ltx" . emacs)
1164 ("org" . emacs)
1165 ("el" . emacs)
1166 ("bib" . emacs)
1168 "External applications for opening `file:path' items in a document.
1169 Org-mode uses system defaults for different file types, but
1170 you can use this variable to set the application for a given file
1171 extension. The entries in this list are cons cells where the car identifies
1172 files and the cdr the corresponding command. Possible values for the
1173 file identifier are
1174 \"ext\" A string identifying an extension
1175 `directory' Matches a directory
1176 `remote' Matches a remote file, accessible through tramp or efs.
1177 Remote files most likely should be visited through emacs
1178 because external applications cannot handle such paths.
1179 t Default for all remaining files
1181 Possible values for the command are:
1182 `emacs' The file will be visited by the current Emacs process.
1183 `default' Use the default application for this file type.
1184 string A command to be executed by a shell; %s will be replaced
1185 by the path to the file.
1186 sexp A Lisp form which will be evaluated. The file path will
1187 be available in the Lisp variable `file'.
1188 For more examples, see the system specific constants
1189 `org-file-apps-defaults-macosx'
1190 `org-file-apps-defaults-windowsnt'
1191 `org-file-apps-defaults-gnu'."
1192 :group 'org-link-follow
1193 :type '(repeat
1194 (cons (choice :value ""
1195 (string :tag "Extension")
1196 (const :tag "Default for unrecognized files" t)
1197 (const :tag "Remote file" remote)
1198 (const :tag "Links to a directory" directory))
1199 (choice :value ""
1200 (const :tag "Visit with Emacs" emacs)
1201 (const :tag "Use system default" default)
1202 (string :tag "Command")
1203 (sexp :tag "Lisp form")))))
1205 (defcustom org-mhe-search-all-folders nil
1206 "Non-nil means, that the search for the mh-message will be extended to
1207 all folders if the message cannot be found in the folder given in the link.
1208 Searching all folders is very effective with one of the search engines
1209 supported by MH-E, but will be slow with pick."
1210 :group 'org-link-follow
1211 :type 'boolean)
1213 (defgroup org-remember nil
1214 "Options concerning interaction with remember.el."
1215 :tag "Org Remember"
1216 :group 'org)
1218 (defcustom org-directory "~/org"
1219 "Directory with org files.
1220 This directory will be used as default to prompt for org files.
1221 Used by the hooks for remember.el."
1222 :group 'org-remember
1223 :type 'directory)
1225 (defcustom org-default-notes-file "~/.notes"
1226 "Default target for storing notes.
1227 Used by the hooks for remember.el. This can be a string, or nil to mean
1228 the value of `remember-data-file'."
1229 :group 'org-remember
1230 :type '(choice
1231 (const :tag "Default from remember-data-file" nil)
1232 file))
1234 (defcustom org-remember-templates nil
1235 "Templates for the creation of remember buffers.
1236 When nil, just let remember make the buffer.
1237 When not nil, this is a list of 3-element lists. In each entry, the first
1238 element is a character, a unique key to select this template.
1239 The second element is the template. The third element is optional and can
1240 specify a destination file for remember items created with this template.
1241 The default file is given by `org-default-notes-file'.
1243 The template specifies the structure of the remember buffer. It should have
1244 a first line starting with a star, to act as the org-mode headline.
1245 Furthermore, the following %-escapes will be replaced with content:
1246 %t time stamp, date only
1247 %T time stamp with date and time
1248 %u inactive time stamp, date only
1249 %U inactive time stamp with date and time
1250 %n user name
1251 %a annotation, normally the link created with org-store-link
1252 %i initial content, the region when remember is called with C-u.
1253 If %i is indented, the entire inserted text will be indented as well.
1254 %? This will be removed, and the cursor placed at this position."
1255 :group 'org-remember
1256 :type '(repeat :tag "enabled"
1257 (list :value (?a "\n" nil)
1258 (character :tag "Selection Key")
1259 (string :tag "Template")
1260 (file :tag "Destination file (optional)"))))
1262 (defcustom org-reverse-note-order nil
1263 "Non-nil means, store new notes at the beginning of a file or entry.
1264 When nil, new notes will be filed to the end of a file or entry."
1265 :group 'org-remember
1266 :type '(choice
1267 (const :tag "Reverse always" t)
1268 (const :tag "Reverse never" nil)
1269 (repeat :tag "By file name regexp"
1270 (cons regexp boolean))))
1272 (defgroup org-todo nil
1273 "Options concerning TODO items in Org-mode."
1274 :tag "Org TODO"
1275 :group 'org)
1277 (defcustom org-todo-keywords '("TODO" "DONE")
1278 "List of TODO entry keywords.
1279 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1280 considered to mean that the entry is \"done\". All the other mean that
1281 action is required, and will make the entry show up in todo lists, diaries
1282 etc.
1283 The command \\[org-todo] cycles an entry through these states, and an
1284 additional state where no keyword is present. For details about this
1285 cycling, see also the variable `org-todo-interpretation'
1286 Changes become only effective after restarting Emacs."
1287 :group 'org-todo
1288 :group 'org-keywords
1289 :type '(repeat (string :tag "Keyword")))
1291 (defcustom org-todo-interpretation 'sequence
1292 "Controls how TODO keywords are interpreted.
1293 This variable is only relevant if `org-todo-keywords' contains more than two
1294 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1296 When `sequence', \\[org-todo] will always switch to the next state in the
1297 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1298 to state when executed several times in direct succession. Otherwise, it
1299 switches directly to DONE from any state.
1300 See the manual for more information."
1301 :group 'org-todo
1302 :group 'org-keywords
1303 :type '(choice (const sequence)
1304 (const type)))
1306 (defcustom org-after-todo-state-change-hook nil
1307 "Hook which is run after the state of a TODO item was changed.
1308 The new state (a string with a TODO keyword, or nil) is available in the
1309 Lisp variable `state'."
1310 :group 'org-todo
1311 :type 'hook)
1313 (defcustom org-log-done nil
1314 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1315 When the state of an entry is changed from nothing to TODO, remove a previous
1316 closing date.
1318 This can also be a list of symbols indicating under which conditions
1319 the time stamp recording the action should be annotated with a short note.
1320 Valid members of this list are
1322 done Offer to record a note when marking entries done
1323 clock-out Offer to record a note when clocking out of an item.
1325 A separate window will then pop up and allow you to type a note.
1326 After finishing with C-c C-c, the note will be added directly after the
1327 timestamp, as a plain list item. See also the variable
1328 `org-log-note-headings'.
1330 Logging can also be configured on a per-file basis by adding one of
1331 the following lines anywhere in the buffer:
1333 #+STARTUP: logging
1334 #+STARTUP: nologging"
1335 ;; FIXME: in-buffer words for notes???????
1336 :group 'org-todo
1337 :type '(choice
1338 (const :tag "off" nil)
1339 (const :tag "on" t)
1340 (set :tag "on, with notes" :greedy t :value (done)
1341 (const done) (const clock-out))))
1343 (defcustom org-log-note-headings '((done . "CLOSING NOTE") (clock-out . ""))
1344 "Headings for notes added when clocking out or closing TODO items.
1345 The value is an alist, with the car being a sympol indicating the note
1346 context, and the cdr is the heading to be used. The heading may also be the
1347 empty string."
1348 :group 'org-todo
1349 :type '(list :greedy t
1350 (cons (const :tag "Heading when closing an item" done) string)
1351 (cons (const :tag "Heading when clocking out" clock-out) string)))
1353 (defgroup org-priorities nil
1354 "Priorities in Org-mode."
1355 :tag "Org Priorities"
1356 :group 'org-todo)
1358 (defcustom org-default-priority ?B
1359 "The default priority of TODO items.
1360 This is the priority an item get if no explicit priority is given."
1361 :group 'org-priorities
1362 :type 'character)
1364 (defcustom org-lowest-priority ?C
1365 "The lowest priority of TODO items. A character like ?A, ?B etc."
1366 :group 'org-priorities
1367 :type 'character)
1369 (defgroup org-time nil
1370 "Options concerning time stamps and deadlines in Org-mode."
1371 :tag "Org Time"
1372 :group 'org)
1374 (defcustom org-insert-labeled-timestamps-at-point nil
1375 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1376 When nil, these labeled time stamps are forces into the second line of an
1377 entry, just after the headline. When scheduling from the global TODO list,
1378 the time stamp will always be forced into the second line."
1379 :group 'org-time
1380 :type 'boolean)
1382 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1383 "Formats for `format-time-string' which are used for time stamps.
1384 It is not recommended to change this constant.")
1386 (defcustom org-time-stamp-rounding-minutes 0
1387 "Number of minutes to round time stamps to upon insertion.
1388 When zero, insert the time unmodified. Useful rounding numbers
1389 should be factors of 60, so for example 5, 10, 15.
1390 When this is not zero, you can still force an exact time-stamp by using
1391 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1392 :group 'org-time
1393 :type 'integer)
1395 (defcustom org-deadline-warning-days 30
1396 "No. of days before expiration during which a deadline becomes active.
1397 This variable governs the display in the org file."
1398 :group 'org-time
1399 :type 'number)
1401 (defcustom org-popup-calendar-for-date-prompt t
1402 "Non-nil means, pop up a calendar when prompting for a date.
1403 In the calendar, the date can be selected with mouse-1. However, the
1404 minibuffer will also be active, and you can simply enter the date as well.
1405 When nil, only the minibuffer will be available."
1406 :group 'org-time
1407 :type 'boolean)
1409 (defcustom org-calendar-follow-timestamp-change t
1410 "Non-nil means, make the calendar window follow timestamp changes.
1411 When a timestamp is modified and the calendar window is visible, it will be
1412 moved to the new date."
1413 :group 'org-time
1414 :type 'boolean)
1416 (defgroup org-tags nil
1417 "Options concerning tags in Org-mode."
1418 :tag "Org Tags"
1419 :group 'org)
1421 (defcustom org-tag-alist nil
1422 "List of tags allowed in Org-mode files.
1423 When this list is nil, Org-mode will base TAG input on what is already in the
1424 buffer.
1425 The value of this variable is an alist, the car may be (and should) be a
1426 character that is used to select that tag through the fast-tag-selection
1427 interface. See the manual for details."
1428 :group 'org-tags
1429 :type '(repeat
1430 (choice
1431 (cons (string :tag "Tag name")
1432 (character :tag "Access char"))
1433 (const :tag "Start radio group" (:startgroup))
1434 (const :tag "End radio group" (:endgroup)))))
1436 (defcustom org-use-fast-tag-selection 'auto
1437 "Non-nil means, use fast tag selection scheme.
1438 This is a special interface to select and deselect tags with single keys.
1439 When nil, fast selection is never used.
1440 When the symbol `auto', fast selection is used if and only if selection
1441 characters for tags have been configured, either through the variable
1442 `org-tag-alist' or through a #+TAGS line in the buffer.
1443 When t, fast selection is always used and selection keys are assigned
1444 automatically if necessary."
1445 :group 'org-tags
1446 :type '(choice
1447 (const :tag "Always" t)
1448 (const :tag "Never" nil)
1449 (const :tag "When selection characters are configured" 'auto)))
1451 (defcustom org-tags-column 48
1452 "The column to which tags should be indented in a headline.
1453 If this number is positive, it specifies the column. If it is negative,
1454 it means that the tags should be flushright to that column. For example,
1455 -79 works well for a normal 80 character screen."
1456 :group 'org-tags
1457 :type 'integer)
1459 (defcustom org-auto-align-tags t
1460 "Non-nil means, realign tags after pro/demotion of TODO state change.
1461 These operations change the length of a headline and therefore shift
1462 the tags around. With this options turned on, after each such operation
1463 the tags are again aligned to `org-tags-column'."
1464 :group 'org-tags
1465 :type 'boolean)
1467 (defcustom org-use-tag-inheritance t
1468 "Non-nil means, tags in levels apply also for sublevels.
1469 When nil, only the tags directly given in a specific line apply there.
1470 If you turn off this option, you very likely want to turn on the
1471 companion option `org-tags-match-list-sublevels'."
1472 :group 'org-tags
1473 :type 'boolean)
1475 (defcustom org-tags-match-list-sublevels nil
1476 "Non-nil means list also sublevels of headlines matching tag search.
1477 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1478 the sublevels of a headline matching a tag search often also match
1479 the same search. Listing all of them can create very long lists.
1480 Setting this variable to nil causes subtrees of a match to be skipped.
1481 This option is off by default, because inheritance in on. If you turn
1482 inheritance off, you very likely want to turn this option on.
1484 As a special case, if the tag search is restricted to TODO items, the
1485 value of this variable is ignored and sublevels are always checked, to
1486 make sure all corresponding TODO items find their way into the list."
1487 :group 'org-tags
1488 :type 'boolean)
1490 (defvar org-tags-history nil
1491 "History of minibuffer reads for tags.")
1492 (defvar org-last-tags-completion-table nil
1493 "The last used completion table for tags.")
1495 (defgroup org-agenda nil
1496 "Options concerning agenda display Org-mode."
1497 :tag "Org Agenda"
1498 :group 'org)
1500 (defvar org-category nil
1501 "Variable used by org files to set a category for agenda display.
1502 Such files should use a file variable to set it, for example
1504 -*- mode: org; org-category: \"ELisp\"
1506 or contain a special line
1508 #+CATEGORY: ELisp
1510 If the file does not specify a category, then file's base name
1511 is used instead.")
1512 (make-variable-buffer-local 'org-category)
1514 (defcustom org-agenda-files nil
1515 "The files to be used for agenda display.
1516 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1517 \\[org-remove-file]. You can also use customize to edit the list.
1519 If the value of the variable is not a list but a single file name, then
1520 the list of agenda files is actually stored and maintained in that file, one
1521 agenda file per line."
1522 :group 'org-agenda
1523 :type '(choice
1524 (repeat :tag "List of files" file)
1525 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1527 (defcustom org-agenda-custom-commands ;'(("w" todo "WAITING"))
1528 '(("w" todo "WAITING" ((aaa 1) (bbb 2))))
1529 "Custom commands for the agenda.
1530 These commands will be offered on the splash screen displayed by the
1531 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
1533 (key type match options)
1535 key The key (a single char as a string) to be associated with the command.
1536 type The command type, any of the following symbols:
1537 todo Entries with a specific TODO keyword, in all agenda files.
1538 tags Tags match in all agenda files.
1539 tags-todo Tags match in all agenda files, TODO entries only.
1540 todo-tree Sparse tree of specific TODO keyword in *current* file.
1541 tags-tree Sparse tree with all tags matches in *current* file.
1542 occur-tree Occur sparse tree for *current* file.
1543 match What to search for:
1544 - a single keyword for TODO keyword searches
1545 - a tags match expression for tags searches
1546 - a regular expression for occur searches
1547 options A list of option setttings, similar to that in a let form, so like
1548 this: ((opt1 val1) (opt2 val2) ...)
1550 You can also define a set of commands, to create a composite agenda buffer.
1551 In this case, an entry looks like this:
1553 (key desc (cmd1 cmd2 ...) general-options)
1555 where
1557 desc A description string to be displayed in the dispatcher menu.
1558 cmd An agenda command, similar to the above. However, tree commands
1559 are no allowed, but instead you can get agenda and global todo list.
1560 So valid commands for a set are:
1561 (agenda)
1562 (alltodo)
1563 (todo \"match\" options)
1564 (tags \"match\" options )
1565 (tags-todo \"match\" options)
1567 Each command can carry a list of options, and another set of options can be
1568 given for the whole set of commands. Individual command options take
1569 precedence over the general options."
1570 :group 'org-agenda
1571 :type '(repeat
1572 (choice
1573 (list :tag "Single command"
1574 (string :tag "Key")
1575 (choice
1576 (const :tag "Tags search (all agenda files)" tags)
1577 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
1578 (const :tag "TODO keyword search (all agenda files)" todo)
1579 (const :tag "Tags sparse tree (current buffer)" tags-tree)
1580 (const :tag "TODO keyword tree (current buffer)" todo-tree)
1581 (const :tag "Occur tree (current buffer)" occur-tree))
1582 (string :tag "Match")
1583 (repeat :tag "Local options"
1584 (list (variable :tag "Option") (sexp :tag "Value"))))
1585 (list :tag "Command series, all agenda files"
1586 (string :tag "Key")
1587 (string :tag "Description")
1588 (repeat
1589 (choice
1590 (const :tag "Agenda" (agenda))
1591 (const :tag "TODO list" (alltodo))
1592 (list :tag "Tags search"
1593 (const :format "" tags)
1594 (string :tag "Match")
1595 (repeat :tag "Local options"
1596 (list (variable :tag "Option")
1597 (sexp :tag "Value"))))
1599 (list :tag "Tags search, TODO entries only"
1600 (const :format "" tags-todo)
1601 (string :tag "Match")
1602 (repeat :tag "Local options"
1603 (list (variable :tag "Option")
1604 (sexp :tag "Value"))))
1606 (list :tag "TODO keyword search"
1607 (const :format "" todo)
1608 (string :tag "Match")
1609 (repeat :tag "Local options"
1610 (list (variable :tag "Option")
1611 (sexp :tag "Value"))))))
1612 (repeat :tag "General options"
1613 (list (variable :tag "Option")
1614 (sexp :tag "Value")))))))
1616 (defcustom org-agenda-todo-list-sublevels t
1617 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1618 When nil, the sublevels of a TODO entry are not checked, resulting in
1619 potentially much shorter TODO lists."
1620 :group 'org-agenda
1621 :group 'org-todo
1622 :type 'boolean)
1624 (defcustom org-agenda-todo-ignore-scheduled nil
1625 "Non-nil means, don't show scheduled entries in the global todo list.
1626 The idea behind this is that by scheduling it, you have already taken care
1627 of this item."
1628 :group 'org-agenda
1629 :group 'org-todo
1630 :type 'boolean)
1632 (defcustom org-timeline-show-empty-dates 3
1633 "Non-nil means, `org-timeline' also shows dates without an entry.
1634 When nil, only the days which actually have entries are shown.
1635 When t, all days between the first and the last date are shown.
1636 When an integer, show also empty dates, but if there is a gap of more than
1637 N days, just insert a special line indicating the size of the gap."
1638 :group 'org-agenda
1639 :type '(choice
1640 (const :tag "None" nil)
1641 (const :tag "All" t)
1642 (number :tag "at most")))
1644 (defcustom org-agenda-include-all-todo nil
1645 "Set means weekly/daily agenda will always contain all TODO entries.
1646 The TODO entries will be listed at the top of the agenda, before
1647 the entries for specific days."
1648 :group 'org-agenda
1649 :type 'boolean)
1651 (defcustom org-agenda-include-diary nil
1652 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1653 :group 'org-agenda
1654 :type 'boolean)
1656 (defcustom org-calendar-to-agenda-key [?c]
1657 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1658 The command `org-calendar-goto-agenda' will be bound to this key. The
1659 default is the character `c' because then `c' can be used to switch back and
1660 forth between agenda and calendar."
1661 :group 'org-agenda
1662 :type 'sexp)
1664 (defgroup org-agenda-setup nil
1665 "Options concerning setting up the Agenda window in Org Mode."
1666 :tag "Org Agenda Window Setup"
1667 :group 'org-agenda)
1669 (defcustom org-agenda-window-setup 'reorganize-frame
1670 "How the agenda buffer should be displayed.
1671 Possible values for this option are:
1673 current-window Show agenda in the current window, keeping all other windows.
1674 other-frame Use `switch-to-buffer-other-frame' to display agenda.
1675 other-window Use `switch-to-buffer-other-window' to display agenda.
1676 reorganize-frame Show only two windows on the current frame, the current
1677 window and the agenda. Also, if the option
1678 `org-fit-agenda-window' is set, resize the agenda window to
1679 try to as much as possible of the buffer content.
1680 See also the variable `org-agenda-restore-windows-after-quit'."
1681 :group 'org-agenda-setup
1682 :type '(choice
1683 (const current-window)
1684 (const other-frame)
1685 (const other-window)
1686 (const reorganize-frame)))
1688 (defcustom org-agenda-restore-windows-after-quit nil
1689 "Non-nil means, restore window configuration open exiting agenda.
1690 Before the window configuration is changed for displaying the agenda,
1691 the current status is recorded. When the agenda is exited with
1692 `q' or `x' and this option is set, the old state is restored. If
1693 `org-agenda-window-setup' is `other-frame', the value of this
1694 option will be ignored.."
1695 :group 'org-agenda-setup
1696 :type 'boolean)
1698 ;; FIXME: I think this variable could be removed.
1699 (defcustom org-select-agenda-window t
1700 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1701 When nil, cursor will remain in the current window."
1702 :group 'org-agenda-setup
1703 :type 'boolean)
1705 ;; FIXME: I think this variable could be removed.
1706 (defcustom org-fit-agenda-window t
1707 "Non-nil means, change window size of agenda to fit content.
1708 This is only effective if `org-agenda-window-setup' is `reorganize-frame'."
1709 :group 'org-agenda-setup
1710 :type 'boolean)
1712 (defcustom org-finalize-agenda-hook nil
1713 "Hook run just before displaying an agenda buffer."
1714 :group 'org-agenda-setup
1715 :type 'hook)
1717 (defcustom org-agenda-mouse-1-follows-link nil
1718 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1719 A longer mouse click will still set point. Does not wortk on XEmacs.
1720 Needs to be set before org.el is loaded."
1721 :group 'org-agenda-setup
1722 :type 'boolean)
1724 (defcustom org-agenda-start-with-follow-mode nil
1725 "The initial value of follwo-mode in a newly created agenda window."
1726 :group 'org-agenda-setup
1727 :type 'boolean)
1729 (defgroup org-agenda-display nil
1730 "Options concerning what to display initially in Agenda."
1731 :tag "Org Agenda Display"
1732 :group 'org-agenda)
1734 (defcustom org-agenda-show-all-dates t
1735 "Non-nil means, `org-agenda' shows every day in the selected range.
1736 When nil, only the days which actually have entries are shown."
1737 :group 'org-agenda-display
1738 :type 'boolean)
1740 (defcustom org-agenda-start-on-weekday 1
1741 "Non-nil means, start the overview always on the specified weekday.
1742 0 denotes Sunday, 1 denotes Monday etc.
1743 When nil, always start on the current day."
1744 :group 'org-agenda-display
1745 :type '(choice (const :tag "Today" nil)
1746 (number :tag "Weekday No.")))
1748 (defcustom org-agenda-ndays 7
1749 "Number of days to include in overview display.
1750 Should be 1 or 7."
1751 :group 'org-agenda-display
1752 :type 'number)
1754 (defcustom org-agenda-use-time-grid t
1755 "Non-nil means, show a time grid in the agenda schedule.
1756 A time grid is a set of lines for specific times (like every two hours between
1757 8:00 and 20:00). The items scheduled for a day at specific times are
1758 sorted in between these lines.
1759 For details about when the grid will be shown, and what it will look like, see
1760 the variable `org-agenda-time-grid'."
1761 :group 'org-agenda-display
1762 :type 'boolean)
1764 (defcustom org-agenda-time-grid
1765 '((daily today require-timed)
1766 "----------------"
1767 (800 1000 1200 1400 1600 1800 2000))
1769 "The settings for time grid for agenda display.
1770 This is a list of three items. The first item is again a list. It contains
1771 symbols specifying conditions when the grid should be displayed:
1773 daily if the agenda shows a single day
1774 weekly if the agenda shows an entire week
1775 today show grid on current date, independent of daily/weekly display
1776 require-timed show grid only if at least one item has a time specification
1778 The second item is a string which will be places behing the grid time.
1780 The third item is a list of integers, indicating the times that should have
1781 a grid line."
1782 :group 'org-agenda-display
1783 :type
1784 '(list
1785 (set :greedy t :tag "Grid Display Options"
1786 (const :tag "Show grid in single day agenda display" daily)
1787 (const :tag "Show grid in weekly agenda display" weekly)
1788 (const :tag "Always show grid for today" today)
1789 (const :tag "Show grid only if any timed entries are present"
1790 require-timed)
1791 (const :tag "Skip grid times already present in an entry"
1792 remove-match))
1793 (string :tag "Grid String")
1794 (repeat :tag "Grid Times" (integer :tag "Time"))))
1796 (let ((sorting-choice
1797 '(choice
1798 (const time-up) (const time-down)
1799 (const category-keep) (const category-up) (const category-down)
1800 (const tag-down) (const tag-up)
1801 (const priority-up) (const priority-down))))
1803 (defcustom org-agenda-sorting-strategy
1804 '((agenda time-up category-keep priority-down)
1805 (todo category-keep priority-down)
1806 (tags category-keep))
1807 "Sorting structure for the agenda items of a single day.
1808 This is a list of symbols which will be used in sequence to determine
1809 if an entry should be listed before another entry. The following
1810 symbols are recognized:
1812 time-up Put entries with time-of-day indications first, early first
1813 time-down Put entries with time-of-day indications first, late first
1814 category-keep Keep the default order of categories, corresponding to the
1815 sequence in `org-agenda-files'.
1816 category-up Sort alphabetically by category, A-Z.
1817 category-down Sort alphabetically by category, Z-A.
1818 tag-up Sort alphabetically by last tag, A-Z.
1819 tag-down Sort alphabetically by last tag, Z-A.
1820 priority-up Sort numerically by priority, high priority last.
1821 priority-down Sort numerically by priority, high priority first.
1823 The different possibilities will be tried in sequence, and testing stops
1824 if one comparison returns a \"not-equal\". For example, the default
1825 '(time-up category-keep priority-down)
1826 means: Pull out all entries having a specified time of day and sort them,
1827 in order to make a time schedule for the current day the first thing in the
1828 agenda listing for the day. Of the entries without a time indication, keep
1829 the grouped in categories, don't sort the categories, but keep them in
1830 the sequence given in `org-agenda-files'. Within each category sort by
1831 priority.
1833 Leaving out `category-keep' would mean that items will be sorted across
1834 categories by priority."
1835 :group 'org-agenda-display
1836 :type `(choice
1837 (repeat :tag "General" ,sorting-choice)
1838 (list :tag "Individually"
1839 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
1840 (repeat ,sorting-choice))
1841 (cons (const :tag "Strategy for TODO lists" todo)
1842 (repeat ,sorting-choice))
1843 (cons (const :tag "Strategy for Tags matches" tags)
1844 (repeat ,sorting-choice))))))
1846 (defcustom org-sort-agenda-notime-is-late t
1847 "Non-nil means, items without time are considered late.
1848 This is only relevant for sorting. When t, items which have no explicit
1849 time like 15:30 will be considered as 99:01, i.e. later than any items which
1850 do have a time. When nil, the default time is before 0:00. You can use this
1851 option to decide if the schedule for today should come before or after timeless
1852 agenda entries."
1853 :group 'org-agenda-display
1854 :type 'boolean)
1856 (defgroup org-agenda-prefix nil
1857 "Options concerning the entry prefix in the Org-mode agenda display."
1858 :tag "Org Agenda Prefix"
1859 :group 'org-agenda)
1861 (defcustom org-agenda-prefix-format
1862 '((agenda . " %-12:c%?-12t% s")
1863 (timeline . " % s")
1864 (todo . " %-12:c")
1865 (tags . " %-12:c"))
1866 "Format specifications for the prefix of items in the agenda views.
1867 An alist with four entries, for the different agenda types. The keys to the
1868 sublists are `agenda', `timeline', `todo', and `tags'. The values
1869 are format strings.
1870 This format works similar to a printf format, with the following meaning:
1872 %c the category of the item, \"Diary\" for entries from the diary, or
1873 as given by the CATEGORY keyword or derived from the file name.
1874 %T the *last* tag of the item. Last because inherited tags come
1875 first in the list.
1876 %t the time-of-day specification if one applies to the entry, in the
1877 format HH:MM
1878 %s Scheduling/Deadline information, a short string
1880 All specifiers work basically like the standard `%s' of printf, but may
1881 contain two additional characters: A question mark just after the `%' and
1882 a whitespace/punctuation character just before the final letter.
1884 If the first character after `%' is a question mark, the entire field
1885 will only be included if the corresponding value applies to the
1886 current entry. This is useful for fields which should have fixed
1887 width when present, but zero width when absent. For example,
1888 \"%?-12t\" will result in a 12 character time field if a time of the
1889 day is specified, but will completely disappear in entries which do
1890 not contain a time.
1892 If there is punctuation or whitespace character just before the final
1893 format letter, this character will be appended to the field value if
1894 the value is not empty. For example, the format \"%-12:c\" leads to
1895 \"Diary: \" if the category is \"Diary\". If the category were be
1896 empty, no additional colon would be interted.
1898 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1899 - Indent the line with two space characters
1900 - Give the category in a 12 chars wide field, padded with whitespace on
1901 the right (because of `-'). Append a colon if there is a category
1902 (because of `:').
1903 - If there is a time-of-day, put it into a 12 chars wide field. If no
1904 time, don't put in an empty field, just skip it (because of '?').
1905 - Finally, put the scheduling information and append a whitespace.
1907 As another example, if you don't want the time-of-day of entries in
1908 the prefix, you could use:
1910 (setq org-agenda-prefix-format \" %-11:c% s\")
1912 See also the variables `org-agenda-remove-times-when-in-prefix' and
1913 `org-agenda-remove-tags-when-in-prefix'."
1914 :type '(choice
1915 (string :tag "General format")
1916 (list :greedy t :tag "View dependent"
1917 (cons (const agenda) (string :tag "Format"))
1918 (cons (const timeline) (string :tag "Format"))
1919 (cons (const todo) (string :tag "Format"))
1920 (cons (const tags) (string :tag "Format"))))
1921 :group 'org-agenda-prefix)
1923 (defvar org-prefix-format-compiled nil
1924 "The compiled version of the most recently used prefix format.
1925 See the variable `org-agenda-prefix-format'.")
1927 (defcustom org-agenda-remove-times-when-in-prefix t
1928 "Non-nil means, remove duplicate time specifications in agenda items.
1929 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1930 time-of-day specification in a headline or diary entry is extracted and
1931 placed into the prefix. If this option is non-nil, the original specification
1932 \(a timestamp or -range, or just a plain time(range) specification like
1933 11:30-4pm) will be removed for agenda display. This makes the agenda less
1934 cluttered.
1935 The option can be t or nil. It may also be the symbol `beg', indicating
1936 that the time should only be removed what it is located at the beginning of
1937 the headline/diary entry."
1938 :group 'org-agenda-prefix
1939 :type '(choice
1940 (const :tag "Always" t)
1941 (const :tag "Never" nil)
1942 (const :tag "When at beginning of entry" beg)))
1944 (defcustom org-agenda-remove-tags-when-in-prefix nil
1945 "Non-nil means, remove the tags from the headline copy in the agenda.
1946 When this is the symbol `prefix', only remove tags when
1947 `org-agenda-prefix-format' contains a `%T' specifier."
1948 :group 'org-agenda-prefix
1949 :type '(choice
1950 (const :tag "Always" t)
1951 (const :tag "Never" nil)
1952 (const :tag "When prefix format contains %T" prefix)))
1954 (defcustom org-agenda-align-tags-to-column 65
1955 "Shift tags in agenda items to this column."
1956 :group 'org-agenda-prefix
1957 :type 'integer)
1959 (defgroup org-latex nil
1960 "Options for embedding LaTeX code into Org-mode"
1961 :tag "Org LaTeX"
1962 :group 'org)
1964 (defcustom org-format-latex-options
1965 '(:foreground "Black" :background "Transparent" :scale 1.0
1966 :matchers ("begin" "$" "$$" "\\(" "\\["))
1967 "Options for creating images from LaTeX fragments.
1968 This is a property list with the following properties:
1969 :foreground the foreground color, for example \"Black\".
1970 :background the background color, or \"Transparent\".
1971 :scale a scaling factor for the size of the images
1972 :matchers a list indicating which matchers should be used to
1973 find LaTeX fragments. Valid members of this list are:
1974 \"begin\" find environments
1975 \"$\" find math expressions surrounded by $...$
1976 \"$$\" find math expressions surrounded by $$....$$
1977 \"\\(\" find math expressions surrounded by \\(...\\)
1978 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1979 :group 'org-latex
1980 :type 'plist)
1982 (defgroup org-export nil
1983 "Options for exporting org-listings."
1984 :tag "Org Export"
1985 :group 'org)
1987 (defgroup org-export-general nil
1988 "General options for exporting Org-mode files."
1989 :tag "Org Export General"
1990 :group 'org-export)
1992 (defcustom org-export-publishing-directory "."
1993 "Path to the location where exported files should be located.
1994 This path may be relative to the directory where the Org-mode file lives.
1995 The default is to put them into the same directory as the Org-mode file.
1996 The variable may also be an alist with export types `:html', `:ascii',
1997 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
1998 is relative, it is interpreted relative to the directory where the exported
1999 Org-mode files lives."
2000 :group 'org-export-general
2001 :type '(choice
2002 (directory)
2003 (repeat
2004 (cons
2005 (choice :tag "Type"
2006 (const :html) (const :ascii) (const :ical) (const :xoxo))
2007 (directory)))))
2009 (defcustom org-export-language-setup
2010 '(("en" "Author" "Date" "Table of Contents")
2011 ("cs" "Autor" "Datum" "Obsah")
2012 ("da" "Ophavsmand" "Dato" "Indhold")
2013 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2014 ("es" "Autor" "Fecha" "\xccndice")
2015 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
2016 ("it" "Autore" "Data" "Indice")
2017 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2018 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2019 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2020 "Terms used in export text, translated to different languages.
2021 Use the variable `org-export-default-language' to set the language,
2022 or use the +OPTION lines for a per-file setting."
2023 :group 'org-export-general
2024 :type '(repeat
2025 (list
2026 (string :tag "HTML language tag")
2027 (string :tag "Author")
2028 (string :tag "Date")
2029 (string :tag "Table of Contents"))))
2031 (defcustom org-export-default-language "en"
2032 "The default language of HTML export, as a string.
2033 This should have an association in `org-export-language-setup'."
2034 :group 'org-export-general
2035 :type 'string)
2037 (defcustom org-export-headline-levels 3
2038 "The last level which is still exported as a headline.
2039 Inferior levels will produce itemize lists when exported.
2040 Note that a numeric prefix argument to an exporter function overrides
2041 this setting.
2043 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2044 :group 'org-export-general
2045 :type 'number)
2047 (defcustom org-export-with-section-numbers t
2048 "Non-nil means, add section numbers to headlines when exporting.
2050 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2051 :group 'org-export-general
2052 :type 'boolean)
2054 (defcustom org-export-with-toc t
2055 "Non-nil means, create a table of contents in exported files.
2056 The TOC contains headlines with levels up to`org-export-headline-levels'.
2058 Headlines which contain any TODO items will be marked with \"(*)\" in
2059 ASCII export, and with red color in HTML output.
2061 In HTML output, the TOC will be clickable.
2063 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
2064 :group 'org-export-general
2065 :type 'boolean)
2067 (defcustom org-export-mark-todo-in-toc nil
2068 "Non-nil means, mark TOC lines that contain any open TODO items."
2069 :group 'org-export-general
2070 :type 'boolean)
2072 (defcustom org-export-preserve-breaks nil
2073 "Non-nil means, preserve all line breaks when exporting.
2074 Normally, in HTML output paragraphs will be reformatted. In ASCII
2075 export, line breaks will always be preserved, regardless of this variable.
2077 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
2078 :group 'org-export-general
2079 :type 'boolean)
2081 (defcustom org-export-with-archived-trees 'headline
2082 "Whether subtrees with the ARCHIVE tag should be exported.
2083 This can have three different values
2084 nil Do not export, pretend this tree is not present
2085 t Do export the entire tree
2086 headline Only export the headline, but skip the tree below it."
2087 :group 'org-export-general
2088 :group 'org-archive
2089 :type '(choice
2090 (const :tag "not at all" nil)
2091 (const :tag "headline only" 'headline)
2092 (const :tag "entirely" t)))
2094 (defcustom org-export-with-timestamps t
2095 "Nil means, do not export time stamps and associated keywords."
2096 :group 'org-export-general
2097 :type 'boolean)
2099 (defcustom org-export-remove-timestamps-from-toc t
2100 "Nil means, remove timestamps from the table of contents entries."
2101 :group 'org-export-general
2102 :type 'boolean)
2104 (defcustom org-export-with-tags 'not-in-toc
2105 "Nil means, do not export tags, just remove them from headlines.
2106 If this is the sysmbol `not-in-toc', tags will be removed from table of
2107 contents entries, but still be shown in the headlines of the document."
2108 :group 'org-export-general
2109 :type '(choice
2110 (const :tag "Off" nil)
2111 (const :tag "Not in TOC" not-in-toc)
2112 (const :tag "On" t)))
2114 (defgroup org-export-translation nil
2115 "Options for translating special ascii sequences for the export backends."
2116 :tag "Org Export Translation"
2117 :group 'org-export)
2119 (defcustom org-export-with-emphasize t
2120 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
2121 If the export target supports emphasizing text, the word will be
2122 typeset in bold, italic, or underlined, respectively. Works only for
2123 single words, but you can say: I *really* *mean* *this*.
2124 Not all export backends support this.
2126 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
2127 :group 'org-export-translation
2128 :type 'boolean)
2130 (defcustom org-export-with-sub-superscripts t
2131 "Non-nil means, interpret \"_\" and \"^\" for export.
2132 When this option is turned on, you can use TeX-like syntax for sub- and
2133 superscripts. Several characters after \"_\" or \"^\" will be
2134 considered as a single item - so grouping with {} is normally not
2135 needed. For example, the following things will be parsed as single
2136 sub- or superscripts.
2138 10^24 or 10^tau several digits will be considered 1 item.
2139 10^-12 or 10^-tau a leading sign with digits or a word
2140 x^2-y^3 will be read as x^2 - y^3, because items are
2141 terminated by almost any nonword/nondigit char.
2142 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
2144 Still, ambiguity is possible - so when in doubt use {} to enclose the
2145 sub/superscript.
2146 Not all export backends support this, but HTML does.
2148 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
2149 :group 'org-export-translation
2150 :type 'boolean)
2152 (defcustom org-export-with-TeX-macros t
2153 "Non-nil means, interpret simple TeX-like macros when exporting.
2154 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
2155 No only real TeX macros will work here, but the standard HTML entities
2156 for math can be used as macro names as well. For a list of supported
2157 names in HTML export, see the constant `org-html-entities'.
2158 Not all export backends support this.
2160 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
2161 :group 'org-export-translation
2162 :group 'org-latex
2163 :type 'boolean)
2165 (defcustom org-export-with-LaTeX-fragments nil
2166 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
2167 When set, the exporter will find LaTeX environments if the \\begin line is
2168 the first non-white thing on a line. It will also find the math delimiters
2169 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
2170 display math.
2172 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
2173 :group 'org-export-translation
2174 :group 'org-latex
2175 :type 'boolean)
2177 (defcustom org-export-with-fixed-width t
2178 "Non-nil means, lines starting with \":\" will be in fixed width font.
2179 This can be used to have pre-formatted text, fragments of code etc. For
2180 example:
2181 : ;; Some Lisp examples
2182 : (while (defc cnt)
2183 : (ding))
2184 will be looking just like this in also HTML. See also the QUOTE keyword.
2185 Not all export backends support this.
2187 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2188 :group 'org-export-translation
2189 :type 'boolean)
2191 (defcustom org-match-sexp-depth 3
2192 "Number of stacked braces for sub/superscript matching.
2193 This has to be set before loading org.el to be effective."
2194 :group 'org-export-translation
2195 :type 'integer)
2197 (defgroup org-export-tables nil
2198 "Options for exporting tables in Org-mode."
2199 :tag "Org Export Tables"
2200 :group 'org-export)
2202 (defcustom org-export-with-tables t
2203 "If non-nil, lines starting with \"|\" define a table.
2204 For example:
2206 | Name | Address | Birthday |
2207 |-------------+----------+-----------|
2208 | Arthur Dent | England | 29.2.2100 |
2210 Not all export backends support this.
2212 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2213 :group 'org-export-tables
2214 :type 'boolean)
2216 (defcustom org-export-highlight-first-table-line t
2217 "Non-nil means, highlight the first table line.
2218 In HTML export, this means use <th> instead of <td>.
2219 In tables created with table.el, this applies to the first table line.
2220 In Org-mode tables, all lines before the first horizontal separator
2221 line will be formatted with <th> tags."
2222 :group 'org-export-tables
2223 :type 'boolean)
2225 (defcustom org-export-table-remove-special-lines t
2226 "Remove special lines and marking characters in calculating tables.
2227 This removes the special marking character column from tables that are set
2228 up for spreadsheet calculations. It also removes the entire lines
2229 marked with `!', `_', or `^'. The lines with `$' are kept, because
2230 the values of constants may be useful to have."
2231 :group 'org-export-tables
2232 :type 'boolean)
2234 (defcustom org-export-prefer-native-exporter-for-tables nil
2235 "Non-nil means, always export tables created with table.el natively.
2236 Natively means, use the HTML code generator in table.el.
2237 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2238 the table does not use row- or column-spanning). This has the
2239 advantage, that the automatic HTML conversions for math symbols and
2240 sub/superscripts can be applied. Org-mode's HTML generator is also
2241 much faster."
2242 :group 'org-export-tables
2243 :type 'boolean)
2245 (defgroup org-export-ascii nil
2246 "Options specific for ASCII export of Org-mode files."
2247 :tag "Org Export ASCII"
2248 :group 'org-export)
2250 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2251 "Characters for underlining headings in ASCII export.
2252 In the given sequence, these characters will be used for level 1, 2, ..."
2253 :group 'org-export-ascii
2254 :type '(repeat character))
2256 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2257 "Bullet characters for headlines converted to lists in ASCII export.
2258 The first character is is used for the first lest level generated in this
2259 way, and so on. If there are more levels than characters given here,
2260 the list will be repeated.
2261 Note that plain lists will keep the same bullets as the have in the
2262 Org-mode file."
2263 :group 'org-export-ascii
2264 :type '(repeat character))
2266 (defcustom org-export-ascii-show-new-buffer t
2267 "Non-nil means, popup buffer containing the exported ASCII text.
2268 Otherwise the buffer will just be saved to a file and stay hidden."
2269 :group 'org-export-ascii
2270 :type 'boolean)
2272 (defgroup org-export-xml nil
2273 "Options specific for XML export of Org-mode files."
2274 :tag "Org Export XML"
2275 :group 'org-export)
2277 (defgroup org-export-html nil
2278 "Options specific for HTML export of Org-mode files."
2279 :tag "Org Export HTML"
2280 :group 'org-export)
2282 (defcustom org-export-html-style
2283 "<style type=\"text/css\">
2284 html {
2285 font-family: Times, serif;
2286 font-size: 12pt;
2288 .title { text-align: center; }
2289 .todo { color: red; }
2290 .done { color: green; }
2291 .timestamp { color: grey }
2292 .timestamp-kwd { color: CadetBlue }
2293 .tag { background-color:lightblue; font-weight:normal }
2294 .target { background-color: lavender; }
2295 pre {
2296 border: 1pt solid #AEBDCC;
2297 background-color: #F3F5F7;
2298 padding: 5pt;
2299 font-family: courier, monospace;
2301 table { border-collapse: collapse; }
2302 td, th {
2303 vertical-align: top;
2304 border: 1pt solid #ADB9CC;
2306 </style>"
2307 "The default style specification for exported HTML files.
2308 Since there are different ways of setting style information, this variable
2309 needs to contain the full HTML structure to provide a style, including the
2310 surrounding HTML tags. The style specifications should include definitions
2311 for new classes todo, done, title, and deadline. For example, legal values
2312 would be:
2314 <style type=\"text/css\">
2315 p { font-weight: normal; color: gray; }
2316 h1 { color: black; }
2317 .title { text-align: center; }
2318 .todo, .deadline { color: red; }
2319 .done { color: green; }
2320 </style>
2322 or, if you want to keep the style in a file,
2324 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2326 As the value of this option simply gets inserted into the HTML <head> header,
2327 you can \"misuse\" it to add arbitrary text to the header."
2328 :group 'org-export-html
2329 :type 'string)
2331 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
2332 "Format for typesetting the document title in HTML export."
2333 :group 'org-export-html
2334 :type 'string)
2336 (defcustom org-export-html-toplevel-hlevel 2
2337 "The <H> level for level 1 headings in HTML export."
2338 :group 'org-export-html
2339 :type 'string)
2341 (defcustom org-export-html-link-org-files-as-html t
2342 "Non-nil means, make file links to `file.org' point to `file.html'.
2343 When org-mode is exporting an org-mode file to HTML, links to
2344 non-html files are directly put into a href tag in HTML.
2345 However, links to other Org-mode files (recognized by the
2346 extension `.org.) should become links to the corresponding html
2347 file, assuming that the linked org-mode file will also be
2348 converted to HTML.
2349 When nil, the links still point to the plain `.org' file."
2350 :group 'org-export-html
2351 :type 'boolean)
2353 (defcustom org-export-html-inline-images 'maybe
2354 "Non-nil means, inline images into exported HTML pages.
2355 This is done using an <img> tag. When nil, an anchor with href is used to
2356 link to the image. If this option is `maybe', then images in links with
2357 an empty description will be inlined, while images with a description will
2358 be linked only."
2359 :group 'org-export-html
2360 :type '(choice (const :tag "Never" nil)
2361 (const :tag "Always" t)
2362 (const :tag "When there is no description" maybe)))
2364 (defcustom org-export-html-expand t
2365 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2366 When nil, these tags will be exported as plain text and therefore
2367 not be interpreted by a browser.
2369 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2370 :group 'org-export-html
2371 :type 'boolean)
2373 (defcustom org-export-html-table-tag
2374 "<table border=\"1\" cellspacing=\"0\" cellpadding=\"6\">"
2375 "The HTML tag used to start a table.
2376 This must be a <table> tag, but you may change the options like
2377 borders and spacing."
2378 :group 'org-export-html
2379 :type 'string)
2381 (defcustom org-export-html-with-timestamp nil
2382 "If non-nil, write `org-export-html-html-helper-timestamp'
2383 into the exported HTML text. Otherwise, the buffer will just be saved
2384 to a file."
2385 :group 'org-export-html
2386 :type 'boolean)
2388 (defcustom org-export-html-html-helper-timestamp
2389 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2390 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2391 :group 'org-export-html
2392 :type 'string)
2394 (defcustom org-export-html-show-new-buffer nil
2395 "Non-nil means, popup buffer containing the exported html text.
2396 Otherwise, the buffer will just be saved to a file and stay hidden."
2397 :group 'org-export-html
2398 :type 'boolean)
2400 (defgroup org-export-icalendar nil
2401 "Options specific for iCalendar export of Org-mode files."
2402 :tag "Org Export iCalendar"
2403 :group 'org-export)
2405 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2406 "The file name for the iCalendar file covering all agenda files.
2407 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2408 The file name should be absolute."
2409 :group 'org-export-icalendar
2410 :type 'file)
2412 (defcustom org-icalendar-include-todo nil
2413 "Non-nil means, export to iCalendar files should also cover TODO items."
2414 :group 'org-export-icalendar
2415 :type 'boolean)
2417 (defcustom org-icalendar-combined-name "OrgMode"
2418 "Calendar name for the combined iCalendar representing all agenda files."
2419 :group 'org-export-icalendar
2420 :type 'string)
2422 (defgroup org-font-lock nil
2423 "Font-lock settings for highlighting in Org-mode."
2424 :tag "Org Font Lock"
2425 :group 'org)
2427 (defcustom org-level-color-stars-only nil
2428 "Non-nil means fontify only the stars in each headline.
2429 When nil, the entire headline is fontified.
2430 Changing it requires restart of `font-lock-mode' to become effective
2431 also in regions already fontified."
2432 :group 'org-font-lock
2433 :type 'boolean)
2435 (defcustom org-hide-leading-stars nil
2436 "Non-nil means, hide the first N-1 stars in a headline.
2437 This works by using the face `org-hide' for these stars. This
2438 face is white for a light background, and black for a dark
2439 background. You may have to customize the face `org-hide' to
2440 make this work.
2441 Changing it requires restart of `font-lock-mode' to become effective
2442 also in regions already fontified.
2443 You may also set this on a per-file basis by adding one of the following
2444 lines to the buffer:
2446 #+STARTUP: hidestars
2447 #+STARTUP: showstars"
2448 :group 'org-font-lock
2449 :type 'boolean)
2451 (defcustom org-fontify-done-headline nil
2452 "Non-nil means, change the face of a headline if it is marked DONE.
2453 Normally, only the TODO/DONE keyword indicates the state of a headline.
2454 When this is non-nil, the headline after the keyword is set to the
2455 `org-headline-done' as an additional indication."
2456 :group 'org-font-lock
2457 :type 'boolean)
2459 (defcustom org-fontify-emphasized-text t
2460 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2461 Changing this variable requires a restart of Emacs to take effect."
2462 :group 'org-font-lock
2463 :type 'boolean)
2465 (defvar org-emph-re nil
2466 "Regular expression for matching emphasis.")
2467 (defvar org-emphasis-regexp-components) ; defined just below
2468 (defvar org-emphasis-alist) ; defined just below
2469 (defun org-set-emph-re (var val)
2470 "Set variable and compute the emphasis regular expression."
2471 (set var val)
2472 (when (and (boundp 'org-emphasis-alist)
2473 (boundp 'org-emphasis-regexp-components)
2474 org-emphasis-alist org-emphasis-regexp-components)
2475 (let* ((e org-emphasis-regexp-components)
2476 (pre (car e))
2477 (post (nth 1 e))
2478 (border (nth 2 e))
2479 (body (nth 3 e))
2480 (nl (nth 4 e))
2481 (stacked (nth 5 e))
2482 (body1 (concat body "*?"))
2483 (markers (mapconcat 'car org-emphasis-alist "")))
2484 ;; make sure special characters appear at the right position in the class
2485 (if (string-match "\\^" markers)
2486 (setq markers (concat (replace-match "" t t markers) "^")))
2487 (if (string-match "-" markers)
2488 (setq markers (concat (replace-match "" t t markers) "-")))
2489 ; (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\n?" body "*?")))
2490 ; (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\\(?:\n?" body "*?\\)?")))
2491 (if (> nl 0)
2492 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2493 (int-to-string nl) "\\}")))
2494 ;; Make the regexp
2495 (setq org-emph-re
2496 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2497 "\\("
2498 "\\([" markers "]\\)"
2499 "\\("
2500 "[^" border markers "]"
2501 body1
2502 "[^" border markers "]"
2503 "\\)"
2504 "\\3\\)"
2505 "\\([" post (if stacked markers) "]\\|$\\)")))))
2507 (defcustom org-emphasis-regexp-components
2508 '(" \t(" " \t.,?;'\")" " \t\r\n," "." 1 nil)
2509 "Components used to build the reqular expression for emphasis.
2510 This is a list with 6 entries. Terminology: In an emphasis string
2511 like \" *strong word* \", we call the initial space PREMATCH, the final
2512 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2513 and \"trong wor\" is the body. The different components in this variable
2514 specify what is allowed/forbidden in each part:
2516 pre Chars allowed as prematch. Beginning of line will be allowed too.
2517 post Chars allowed as postmatch. End of line will be allowed too.
2518 border The chars *forbidden* as border characters. In addition to the
2519 characters given here, all marker characters are forbidden too.
2520 body-regexp A regexp like \".\" to match a body character. Don't use
2521 non-shy groups here, and don't allow newline here.
2522 newline The maximum number of newlines allowed in an emphasis exp.
2523 stacked Non-nil means, allow stacked styles. This works only in HTML
2524 export. When this is set, all marker characters (as given in
2525 `org-emphasis-alist') will be allowed as pre/post, aiding
2526 inside-out matching.
2527 Use customize to modify this, or restart emacs after changing it."
2528 :group 'org-font-lock
2529 :set 'org-set-emph-re
2530 :type '(list
2531 (sexp :tag "Allowed chars in pre ")
2532 (sexp :tag "Allowed chars in post ")
2533 (sexp :tag "Forbidden chars in border ")
2534 (sexp :tag "Regexp for body ")
2535 (integer :tag "number of newlines allowed")
2536 (boolean :tag "Stacking allowed ")))
2538 (defcustom org-emphasis-alist
2539 '(("*" bold "<b>" "</b>")
2540 ("/" italic "<i>" "</i>")
2541 ("_" underline "<u>" "</u>")
2542 ("=" shadow "<code>" "</code>")
2543 ("+" (:strike-through t) "<del>" "</del>")
2545 "Special syntax for emphasised text.
2546 Text starting and ending with a special character will be emphasized, for
2547 example *bold*, _underlined_ and /italic/. This variable sets the marker
2548 characters, the face to bbe used by font-lock for highlighting in Org-mode
2549 emacs buffers, and the HTML tags to be used for this.
2550 Use customize to modify this, or restart emacs after changing it."
2551 :group 'org-font-lock
2552 :set 'org-set-emph-re
2553 :type '(repeat
2554 (list
2555 (string :tag "Marker character")
2556 (choice
2557 (face :tag "Font-lock-face")
2558 (plist :tag "Face property list"))
2559 (string :tag "HTML start tag")
2560 (string :tag "HTML end tag"))))
2562 (defgroup org-faces nil
2563 "Faces in Org-mode."
2564 :tag "Org Faces"
2565 :group 'org-font-lock)
2567 (defun org-compatible-face (specs)
2568 "Make a compatible face specification.
2569 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2570 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2571 to the top of the list. The `min-colors' attribute will be removed from
2572 any other entries, and any resulting duplicates will be removed entirely."
2573 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2574 (let (r e a)
2575 (while (setq e (pop specs))
2576 (cond
2577 ((memq (car e) '(t default)) (push e r))
2578 ((setq a (member '(min-colors 8) (car e)))
2579 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2580 (cdr e)))))
2581 ((setq a (assq 'min-colors (car e)))
2582 (setq e (cons (delq a (car e)) (cdr e)))
2583 (or (assoc (car e) r) (push e r)))
2584 (t (or (assoc (car e) r) (push e r)))))
2585 (nreverse r))
2586 specs))
2588 (defface org-hide
2589 '((((background light)) (:foreground "white"))
2590 (((background dark)) (:foreground "black")))
2591 "Face used to hide leading stars in headlines.
2592 The forground color of this face should be equal to the background
2593 color of the frame."
2594 :group 'org-faces)
2596 (defface org-level-1 ;; font-lock-function-name-face
2597 (org-compatible-face
2598 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2599 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2600 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2601 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2602 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2603 (t (:bold t))))
2604 "Face used for level 1 headlines."
2605 :group 'org-faces)
2607 (defface org-level-2 ;; font-lock-variable-name-face
2608 (org-compatible-face
2609 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2610 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2611 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2612 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2613 (t (:bold t))))
2614 "Face used for level 2 headlines."
2615 :group 'org-faces)
2617 (defface org-level-3 ;; font-lock-keyword-face
2618 (org-compatible-face
2619 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2620 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2621 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2622 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2623 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2624 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2625 (t (:bold t))))
2626 "Face used for level 3 headlines."
2627 :group 'org-faces)
2629 (defface org-level-4 ;; font-lock-comment-face
2630 (org-compatible-face
2631 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2632 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2633 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2634 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2635 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2636 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2637 (t (:bold t))))
2638 "Face used for level 4 headlines."
2639 :group 'org-faces)
2641 (defface org-level-5 ;; font-lock-type-face
2642 (org-compatible-face
2643 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2644 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2645 (((class color) (min-colors 8)) (:foreground "green"))))
2646 "Face used for level 5 headlines."
2647 :group 'org-faces)
2649 (defface org-level-6 ;; font-lock-constant-face
2650 (org-compatible-face
2651 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2652 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2653 (((class color) (min-colors 8)) (:foreground "magenta"))))
2654 "Face used for level 6 headlines."
2655 :group 'org-faces)
2657 (defface org-level-7 ;; font-lock-builtin-face
2658 (org-compatible-face
2659 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2660 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2661 (((class color) (min-colors 8)) (:foreground "blue"))))
2662 "Face used for level 7 headlines."
2663 :group 'org-faces)
2665 (defface org-level-8 ;; font-lock-string-face
2666 (org-compatible-face
2667 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2668 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2669 (((class color) (min-colors 8)) (:foreground "green"))))
2670 "Face used for level 8 headlines."
2671 :group 'org-faces)
2673 (defface org-special-keyword ;; font-lock-string-face
2674 (org-compatible-face
2675 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2676 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2677 (t (:italic t))))
2678 "Face used for special keywords."
2679 :group 'org-faces)
2681 (defface org-warning ;; font-lock-warning-face
2682 (org-compatible-face
2683 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2684 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2685 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2686 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2687 (t (:bold t))))
2688 "Face for deadlines and TODO keywords."
2689 :group 'org-faces)
2691 (defface org-headline-done ;; font-lock-string-face
2692 (org-compatible-face
2693 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2694 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2695 (((class color) (min-colors 8) (background light)) (:bold nil))))
2696 "Face used to indicate that a headline is DONE.
2697 This face is only used if `org-fontify-done-headline' is set."
2698 :group 'org-faces)
2700 (defface org-archived ; similar to shadow
2701 (org-compatible-face
2702 '((((class color grayscale) (min-colors 88) (background light))
2703 (:foreground "grey50"))
2704 (((class color grayscale) (min-colors 88) (background dark))
2705 (:foreground "grey70"))
2706 (((class color) (min-colors 8) (background light))
2707 (:foreground "green"))
2708 (((class color) (min-colors 8) (background dark))
2709 (:foreground "yellow"))))
2710 "Face for headline with the ARCHIVE tag."
2711 :group 'org-faces)
2713 (defface org-link
2714 '((((class color) (background light)) (:foreground "Purple" :underline t))
2715 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2716 (t (:underline t)))
2717 "Face for links."
2718 :group 'org-faces)
2720 (defface org-date
2721 '((((class color) (background light)) (:foreground "Purple" :underline t))
2722 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2723 (t (:underline t)))
2724 "Face for links."
2725 :group 'org-faces)
2727 (defface org-tag
2728 '((t (:bold t)))
2729 "Face for tags."
2730 :group 'org-faces)
2732 (defface org-todo ;; font-lock-warning-face
2733 (org-compatible-face
2734 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2735 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2736 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2737 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2738 (t (:inverse-video t :bold t))))
2739 "Face for TODO keywords."
2740 :group 'org-faces)
2742 (defface org-done ;; font-lock-type-face
2743 (org-compatible-face
2744 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
2745 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
2746 (((class color) (min-colors 8)) (:foreground "green"))
2747 (t (:bold t))))
2748 "Face used for DONE."
2749 :group 'org-faces)
2751 (defface org-table ;; font-lock-function-name-face
2752 (org-compatible-face
2753 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2754 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2755 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2756 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2757 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2758 (((class color) (min-colors 8) (background dark)))))
2759 "Face used for tables."
2760 :group 'org-faces)
2762 (defface org-formula
2763 (org-compatible-face
2764 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2765 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2766 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2767 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2768 (t (:bold t :italic t))))
2769 "Face for formulas."
2770 :group 'org-faces)
2772 (defface org-scheduled-today
2773 (org-compatible-face
2774 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2775 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2776 (((class color) (min-colors 8)) (:foreground "green"))
2777 (t (:bold t :italic t))))
2778 "Face for items scheduled for a certain day."
2779 :group 'org-faces)
2781 (defface org-scheduled-previously
2782 (org-compatible-face
2783 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2784 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2785 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2786 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2787 (t (:bold t))))
2788 "Face for items scheduled previously, and not yet done."
2789 :group 'org-faces)
2791 (defface org-upcoming-deadline
2792 (org-compatible-face
2793 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2794 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2795 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2796 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2797 (t (:bold t))))
2798 "Face for items scheduled previously, and not yet done."
2799 :group 'org-faces)
2801 (defface org-time-grid ;; font-lock-variable-name-face
2802 (org-compatible-face
2803 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2804 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2805 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
2806 "Face used for time grids."
2807 :group 'org-faces)
2809 (defconst org-level-faces
2810 '(org-level-1 org-level-2 org-level-3 org-level-4
2811 org-level-5 org-level-6 org-level-7 org-level-8
2813 (defconst org-n-levels (length org-level-faces))
2816 ;; Variables for pre-computed regular expressions, all buffer local
2817 (defvar org-done-string nil
2818 "The last string in `org-todo-keywords', indicating an item is DONE.")
2819 (make-variable-buffer-local 'org-done-string)
2820 (defvar org-todo-regexp nil
2821 "Matches any of the TODO state keywords.")
2822 (make-variable-buffer-local 'org-todo-regexp)
2823 (defvar org-not-done-regexp nil
2824 "Matches any of the TODO state keywords except the last one.")
2825 (make-variable-buffer-local 'org-not-done-regexp)
2826 (defvar org-todo-line-regexp nil
2827 "Matches a headline and puts TODO state into group 2 if present.")
2828 (make-variable-buffer-local 'org-todo-line-regexp)
2829 (defvar org-todo-line-tags-regexp nil
2830 "Matches a headline and puts TODO state into group 2 if present.
2831 Also put tags into group 4 if tags are present.")
2832 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2833 (defvar org-nl-done-regexp nil
2834 "Matches newline followed by a headline with the DONE keyword.")
2835 (make-variable-buffer-local 'org-nl-done-regexp)
2836 (defvar org-looking-at-done-regexp nil
2837 "Matches the DONE keyword a point.")
2838 (make-variable-buffer-local 'org-looking-at-done-regexp)
2839 (defvar org-todo-kwd-priority-p nil
2840 "Do TODO items have priorities?")
2841 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2842 (defvar org-todo-kwd-max-priority nil
2843 "Maximum priority of TODO items.")
2844 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2845 (defvar org-ds-keyword-length 12
2846 "Maximum length of the Deadline and SCHEDULED keywords.")
2847 (make-variable-buffer-local 'org-ds-keyword-length)
2848 (defvar org-deadline-regexp nil
2849 "Matches the DEADLINE keyword.")
2850 (make-variable-buffer-local 'org-deadline-regexp)
2851 (defvar org-deadline-time-regexp nil
2852 "Matches the DEADLINE keyword together with a time stamp.")
2853 (make-variable-buffer-local 'org-deadline-time-regexp)
2854 (defvar org-deadline-line-regexp nil
2855 "Matches the DEADLINE keyword and the rest of the line.")
2856 (make-variable-buffer-local 'org-deadline-line-regexp)
2857 (defvar org-scheduled-regexp nil
2858 "Matches the SCHEDULED keyword.")
2859 (make-variable-buffer-local 'org-scheduled-regexp)
2860 (defvar org-scheduled-time-regexp nil
2861 "Matches the SCHEDULED keyword together with a time stamp.")
2862 (make-variable-buffer-local 'org-scheduled-time-regexp)
2863 (defvar org-closed-time-regexp nil
2864 "Matches the CLOSED keyword together with a time stamp.")
2865 (make-variable-buffer-local 'org-closed-time-regexp)
2867 (defvar org-keyword-time-regexp nil
2868 "Matches any of the 3 keywords, together with the time stamp.")
2869 (make-variable-buffer-local 'org-keyword-time-regexp)
2870 (defvar org-maybe-keyword-time-regexp nil
2871 "Matches a timestamp, possibly preceeded by a keyword.")
2872 (make-variable-buffer-local 'org-keyword-time-regexp)
2874 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2875 mouse-map t)
2876 "Properties to remove when a string without properties is wanted.")
2878 (defsubst org-match-string-no-properties (num &optional string)
2879 (if (featurep 'xemacs)
2880 (let ((s (match-string num string)))
2881 (remove-text-properties 0 (length s) org-rm-props s)
2883 (match-string-no-properties num string)))
2885 (defsubst org-no-properties (s)
2886 (remove-text-properties 0 (length s) org-rm-props s)
2889 (defsubst org-get-alist-option (option key)
2890 (cond ((eq key t) t)
2891 ((eq option t) t)
2892 ((assoc key option) (cdr (assoc key option)))
2893 (t (cdr (assq 'default option)))))
2895 (defsubst org-set-local (var value)
2896 "Make VAR local in current buffer and set it to VALUE."
2897 (set (make-variable-buffer-local var) value))
2899 (defsubst org-mode-p ()
2900 "Check if the current buffer is in Org-mode."
2901 (eq major-mode 'org-mode))
2903 (defsubst org-last (list)
2904 "Return the last element of LIST."
2905 (car (last list)))
2907 (defun org-let (list &rest body)
2908 (eval (cons 'let (cons list body))))
2909 (put 'org-let 'lisp-indent-function 1)
2911 (defun org-let2 (list1 list2 &rest body)
2912 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
2913 (put 'org-let2 'lisp-indent-function 2)
2915 (defconst org-startup-options
2916 '(("fold" org-startup-folded t)
2917 ("overview" org-startup-folded t)
2918 ("nofold" org-startup-folded nil)
2919 ("showall" org-startup-folded nil)
2920 ("content" org-startup-folded content)
2921 ("hidestars" org-hide-leading-stars t)
2922 ("showstars" org-hide-leading-stars nil)
2923 ("odd" org-odd-levels-only t)
2924 ("oddeven" org-odd-levels-only nil)
2925 ("align" org-startup-align-all-tables t)
2926 ("noalign" org-startup-align-all-tables nil)
2927 ("logging" org-log-done t)
2928 ("nologging" org-log-done nil)
2929 ("dlcheck" org-startup-with-deadline-check t)
2930 ("nodlcheck" org-startup-with-deadline-check nil)))
2932 (defun org-set-regexps-and-options ()
2933 "Precompute regular expressions for current buffer."
2934 (when (org-mode-p)
2935 (let ((re (org-make-options-regexp
2936 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2937 "STARTUP" "ARCHIVE" "TAGS" "LINK")))
2938 (splitre "[ \t]+")
2939 kwds int key value cat arch tags links tmp)
2940 (save-excursion
2941 (save-restriction
2942 (widen)
2943 (goto-char (point-min))
2944 (while (re-search-forward re nil t)
2945 (setq key (match-string 1) value (org-match-string-no-properties 2))
2946 (cond
2947 ((equal key "CATEGORY")
2948 (if (string-match "[ \t]+$" value)
2949 (setq value (replace-match "" t t value)))
2950 (setq cat (intern value)))
2951 ((equal key "SEQ_TODO")
2952 (setq int 'sequence
2953 kwds (append kwds (org-split-string value splitre))))
2954 ((equal key "PRI_TODO")
2955 (setq int 'priority
2956 kwds (append kwds (org-split-string value splitre))))
2957 ((equal key "TYP_TODO")
2958 (setq int 'type
2959 kwds (append kwds (org-split-string value splitre))))
2960 ((equal key "TAGS")
2961 (setq tags (append tags (org-split-string value splitre))))
2962 ((equal key "LINK")
2963 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2964 (push (cons (match-string 1 value)
2965 (org-trim (match-string 2 value)))
2966 links)))
2967 ((equal key "STARTUP")
2968 (let ((opts (org-split-string value splitre))
2969 l var val)
2970 (while (setq l (assoc (pop opts) org-startup-options))
2971 (setq var (nth 1 l) val (nth 2 l))
2972 (set (make-local-variable var) val))))
2973 ((equal key "ARCHIVE")
2974 (string-match " *$" value)
2975 (setq arch (replace-match "" t t value))
2976 (remove-text-properties 0 (length arch)
2977 '(face t fontified t) arch)))
2979 (and cat (org-set-local 'org-category cat))
2980 (and kwds (org-set-local 'org-todo-keywords kwds))
2981 (and arch (org-set-local 'org-archive-location arch))
2982 (and int (org-set-local 'org-todo-interpretation int))
2983 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2984 (when tags
2985 (let (e tgs)
2986 (while (setq e (pop tags))
2987 (cond
2988 ((equal e "{") (push '(:startgroup) tgs))
2989 ((equal e "}") (push '(:endgroup) tgs))
2990 ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
2991 (push (cons (match-string 1 e)
2992 (string-to-char (match-string 2 e)))
2993 tgs))
2994 (t (push (list e) tgs))))
2995 (org-set-local 'org-tag-alist nil)
2996 (while (setq e (pop tgs))
2997 (or (and (stringp (car e))
2998 (assoc (car e) org-tag-alist))
2999 (push e org-tag-alist))))))
3001 ;; Compute the regular expressions and other local variables
3002 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
3003 org-todo-kwd-max-priority (1- (length org-todo-keywords))
3004 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3005 (length org-scheduled-string)))
3006 org-done-string
3007 (nth (1- (length org-todo-keywords)) org-todo-keywords)
3008 org-todo-regexp
3009 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
3010 "\\|") "\\)\\>")
3011 org-not-done-regexp
3012 (concat "\\<\\("
3013 (mapconcat 'regexp-quote
3014 (nreverse (cdr (reverse org-todo-keywords)))
3015 "\\|")
3016 "\\)\\>")
3017 org-todo-line-regexp
3018 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3019 (mapconcat 'regexp-quote org-todo-keywords "\\|")
3020 "\\)\\>\\)? *\\(.*\\)")
3021 org-nl-done-regexp
3022 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
3023 org-todo-line-tags-regexp
3024 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3025 (mapconcat 'regexp-quote org-todo-keywords "\\|")
3026 "\\)\\>\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
3027 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
3028 org-deadline-regexp (concat "\\<" org-deadline-string)
3029 org-deadline-time-regexp
3030 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3031 org-deadline-line-regexp
3032 (concat "\\<\\(" org-deadline-string "\\).*")
3033 org-scheduled-regexp
3034 (concat "\\<" org-scheduled-string)
3035 org-scheduled-time-regexp
3036 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3037 org-closed-time-regexp
3038 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3039 org-keyword-time-regexp
3040 (concat "\\<\\(" org-scheduled-string
3041 "\\|" org-deadline-string
3042 "\\|" org-closed-string
3043 "\\|" org-clock-string "\\)"
3044 " *[[<]\\([^]>]+\\)[]>]")
3045 org-maybe-keyword-time-regexp
3046 (concat "\\(\\<\\(" org-scheduled-string
3047 "\\|" org-deadline-string
3048 "\\|" org-closed-string
3049 "\\|" org-clock-string "\\)\\)?"
3050 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
3052 (org-set-font-lock-defaults)))
3054 ;; Tell the compiler about dynamically scoped variables,
3055 ;; and variables from other packages
3056 (defvar calc-embedded-close-formula) ; defined by the calc package
3057 (defvar calc-embedded-open-formula) ; defined by the calc package
3058 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
3059 (defvar zmacs-regions) ; XEmacs regions
3060 (defvar original-date) ; dynamically scoped in calendar
3061 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
3062 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
3063 (defvar org-html-entities) ; defined later in this file
3064 (defvar org-goto-start-pos) ; dynamically scoped parameter
3065 (defvar org-time-was-given) ; dynamically scoped parameter
3066 (defvar org-ts-what) ; dynamically scoped parameter
3067 (defvar org-current-export-file) ; dynamically scoped parameter
3068 (defvar org-current-export-dir) ; dynamically scoped parameter
3069 (defvar mark-active) ; Emacs only, not available in XEmacs.
3070 (defvar timecnt) ; dynamically scoped parameter
3071 (defvar levels-open) ; dynamically scoped parameter
3072 (defvar entry) ; dynamically scoped parameter
3073 (defvar state) ; dynamically scoped into `org-after-todo-state-change-hook'
3074 (defvar date) ; dynamically scoped parameter
3075 (defvar description) ; dynamically scoped parameter
3076 (defvar ans1) ; dynamically scoped parameter
3077 (defvar ans2) ; dynamically scoped parameter
3078 (defvar starting-day) ; local variable
3079 (defvar include-all-loc) ; local variable
3080 (defvar vm-message-pointer) ; from vm
3081 (defvar vm-folder-directory) ; from vm
3082 (defvar gnus-other-frame-object) ; from gnus
3083 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
3084 (defvar wl-summary-buffer-folder-name) ; from wanderlust
3085 (defvar gnus-group-name) ; from gnus
3086 (defvar gnus-article-current) ; from gnus
3087 (defvar w3m-current-url) ; from w3m
3088 (defvar w3m-current-title) ; from w3m
3089 (defvar mh-progs) ; from MH-E
3090 (defvar mh-current-folder) ; from MH-E
3091 (defvar mh-show-folder-buffer) ; from MH-E
3092 (defvar mh-index-folder) ; from MH-E
3093 (defvar mh-searcher) ; from MH-E
3094 (defvar org-selected-point) ; dynamically scoped parameter
3095 (defvar calendar-mode-map) ; from calendar.el
3096 (defvar last-arg) ; local variable
3097 (defvar remember-save-after-remembering) ; from remember.el
3098 (defvar remember-data-file) ; from remember.el
3099 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
3100 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
3101 (defvar orgtbl-mode) ; defined later in this file
3102 (defvar Info-current-file) ; from info.el
3103 (defvar Info-current-node) ; from info.el
3104 (defvar texmathp-why) ; from texmathp.el
3105 (defvar org-latex-regexps)
3107 ;;; Define the mode
3109 (defvar org-mode-map
3110 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3111 (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.")
3112 (copy-keymap outline-mode-map))
3113 "Keymap for Org-mode.")
3115 (defvar org-struct-menu) ; defined later in this file
3116 (defvar org-org-menu) ; defined later in this file
3117 (defvar org-tbl-menu) ; defined later in this file
3119 ;; We use a before-change function to check if a table might need
3120 ;; an update.
3121 (defvar org-table-may-need-update t
3122 "Indicates that a table might need an update.
3123 This variable is set by `org-before-change-function'.
3124 `org-table-align' sets it back to nil.")
3125 (defvar org-mode-hook nil)
3126 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3127 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3130 ;;;###autoload
3131 (define-derived-mode org-mode outline-mode "Org"
3132 "Outline-based notes management and organizer, alias
3133 \"Carsten's outline-mode for keeping track of everything.\"
3135 Org-mode develops organizational tasks around a NOTES file which
3136 contains information about projects as plain text. Org-mode is
3137 implemented on top of outline-mode, which is ideal to keep the content
3138 of large files well structured. It supports ToDo items, deadlines and
3139 time stamps, which magically appear in the diary listing of the Emacs
3140 calendar. Tables are easily created with a built-in table editor.
3141 Plain text URL-like links connect to websites, emails (VM), Usenet
3142 messages (Gnus), BBDB entries, and any files related to the project.
3143 For printing and sharing of notes, an Org-mode file (or a part of it)
3144 can be exported as a structured ASCII or HTML file.
3146 The following commands are available:
3148 \\{org-mode-map}"
3150 ;; Get rid of Outline menus, they are not needed
3151 ;; Need to do this here because define-derived-mode sets up
3152 ;; the keymap so late.
3153 (if (featurep 'xemacs)
3154 (progn
3155 ;; Assume this is Greg's port, it used easymenu
3156 (easy-menu-remove outline-mode-menu-heading)
3157 (easy-menu-remove outline-mode-menu-show)
3158 (easy-menu-remove outline-mode-menu-hide))
3159 (define-key org-mode-map [menu-bar headings] 'undefined)
3160 (define-key org-mode-map [menu-bar hide] 'undefined)
3161 (define-key org-mode-map [menu-bar show] 'undefined))
3163 (easy-menu-add org-org-menu)
3164 (easy-menu-add org-tbl-menu)
3165 (org-install-agenda-files-menu)
3166 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3167 (org-add-to-invisibility-spec '(org-cwidth))
3168 (when (featurep 'xemacs)
3169 (org-set-local 'line-move-ignore-invisible t))
3170 (setq outline-regexp "\\*+")
3171 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
3172 (setq outline-level 'org-outline-level)
3173 (when (and org-ellipsis (stringp org-ellipsis))
3174 (unless org-display-table
3175 (setq org-display-table (make-display-table)))
3176 (set-display-table-slot org-display-table
3177 4 (string-to-vector org-ellipsis))
3178 (setq buffer-display-table org-display-table))
3179 (org-set-regexps-and-options)
3180 ;; Calc embedded
3181 (org-set-local 'calc-embedded-open-mode "# ")
3182 (modify-syntax-entry ?# "<")
3183 (if org-startup-truncated (setq truncate-lines t))
3184 (org-set-local 'font-lock-unfontify-region-function
3185 'org-unfontify-region)
3186 ;; Activate before-change-function
3187 (org-set-local 'org-table-may-need-update t)
3188 (org-add-hook 'before-change-functions 'org-before-change-function nil
3189 'local)
3190 ;; Check for running clock before killing a buffer
3191 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3192 ;; Paragraphs and auto-filling
3193 (org-set-autofill-regexps)
3194 (org-update-radio-target-regexp)
3196 (if (and org-insert-mode-line-in-empty-file
3197 (interactive-p)
3198 (= (point-min) (point-max)))
3199 (insert " -*- mode: org -*-\n\n"))
3201 (unless org-inhibit-startup
3202 (when org-startup-align-all-tables
3203 (let ((bmp (buffer-modified-p)))
3204 (org-table-map-tables 'org-table-align)
3205 (set-buffer-modified-p bmp)))
3206 (if org-startup-with-deadline-check
3207 (call-interactively 'org-check-deadlines)
3208 (cond
3209 ((eq org-startup-folded t)
3210 (org-cycle '(4)))
3211 ((eq org-startup-folded 'content)
3212 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3213 (org-cycle '(4)) (org-cycle '(4))))))))
3215 (defsubst org-call-with-arg (command arg)
3216 "Call COMMAND interactively, but pretend prefix are was ARG."
3217 (let ((current-prefix-arg arg)) (call-interactively command)))
3219 (defsubst org-current-line (&optional pos)
3220 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
3222 (defun org-current-time ()
3223 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3224 (if (> org-time-stamp-rounding-minutes 0)
3225 (let ((r org-time-stamp-rounding-minutes)
3226 (time (decode-time)))
3227 (apply 'encode-time
3228 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3229 (nthcdr 2 time))))
3230 (current-time)))
3232 (defun org-add-props (string plist &rest props)
3233 "Add text properties to entire string, from beginning to end.
3234 PLIST may be a list of properties, PROPS are individual properties and values
3235 that will be added to PLIST. Returns the string that was modified."
3236 (add-text-properties
3237 0 (length string) (if props (append plist props) plist) string)
3238 string)
3239 (put 'org-add-props 'lisp-indent-function 2)
3242 ;;; Font-Lock stuff
3244 (defvar org-mouse-map (make-sparse-keymap))
3245 (define-key org-mouse-map
3246 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3247 (define-key org-mouse-map
3248 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3249 (when org-mouse-1-follows-link
3250 (define-key org-mouse-map [follow-link] 'mouse-face))
3251 (when org-tab-follows-link
3252 (define-key org-mouse-map [(tab)] 'org-open-at-point)
3253 (define-key org-mouse-map "\C-i" 'org-open-at-point))
3254 (when org-return-follows-link
3255 (define-key org-mouse-map [(return)] 'org-open-at-point)
3256 (define-key org-mouse-map "\C-m" 'org-open-at-point))
3258 (require 'font-lock)
3260 (defconst org-non-link-chars "]\t\n\r<>")
3261 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
3262 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
3263 (defconst org-link-re-with-space
3264 (concat
3265 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3266 "\\([^" org-non-link-chars " ]"
3267 "[^" org-non-link-chars "]*"
3268 "[^" org-non-link-chars " ]\\)>?")
3269 "Matches a link with spaces, optional angular brackets around it.")
3271 (defconst org-link-re-with-space2
3272 (concat
3273 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3274 "\\([^" org-non-link-chars " ]"
3275 "[^]\t\n\r]*"
3276 "[^" org-non-link-chars " ]\\)>?")
3277 "Matches a link with spaces, optional angular brackets around it.")
3279 (defconst org-angle-link-re
3280 (concat
3281 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3282 "\\([^" org-non-link-chars " ]"
3283 "[^" org-non-link-chars "]*"
3284 "\\)>")
3285 "Matches link with angular brackets, spaces are allowed.")
3286 (defconst org-plain-link-re
3287 (concat
3288 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3289 "\\([^]\t\n\r<>,;() ]+\\)")
3290 "Matches plain link, without spaces.")
3292 (defconst org-bracket-link-regexp
3293 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
3294 "Matches a link in double brackets.")
3296 (defconst org-bracket-link-analytic-regexp
3297 (concat
3298 "\\[\\["
3299 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3300 "\\([^]]+\\)"
3301 "\\]"
3302 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3303 "\\]"))
3304 ; 1: http:
3305 ; 2: http
3306 ; 3: path
3307 ; 4: [desc]
3308 ; 5: desc
3311 (defconst org-ts-lengths
3312 (cons (length (format-time-string (car org-time-stamp-formats)))
3313 (length (format-time-string (cdr org-time-stamp-formats))))
3314 "This holds the lengths of the two different time formats.")
3315 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
3316 "Regular expression for fast time stamp matching.")
3317 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
3318 "Regular expression for fast time stamp matching.")
3319 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3320 "Regular expression matching time strings for analysis.")
3321 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
3322 "Regular expression matching time stamps, with groups.")
3323 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[]>]")
3324 "Regular expression matching time stamps (also [..]), with groups.")
3325 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3326 "Regular expression matching a time stamp range.")
3327 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3328 org-ts-regexp "\\)?")
3329 "Regular expression matching a time stamp or time stamp range.")
3331 (defvar org-�§emph-face nil)
3333 (defun org-do-emphasis-faces (limit)
3334 "Run through the buffer and add overlays to links."
3335 (if (re-search-forward org-emph-re limit t)
3336 (progn
3337 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3338 'face
3339 (nth 1 (assoc (match-string 3)
3340 org-emphasis-alist)))
3341 (add-text-properties (match-beginning 2) (match-end 2)
3342 '(font-lock-multiline t))
3343 (backward-char 1)
3344 t)))
3346 (defun org-activate-plain-links (limit)
3347 "Run through the buffer and add overlays to links."
3348 (if (re-search-forward org-plain-link-re limit t)
3349 (progn
3350 (add-text-properties (match-beginning 0) (match-end 0)
3351 (list 'mouse-face 'highlight
3352 'keymap org-mouse-map
3354 t)))
3356 (defun org-activate-angle-links (limit)
3357 "Run through the buffer and add overlays to links."
3358 (if (re-search-forward org-angle-link-re limit t)
3359 (progn
3360 (add-text-properties (match-beginning 0) (match-end 0)
3361 (list 'mouse-face 'highlight
3362 'keymap org-mouse-map
3364 t)))
3366 (defun org-activate-bracket-links (limit)
3367 "Run through the buffer and add overlays to bracketed links."
3368 (if (re-search-forward org-bracket-link-regexp limit t)
3369 (let* ((help (concat "LINK: "
3370 (org-match-string-no-properties 1)))
3371 ;; FIXME: above we should remove the escapes.
3372 ;; but that requires another match, protecting match data,
3373 ;; a lot of overhead for font-lock.
3374 (ip (list 'invisible 'org-link 'intangible t 'rear-nonsticky t
3375 'keymap org-mouse-map 'mouse-face 'highlight
3376 'help-echo help))
3377 (vp (list 'rear-nonsticky t
3378 'keymap org-mouse-map 'mouse-face 'highlight
3379 'help-echo help)))
3380 ;; We need to remove the invisible property here. Table narrowing
3381 ;; may have made some of this invisible.
3382 (remove-text-properties (match-beginning 0) (match-end 0)
3383 '(invisible nil))
3384 (if (match-end 3)
3385 (progn
3386 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3387 (add-text-properties (match-beginning 3) (match-end 3) vp)
3388 (add-text-properties (match-end 3) (match-end 0) ip))
3389 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3390 (add-text-properties (match-beginning 1) (match-end 1) vp)
3391 (add-text-properties (match-end 1) (match-end 0) ip))
3392 t)))
3394 (defun org-activate-dates (limit)
3395 "Run through the buffer and add overlays to dates."
3396 (if (re-search-forward org-tsr-regexp limit t)
3397 (progn
3398 (add-text-properties (match-beginning 0) (match-end 0)
3399 (list 'mouse-face 'highlight
3400 'keymap org-mouse-map))
3401 t)))
3403 (defvar org-target-link-regexp nil
3404 "Regular expression matching radio targets in plain text.")
3405 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3406 "Regular expression matching a link target.")
3407 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3408 "Regular expression matching a link target.")
3410 (defun org-activate-target-links (limit)
3411 "Run through the buffer and add overlays to target matches."
3412 (when org-target-link-regexp
3413 (let ((case-fold-search t))
3414 (if (re-search-forward org-target-link-regexp limit t)
3415 (progn
3416 (add-text-properties (match-beginning 0) (match-end 0)
3417 (list 'mouse-face 'highlight
3418 'keymap org-mouse-map
3419 'help-echo "Radio target link"
3420 'org-linked-text t))
3421 t)))))
3423 (defun org-update-radio-target-regexp ()
3424 "Find all radio targets in this file and update the regular expression."
3425 (interactive)
3426 (when (memq 'radio org-activate-links)
3427 (setq org-target-link-regexp
3428 (org-make-target-link-regexp (org-all-targets 'radio)))
3429 (org-restart-font-lock)))
3431 (defun org-hide-wide-columns (limit)
3432 (let (s e)
3433 (setq s (text-property-any (point) (or limit (point-max))
3434 'org-cwidth t))
3435 (when s
3436 (setq e (next-single-property-change s 'org-cwidth))
3437 (add-text-properties s e '(invisible org-cwidth intangible t))
3438 (goto-char e)
3439 t)))
3441 (defun org-restart-font-lock ()
3442 "Restart font-lock-mode, to force refontification."
3443 (when (and (boundp 'font-lock-mode) font-lock-mode)
3444 (font-lock-mode -1)
3445 (font-lock-mode 1)))
3447 (defun org-all-targets (&optional radio)
3448 "Return a list of all targets in this file.
3449 With optional argument RADIO, only find radio targets."
3450 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3451 rtn)
3452 (save-excursion
3453 (goto-char (point-min))
3454 (while (re-search-forward re nil t)
3455 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3456 rtn)))
3458 (defun org-make-target-link-regexp (targets)
3459 "Make regular expression matching all strings in TARGETS.
3460 The regular expression finds the targets also if there is a line break
3461 between words."
3462 (and targets
3463 (concat
3464 "\\<\\("
3465 (mapconcat
3466 (lambda (x)
3467 (while (string-match " +" x)
3468 (setq x (replace-match "\\s-+" t t x)))
3470 targets
3471 "\\|")
3472 "\\)\\>")))
3474 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
3475 "Matches CamelCase words, possibly with a star before it.")
3477 (defun org-activate-camels (limit)
3478 "Run through the buffer and add overlays to dates."
3479 (if (re-search-forward org-camel-regexp limit t)
3480 (progn
3481 (add-text-properties (match-beginning 0) (match-end 0)
3482 (list 'mouse-face 'highlight
3483 'keymap org-mouse-map))
3484 t)))
3486 (defun org-activate-tags (limit)
3487 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3488 (progn
3489 (add-text-properties (match-beginning 1) (match-end 1)
3490 (list 'mouse-face 'highlight
3491 'keymap org-mouse-map))
3492 t)))
3494 (defun org-font-lock-level ()
3495 (save-excursion
3496 (org-back-to-heading t)
3497 (- (match-end 0) (match-beginning 0))))
3499 (defun org-outline-level ()
3500 (save-excursion
3501 (looking-at outline-regexp)
3502 (if (match-beginning 1)
3503 (+ (org-get-string-indentation (match-string 1)) 1000)
3504 (- (match-end 0) (match-beginning 0)))))
3506 (defvar org-font-lock-keywords nil)
3508 (defun org-set-font-lock-defaults ()
3509 (let* ((em org-fontify-emphasized-text)
3510 (lk org-activate-links)
3511 (org-font-lock-extra-keywords
3512 ;; Headlines
3513 (list
3514 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3515 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3516 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3517 (1 'org-table))
3518 ;; Links
3519 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3520 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3521 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3522 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3523 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3524 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
3525 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3526 (if org-table-limit-column-width
3527 '(org-hide-wide-columns (0 nil append)))
3528 ;; TODO lines
3529 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3530 '(1 'org-todo t))
3531 ;; Priorities
3532 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3533 ;; Special keywords
3534 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3535 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3536 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3537 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3538 ;; Emphasis
3539 (if em
3540 (if (featurep 'xemacs)
3541 '(org-do-emphasis-faces (0 nil append))
3542 '(org-do-emphasis-faces)))
3543 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
3544 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
3545 2 'bold prepend)
3546 (if org-provide-checkbox-statistics
3547 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3548 (0 (org-get-checkbox-statistics-face) t)))
3549 ;; COMMENT
3550 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
3551 "\\|" org-quote-string "\\)\\>")
3552 '(1 'org-special-keyword t))
3553 '("^#.*" (0 'font-lock-comment-face t))
3554 ;; DONE
3555 (if org-fontify-done-headline
3556 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
3557 '(1 'org-done t) '(2 'org-headline-done t))
3558 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
3559 '(1 'org-done t)))
3560 ;; Table stuff
3561 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
3562 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3563 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
3564 (if org-format-transports-properties-p
3565 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3566 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
3568 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3569 ;; Now set the full font-lock-keywords
3570 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3571 (org-set-local 'font-lock-defaults
3572 '(org-font-lock-keywords t nil nil backward-paragraph))
3573 (kill-local-variable 'font-lock-keywords) nil))
3575 (defvar org-m nil)
3576 (defvar org-l nil)
3577 (defvar org-f nil)
3578 (defun org-get-level-face (n)
3579 "Get the right face for match N in font-lock matching of healdines."
3580 (setq org-l (- (match-end 2) (match-beginning 1)))
3581 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3582 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
3583 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
3584 (cond
3585 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3586 ((eq n 2) org-f)
3587 (t (if org-level-color-stars-only nil org-f))))
3589 (defun org-unfontify-region (beg end &optional maybe_loudly)
3590 "Remove fontification and activation overlays from links."
3591 (font-lock-default-unfontify-region beg end)
3592 (let* ((buffer-undo-list t)
3593 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3594 (inhibit-modification-hooks t)
3595 deactivate-mark buffer-file-name buffer-file-truename)
3596 (remove-text-properties beg end
3597 '(mouse-face nil keymap nil org-linked-text nil
3598 invisible nil intangible nil))))
3599 ;;; Visibility cycling
3601 (defvar org-cycle-global-status nil)
3602 (make-variable-buffer-local 'org-cycle-global-status)
3603 (defvar org-cycle-subtree-status nil)
3604 (make-variable-buffer-local 'org-cycle-subtree-status)
3606 ;;;###autoload
3607 (defun org-cycle (&optional arg)
3608 "Visibility cycling for Org-mode.
3610 - When this function is called with a prefix argument, rotate the entire
3611 buffer through 3 states (global cycling)
3612 1. OVERVIEW: Show only top-level headlines.
3613 2. CONTENTS: Show all headlines of all levels, but no body text.
3614 3. SHOW ALL: Show everything.
3616 - When point is at the beginning of a headline, rotate the subtree started
3617 by this line through 3 different states (local cycling)
3618 1. FOLDED: Only the main headline is shown.
3619 2. CHILDREN: The main headline and the direct children are shown.
3620 From this state, you can move to one of the children
3621 and zoom in further.
3622 3. SUBTREE: Show the entire subtree, including body text.
3624 - When there is a numeric prefix, go up to a heading with level ARG, do
3625 a `show-subtree' and return to the previous cursor position. If ARG
3626 is negative, go up that many levels.
3628 - When point is not at the beginning of a headline, execute
3629 `indent-relative', like TAB normally does. See the option
3630 `org-cycle-emulate-tab' for details.
3632 - Special case: if point is the the beginning of the buffer and there is
3633 no headline in line 1, this function will act as if called with prefix arg."
3634 (interactive "P")
3635 (let* ((outline-regexp
3636 (if (and (org-mode-p) org-cycle-include-plain-lists)
3637 "\\(?:\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3638 outline-regexp))
3639 (bob-special (and org-cycle-global-at-bob (bobp)
3640 (not (looking-at outline-regexp))))
3641 (org-cycle-hook
3642 (if bob-special
3643 (delq 'org-optimize-window-after-visibility-change
3644 (copy-sequence org-cycle-hook))
3645 org-cycle-hook))
3646 (pos (point)))
3648 (if (or bob-special (equal arg '(4)))
3649 ;; special case: use global cycling
3650 (setq arg t))
3652 (cond
3654 ((org-at-table-p 'any)
3655 ;; Enter the table or move to the next field in the table
3656 (or (org-table-recognize-table.el)
3657 (progn
3658 (if arg (org-table-edit-field t)
3659 (org-table-justify-field-maybe)
3660 (call-interactively 'org-table-next-field)))))
3662 ((eq arg t) ;; Global cycling
3664 (cond
3665 ((and (eq last-command this-command)
3666 (eq org-cycle-global-status 'overview))
3667 ;; We just created the overview - now do table of contents
3668 ;; This can be slow in very large buffers, so indicate action
3669 (message "CONTENTS...")
3670 (org-content)
3671 (message "CONTENTS...done")
3672 (setq org-cycle-global-status 'contents)
3673 (run-hook-with-args 'org-cycle-hook 'contents))
3675 ((and (eq last-command this-command)
3676 (eq org-cycle-global-status 'contents))
3677 ;; We just showed the table of contents - now show everything
3678 (show-all)
3679 (message "SHOW ALL")
3680 (setq org-cycle-global-status 'all)
3681 (run-hook-with-args 'org-cycle-hook 'all))
3684 ;; Default action: go to overview
3685 (org-overview)
3686 (message "OVERVIEW")
3687 (setq org-cycle-global-status 'overview)
3688 (run-hook-with-args 'org-cycle-hook 'overview))))
3690 ((integerp arg)
3691 ;; Show-subtree, ARG levels up from here.
3692 (save-excursion
3693 (org-back-to-heading)
3694 (outline-up-heading (if (< arg 0) (- arg)
3695 (- (funcall outline-level) arg)))
3696 (org-show-subtree)))
3698 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3699 ;; At a heading: rotate between three different views
3700 (org-back-to-heading)
3701 (let ((goal-column 0) eoh eol eos)
3702 ;; First, some boundaries
3703 (save-excursion
3704 (org-back-to-heading)
3705 (save-excursion
3706 (beginning-of-line 2)
3707 (while (and (not (eobp)) ;; this is like `next-line'
3708 (get-char-property (1- (point)) 'invisible))
3709 (beginning-of-line 2)) (setq eol (point)))
3710 (outline-end-of-heading) (setq eoh (point))
3711 (org-end-of-subtree t) (setq eos (point))
3712 (outline-next-heading))
3713 ;; Find out what to do next and set `this-command'
3714 (cond
3715 ((and (= eos eoh)
3716 ;; Nothing is hidden behind this heading
3717 (message "EMPTY ENTRY")
3718 (setq org-cycle-subtree-status nil)))
3719 ((>= eol eos)
3720 ;; Entire subtree is hidden in one line: open it
3721 (org-show-entry)
3722 (show-children)
3723 (message "CHILDREN")
3724 (setq org-cycle-subtree-status 'children)
3725 (run-hook-with-args 'org-cycle-hook 'children))
3726 ((and (eq last-command this-command)
3727 (eq org-cycle-subtree-status 'children))
3728 ;; We just showed the children, now show everything.
3729 (org-show-subtree)
3730 (message "SUBTREE")
3731 (setq org-cycle-subtree-status 'subtree)
3732 (run-hook-with-args 'org-cycle-hook 'subtree))
3734 ;; Default action: hide the subtree.
3735 (hide-subtree)
3736 (message "FOLDED")
3737 (setq org-cycle-subtree-status 'folded)
3738 (run-hook-with-args 'org-cycle-hook 'folded)))))
3740 ;; TAB emulation
3741 (buffer-read-only (org-back-to-heading))
3743 ((org-try-cdlatex-tab))
3745 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3746 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3747 (or (and (eq org-cycle-emulate-tab 'white)
3748 (= (match-end 0) (point-at-eol)))
3749 (and (eq org-cycle-emulate-tab 'whitestart)
3750 (>= (match-end 0) pos))))
3752 (eq org-cycle-emulate-tab t))
3753 (if (and (looking-at "[ \n\r\t]")
3754 (string-match "^[ \t]*$" (buffer-substring
3755 (point-at-bol) (point))))
3756 (progn
3757 (beginning-of-line 1)
3758 (and (looking-at "[ \t]+") (replace-match ""))))
3759 (indent-relative))
3761 (t (save-excursion
3762 (org-back-to-heading)
3763 (org-cycle))))))
3765 ;;;###autoload
3766 (defun org-global-cycle (&optional arg)
3767 "Cycle the global visibility. For details see `org-cycle'."
3768 (interactive "P")
3769 (let ((org-cycle-include-plain-lists
3770 (if (org-mode-p) org-cycle-include-plain-lists nil)))
3771 (if (integerp arg)
3772 (progn
3773 (show-all)
3774 (hide-sublevels arg)
3775 (setq org-cycle-global-status 'contents))
3776 (org-cycle '(4)))))
3778 (defun org-overview ()
3779 "Switch to overview mode, shoing only top-level headlines.
3780 Really, this shows all headlines with level equal or greater than the level
3781 of the first headline in the buffer. This is important, because if the
3782 first headline is not level one, then (hide-sublevels 1) gives confusing
3783 results."
3784 (interactive)
3785 (hide-sublevels (save-excursion
3786 (goto-char (point-min))
3787 (if (re-search-forward (concat "^" outline-regexp) nil t)
3788 (progn
3789 (goto-char (match-beginning 0))
3790 (funcall outline-level))
3791 1))))
3793 ;; FIXME: allow an argument to give a limiting level for this.
3794 (defun org-content ()
3795 "Show all headlines in the buffer, like a table of contents"
3796 (interactive)
3797 (save-excursion
3798 ;; Visit all headings and show their offspring
3799 (goto-char (point-max))
3800 (catch 'exit
3801 (while (and (progn (condition-case nil
3802 (outline-previous-visible-heading 1)
3803 (error (goto-char (point-min))))
3805 (looking-at outline-regexp))
3806 (show-branches)
3807 (if (bobp) (throw 'exit nil))))))
3810 (defun org-optimize-window-after-visibility-change (state)
3811 "Adjust the window after a change in outline visibility.
3812 This function is the default value of the hook `org-cycle-hook'."
3813 (when (get-buffer-window (current-buffer))
3814 (cond
3815 ((eq state 'overview) (org-first-headline-recenter 1))
3816 ((eq state 'content) nil)
3817 ((eq state 'all) nil)
3818 ((eq state 'folded) nil)
3819 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3820 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3822 (defun org-subtree-end-visible-p ()
3823 "Is the end of the current subtree visible?"
3824 (pos-visible-in-window-p
3825 (save-excursion (org-end-of-subtree t) (point))))
3827 (defun org-first-headline-recenter (&optional N)
3828 "Move cursor to the first headline and recenter the headline.
3829 Optional argument N means, put the headline into the Nth line of the window."
3830 (goto-char (point-min))
3831 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
3832 (beginning-of-line)
3833 (recenter (prefix-numeric-value N))))
3835 (defvar org-goto-window-configuration nil)
3836 (defvar org-goto-marker nil)
3837 (defvar org-goto-map (make-sparse-keymap))
3838 (let ((cmds '(isearch-forward isearch-backward)) cmd)
3839 (while (setq cmd (pop cmds))
3840 (substitute-key-definition cmd cmd org-goto-map global-map)))
3841 (define-key org-goto-map "\C-m" 'org-goto-ret)
3842 (define-key org-goto-map [(left)] 'org-goto-left)
3843 (define-key org-goto-map [(right)] 'org-goto-right)
3844 (define-key org-goto-map [(?q)] 'org-goto-quit)
3845 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
3846 (define-key org-goto-map "\C-i" 'org-cycle)
3847 (define-key org-goto-map [(tab)] 'org-cycle)
3848 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
3849 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
3850 (define-key org-goto-map "n" 'outline-next-visible-heading)
3851 (define-key org-goto-map "p" 'outline-previous-visible-heading)
3852 (define-key org-goto-map "f" 'outline-forward-same-level)
3853 (define-key org-goto-map "b" 'outline-backward-same-level)
3854 (define-key org-goto-map "u" 'outline-up-heading)
3855 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
3856 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
3857 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
3858 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
3859 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
3860 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3861 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
3863 (defconst org-goto-help
3864 "Select a location to jump to, press RET
3865 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
3867 (defun org-goto ()
3868 "Go to a different location of the document, keeping current visibility.
3870 When you want to go to a different location in a document, the fastest way
3871 is often to fold the entire buffer and then dive into the tree. This
3872 method has the disadvantage, that the previous location will be folded,
3873 which may not be what you want.
3875 This command works around this by showing a copy of the current buffer in
3876 overview mode. You can dive into the tree in that copy, to find the
3877 location you want to reach. When pressing RET, the command returns to the
3878 original buffer in which the visibility is still unchanged. It then jumps
3879 to the new location, making it and the headline hierarchy above it visible."
3880 (interactive)
3881 (let* ((org-goto-start-pos (point))
3882 (selected-point
3883 (org-get-location (current-buffer) org-goto-help)))
3884 (if selected-point
3885 (progn
3886 (org-mark-ring-push org-goto-start-pos)
3887 (goto-char selected-point)
3888 (if (or (org-invisible-p) (org-invisible-p2))
3889 (org-show-hierarchy-above 'org-goto)))
3890 (error "Quit"))))
3892 (defun org-get-location (buf help)
3893 "Let the user select a location in the Org-mode buffer BUF.
3894 This function uses a recursive edit. It returns the selected position
3895 or nil."
3896 (let (org-selected-point)
3897 (save-excursion
3898 (save-window-excursion
3899 (delete-other-windows)
3900 (switch-to-buffer (get-buffer-create "*org-goto*"))
3901 (with-output-to-temp-buffer "*Help*"
3902 (princ help))
3903 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
3904 (setq buffer-read-only nil)
3905 (erase-buffer)
3906 (insert-buffer-substring buf)
3907 (let ((org-startup-truncated t)
3908 (org-startup-folded t)
3909 (org-startup-align-all-tables nil)
3910 (org-startup-with-deadline-check nil))
3911 (org-mode))
3912 (setq buffer-read-only t)
3913 (if (boundp 'org-goto-start-pos)
3914 (goto-char org-goto-start-pos)
3915 (goto-char (point-min)))
3916 (org-beginning-of-line)
3917 (message "Select location and press RET")
3918 ;; now we make sure that during selection, ony very few keys work
3919 ;; and that it is impossible to switch to another window.
3920 (let ((gm (current-global-map))
3921 (overriding-local-map org-goto-map))
3922 (unwind-protect
3923 (progn
3924 (use-global-map org-goto-map)
3925 (recursive-edit))
3926 (use-global-map gm)))))
3927 (kill-buffer "*org-goto*")
3928 org-selected-point))
3930 (defun org-goto-ret (&optional arg)
3931 "Finish `org-goto' by going to the new location."
3932 (interactive "P")
3933 (setq org-selected-point (point)
3934 current-prefix-arg arg)
3935 (throw 'exit nil))
3937 (defun org-goto-left ()
3938 "Finish `org-goto' by going to the new location."
3939 (interactive)
3940 (if (org-on-heading-p)
3941 (progn
3942 (beginning-of-line 1)
3943 (setq org-selected-point (point)
3944 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3945 (throw 'exit nil))
3946 (error "Not on a heading")))
3948 (defun org-goto-right ()
3949 "Finish `org-goto' by going to the new location."
3950 (interactive)
3951 (if (org-on-heading-p)
3952 (progn
3953 (outline-end-of-subtree)
3954 (or (eobp) (forward-char 1))
3955 (setq org-selected-point (point)
3956 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3957 (throw 'exit nil))
3958 (error "Not on a heading")))
3960 (defun org-goto-quit ()
3961 "Finish `org-goto' without cursor motion."
3962 (interactive)
3963 (setq org-selected-point nil)
3964 (throw 'exit nil))
3966 ;;; Promotion, Demotion, Inserting new headlines
3968 (defvar org-ignore-region nil
3969 "To temporarily disable the active region.")
3971 (defun org-insert-heading (&optional force-heading)
3972 "Insert a new heading or item with same depth at point.
3973 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
3974 If point is at the beginning of a headline, insert a sibling before the
3975 current headline. If point is in the middle of a headline, split the headline
3976 at that position and make the rest of the headline part of the sibling below
3977 the current headline."
3978 (interactive "P")
3979 (if (= (buffer-size) 0)
3980 (insert "\n* ")
3981 (when (or force-heading (not (org-insert-item)))
3982 (let* ((head (save-excursion
3983 (condition-case nil
3984 (progn
3985 (org-back-to-heading)
3986 (match-string 0))
3987 (error "*"))))
3988 (blank (cdr (assq 'heading org-blank-before-new-entry)))
3989 pos)
3990 (cond
3991 ((and (org-on-heading-p) (bolp)
3992 (save-excursion (backward-char 1) (not (org-invisible-p))))
3993 (open-line (if blank 2 1)))
3994 ((and (bolp) (save-excursion
3995 (backward-char 1) (not (org-invisible-p))))
3996 nil)
3997 (t (newline (if blank 2 1))))
3998 (insert head) (just-one-space)
3999 (setq pos (point))
4000 (end-of-line 1)
4001 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4002 (run-hooks 'org-insert-heading-hook)))))
4004 (defun org-in-item-p ()
4005 "It the cursor inside a plain list item.
4006 Does not have to be the first line."
4007 (save-excursion
4008 (condition-case nil
4009 (progn
4010 (org-beginning-of-item)
4011 (org-at-item-p)
4013 (error nil))))
4015 (defun org-insert-item (&optional checkbox)
4016 "Insert a new item at the current level.
4017 Return t when things worked, nil when we are not in an item."
4018 (when (save-excursion
4019 (condition-case nil
4020 (progn
4021 (org-beginning-of-item)
4022 (org-at-item-p)
4024 (error nil)))
4025 (let* ((bul (match-string 0))
4026 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
4027 (match-end 0)))
4028 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
4029 pos)
4030 (cond
4031 ((and (org-at-item-p) (<= (point) eow))
4032 ;; before the bullet
4033 (beginning-of-line 1)
4034 (open-line (if blank 2 1)))
4035 ((<= (point) eow)
4036 (beginning-of-line 1))
4037 (t (newline (if blank 2 1))))
4038 (insert bul (if checkbox "[ ]" ""))
4039 (just-one-space)
4040 (setq pos (point))
4041 (end-of-line 1)
4042 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
4043 (org-maybe-renumber-ordered-list)
4044 (and checkbox (org-update-checkbox-count-maybe))
4047 (defun org-insert-todo-heading (arg)
4048 "Insert a new heading with the same level and TODO state as current heading.
4049 If the heading has no TODO state, or if the state is DONE, use the first
4050 state (TODO by default). Also with prefix arg, force first state."
4051 (interactive "P")
4052 (when (not (org-insert-item 'checkbox))
4053 (org-insert-heading)
4054 (save-excursion
4055 (org-back-to-heading)
4056 (outline-previous-heading)
4057 (looking-at org-todo-line-regexp))
4058 (if (or arg
4059 (not (match-beginning 2))
4060 (equal (match-string 2) org-done-string))
4061 (insert (car org-todo-keywords) " ")
4062 (insert (match-string 2) " "))))
4064 (defun org-promote-subtree ()
4065 "Promote the entire subtree.
4066 See also `org-promote'."
4067 (interactive)
4068 (save-excursion
4069 (org-map-tree 'org-promote))
4070 (org-fix-position-after-promote))
4072 (defun org-demote-subtree ()
4073 "Demote the entire subtree. See `org-demote'.
4074 See also `org-promote'."
4075 (interactive)
4076 (save-excursion
4077 (org-map-tree 'org-demote))
4078 (org-fix-position-after-promote))
4081 (defun org-do-promote ()
4082 "Promote the current heading higher up the tree.
4083 If the region is active in `transient-mark-mode', promote all headings
4084 in the region."
4085 (interactive)
4086 (save-excursion
4087 (if (org-region-active-p)
4088 (org-map-region 'org-promote (region-beginning) (region-end))
4089 (org-promote)))
4090 (org-fix-position-after-promote))
4092 (defun org-do-demote ()
4093 "Demote the current heading lower down the tree.
4094 If the region is active in `transient-mark-mode', demote all headings
4095 in the region."
4096 (interactive)
4097 (save-excursion
4098 (if (org-region-active-p)
4099 (org-map-region 'org-demote (region-beginning) (region-end))
4100 (org-demote)))
4101 (org-fix-position-after-promote))
4103 (defun org-fix-position-after-promote ()
4104 "Make sure that after pro/demotion cursor position is right."
4105 (if (and (equal (char-after) ?\n)
4106 (save-excursion
4107 (skip-chars-backward "a-zA-Z0-9_@")
4108 (looking-at org-todo-regexp)))
4109 (insert " "))
4110 (and (equal (char-after) ?\ )
4111 (equal (char-before) ?*)
4112 (forward-char 1)))
4114 (defun org-get-legal-level (level change)
4115 "Rectify a level change under the influence of `org-odd-levels-only'
4116 LEVEL is a current level, CHANGE is by how much the level should be
4117 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4118 even level numbers will become the next higher odd number."
4119 (if org-odd-levels-only
4120 (cond ((not change) (1+ (* 2 (/ level 2))))
4121 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4122 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4123 (max 1 (+ level change))))
4125 (defun org-promote ()
4126 "Promote the current heading higher up the tree.
4127 If the region is active in `transient-mark-mode', promote all headings
4128 in the region."
4129 (org-back-to-heading t)
4130 (let* ((level (save-match-data (funcall outline-level)))
4131 (up-head (make-string (org-get-legal-level level -1) ?*))
4132 (diff (abs (- level (length up-head)))))
4133 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
4134 (replace-match up-head nil t)
4135 ;; Fixup tag positioning
4136 (and org-auto-align-tags (org-set-tags nil t))
4137 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4139 (defun org-demote ()
4140 "Demote the current heading lower down the tree.
4141 If the region is active in `transient-mark-mode', demote all headings
4142 in the region."
4143 (org-back-to-heading t)
4144 (let* ((level (save-match-data (funcall outline-level)))
4145 (down-head (make-string (org-get-legal-level level 1) ?*))
4146 (diff (abs (- level (length down-head)))))
4147 (replace-match down-head nil t)
4148 ;; Fixup tag positioning
4149 (and org-auto-align-tags (org-set-tags nil t))
4150 (if org-adapt-indentation (org-fixup-indentation diff))))
4152 (defun org-map-tree (fun)
4153 "Call FUN for every heading underneath the current one."
4154 (org-back-to-heading)
4155 (let ((level (funcall outline-level)))
4156 (save-excursion
4157 (funcall fun)
4158 (while (and (progn
4159 (outline-next-heading)
4160 (> (funcall outline-level) level))
4161 (not (eobp)))
4162 (funcall fun)))))
4164 (defun org-map-region (fun beg end)
4165 "Call FUN for every heading between BEG and END."
4166 (let ((org-ignore-region t))
4167 (save-excursion
4168 (setq end (copy-marker end))
4169 (goto-char beg)
4170 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4171 (< (point) end))
4172 (funcall fun))
4173 (while (and (progn
4174 (outline-next-heading)
4175 (< (point) end))
4176 (not (eobp)))
4177 (funcall fun)))))
4179 (defun org-fixup-indentation (diff)
4180 "Change the indentation in the current entry by DIFF
4181 However, if any line in the current entry has no indentation, or if it
4182 would end up with no indentation after the change, nothing at all is done."
4183 (save-excursion
4184 (let ((end (save-excursion (outline-next-heading)
4185 (point-marker)))
4186 (prohibit (if (> diff 0)
4187 "^\\S-"
4188 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4189 col)
4190 (unless (save-excursion (re-search-forward prohibit end t))
4191 (while (re-search-forward "^[ \t]+" end t)
4192 (goto-char (match-end 0))
4193 (setq col (current-column))
4194 (if (< diff 0) (replace-match ""))
4195 (indent-to (+ diff col))))
4196 (move-marker end nil))))
4198 ;;; Vertical tree motion, cutting and pasting of subtrees
4200 (defun org-move-subtree-up (&optional arg)
4201 "Move the current subtree up past ARG headlines of the same level."
4202 (interactive "p")
4203 (org-move-subtree-down (- (prefix-numeric-value arg))))
4205 (defun org-move-subtree-down (&optional arg)
4206 "Move the current subtree down past ARG headlines of the same level."
4207 (interactive "p")
4208 (setq arg (prefix-numeric-value arg))
4209 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4210 'outline-get-last-sibling))
4211 (ins-point (make-marker))
4212 (cnt (abs arg))
4213 beg end txt folded)
4214 ;; Select the tree
4215 (org-back-to-heading)
4216 (setq beg (point))
4217 (save-match-data
4218 (save-excursion (outline-end-of-heading)
4219 (setq folded (org-invisible-p)))
4220 (outline-end-of-subtree))
4221 (outline-next-heading)
4222 (setq end (point))
4223 ;; Find insertion point, with error handling
4224 (goto-char beg)
4225 (while (> cnt 0)
4226 (or (and (funcall movfunc) (looking-at outline-regexp))
4227 (progn (goto-char beg)
4228 (error "Cannot move past superior level or buffer limit")))
4229 (setq cnt (1- cnt)))
4230 (if (> arg 0)
4231 ;; Moving forward - still need to move over subtree
4232 (progn (outline-end-of-subtree)
4233 (outline-next-heading)
4234 (if (not (or (looking-at (concat "^" outline-regexp))
4235 (bolp)))
4236 (newline))))
4237 (move-marker ins-point (point))
4238 (setq txt (buffer-substring beg end))
4239 (delete-region beg end)
4240 (insert txt)
4241 (goto-char ins-point)
4242 (if folded (hide-subtree))
4243 (move-marker ins-point nil)))
4245 (defvar org-subtree-clip ""
4246 "Clipboard for cut and paste of subtrees.
4247 This is actually only a copy of the kill, because we use the normal kill
4248 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4250 (defvar org-subtree-clip-folded nil
4251 "Was the last copied subtree folded?
4252 This is used to fold the tree back after pasting.")
4254 (defun org-cut-subtree ()
4255 "Cut the current subtree into the clipboard.
4256 This is a short-hand for marking the subtree and then cutting it."
4257 (interactive)
4258 (org-copy-subtree 'cut))
4260 (defun org-copy-subtree (&optional cut)
4261 "Cut the current subtree into the clipboard.
4262 This is a short-hand for marking the subtree and then copying it.
4263 If CUT is non nil, actually cut the subtree."
4264 (interactive)
4265 (let (beg end folded)
4266 (org-back-to-heading)
4267 (setq beg (point))
4268 (save-match-data
4269 (save-excursion (outline-end-of-heading)
4270 (setq folded (org-invisible-p)))
4271 (outline-end-of-subtree))
4272 (if (equal (char-after) ?\n) (forward-char 1))
4273 (setq end (point))
4274 (goto-char beg)
4275 (when (> end beg)
4276 (setq org-subtree-clip-folded folded)
4277 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4278 (setq org-subtree-clip (current-kill 0))
4279 (message "%s: Subtree with %d characters"
4280 (if cut "Cut" "Copied")
4281 (length org-subtree-clip)))))
4283 (defun org-paste-subtree (&optional level tree)
4284 "Paste the clipboard as a subtree, with modification of headline level.
4285 The entire subtree is promoted or demoted in order to match a new headline
4286 level. By default, the new level is derived from the visible headings
4287 before and after the insertion point, and taken to be the inferior headline
4288 level of the two. So if the previous visible heading is level 3 and the
4289 next is level 4 (or vice versa), level 4 will be used for insertion.
4290 This makes sure that the subtree remains an independent subtree and does
4291 not swallow low level entries.
4293 You can also force a different level, either by using a numeric prefix
4294 argument, or by inserting the heading marker by hand. For example, if the
4295 cursor is after \"*****\", then the tree will be shifted to level 5.
4297 If you want to insert the tree as is, just use \\[yank].
4299 If optional TREE is given, use this text instead of the kill ring."
4300 (interactive "P")
4301 (unless (org-kill-is-subtree-p tree)
4302 (error
4303 (substitute-command-keys
4304 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4305 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4306 (^re (concat "^\\(" outline-regexp "\\)"))
4307 (re (concat "\\(" outline-regexp "\\)"))
4308 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
4310 (old-level (if (string-match ^re txt)
4311 (- (match-end 0) (match-beginning 0))
4312 -1))
4313 (force-level (cond (level (prefix-numeric-value level))
4314 ((string-match
4315 ^re_ (buffer-substring (point-at-bol) (point)))
4316 (- (match-end 0) (match-beginning 0)))
4317 (t nil)))
4318 (previous-level (save-excursion
4319 (condition-case nil
4320 (progn
4321 (outline-previous-visible-heading 1)
4322 (if (looking-at re)
4323 (- (match-end 0) (match-beginning 0))
4325 (error 1))))
4326 (next-level (save-excursion
4327 (condition-case nil
4328 (progn
4329 (outline-next-visible-heading 1)
4330 (if (looking-at re)
4331 (- (match-end 0) (match-beginning 0))
4333 (error 1))))
4334 (new-level (or force-level (max previous-level next-level)))
4335 (shift (if (or (= old-level -1)
4336 (= new-level -1)
4337 (= old-level new-level))
4339 (- new-level old-level)))
4340 (shift1 shift)
4341 (delta (if (> shift 0) -1 1))
4342 (func (if (> shift 0) 'org-demote 'org-promote))
4343 (org-odd-levels-only nil)
4344 beg end)
4345 ;; Remove the forces level indicator
4346 (if force-level
4347 (delete-region (point-at-bol) (point)))
4348 ;; Make sure we start at the beginning of an empty line
4349 (if (not (bolp)) (insert "\n"))
4350 (if (not (looking-at "[ \t]*$"))
4351 (progn (insert "\n") (backward-char 1)))
4352 ;; Paste
4353 (setq beg (point))
4354 (if (string-match "[ \t\r\n]+\\'" txt)
4355 (setq txt (replace-match "\n" t t txt)))
4356 (insert txt)
4357 (setq end (point))
4358 (if (looking-at "[ \t\r\n]+")
4359 (replace-match "\n"))
4360 (goto-char beg)
4361 ;; Shift if necessary
4362 (if (= shift 0)
4363 (message "Pasted at level %d, without shift" new-level)
4364 (save-restriction
4365 (narrow-to-region beg end)
4366 (while (not (= shift 0))
4367 (org-map-region func (point-min) (point-max))
4368 (setq shift (+ delta shift)))
4369 (goto-char (point-min))
4370 (message "Pasted at level %d, with shift by %d levels"
4371 new-level shift1)))
4372 (if (and kill-ring
4373 (eq org-subtree-clip (current-kill 0))
4374 org-subtree-clip-folded)
4375 ;; The tree was folded before it was killed/copied
4376 (hide-subtree))))
4378 (defun org-kill-is-subtree-p (&optional txt)
4379 "Check if the current kill is an outline subtree, or a set of trees.
4380 Returns nil if kill does not start with a headline, or if the first
4381 headline level is not the largest headline level in the tree.
4382 So this will actually accept several entries of equal levels as well,
4383 which is OK for `org-paste-subtree'.
4384 If optional TXT is given, check this string instead of the current kill."
4385 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4386 (start-level (and kill
4387 (string-match (concat "\\`" outline-regexp) kill)
4388 (- (match-end 0) (match-beginning 0))))
4389 (re (concat "^" outline-regexp))
4390 (start 1))
4391 (if (not start-level)
4392 nil ;; does not even start with a heading
4393 (catch 'exit
4394 (while (setq start (string-match re kill (1+ start)))
4395 (if (< (- (match-end 0) (match-beginning 0)) start-level)
4396 (throw 'exit nil)))
4397 t))))
4399 (defun org-narrow-to-subtree ()
4400 "Narrow buffer to the current subtree."
4401 (interactive)
4402 (save-excursion
4403 (narrow-to-region
4404 (progn (org-back-to-heading) (point))
4405 (progn (org-end-of-subtree t) (point)))))
4407 ;;; Plain list items
4409 (defun org-at-item-p ()
4410 "Is point in a line starting a hand-formatted item?"
4411 (let ((llt org-plain-list-ordered-item-terminator))
4412 (save-excursion
4413 (goto-char (point-at-bol))
4414 (looking-at
4415 (cond
4416 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4417 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4418 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4419 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
4421 (defun org-at-item-checkbox-p ()
4422 "Is point at a line starting a plain-list item with a checklet?"
4423 (and (org-at-item-p)
4424 (save-excursion
4425 (goto-char (match-end 0))
4426 (skip-chars-forward " \t")
4427 (looking-at "\\[[ X]\\]"))))
4429 (defun org-toggle-checkbox (&optional arg)
4430 "Toggle the checkbox in the current line."
4431 (interactive "P")
4432 (catch 'exit
4433 (let (beg end status (firstnew 'unknown))
4434 (cond
4435 ((org-region-active-p)
4436 (setq beg (region-beginning) end (region-end)))
4437 ((org-on-heading-p)
4438 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
4439 ((org-at-item-checkbox-p)
4440 (save-excursion
4441 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))
4442 (throw 'exit t))
4443 (t (error "Not at a checkbox or heading, and no active region")))
4444 (save-excursion
4445 (goto-char beg)
4446 (while (< (point) end)
4447 (when (org-at-item-checkbox-p)
4448 (setq status (equal (match-string 0) "[X]"))
4449 (when (eq firstnew 'unknown)
4450 (setq firstnew (not status)))
4451 (replace-match
4452 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
4453 (beginning-of-line 2)))))
4454 (org-update-checkbox-count-maybe))
4456 (defun org-update-checkbox-count-maybe ()
4457 "Update checkbox statistics unless turned off by user."
4458 (when org-provide-checkbox-statistics
4459 (org-update-checkbox-count)))
4461 (defun org-update-checkbox-count (&optional all)
4462 "Update the checkbox statistics in the current section.
4463 This will find all statistic cookies like [57%] and [6/12] and update them
4464 with the current numbers. With optional prefix argument ALL, do this for
4465 the whole buffer."
4466 (interactive "P")
4467 (save-excursion
4468 (let* ((buffer-invisibility-spec nil) ; Emacs 21 compatibility
4469 (beg (progn (outline-back-to-heading) (point)))
4470 (end (move-marker (make-marker)
4471 (progn (outline-next-heading) (point))))
4472 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
4473 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)")
4474 b1 e1 f1 c-on c-off lim (cstat 0))
4475 (when all
4476 (goto-char (point-min))
4477 (outline-next-heading)
4478 (setq beg (point) end (point-max)))
4479 (goto-char beg)
4480 (while (re-search-forward re end t)
4481 (setq cstat (1+ cstat)
4482 b1 (match-beginning 0)
4483 e1 (match-end 0)
4484 f1 (match-beginning 1)
4485 lim (cond
4486 ((org-on-heading-p) (outline-next-heading) (point))
4487 ((org-at-item-p) (org-end-of-item) (point))
4488 (t nil))
4489 c-on 0 c-off 0)
4490 (goto-char e1)
4491 (when lim
4492 (while (re-search-forward re-box lim t)
4493 (if (equal (match-string 2) "[ ]")
4494 (setq c-off (1+ c-off))
4495 (setq c-on (1+ c-on))))
4496 (delete-region b1 e1)
4497 (goto-char b1)
4498 (insert (if f1
4499 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
4500 (format "[%d/%d]" c-on (+ c-on c-off))))))
4501 (when (interactive-p)
4502 (message "Checkbox satistics updated %s (%d places)"
4503 (if all "in entire file" "in current outline entry") cstat)))))
4505 (defun org-get-checkbox-statistics-face ()
4506 "Select the face for checkbox statistics.
4507 The face will be `org-done' when all relevant boxes are checked. Otherwise
4508 it will be `org-todo'."
4509 (if (match-end 1)
4510 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
4511 (if (and (> (match-end 2) (match-beginning 2))
4512 (equal (match-string 2) (match-string 3)))
4513 'org-done
4514 'org-todo)))
4516 (defun org-get-indentation (&optional line)
4517 "Get the indentation of the current line, interpreting tabs.
4518 When LINE is given, assume it represents a line and compute its indentation."
4519 (if line
4520 (if (string-match "^ *" (org-remove-tabs line))
4521 (match-end 0))
4522 (save-excursion
4523 (beginning-of-line 1)
4524 (skip-chars-forward " \t")
4525 (current-column))))
4527 (defun org-remove-tabs (s &optional width)
4528 "Replace tabulators in S with spaces.
4529 Assumes that s is a single line, starting in column 0."
4530 (setq width (or width tab-width))
4531 (while (string-match "\t" s)
4532 (setq s (replace-match
4533 (make-string
4534 (- (* width (/ (+ (match-beginning 0) width) width))
4535 (match-beginning 0)) ?\ )
4536 t t s)))
4539 ;; FIXME: document properly.
4540 (defun org-fix-indentation (line ind)
4541 "If the current indenation is smaller than ind1, leave it alone.
4542 If it is larger than ind, reduce it by ind."
4543 (let* ((l (org-remove-tabs line))
4544 (i (org-get-indentation l))
4545 (i1 (car ind)) (i2 (cdr ind)))
4546 (if (>= i i2) (setq l (substring line i2)))
4547 (if (> i1 0)
4548 (concat (make-string i1 ?\ ) l)
4549 l)))
4551 (defun org-beginning-of-item ()
4552 "Go to the beginning of the current hand-formatted item.
4553 If the cursor is not in an item, throw an error."
4554 (interactive)
4555 (let ((pos (point))
4556 (limit (save-excursion (org-back-to-heading)
4557 (beginning-of-line 2) (point)))
4558 ind ind1)
4559 (if (org-at-item-p)
4560 (beginning-of-line 1)
4561 (beginning-of-line 1)
4562 (skip-chars-forward " \t")
4563 (setq ind (current-column))
4564 (if (catch 'exit
4565 (while t
4566 (beginning-of-line 0)
4567 (if (< (point) limit) (throw 'exit nil))
4568 (unless (looking-at "[ \t]*$")
4569 (skip-chars-forward " \t")
4570 (setq ind1 (current-column))
4571 (if (< ind1 ind)
4572 (throw 'exit (org-at-item-p))))))
4574 (goto-char pos)
4575 (error "Not in an item")))))
4577 (defun org-end-of-item ()
4578 "Go to the end of the current hand-formatted item.
4579 If the cursor is not in an item, throw an error."
4580 (interactive)
4581 (let ((pos (point))
4582 (limit (save-excursion (outline-next-heading) (point)))
4583 (ind (save-excursion
4584 (org-beginning-of-item)
4585 (skip-chars-forward " \t")
4586 (current-column)))
4587 ind1)
4588 (if (catch 'exit
4589 (while t
4590 (beginning-of-line 2)
4591 (if (>= (point) limit) (throw 'exit t))
4592 (unless (looking-at "[ \t]*$")
4593 (skip-chars-forward " \t")
4594 (setq ind1 (current-column))
4595 (if (<= ind1 ind) (throw 'exit t)))))
4596 (beginning-of-line 1)
4597 (goto-char pos)
4598 (error "Not in an item"))))
4600 (defun org-next-item ()
4601 "Move to the beginning of the next item in the current plain list.
4602 Error if not at a plain list, or if this is the last item in the list."
4603 (interactive)
4604 (let (ind ind1 (pos (point)))
4605 (org-beginning-of-item)
4606 (setq ind (org-get-indentation))
4607 (org-end-of-item)
4608 (setq ind1 (org-get-indentation))
4609 (unless (and (org-at-item-p) (= ind ind1))
4610 (goto-char pos)
4611 (error "On last item"))))
4613 (defun org-previous-item ()
4614 "Move to the beginning of the previous item in the current plain list.
4615 Error if not at a plain list, or if this is the last item in the list."
4616 (interactive)
4617 (let (beg ind (pos (point)))
4618 (org-beginning-of-item)
4619 (setq beg (point))
4620 (setq ind (org-get-indentation))
4621 (goto-char beg)
4622 (catch 'exit
4623 (while t
4624 (beginning-of-line 0)
4625 (if (looking-at "[ \t]*$")
4627 (if (<= (org-get-indentation) ind)
4628 (throw 'exit t)))))
4629 (condition-case nil
4630 (org-beginning-of-item)
4631 (error (goto-char pos)
4632 (error "On first item")))))
4634 (defun org-move-item-down ()
4635 "Move the plain list item at point down, i.e. swap with following item.
4636 Subitems (items with larger indentation) are considered part of the item,
4637 so this really moves item trees."
4638 (interactive)
4639 (let (beg end ind ind1 (pos (point)) txt)
4640 (org-beginning-of-item)
4641 (setq beg (point))
4642 (setq ind (org-get-indentation))
4643 (org-end-of-item)
4644 (setq end (point))
4645 (setq ind1 (org-get-indentation))
4646 (if (and (org-at-item-p) (= ind ind1))
4647 (progn
4648 (org-end-of-item)
4649 (setq txt (buffer-substring beg end))
4650 (save-excursion
4651 (delete-region beg end))
4652 (setq pos (point))
4653 (insert txt)
4654 (goto-char pos)
4655 (org-maybe-renumber-ordered-list))
4656 (goto-char pos)
4657 (error "Cannot move this item further down"))))
4659 (defun org-move-item-up (arg)
4660 "Move the plain list item at point up, i.e. swap with previous item.
4661 Subitems (items with larger indentation) are considered part of the item,
4662 so this really moves item trees."
4663 (interactive "p")
4664 (let (beg end ind ind1 (pos (point)) txt)
4665 (org-beginning-of-item)
4666 (setq beg (point))
4667 (setq ind (org-get-indentation))
4668 (org-end-of-item)
4669 (setq end (point))
4670 (goto-char beg)
4671 (catch 'exit
4672 (while t
4673 (beginning-of-line 0)
4674 (if (looking-at "[ \t]*$")
4676 (if (<= (setq ind1 (org-get-indentation)) ind)
4677 (throw 'exit t)))))
4678 (condition-case nil
4679 (org-beginning-of-item)
4680 (error (goto-char beg)
4681 (error "Cannot move this item further up")))
4682 (setq ind1 (org-get-indentation))
4683 (if (and (org-at-item-p) (= ind ind1))
4684 (progn
4685 (setq txt (buffer-substring beg end))
4686 (save-excursion
4687 (delete-region beg end))
4688 (setq pos (point))
4689 (insert txt)
4690 (goto-char pos)
4691 (org-maybe-renumber-ordered-list))
4692 (goto-char pos)
4693 (error "Cannot move this item further up"))))
4695 (defun org-maybe-renumber-ordered-list ()
4696 "Renumber the ordered list at point if setup allows it.
4697 This tests the user option `org-auto-renumber-ordered-lists' before
4698 doing the renumbering."
4699 (and org-auto-renumber-ordered-lists
4700 (org-at-item-p)
4701 (match-beginning 3)
4702 (org-renumber-ordered-list 1)))
4704 (defun org-get-string-indentation (s)
4705 "What indentation has S due to SPACE and TAB at the beginning of the string?"
4706 (let ((n -1) (i 0) (w tab-width) c)
4707 (catch 'exit
4708 (while (< (setq n (1+ n)) (length s))
4709 (setq c (aref s n))
4710 (cond ((= c ?\ ) (setq i (1+ i)))
4711 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
4712 (t (throw 'exit t)))))
4715 (defun org-renumber-ordered-list (arg)
4716 "Renumber an ordered plain list.
4717 Cursor needs to be in the first line of an item, the line that starts
4718 with something like \"1.\" or \"2)\"."
4719 (interactive "p")
4720 (unless (and (org-at-item-p)
4721 (match-beginning 3))
4722 (error "This is not an ordered list"))
4723 (let ((line (org-current-line))
4724 (col (current-column))
4725 (ind (org-get-string-indentation
4726 (buffer-substring (point-at-bol) (match-beginning 3))))
4727 ;; (term (substring (match-string 3) -1))
4728 ind1 (n (1- arg)))
4729 ;; find where this list begins
4730 (catch 'exit
4731 (while t
4732 (catch 'next
4733 (beginning-of-line 0)
4734 (if (looking-at "[ \t]*$") (throw 'next t))
4735 (skip-chars-forward " \t") (setq ind1 (current-column))
4736 (if (or (< ind1 ind)
4737 (and (= ind1 ind)
4738 (not (org-at-item-p))))
4739 (throw 'exit t)))))
4740 ;; Walk forward and replace these numbers
4741 (catch 'exit
4742 (while t
4743 (catch 'next
4744 (beginning-of-line 2)
4745 (if (eobp) (throw 'exit nil))
4746 (if (looking-at "[ \t]*$") (throw 'next nil))
4747 (skip-chars-forward " \t") (setq ind1 (current-column))
4748 (if (> ind1 ind) (throw 'next t))
4749 (if (< ind1 ind) (throw 'exit t))
4750 (if (not (org-at-item-p)) (throw 'exit nil))
4751 (if (not (match-beginning 3))
4752 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
4753 (delete-region (match-beginning 3) (1- (match-end 3)))
4754 (goto-char (match-beginning 3))
4755 (insert (format "%d" (setq n (1+ n)))))))
4756 (goto-line line)
4757 (move-to-column col)))
4759 (defvar org-last-indent-begin-marker (make-marker))
4760 (defvar org-last-indent-end-marker (make-marker))
4762 (defun org-outdent-item (arg)
4763 "Outdent a local list item."
4764 (interactive "p")
4765 (org-indent-item (- arg)))
4767 (defun org-indent-item (arg)
4768 "Indent a local list item."
4769 (interactive "p")
4770 (unless (org-at-item-p)
4771 (error "Not on an item"))
4772 (save-excursion
4773 (let (beg end ind ind1)
4774 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
4775 (setq beg org-last-indent-begin-marker
4776 end org-last-indent-end-marker)
4777 (org-beginning-of-item)
4778 (setq beg (move-marker org-last-indent-begin-marker (point)))
4779 (org-end-of-item)
4780 (setq end (move-marker org-last-indent-end-marker (point))))
4781 (goto-char beg)
4782 (skip-chars-forward " \t") (setq ind (current-column))
4783 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
4784 (while (< (point) end)
4785 (beginning-of-line 1)
4786 (skip-chars-forward " \t") (setq ind1 (current-column))
4787 (delete-region (point-at-bol) (point))
4788 (indent-to-column (+ ind1 arg))
4789 (beginning-of-line 2)))))
4791 ;;; Archiving
4793 (defun org-archive-subtree (&optional find-done)
4794 "Move the current subtree to the archive.
4795 The archive can be a certain top-level heading in the current file, or in
4796 a different file. The tree will be moved to that location, the subtree
4797 heading be marked DONE, and the current time will be added.
4799 When called with prefix argument FIND-DONE, find whole trees without any
4800 open TODO items and archive them (after getting confirmation from the user).
4801 If the cursor is not at a headline when this comand is called, try all level
4802 1 trees. If the cursor is on a headline, only try the direct children of
4803 this heading. "
4804 (interactive "P")
4805 (if find-done
4806 (org-archive-all-done)
4807 ;; Save all relevant TODO keyword-relatex variables
4809 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
4810 (tr-org-todo-keywords org-todo-keywords)
4811 (tr-org-todo-interpretation org-todo-interpretation)
4812 (tr-org-done-string org-done-string)
4813 (tr-org-todo-regexp org-todo-regexp)
4814 (tr-org-todo-line-regexp org-todo-line-regexp)
4815 (this-buffer (current-buffer))
4816 file heading buffer level newfile-p)
4817 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
4818 (progn
4819 (setq file (format (match-string 1 org-archive-location)
4820 (file-name-nondirectory buffer-file-name))
4821 heading (match-string 2 org-archive-location)))
4822 (error "Invalid `org-archive-location'"))
4823 (if (> (length file) 0)
4824 (setq newfile-p (not (file-exists-p file))
4825 buffer (find-file-noselect file))
4826 (setq buffer (current-buffer)))
4827 (unless buffer
4828 (error "Cannot access file \"%s\"" file))
4829 (if (and (> (length heading) 0)
4830 (string-match "^\\*+" heading))
4831 (setq level (match-end 0))
4832 (setq heading nil level 0))
4833 (save-excursion
4834 ;; We first only copy, in case something goes wrong
4835 ;; we need to protect this-command, to avoid kill-region sets it,
4836 ;; which would lead to duplication of subtrees
4837 (let (this-command) (org-copy-subtree))
4838 (set-buffer buffer)
4839 ;; Enforce org-mode for the archive buffer
4840 (if (not (org-mode-p))
4841 ;; Force the mode for future visits.
4842 (let ((org-insert-mode-line-in-empty-file t))
4843 (call-interactively 'org-mode)))
4844 (when newfile-p
4845 (goto-char (point-max))
4846 (insert (format "\nArchived entries from file %s\n\n"
4847 (buffer-file-name this-buffer))))
4848 ;; Force the TODO keywords of the original buffer
4849 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
4850 (org-todo-keywords tr-org-todo-keywords)
4851 (org-todo-interpretation tr-org-todo-interpretation)
4852 (org-done-string tr-org-done-string)
4853 (org-todo-regexp tr-org-todo-regexp)
4854 (org-todo-line-regexp tr-org-todo-line-regexp))
4855 (goto-char (point-min))
4856 (if heading
4857 (progn
4858 (if (re-search-forward
4859 (concat "\\(^\\|\r\\)"
4860 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
4861 nil t)
4862 (goto-char (match-end 0))
4863 ;; Heading not found, just insert it at the end
4864 (goto-char (point-max))
4865 (or (bolp) (insert "\n"))
4866 (insert "\n" heading "\n")
4867 (end-of-line 0))
4868 ;; Make the subtree visible
4869 (show-subtree)
4870 (org-end-of-subtree t)
4871 (skip-chars-backward " \t\r\n")
4872 (and (looking-at "[ \t\r\n]*")
4873 (replace-match "\n\n")))
4874 ;; No specific heading, just go to end of file.
4875 (goto-char (point-max)) (insert "\n"))
4876 ;; Paste
4877 (org-paste-subtree (1+ level))
4878 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
4879 (if org-archive-mark-done
4880 (org-todo (length org-todo-keywords)))
4881 ;; Move cursor to right after the TODO keyword
4882 (when org-archive-stamp-time
4883 (beginning-of-line 1)
4884 (looking-at org-todo-line-regexp)
4885 (goto-char (or (match-end 2) (match-beginning 3)))
4886 (insert "(" (format-time-string (cdr org-time-stamp-formats)
4887 (org-current-time))
4888 ")"))
4889 ;; Save the buffer, if it is not the same buffer.
4890 (if (not (eq this-buffer buffer)) (save-buffer))))
4891 ;; Here we are back in the original buffer. Everything seems to have
4892 ;; worked. So now cut the tree and finish up.
4893 (let (this-command) (org-cut-subtree))
4894 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
4895 (message "Subtree archived %s"
4896 (if (eq this-buffer buffer)
4897 (concat "under heading: " heading)
4898 (concat "in file: " (abbreviate-file-name file)))))))
4900 (defun org-archive-all-done (&optional tag)
4901 "Archive sublevels of the current tree without open TODO items.
4902 If the cursor is not on a headline, try all level 1 trees. If
4903 it is on a headline, try all direct children.
4904 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
4905 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
4906 (rea (concat ".*:" org-archive-tag ":"))
4907 (begm (make-marker))
4908 (endm (make-marker))
4909 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
4910 "Move subtree to archive (no open TODO items)? "))
4911 beg end (cntarch 0))
4912 (if (org-on-heading-p)
4913 (progn
4914 (setq re1 (concat "^" (regexp-quote
4915 (make-string
4916 (1+ (- (match-end 0) (match-beginning 0)))
4917 ?*))
4918 " "))
4919 (move-marker begm (point))
4920 (move-marker endm (org-end-of-subtree t)))
4921 (setq re1 "^* ")
4922 (move-marker begm (point-min))
4923 (move-marker endm (point-max)))
4924 (save-excursion
4925 (goto-char begm)
4926 (while (re-search-forward re1 endm t)
4927 (setq beg (match-beginning 0)
4928 end (save-excursion (org-end-of-subtree t) (point)))
4929 (goto-char beg)
4930 (if (re-search-forward re end t)
4931 (goto-char end)
4932 (goto-char beg)
4933 (if (and (or (not tag) (not (looking-at rea)))
4934 (y-or-n-p question))
4935 (progn
4936 (if tag
4937 (org-toggle-tag org-archive-tag 'on)
4938 (org-archive-subtree))
4939 (setq cntarch (1+ cntarch)))
4940 (goto-char end)))))
4941 (message "%d trees archived" cntarch)))
4943 (defun org-cycle-hide-archived-subtrees (state)
4944 "Re-hide all archived subtrees after a visibility state change."
4945 (when (and (not org-cycle-open-archived-trees)
4946 (not (memq state '(overview folded))))
4947 (save-excursion
4948 (let* ((globalp (memq state '(contents all)))
4949 (beg (if globalp (point-min) (point)))
4950 (end (if globalp (point-max) (org-end-of-subtree t))))
4951 (org-hide-archived-subtrees beg end)
4952 (goto-char beg)
4953 (if (looking-at (concat ".*:" org-archive-tag ":"))
4954 (message (substitute-command-keys
4955 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4957 (defun org-force-cycle-archived ()
4958 "Cycle subtree even if it is archived."
4959 (interactive)
4960 (setq this-command 'org-cycle)
4961 (let ((org-cycle-open-archived-trees t))
4962 (call-interactively 'org-cycle)))
4964 (defun org-hide-archived-subtrees (beg end)
4965 "Re-hide all archived subtrees after a visibility state change."
4966 (save-excursion
4967 (let* ((re (concat ":" org-archive-tag ":")))
4968 (goto-char beg)
4969 (while (re-search-forward re end t)
4970 (and (org-on-heading-p) (hide-subtree))
4971 (org-end-of-subtree t)))))
4973 (defun org-toggle-tag (tag &optional onoff)
4974 "Toggle the tag TAG for the current line.
4975 If ONOFF is `on' or `off', don't toggle but set to this state."
4976 (unless (org-on-heading-p) (error "Not on headling"))
4977 (let (res current)
4978 (save-excursion
4979 (beginning-of-line)
4980 (if (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t]*$"
4981 (point-at-eol) t)
4982 (progn
4983 (setq current (match-string 1))
4984 (replace-match ""))
4985 (setq current ""))
4986 (setq current (nreverse (org-split-string current ":")))
4987 (cond
4988 ((eq onoff 'on)
4989 (setq res t)
4990 (or (member tag current) (push tag current)))
4991 ((eq onoff 'off)
4992 (or (not (member tag current)) (setq current (delete tag current))))
4993 (t (if (member tag current)
4994 (setq current (delete tag current))
4995 (setq res t)
4996 (push tag current))))
4997 (end-of-line 1)
4998 (when current
4999 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
5000 (org-set-tags nil t))
5001 res))
5003 (defun org-toggle-archive-tag (&optional arg)
5004 "Toggle the archive tag for the current headline.
5005 With prefix ARG, check all children of current headline and offer tagging
5006 the children that do not contain any open TODO items."
5007 (interactive "P")
5008 (if arg
5009 (org-archive-all-done 'tag)
5010 (let (set)
5011 (save-excursion
5012 (org-back-to-heading t)
5013 (setq set (org-toggle-tag org-archive-tag))
5014 (when set (hide-subtree)))
5015 (and set (beginning-of-line 1))
5016 (message "Subtree %s" (if set "archived" "unarchived")))))
5018 (defvar org-agenda-multi nil) ; dynammically scoped
5019 (defvar org-agenda-buffer-name "*Org Agenda*")
5020 (defvar org-pre-agenda-window-conf nil)
5021 (defun org-prepare-agenda ()
5022 (if org-agenda-multi
5023 (progn
5024 (setq buffer-read-only nil)
5025 (goto-char (point-max))
5026 (unless (= (point) 1)
5027 (insert "\n" (make-string (window-width) ?=) "\n"))
5028 (narrow-to-region (point) (point-max)))
5029 (org-agenda-maybe-reset-markers 'force)
5030 (org-prepare-agenda-buffers (org-agenda-files))
5031 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
5032 (awin (get-buffer-window abuf)))
5033 (cond
5034 ((equal (current-buffer) abuf) nil)
5035 (awin (select-window awin))
5036 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
5037 ((equal org-agenda-window-setup 'current-window)
5038 (switch-to-buffer abuf))
5039 ((equal org-agenda-window-setup 'other-window)
5040 (switch-to-buffer-other-window abuf))
5041 ((equal org-agenda-window-setup 'other-frame)
5042 (switch-to-buffer-other-frame abuf))
5043 ((equal org-agenda-window-setup 'reorganize-frame)
5044 (delete-other-windows)
5045 (switch-to-buffer-other-window abuf))))
5046 (setq buffer-read-only nil)
5047 (erase-buffer)
5048 (org-agenda-mode))
5049 (setq buffer-read-only nil))
5051 (defun org-finalize-agenda ()
5052 "Finishing touch for the agenda buffer, called just before displaying it."
5053 (unless org-agenda-multi
5054 (org-agenda-align-tags)
5055 (save-excursion
5056 (let ((buffer-read-only))
5057 (goto-char (point-min))
5058 (while (org-activate-bracket-links (point-max))
5059 (add-text-properties (match-beginning 0) (match-end 0)
5060 '(face org-link))))
5061 (run-hooks 'org-finalize-agenda-hook))))
5063 (defun org-prepare-agenda-buffers (files)
5064 "Create buffers for all agenda files, protect archived trees and comments."
5065 (interactive)
5066 (let ((pa '(:org-archived t))
5067 (pc '(:org-comment t))
5068 (pall '(:org-archived t :org-comment t))
5069 (rea (concat ":" org-archive-tag ":"))
5070 bmp file re)
5071 (save-excursion
5072 (while (setq file (pop files))
5073 (org-check-agenda-file file)
5074 (set-buffer (org-get-agenda-file-buffer file))
5075 (widen)
5076 (setq bmp (buffer-modified-p))
5077 (save-excursion
5078 (remove-text-properties (point-min) (point-max) pall)
5079 (when org-agenda-skip-archived-trees
5080 (goto-char (point-min))
5081 (while (re-search-forward rea nil t)
5082 (if (org-on-heading-p)
5083 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
5084 (goto-char (point-min))
5085 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
5086 (while (re-search-forward re nil t)
5087 (add-text-properties
5088 (match-beginning 0) (org-end-of-subtree t) pc)))
5089 (set-buffer-modified-p bmp)))))
5091 (defun org-agenda-skip ()
5092 "Throw to `:skip' in places that should be skipped."
5093 (let ((p (point-at-bol)))
5094 (and org-agenda-skip-archived-trees
5095 (get-text-property p :org-archived)
5096 (org-end-of-subtree t)
5097 (throw :skip t))
5098 (and (get-text-property p :org-comment)
5099 (org-end-of-subtree t)
5100 (throw :skip t))
5101 (if (equal (char-after p) ?#) (throw :skip t))))
5103 (defun org-agenda-toggle-archive-tag ()
5104 "Toggle the archive tag for the current entry."
5105 (interactive)
5106 (org-agenda-check-no-diary)
5107 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
5108 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
5109 (org-agenda-error)))
5110 (buffer (marker-buffer hdmarker))
5111 (pos (marker-position hdmarker))
5112 (buffer-read-only nil)
5113 newhead)
5114 (with-current-buffer buffer
5115 (widen)
5116 (goto-char pos)
5117 (org-show-hierarchy-above 'agenda)
5118 (save-excursion
5119 (and (outline-next-heading)
5120 (org-flag-heading nil))) ; show the next heading
5121 (call-interactively 'org-toggle-archive-tag)
5122 (end-of-line 1)
5123 (setq newhead (org-get-heading)))
5124 (org-agenda-change-all-lines newhead hdmarker)
5125 (beginning-of-line 1)))
5127 ;;; Dynamic blocks
5129 (defun org-find-dblock (name)
5130 "Find the first dynamic block with name NAME in the buffer.
5131 If not found, stay at current position and return nil."
5132 (let (pos)
5133 (save-excursion
5134 (goto-char (point-min))
5135 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
5136 nil t)
5137 (match-beginning 0))))
5138 (if pos (goto-char pos))
5139 pos))
5141 (defconst org-dblock-start-re
5142 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
5143 "Matches the startline of a dynamic block, with parameters.")
5145 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
5146 "Matches the end of a dyhamic block.")
5148 (defun org-create-dblock (plist)
5149 "Create a dynamic block section, with parameters taken from PLIST.
5150 PLIST must containe a :name entry which is used as name of the block."
5151 (unless (bolp) (newline))
5152 (let ((name (plist-get plist :name)))
5153 (insert "#+BEGIN: " name)
5154 (while plist
5155 (if (eq (car plist) :name)
5156 (setq plist (cddr plist))
5157 (insert " " (prin1-to-string (pop plist)))))
5158 (insert "\n\n#+END:\n")
5159 (beginning-of-line -2)))
5161 (defun org-prepare-dblock ()
5162 "Prepare dynamic block for refresh.
5163 This empties the block, puts the cursor at the insert position and returns
5164 the property list including an extra property :name with the block name."
5165 (unless (looking-at org-dblock-start-re)
5166 (error "Not at a dynamic block"))
5167 (let* ((begdel (1+ (match-end 0)))
5168 (name (match-string 1))
5169 (params (append (list :name name)
5170 (read (concat "(" (match-string 3) ")")))))
5171 (unless (re-search-forward org-dblock-end-re nil t)
5172 (error "Dynamic block not terminated"))
5173 (delete-region begdel (match-beginning 0))
5174 (goto-char begdel)
5175 (open-line 1)
5176 params))
5178 (defun org-map-dblocks (&optional command)
5179 "Apply COMMAND to all dynamic blocks in the current buffer.
5180 If COMMAND is not given, use `org-update-dblock'."
5181 (let ((cmd (or command 'org-update-dblock))
5182 pos)
5183 (save-excursion
5184 (goto-char (point-min))
5185 (while (re-search-forward org-dblock-start-re nil t)
5186 (goto-char (setq pos (match-beginning 0)))
5187 (condition-case nil
5188 (funcall cmd)
5189 (error (message "Error during update of dynamic block")))
5190 (goto-char pos)
5191 (unless (re-search-forward org-dblock-end-re nil t)
5192 (error "Dynamic block not terminated"))))))
5194 (defun org-dblock-update (&optional arg)
5195 "User command for updating dynamic blocks.
5196 Update the dynamic block at point. With prefix ARG, update all dynamic
5197 blocks in the buffer."
5198 (interactive "P")
5199 (if arg
5200 (org-update-all-dblocks)
5201 (or (looking-at org-dblock-start-re)
5202 (org-beginning-of-dblock))
5203 (org-update-dblock)))
5205 (defun org-update-dblock ()
5206 "Update the dynamic block at point
5207 This means to empty the block, parse for parameters and then call
5208 the correct writing function."
5209 (let* ((pos (point))
5210 (params (org-prepare-dblock))
5211 (name (plist-get params :name))
5212 (cmd (intern (concat "org-dblock-write:" name))))
5213 (funcall cmd params)
5214 (goto-char pos)))
5216 (defun org-beginning-of-dblock ()
5217 "Find the beginning of the dynamic block at point.
5218 Error if there is no scuh block at point."
5219 (let ((pos (point))
5220 beg)
5221 (end-of-line 1)
5222 (if (and (re-search-backward org-dblock-start-re nil t)
5223 (setq beg (match-beginning 0))
5224 (re-search-forward org-dblock-end-re nil t)
5225 (> (match-end 0) pos))
5226 (goto-char beg)
5227 (goto-char pos)
5228 (error "Not in a dynamic block"))))
5230 (defun org-update-all-dblocks ()
5231 "Update all dynamic blocks in the buffer.
5232 This function can be used in a hook."
5233 (when (org-mode-p)
5234 (org-map-dblocks 'org-update-dblock)))
5237 ;;; Completion
5239 (defun org-complete (&optional arg)
5240 "Perform completion on word at point.
5241 At the beginning of a headline, this completes TODO keywords as given in
5242 `org-todo-keywords'.
5243 If the current word is preceded by a backslash, completes the TeX symbols
5244 that are supported for HTML support.
5245 If the current word is preceded by \"#+\", completes special words for
5246 setting file options.
5247 In the line after \"#+STARTUP:, complete valid keywords.\"
5248 At all other locations, this simply calls `ispell-complete-word'."
5249 (interactive "P")
5250 (catch 'exit
5251 (let* ((end (point))
5252 (beg1 (save-excursion
5253 (skip-chars-backward "a-zA-Z_@0-9")
5254 (point)))
5255 (beg (save-excursion
5256 (skip-chars-backward "a-zA-Z0-9_:$")
5257 (point)))
5258 (confirm (lambda (x) (stringp (car x))))
5259 (camel (equal (char-before beg) ?*))
5260 (tag (equal (char-before beg1) ?:))
5261 (texp (equal (char-before beg) ?\\))
5262 (link (equal (char-before beg) ?\[))
5263 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
5264 beg)
5265 "#+"))
5266 (startup (string-match "^#\\+STARTUP:.*"
5267 (buffer-substring (point-at-bol) (point))))
5268 (completion-ignore-case opt)
5269 (type nil)
5270 (tbl nil)
5271 (table (cond
5272 (opt
5273 (setq type :opt)
5274 (mapcar (lambda (x)
5275 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
5276 (cons (match-string 2 x) (match-string 1 x)))
5277 (org-split-string (org-get-current-options) "\n")))
5278 (startup
5279 (setq type :startup)
5280 org-startup-options)
5281 (link (append org-link-abbrev-alist-local
5282 org-link-abbrev-alist))
5283 (texp
5284 (setq type :tex)
5285 org-html-entities)
5286 ((string-match "\\`\\*+[ \t]*\\'"
5287 (buffer-substring (point-at-bol) beg))
5288 (setq type :todo)
5289 (mapcar 'list org-todo-keywords))
5290 (camel
5291 (setq type :camel)
5292 (save-excursion
5293 (goto-char (point-min))
5294 (while (re-search-forward org-todo-line-regexp nil t)
5295 (push (list
5296 (if org-file-link-context-use-camel-case
5297 (org-make-org-heading-camel (match-string 3) t)
5298 (org-make-org-heading-search-string
5299 (match-string 3) t)))
5300 tbl)))
5301 tbl)
5302 (tag (setq type :tag beg beg1)
5303 (or org-tag-alist (org-get-buffer-tags)))
5304 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
5305 (pattern (buffer-substring-no-properties beg end))
5306 (completion (try-completion pattern table confirm)))
5307 (cond ((eq completion t)
5308 (if (equal type :opt)
5309 (insert (substring (cdr (assoc (upcase pattern) table))
5310 (length pattern)))))
5311 ((null completion)
5312 (message "Can't find completion for \"%s\"" pattern)
5313 (ding))
5314 ((not (string= pattern completion))
5315 (delete-region beg end)
5316 (if (string-match " +$" completion)
5317 (setq completion (replace-match "" t t completion)))
5318 (insert completion)
5319 (if (get-buffer-window "*Completions*")
5320 (delete-window (get-buffer-window "*Completions*")))
5321 (if (assoc completion table)
5322 (if (eq type :todo) (insert " ")
5323 (if (eq type :tag) (insert ":"))))
5324 (if (and (equal type :opt) (assoc completion table))
5325 (message "%s" (substitute-command-keys
5326 "Press \\[org-complete] again to insert example settings"))))
5328 (message "Making completion list...")
5329 (let ((list (sort (all-completions pattern table confirm)
5330 'string<)))
5331 (with-output-to-temp-buffer "*Completions*"
5332 (condition-case nil
5333 ;; Protection needed for XEmacs and emacs 21
5334 (display-completion-list list pattern)
5335 (error (display-completion-list list)))))
5336 (message "Making completion list...%s" "done"))))))
5338 ;;; Comments, TODO and DEADLINE
5340 (defun org-toggle-comment ()
5341 "Change the COMMENT state of an entry."
5342 (interactive)
5343 (save-excursion
5344 (org-back-to-heading)
5345 (if (looking-at (concat outline-regexp
5346 "\\( +\\<" org-comment-string "\\>\\)"))
5347 (replace-match "" t t nil 1)
5348 (if (looking-at outline-regexp)
5349 (progn
5350 (goto-char (match-end 0))
5351 (insert " " org-comment-string))))))
5353 (defvar org-last-todo-state-is-todo nil
5354 "This is non-nil when the last TODO state change led to a TODO state.
5355 If the last change removed the TODO tag or switched to DONE, then
5356 this is nil.")
5358 (defun org-todo (&optional arg)
5359 "Change the TODO state of an item.
5360 The state of an item is given by a keyword at the start of the heading,
5361 like
5362 *** TODO Write paper
5363 *** DONE Call mom
5365 The different keywords are specified in the variable `org-todo-keywords'.
5366 By default the available states are \"TODO\" and \"DONE\".
5367 So for this example: when the item starts with TODO, it is changed to DONE.
5368 When it starts with DONE, the DONE is removed. And when neither TODO nor
5369 DONE are present, add TODO at the beginning of the heading.
5371 With prefix arg, use completion to determine the new state. With numeric
5372 prefix arg, switch to that state."
5373 (interactive "P")
5374 (save-excursion
5375 (org-back-to-heading)
5376 (if (looking-at outline-regexp) (goto-char (match-end 0)))
5377 (or (looking-at (concat " +" org-todo-regexp " *"))
5378 (looking-at " *"))
5379 (let* ((this (match-string 1))
5380 (completion-ignore-case t)
5381 (member (member this org-todo-keywords))
5382 (tail (cdr member))
5383 (state (cond
5384 ((equal arg '(4))
5385 ;; Read a state with completion
5386 (completing-read "State: " (mapcar (lambda(x) (list x))
5387 org-todo-keywords)
5388 nil t))
5389 ((eq arg 'right)
5390 (if this
5391 (if tail (car tail) nil)
5392 (car org-todo-keywords)))
5393 ((eq arg 'left)
5394 (if (equal member org-todo-keywords)
5396 (if this
5397 (nth (- (length org-todo-keywords) (length tail) 2)
5398 org-todo-keywords)
5399 org-done-string)))
5400 (arg
5401 ;; user requests a specific state
5402 (nth (1- (prefix-numeric-value arg))
5403 org-todo-keywords))
5404 ((null member) (car org-todo-keywords))
5405 ((null tail) nil) ;; -> first entry
5406 ((eq org-todo-interpretation 'sequence)
5407 (car tail))
5408 ((memq org-todo-interpretation '(type priority))
5409 (if (eq this-command last-command)
5410 (car tail)
5411 (if (> (length tail) 0) org-done-string nil)))
5412 (t nil)))
5413 (next (if state (concat " " state " ") " ")))
5414 (replace-match next t t)
5415 (setq org-last-todo-state-is-todo
5416 (not (equal state org-done-string)))
5417 (when org-log-done
5418 (if (equal state org-done-string)
5419 (org-add-planning-info 'closed (current-time) 'scheduled)
5420 (if (not this)
5421 (org-add-planning-info nil nil 'closed))))
5422 ;; Fixup tag positioning
5423 (and org-auto-align-tags (org-set-tags nil t))
5424 (run-hooks 'org-after-todo-state-change-hook)))
5425 ;; Fixup cursor location if close to the keyword
5426 (if (and (outline-on-heading-p)
5427 (not (bolp))
5428 (save-excursion (beginning-of-line 1)
5429 (looking-at org-todo-line-regexp))
5430 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
5431 (progn
5432 (goto-char (or (match-end 2) (match-end 1)))
5433 (just-one-space))))
5435 (defun org-show-todo-tree (arg)
5436 "Make a compact tree which shows all headlines marked with TODO.
5437 The tree will show the lines where the regexp matches, and all higher
5438 headlines above the match.
5439 With \\[universal-argument] prefix, also show the DONE entries.
5440 With a numeric prefix N, construct a sparse tree for the Nth element
5441 of `org-todo-keywords'."
5442 (interactive "P")
5443 (let ((case-fold-search nil)
5444 (kwd-re
5445 (cond ((null arg) org-not-done-regexp)
5446 ((equal arg '(4)) org-todo-regexp)
5447 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
5448 (regexp-quote (nth (1- (prefix-numeric-value arg))
5449 org-todo-keywords)))
5450 (t (error "Invalid prefix argument: %s" arg)))))
5451 (message "%d TODO entries found"
5452 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
5454 (defun org-deadline ()
5455 "Insert the DEADLINE: string to make a deadline.
5456 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5457 to modify it to the correct date."
5458 (interactive)
5459 (org-add-planning-info 'deadline nil 'closed))
5461 (defun org-schedule ()
5462 "Insert the SCHEDULED: string to schedule a TODO item.
5463 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5464 to modify it to the correct date."
5465 (interactive)
5466 (org-add-planning-info 'scheduled nil 'closed))
5468 (defun org-add-planning-info (what &optional time &rest remove)
5469 "Insert new timestamp with keyword in the line directly after the headline.
5470 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
5471 If non is given, the user is prompted for a date.
5472 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
5473 be removed."
5474 (interactive)
5475 (when what (setq time (or time (org-read-date nil 'to-time))))
5476 (when (and org-insert-labeled-timestamps-at-point
5477 (member what '(scheduled deadline)))
5478 (insert
5479 (if (eq what 'scheduled) org-scheduled-string org-deadline-string)
5481 (format-time-string (car org-time-stamp-formats) time))
5482 (setq what nil))
5483 (save-excursion
5484 (let (col list elt ts buffer-invisibility-spec)
5485 (org-back-to-heading t)
5486 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
5487 (goto-char (match-end 1))
5488 (setq col (current-column))
5489 (goto-char (1+ (match-end 0)))
5490 (if (and (not (looking-at outline-regexp))
5491 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
5492 "[^\r\n]*"))
5493 (not (equal (match-string 1) org-clock-string)))
5494 (narrow-to-region (match-beginning 0) (match-end 0))
5495 (insert "\n")
5496 (backward-char 1)
5497 (narrow-to-region (point) (point))
5498 (indent-to-column col))
5499 ;; Check if we have to remove something.
5500 (setq list (cons what remove))
5501 (while list
5502 (setq elt (pop list))
5503 (goto-char (point-min))
5504 (when (or (and (eq elt 'scheduled)
5505 (re-search-forward org-scheduled-time-regexp nil t))
5506 (and (eq elt 'deadline)
5507 (re-search-forward org-deadline-time-regexp nil t))
5508 (and (eq elt 'closed)
5509 (re-search-forward org-closed-time-regexp nil t)))
5510 (replace-match "")
5511 (if (looking-at " +") (replace-match ""))))
5512 (goto-char (point-max))
5513 (when what
5514 (insert
5515 (if (not (equal (char-before) ?\ )) " " "")
5516 (cond ((eq what 'scheduled) org-scheduled-string)
5517 ((eq what 'deadline) org-deadline-string)
5518 ((eq what 'closed) org-closed-string))
5519 " ")
5520 (insert
5521 (setq ts
5522 (format-time-string
5523 (if (eq what 'closed)
5524 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
5525 (car org-time-stamp-formats))
5526 time)))
5527 (end-of-line 1)
5528 (org-add-log-maybe 'done))
5529 (goto-char (point-min))
5530 (widen)
5531 (if (looking-at "[ \t]+\r?\n")
5532 (replace-match ""))
5533 ts)))
5535 (defvar org-log-note-marker (make-marker))
5536 (defvar org-log-note-purpose nil)
5537 (defvar org-log-note-window-configuration nil)
5539 (defun org-add-log-maybe (&optional purpose)
5540 (when (and (listp org-log-done)
5541 (memq purpose org-log-done))
5542 (move-marker org-log-note-marker (point))
5543 (setq org-log-note-purpose purpose)
5544 (add-hook 'post-command-hook 'org-add-log-note 'append)))
5546 (defun org-add-log-note (&optional purpose)
5547 "Pop up a window for taking a note, and add this note later at point."
5548 (remove-hook 'post-command-hook 'org-add-log-note)
5549 (setq org-log-note-window-configuration (current-window-configuration))
5550 (delete-other-windows)
5551 (switch-to-buffer (marker-buffer org-log-note-marker))
5552 (goto-char org-log-note-marker)
5553 (switch-to-buffer-other-window "*Org Note*")
5554 (erase-buffer)
5555 (org-mode)
5556 (insert (format "# Insert note for %s, finish with C-c C-c.\n\n"
5557 (cond
5558 ((eq org-log-note-purpose 'clock-out) "stopped clock")
5559 ((eq org-log-note-purpose 'done) "closed todo item")
5560 (t (error "This should not happen")))))
5561 (org-set-local 'org-finish-function 'org-store-log-note))
5563 (defun org-store-log-note ()
5564 "Finish taking a log note, and insert it to where it belongs."
5565 (let ((txt (buffer-string))
5566 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
5567 lines ind)
5568 (kill-buffer (current-buffer))
5569 (if (string-match "^#.*\n[ \t\\n]*" txt)
5570 (setq txt (replace-match "" t t txt)))
5571 (when (string-match "\\S-" txt)
5572 (if (string-match "\\s-+\\'" txt)
5573 (setq txt (replace-match "" t t txt)))
5574 (setq lines (org-split-string txt "\n"))
5575 (and note (string-match "\\S-" note) (push note lines))
5576 (save-excursion
5577 (set-buffer (marker-buffer org-log-note-marker))
5578 (save-excursion
5579 (goto-char org-log-note-marker)
5580 (if (not (bolp)) (newline))
5581 (indent-relative t)
5582 (setq ind (concat (buffer-substring (point-at-bol) (point)) " "))
5583 (insert "- " (pop lines))
5584 (while lines
5585 (insert "\n" ind (pop lines))))))
5586 (set-window-configuration org-log-note-window-configuration)))
5588 (defvar org-occur-highlights nil)
5589 (make-variable-buffer-local 'org-occur-highlights)
5591 (defun org-occur (regexp &optional keep-previous callback)
5592 "Make a compact tree which shows all matches of REGEXP.
5593 The tree will show the lines where the regexp matches, and all higher
5594 headlines above the match. It will also show the heading after the match,
5595 to make sure editing the matching entry is easy.
5596 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
5597 call to `org-occur' will be kept, to allow stacking of calls to this
5598 command.
5599 If CALLBACK is non-nil, it is a function which is called to confirm
5600 that the match should indeed be shown."
5601 (interactive "sRegexp: \nP")
5602 (or keep-previous (org-remove-occur-highlights nil nil t))
5603 (let ((cnt 0))
5604 (save-excursion
5605 (goto-char (point-min))
5606 (if (or (not keep-previous) ; do not want to keep
5607 (not org-occur-highlights)) ; no previous matches
5608 ;; hide everything
5609 (org-overview))
5610 (while (re-search-forward regexp nil t)
5611 (when (or (not callback)
5612 (save-match-data (funcall callback)))
5613 (setq cnt (1+ cnt))
5614 (org-highlight-new-match (match-beginning 0) (match-end 0))
5615 (org-show-hierarchy-above 'occur-tree))))
5616 (when org-remove-highlights-with-change
5617 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
5618 nil 'local))
5619 (unless org-sparse-tree-open-archived-trees
5620 (org-hide-archived-subtrees (point-min) (point-max)))
5621 (run-hooks 'org-occur-hook)
5622 (if (interactive-p)
5623 (message "%d match(es) for regexp %s" cnt regexp))
5624 cnt))
5626 (defun org-show-hierarchy-above (&optional context)
5627 "Make sure point and the headings hierarchy above is visible."
5628 (catch 'exit
5629 (if (org-on-heading-p t)
5630 (org-flag-heading nil) ; only show the heading
5631 (and (or (org-invisible-p) (org-invisible-p2))
5632 (org-show-hidden-entry))) ; show entire entry
5633 (save-excursion
5634 (and (org-get-alist-option org-show-following-heading context)
5635 (outline-next-heading)
5636 (org-flag-heading nil))) ; show the next heading
5637 (when (org-get-alist-option org-show-hierarchy-above context)
5638 (save-excursion ; show all higher headings
5639 (while (and (condition-case nil
5640 (progn (org-up-heading-all 1) t)
5641 (error nil))
5642 (not (bobp)))
5643 (org-flag-heading nil))))))
5645 ;; Overlay compatibility functions
5646 (defun org-make-overlay (beg end &optional buffer)
5647 (if (featurep 'xemacs)
5648 (make-extent beg end buffer)
5649 (make-overlay beg end buffer)))
5650 (defun org-delete-overlay (ovl)
5651 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
5652 (defun org-detatch-overlay (ovl)
5653 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
5654 (defun org-move-overlay (ovl beg end &optional buffer)
5655 (if (featurep 'xemacs)
5656 (set-extent-endpoints ovl beg end buffer)
5657 (move-overlay ovl beg end buffer)))
5658 (defun org-overlay-put (ovl prop value)
5659 (if (featurep 'xemacs)
5660 (set-extent-property ovl prop value)
5661 (overlay-put ovl prop value)))
5662 (defun org-overlays-at (pos)
5663 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
5664 (defun org-overlay-start (o)
5665 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
5666 (defun org-overlay-end (o)
5667 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
5669 (defun org-highlight-new-match (beg end)
5670 "Highlight from BEG to END and mark the highlight is an occur headline."
5671 (let ((ov (org-make-overlay beg end)))
5672 (org-overlay-put ov 'face 'secondary-selection)
5673 (push ov org-occur-highlights)))
5675 (defvar org-inhibit-highlight-removal nil)
5676 (defun org-remove-occur-highlights (&optional beg end noremove)
5677 "Remove the occur highlights from the buffer.
5678 BEG and END are ignored. If NOREMOVE is nil, remove this function
5679 from the `before-change-functions' in the current buffer."
5680 (interactive)
5681 (unless org-inhibit-highlight-removal
5682 (mapc 'org-delete-overlay org-occur-highlights)
5683 (setq org-occur-highlights nil)
5684 (unless noremove
5685 (remove-hook 'before-change-functions
5686 'org-remove-occur-highlights 'local))))
5688 ;;; Priorities
5690 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
5691 "Regular expression matching the priority indicator.")
5693 (defvar org-remove-priority-next-time nil)
5695 (defun org-priority-up ()
5696 "Increase the priority of the current item."
5697 (interactive)
5698 (org-priority 'up))
5700 (defun org-priority-down ()
5701 "Decrease the priority of the current item."
5702 (interactive)
5703 (org-priority 'down))
5705 (defun org-priority (&optional action)
5706 "Change the priority of an item by ARG.
5707 ACTION can be set, up, or down."
5708 (interactive)
5709 (setq action (or action 'set))
5710 (let (current new news have remove)
5711 (save-excursion
5712 (org-back-to-heading)
5713 (if (looking-at org-priority-regexp)
5714 (setq current (string-to-char (match-string 2))
5715 have t)
5716 (setq current org-default-priority))
5717 (cond
5718 ((eq action 'set)
5719 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
5720 (setq new (read-char-exclusive))
5721 (cond ((equal new ?\ ) (setq remove t))
5722 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
5723 (error "Priority must be between `%c' and `%c'"
5724 ?A org-lowest-priority))))
5725 ((eq action 'up)
5726 (setq new (1- current)))
5727 ((eq action 'down)
5728 (setq new (1+ current)))
5729 (t (error "Invalid action")))
5730 (setq new (min (max ?A (upcase new)) org-lowest-priority))
5731 (setq news (format "%c" new))
5732 (if have
5733 (if remove
5734 (replace-match "" t t nil 1)
5735 (replace-match news t t nil 2))
5736 (if remove
5737 (error "No priority cookie found in line")
5738 (looking-at org-todo-line-regexp)
5739 (if (match-end 2)
5740 (progn
5741 (goto-char (match-end 2))
5742 (insert " [#" news "]"))
5743 (goto-char (match-beginning 3))
5744 (insert "[#" news "] ")))))
5745 (if remove
5746 (message "Priority removed")
5747 (message "Priority of current item set to %s" news))))
5750 (defun org-get-priority (s)
5751 "Find priority cookie and return priority."
5752 (save-match-data
5753 (if (not (string-match org-priority-regexp s))
5754 (* 1000 (- org-lowest-priority org-default-priority))
5755 (* 1000 (- org-lowest-priority
5756 (string-to-char (match-string 2 s)))))))
5758 ;;; Timestamps
5760 (defvar org-last-changed-timestamp nil)
5762 (defun org-time-stamp (arg)
5763 "Prompt for a date/time and insert a time stamp.
5764 If the user specifies a time like HH:MM, or if this command is called
5765 with a prefix argument, the time stamp will contain date and time.
5766 Otherwise, only the date will be included. All parts of a date not
5767 specified by the user will be filled in from the current date/time.
5768 So if you press just return without typing anything, the time stamp
5769 will represent the current date/time. If there is already a timestamp
5770 at the cursor, it will be modified."
5771 (interactive "P")
5772 (let ((fmt (if arg (cdr org-time-stamp-formats)
5773 (car org-time-stamp-formats)))
5774 (org-time-was-given nil)
5775 time)
5776 (cond
5777 ((and (org-at-timestamp-p)
5778 (eq last-command 'org-time-stamp)
5779 (eq this-command 'org-time-stamp))
5780 (insert "--")
5781 (setq time (let ((this-command this-command))
5782 (org-read-date arg 'totime)))
5783 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5784 (insert (format-time-string fmt time)))
5785 ((org-at-timestamp-p)
5786 (setq time (let ((this-command this-command))
5787 (org-read-date arg 'totime)))
5788 (and (org-at-timestamp-p) (replace-match
5789 (setq org-last-changed-timestamp
5790 (format-time-string fmt time))
5791 t t))
5792 (message "Timestamp updated"))
5794 (setq time (let ((this-command this-command))
5795 (org-read-date arg 'totime)))
5796 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5797 (insert (format-time-string fmt time))))))
5799 (defun org-time-stamp-inactive (&optional arg)
5800 "Insert an inactive time stamp.
5801 An inactive time stamp is enclosed in square brackets instead of angle
5802 brackets. It is inactive in the sense that it does not trigger agenda entries,
5803 does not link to the calendar and cannot be changed with the S-cursor keys.
5804 So these are more for recording a certain time/date."
5805 (interactive "P")
5806 (let ((fmt (if arg (cdr org-time-stamp-formats)
5807 (car org-time-stamp-formats)))
5808 (org-time-was-given nil)
5809 time)
5810 (setq time (org-read-date arg 'totime))
5811 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5812 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
5813 (insert (format-time-string fmt time))))
5815 (defvar org-date-ovl (org-make-overlay 1 1))
5816 (org-overlay-put org-date-ovl 'face 'org-warning)
5817 (org-detatch-overlay org-date-ovl)
5819 (defun org-read-date (&optional with-time to-time)
5820 "Read a date and make things smooth for the user.
5821 The prompt will suggest to enter an ISO date, but you can also enter anything
5822 which will at least partially be understood by `parse-time-string'.
5823 Unrecognized parts of the date will default to the current day, month, year,
5824 hour and minute. For example,
5825 3-2-5 --> 2003-02-05
5826 feb 15 --> currentyear-02-15
5827 sep 12 9 --> 2009-09-12
5828 12:45 --> today 12:45
5829 22 sept 0:34 --> currentyear-09-22 0:34
5830 12 --> currentyear-currentmonth-12
5831 Fri --> nearest Friday (today or later)
5832 etc.
5833 The function understands only English month and weekday abbreviations,
5834 but this can be configured with the variables `parse-time-months' and
5835 `parse-time-weekdays'.
5837 While prompting, a calendar is popped up - you can also select the
5838 date with the mouse (button 1). The calendar shows a period of three
5839 months. To scroll it to other months, use the keys `>' and `<'.
5840 If you don't like the calendar, turn it off with
5841 \(setq org-popup-calendar-for-date-prompt Nil)
5843 With optional argument TO-TIME, the date will immediately be converted
5844 to an internal time.
5845 With an optional argument WITH-TIME, the prompt will suggest to also
5846 insert a time. Note that when WITH-TIME is not set, you can still
5847 enter a time, and this function will inform the calling routine about
5848 this change. The calling routine may then choose to change the format
5849 used to insert the time stamp into the buffer to include the time."
5850 (require 'parse-time)
5851 (let* ((org-time-stamp-rounding-minutes
5852 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
5853 (ct (org-current-time))
5854 (default-time
5855 ;; Default time is either today, or, when entering a range,
5856 ;; the range start.
5857 (if (save-excursion
5858 (re-search-backward
5859 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
5860 (- (point) 20) t))
5861 (apply
5862 'encode-time
5863 (mapcar (lambda(x) (or x 0))
5864 (parse-time-string (match-string 1))))
5865 ct))
5866 (calendar-move-hook nil)
5867 (view-diary-entries-initially nil)
5868 (view-calendar-holidays-initially nil)
5869 (timestr (format-time-string
5870 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
5871 (prompt (format "YYYY-MM-DD [%s]: " timestr))
5872 ans ans1 ans2
5873 second minute hour day month year tl wday wday1)
5875 (if org-popup-calendar-for-date-prompt
5876 (save-excursion
5877 (save-window-excursion
5878 (calendar)
5879 (calendar-forward-day (- (time-to-days default-time)
5880 (calendar-absolute-from-gregorian
5881 (calendar-current-date))))
5882 (org-eval-in-calendar nil)
5883 (let* ((old-map (current-local-map))
5884 (map (copy-keymap calendar-mode-map))
5885 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
5886 (define-key map (kbd "RET") 'org-calendar-select)
5887 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
5888 'org-calendar-select-mouse)
5889 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
5890 'org-calendar-select-mouse)
5891 (define-key minibuffer-local-map [(meta shift left)]
5892 (lambda () (interactive)
5893 (org-eval-in-calendar '(calendar-backward-month 1))))
5894 (define-key minibuffer-local-map [(meta shift right)]
5895 (lambda () (interactive)
5896 (org-eval-in-calendar '(calendar-forward-month 1))))
5897 (define-key minibuffer-local-map [(shift up)]
5898 (lambda () (interactive)
5899 (org-eval-in-calendar '(calendar-backward-week 1))))
5900 (define-key minibuffer-local-map [(shift down)]
5901 (lambda () (interactive)
5902 (org-eval-in-calendar '(calendar-forward-week 1))))
5903 (define-key minibuffer-local-map [(shift left)]
5904 (lambda () (interactive)
5905 (org-eval-in-calendar '(calendar-backward-day 1))))
5906 (define-key minibuffer-local-map [(shift right)]
5907 (lambda () (interactive)
5908 (org-eval-in-calendar '(calendar-forward-day 1))))
5909 (define-key minibuffer-local-map ">"
5910 (lambda () (interactive)
5911 (org-eval-in-calendar '(scroll-calendar-left 1))))
5912 (define-key minibuffer-local-map "<"
5913 (lambda () (interactive)
5914 (org-eval-in-calendar '(scroll-calendar-right 1))))
5915 (unwind-protect
5916 (progn
5917 (use-local-map map)
5918 (setq ans (read-string prompt "" nil nil))
5919 (if (not (string-match "\\S-" ans)) (setq ans nil))
5920 (setq ans (or ans1 ans ans2)))
5921 (use-local-map old-map)))))
5922 ;; Naked prompt only
5923 (setq ans (read-string prompt "" nil timestr)))
5924 (org-detatch-overlay org-date-ovl)
5926 (if (string-match
5927 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
5928 (progn
5929 (setq year (if (match-end 2)
5930 (string-to-number (match-string 2 ans))
5931 (string-to-number (format-time-string "%Y")))
5932 month (string-to-number (match-string 3 ans))
5933 day (string-to-number (match-string 4 ans)))
5934 (if (< year 100) (setq year (+ 2000 year)))
5935 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
5936 t nil ans))))
5937 (setq tl (parse-time-string ans)
5938 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
5939 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
5940 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
5941 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
5942 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
5943 second (or (nth 0 tl) 0)
5944 wday (nth 6 tl))
5945 (when (and wday (not (nth 3 tl)))
5946 ;; Weekday was given, but no day, so pick that day in the week
5947 ;; on or after the derived date.
5948 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
5949 (unless (equal wday wday1)
5950 (setq day (+ day (% (- wday wday1 -7) 7)))))
5951 (if (and (boundp 'org-time-was-given)
5952 (nth 2 tl))
5953 (setq org-time-was-given t))
5954 (if (< year 100) (setq year (+ 2000 year)))
5955 (if to-time
5956 (encode-time second minute hour day month year)
5957 (if (or (nth 1 tl) (nth 2 tl))
5958 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
5959 (format "%04d-%02d-%02d" year month day)))))
5961 (defun org-eval-in-calendar (form)
5962 "Eval FORM in the calendar window and return to current window.
5963 Also, store the cursor date in variable ans2."
5964 (let ((sw (selected-window)))
5965 (select-window (get-buffer-window "*Calendar*"))
5966 (eval form)
5967 (when (calendar-cursor-to-date)
5968 (let* ((date (calendar-cursor-to-date))
5969 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5970 (setq ans2 (format-time-string "%Y-%m-%d" time))))
5971 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
5972 (select-window sw)))
5974 (defun org-calendar-select ()
5975 "Return to `org-read-date' with the date currently selected.
5976 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5977 (interactive)
5978 (when (calendar-cursor-to-date)
5979 (let* ((date (calendar-cursor-to-date))
5980 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5981 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5982 (if (active-minibuffer-window) (exit-minibuffer))))
5984 (defun org-calendar-select-mouse (ev)
5985 "Return to `org-read-date' with the date currently selected.
5986 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5987 (interactive "e")
5988 (mouse-set-point ev)
5989 (when (calendar-cursor-to-date)
5990 (let* ((date (calendar-cursor-to-date))
5991 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5992 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5993 (if (active-minibuffer-window) (exit-minibuffer))))
5995 (defun org-check-deadlines (ndays)
5996 "Check if there are any deadlines due or past due.
5997 A deadline is considered due if it happens within `org-deadline-warning-days'
5998 days from today's date. If the deadline appears in an entry marked DONE,
5999 it is not shown. The prefix arg NDAYS can be used to test that many
6000 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
6001 (interactive "P")
6002 (let* ((org-warn-days
6003 (cond
6004 ((equal ndays '(4)) 100000)
6005 (ndays (prefix-numeric-value ndays))
6006 (t org-deadline-warning-days)))
6007 (case-fold-search nil)
6008 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
6009 (callback
6010 (lambda ()
6011 (and (let ((d1 (time-to-days (current-time)))
6012 (d2 (time-to-days
6013 (org-time-string-to-time (match-string 1)))))
6014 (< (- d2 d1) org-warn-days))
6015 (not (org-entry-is-done-p))))))
6016 (message "%d deadlines past-due or due within %d days"
6017 (org-occur regexp nil callback)
6018 org-warn-days)))
6020 (defun org-evaluate-time-range (&optional to-buffer)
6021 "Evaluate a time range by computing the difference between start and end.
6022 Normally the result is just printed in the echo area, but with prefix arg
6023 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
6024 If the time range is actually in a table, the result is inserted into the
6025 next column.
6026 For time difference computation, a year is assumed to be exactly 365
6027 days in order to avoid rounding problems."
6028 (interactive "P")
6030 (org-clock-update-time-maybe)
6031 (save-excursion
6032 (unless (org-at-date-range-p)
6033 (goto-char (point-at-bol))
6034 (re-search-forward org-tr-regexp (point-at-eol) t))
6035 (if (not (org-at-date-range-p))
6036 (error "Not at a time-stamp range, and none found in current line")))
6037 (let* ((ts1 (match-string 1))
6038 (ts2 (match-string 2))
6039 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
6040 (match-end (match-end 0))
6041 (time1 (org-time-string-to-time ts1))
6042 (time2 (org-time-string-to-time ts2))
6043 (t1 (time-to-seconds time1))
6044 (t2 (time-to-seconds time2))
6045 (diff (abs (- t2 t1)))
6046 (negative (< (- t2 t1) 0))
6047 ;; (ys (floor (* 365 24 60 60)))
6048 (ds (* 24 60 60))
6049 (hs (* 60 60))
6050 (fy "%dy %dd %02d:%02d")
6051 (fy1 "%dy %dd")
6052 (fd "%dd %02d:%02d")
6053 (fd1 "%dd")
6054 (fh "%02d:%02d")
6055 y d h m align)
6056 (if havetime
6057 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
6059 d (floor (/ diff ds)) diff (mod diff ds)
6060 h (floor (/ diff hs)) diff (mod diff hs)
6061 m (floor (/ diff 60)))
6062 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
6064 d (floor (+ (/ diff ds) 0.5))
6065 h 0 m 0))
6066 (if (not to-buffer)
6067 (message (org-make-tdiff-string y d h m))
6068 (when (org-at-table-p)
6069 (goto-char match-end)
6070 (setq align t)
6071 (and (looking-at " *|") (goto-char (match-end 0))))
6072 (if (looking-at
6073 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
6074 (replace-match ""))
6075 (if negative (insert " -"))
6076 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
6077 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
6078 (insert " " (format fh h m))))
6079 (if align (org-table-align))
6080 (message "Time difference inserted")))))
6082 (defun org-make-tdiff-string (y d h m)
6083 (let ((fmt "")
6084 (l nil))
6085 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
6086 l (push y l)))
6087 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
6088 l (push d l)))
6089 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
6090 l (push h l)))
6091 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
6092 l (push m l)))
6093 (apply 'format fmt (nreverse l))))
6095 (defun org-time-string-to-time (s)
6096 (apply 'encode-time (org-parse-time-string s)))
6098 (defun org-parse-time-string (s &optional nodefault)
6099 "Parse the standard Org-mode time string.
6100 This should be a lot faster than the normal `parse-time-string'.
6101 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
6102 hour and minute fields will be nil if not given."
6103 (if (string-match org-ts-regexp1 s)
6104 (list 0
6105 (if (or (match-beginning 8) (not nodefault))
6106 (string-to-number (or (match-string 8 s) "0")))
6107 (if (or (match-beginning 7) (not nodefault))
6108 (string-to-number (or (match-string 7 s) "0")))
6109 (string-to-number (match-string 4 s))
6110 (string-to-number (match-string 3 s))
6111 (string-to-number (match-string 2 s))
6112 nil nil nil)
6113 (make-list 9 0)))
6115 (defun org-timestamp-up (&optional arg)
6116 "Increase the date item at the cursor by one.
6117 If the cursor is on the year, change the year. If it is on the month or
6118 the day, change that.
6119 With prefix ARG, change by that many units."
6120 (interactive "p")
6121 (org-timestamp-change (prefix-numeric-value arg)))
6123 (defun org-timestamp-down (&optional arg)
6124 "Decrease the date item at the cursor by one.
6125 If the cursor is on the year, change the year. If it is on the month or
6126 the day, change that.
6127 With prefix ARG, change by that many units."
6128 (interactive "p")
6129 (org-timestamp-change (- (prefix-numeric-value arg))))
6131 (defun org-timestamp-up-day (&optional arg)
6132 "Increase the date in the time stamp by one day.
6133 With prefix ARG, change that many days."
6134 (interactive "p")
6135 (if (and (not (org-at-timestamp-p t))
6136 (org-on-heading-p))
6137 (org-todo 'up)
6138 (org-timestamp-change (prefix-numeric-value arg) 'day)))
6140 (defun org-timestamp-down-day (&optional arg)
6141 "Decrease the date in the time stamp by one day.
6142 With prefix ARG, change that many days."
6143 (interactive "p")
6144 (if (and (not (org-at-timestamp-p t))
6145 (org-on-heading-p))
6146 (org-todo 'down)
6147 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
6149 (defsubst org-pos-in-match-range (pos n)
6150 (and (match-beginning n)
6151 (<= (match-beginning n) pos)
6152 (>= (match-end n) pos)))
6154 (defun org-at-timestamp-p (&optional also-inactive)
6155 "Determine if the cursor is in or at a timestamp."
6156 (interactive)
6157 (let* ((tsr (if also-inactive org-ts-regexp3 org-ts-regexp2))
6158 (pos (point))
6159 (ans (or (looking-at tsr)
6160 (save-excursion
6161 (skip-chars-backward "^[<\n\r\t")
6162 (if (> (point) 1) (backward-char 1))
6163 (and (looking-at tsr)
6164 (> (- (match-end 0) pos) -1))))))
6165 (and (boundp 'org-ts-what)
6166 (setq org-ts-what
6167 (cond
6168 ((org-pos-in-match-range pos 2) 'year)
6169 ((org-pos-in-match-range pos 3) 'month)
6170 ((org-pos-in-match-range pos 7) 'hour)
6171 ((org-pos-in-match-range pos 8) 'minute)
6172 ((or (org-pos-in-match-range pos 4)
6173 (org-pos-in-match-range pos 5)) 'day)
6174 (t 'day))))
6175 ans))
6177 (defun org-timestamp-change (n &optional what)
6178 "Change the date in the time stamp at point.
6179 The date will be changed by N times WHAT. WHAT can be `day', `month',
6180 `year', `minute', `second'. If WHAT is not given, the cursor position
6181 in the timestamp determines what will be changed."
6182 (let ((fmt (car org-time-stamp-formats))
6183 org-ts-what
6184 (pos (point))
6185 ts time time0)
6186 (if (not (org-at-timestamp-p t))
6187 (error "Not at a timestamp"))
6188 (setq org-ts-what (or what org-ts-what))
6189 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
6190 (- (match-end 0) (match-beginning 0))))
6192 (cdr org-time-stamp-formats)
6193 (car org-time-stamp-formats)))
6194 (if (= (char-after (match-beginning 0)) ?\[)
6195 (setq fmt (concat "[" (substring fmt 1 -1) "]")))
6196 (setq ts (match-string 0))
6197 (replace-match "")
6198 (setq time0 (org-parse-time-string ts))
6199 (setq time
6200 (apply 'encode-time
6201 (append
6202 (list (or (car time0) 0))
6203 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
6204 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
6205 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
6206 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
6207 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
6208 (nthcdr 6 time0))))
6209 (if (eq what 'calendar)
6210 (let ((cal-date
6211 (save-excursion
6212 (save-match-data
6213 (set-buffer "*Calendar*")
6214 (calendar-cursor-to-date)))))
6215 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
6216 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
6217 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
6218 (setcar time0 (or (car time0) 0))
6219 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
6220 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
6221 (setq time (apply 'encode-time time0))))
6222 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
6223 (org-clock-update-time-maybe)
6224 (goto-char pos)
6225 ;; Try to recenter the calendar window, if any
6226 (if (and org-calendar-follow-timestamp-change
6227 (get-buffer-window "*Calendar*" t)
6228 (memq org-ts-what '(day month year)))
6229 (org-recenter-calendar (time-to-days time)))))
6231 (defun org-recenter-calendar (date)
6232 "If the calendar is visible, recenter it to DATE."
6233 (let* ((win (selected-window))
6234 (cwin (get-buffer-window "*Calendar*" t))
6235 (calendar-move-hook nil))
6236 (when cwin
6237 (select-window cwin)
6238 (calendar-goto-date (if (listp date) date
6239 (calendar-gregorian-from-absolute date)))
6240 (select-window win))))
6242 (defun org-goto-calendar (&optional arg)
6243 "Go to the Emacs calendar at the current date.
6244 If there is a time stamp in the current line, go to that date.
6245 A prefix ARG can be used to force the current date."
6246 (interactive "P")
6247 (let ((tsr org-ts-regexp) diff
6248 (calendar-move-hook nil)
6249 (view-calendar-holidays-initially nil)
6250 (view-diary-entries-initially nil))
6251 (if (or (org-at-timestamp-p)
6252 (save-excursion
6253 (beginning-of-line 1)
6254 (looking-at (concat ".*" tsr))))
6255 (let ((d1 (time-to-days (current-time)))
6256 (d2 (time-to-days
6257 (org-time-string-to-time (match-string 1)))))
6258 (setq diff (- d2 d1))))
6259 (calendar)
6260 (calendar-goto-today)
6261 (if (and diff (not arg)) (calendar-forward-day diff))))
6263 (defun org-date-from-calendar ()
6264 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
6265 If there is already a time stamp at the cursor position, update it."
6266 (interactive)
6267 (org-timestamp-change 0 'calendar))
6269 ;;; The clock for measuring work time.
6271 (defvar org-clock-marker (make-marker)
6272 "Marker recording the last clock-in.")
6274 (defun org-clock-in ()
6275 "Start the clock on the current item.
6276 If necessary, clock-out of the currently active clock."
6277 (interactive)
6278 (org-clock-out t)
6279 (let (ts)
6280 (save-excursion
6281 (org-back-to-heading t)
6282 (beginning-of-line 2)
6283 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
6284 (not (equal (match-string 1) org-clock-string)))
6285 (beginning-of-line 1))
6286 (insert "\n") (backward-char 1)
6287 (indent-relative)
6288 (insert org-clock-string " "
6289 (setq ts (concat "[" (format-time-string
6290 (substring
6291 (cdr org-time-stamp-formats) 1 -1)
6292 (current-time))
6293 "]")))
6294 (move-marker org-clock-marker (point))
6295 (message "Clock started at %s" ts))))
6297 (defun org-clock-out (&optional fail-quietly)
6298 "Stop the currently running clock.
6299 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
6300 (interactive)
6301 (catch 'exit
6302 (if (not (marker-buffer org-clock-marker))
6303 (if fail-quietly (throw 'exit t) (error "No active clock")))
6304 (let (ts te s h m)
6305 (save-excursion
6306 (set-buffer (marker-buffer org-clock-marker))
6307 (goto-char org-clock-marker)
6308 (beginning-of-line 1)
6309 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
6310 (equal (match-string 1) org-clock-string))
6311 (setq ts (match-string 2))
6312 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
6313 (goto-char org-clock-marker)
6314 (setq te (concat "[" (format-time-string
6315 (substring
6316 (cdr org-time-stamp-formats) 1 -1)
6317 (current-time))
6318 "]"))
6319 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
6320 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
6321 h (floor (/ s 3600))
6322 s (- s (* 3600 h))
6323 m (floor (/ s 60))
6324 s (- s (* 60 s)))
6325 (insert "--" te " => " (format "%2d:%02d" h m))
6326 (move-marker org-clock-marker nil)
6327 (org-add-log-maybe 'clock-out)
6328 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
6330 (defun org-clock-cancel ()
6331 "Cancel the running clock be removing the start timestamp."
6332 (interactive)
6333 (if (not (marker-buffer org-clock-marker))
6334 (error "No active clock"))
6335 (save-excursion
6336 (set-buffer (marker-buffer org-clock-marker))
6337 (goto-char org-clock-marker)
6338 (delete-region (1- (point-at-bol)) (point-at-eol)))
6339 (message "Clock canceled"))
6341 (defvar org-clock-file-total-minutes nil
6342 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
6343 (make-variable-buffer-local 'org-clock-file-total-minutes)
6345 (defun org-clock-sum (&optional tstart tend)
6346 "Sum the times for each subtree.
6347 Puts the resulting times in minutes as a text property on each headline."
6348 (interactive)
6349 (let* ((bmp (buffer-modified-p))
6350 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
6351 org-clock-string
6352 "[ \t]*\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)"))
6353 (lmax 30)
6354 (ltimes (make-vector lmax 0))
6355 (t1 0)
6356 (level 0)
6357 ts te dt
6358 time)
6359 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
6360 (save-excursion
6361 (goto-char (point-max))
6362 (while (re-search-backward re nil t)
6363 (if (match-end 2)
6364 ;; A time
6365 (setq ts (match-string 2)
6366 te (match-string 3)
6367 ts (time-to-seconds
6368 (apply 'encode-time (org-parse-time-string ts)))
6369 te (time-to-seconds
6370 (apply 'encode-time (org-parse-time-string te)))
6371 ts (if tstart (max ts tstart) ts)
6372 te (if tend (min te tend) te)
6373 dt (- te ts)
6374 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1))
6375 ;; A headline
6376 (setq level (- (match-end 1) (match-beginning 1)))
6377 (when (or (> t1 0) (> (aref ltimes level) 0))
6378 (loop for l from 0 to level do
6379 (aset ltimes l (+ (aref ltimes l) t1)))
6380 (setq t1 0 time (aref ltimes level))
6381 (loop for l from level to (1- lmax) do
6382 (aset ltimes l 0))
6383 (goto-char (match-beginning 0))
6384 (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
6385 (setq org-clock-file-total-minutes (aref ltimes 0)))
6386 (set-buffer-modified-p bmp)))
6388 (defun org-clock-display (&optional total-only)
6389 "Show subtree times in the entire buffer.
6390 If TOTAL-ONLY is non-nil, only show the total time for the entire file
6391 in the echo area."
6392 (interactive)
6393 (org-remove-clock-overlays)
6394 (let (time h m p)
6395 (org-clock-sum)
6396 (unless total-only
6397 (save-excursion
6398 (goto-char (point-min))
6399 (while (setq p (next-single-property-change (point) :org-clock-minutes))
6400 (goto-char p)
6401 (when (setq time (get-text-property p :org-clock-minutes))
6402 (org-put-clock-overlay time (funcall outline-level))))
6403 (setq h (/ org-clock-file-total-minutes 60)
6404 m (- org-clock-file-total-minutes (* 60 h)))
6405 ;; Arrange to remove the overlays upon next change.
6406 (when org-remove-highlights-with-change
6407 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
6408 nil 'local))))
6409 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
6411 (defvar org-clock-overlays nil)
6412 (make-variable-buffer-local 'org-clock-overlays)
6414 (defun org-put-clock-overlay (time &optional level)
6415 "Put an overlays on the current line, displaying TIME.
6416 If LEVEL is given, prefix time with a corresponding number of stars.
6417 This creates a new overlay and stores it in `org-clock-overlays', so that it
6418 will be easy to remove."
6419 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
6420 (l (if level (org-get-legal-level level 0) 0))
6421 (off 0)
6422 ov tx)
6423 (move-to-column c)
6424 (unless (eolp) (skip-chars-backward "^ \t"))
6425 (skip-chars-backward " \t")
6426 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
6427 tx (concat (buffer-substring (1- (point)) (point))
6428 (make-string (+ off (max 0 (- c (current-column)))) ?.)
6429 (org-add-props (format "%s %2d:%02d%s"
6430 (make-string l ?*) h m
6431 (make-string (- 10 l) ?\ ))
6432 '(face secondary-selection))
6433 ""))
6434 (org-overlay-put ov 'display tx)
6435 (push ov org-clock-overlays)))
6437 (defun org-remove-clock-overlays (&optional beg end noremove)
6438 "Remove the occur highlights from the buffer.
6439 BEG and END are ignored. If NOREMOVE is nil, remove this function
6440 from the `before-change-functions' in the current buffer."
6441 (interactive)
6442 (unless org-inhibit-highlight-removal
6443 (mapc 'org-delete-overlay org-clock-overlays)
6444 (setq org-clock-overlays nil)
6445 (unless noremove
6446 (remove-hook 'before-change-functions
6447 'org-remove-clock-overlays 'local))))
6449 (defun org-clock-out-if-current ()
6450 "Clock out if the current entry contains the running clock.
6451 This is used to stop the clock after a TODO entry is marked DONE."
6452 (when (and (equal state org-done-string)
6453 (equal (marker-buffer org-clock-marker) (current-buffer))
6454 (< (point) org-clock-marker)
6455 (> (save-excursion (outline-next-heading) (point))
6456 org-clock-marker))
6457 ;; Clock out, but don't accept a logging message for this.
6458 (let ((org-log-done (if (and (listp org-log-done)
6459 (member 'clock-out org-log-done))
6460 '(done)
6461 org-log-done)))
6462 (org-clock-out))))
6464 (add-hook 'org-after-todo-state-change-hook
6465 'org-clock-out-if-current)
6467 (defun org-check-running-clock ()
6468 "Check if the current buffer contains the running clock.
6469 If yes, offer to stop it and to save the buffer with the changes."
6470 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
6471 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
6472 (buffer-name))))
6473 (org-clock-out)
6474 (when (y-or-n-p "Save changed buffer?")
6475 (save-buffer))))
6477 (defun org-clock-report ()
6478 "Create a table containing a report about clocked time.
6479 If the buffer contains lines
6480 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
6482 #+END: clocktable
6483 then the table will be inserted between these lines, replacing whatever
6484 is was there before. If these lines are not in the buffer, the table
6485 is inserted at point, surrounded by the special lines.
6486 The BEGIN line can contain parameters. Allowed are:
6487 :maxlevel The maximum level to be included in the table. Default is 3.
6488 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
6489 (interactive)
6490 (org-remove-clock-overlays)
6491 (unless (org-find-dblock "clocktable")
6492 (org-create-dblock (list :name "clocktable"
6493 :maxlevel 2 :emphasize nil)))
6494 (org-update-dblock))
6496 (defun org-clock-update-time-maybe ()
6497 "If this is a CLOCK line, update it and return t.
6498 Otherwise, return nil."
6499 (interactive)
6500 (save-excursion
6501 (beginning-of-line 1)
6502 (skip-chars-forward " \t")
6503 (when (looking-at org-clock-string)
6504 (let ((re (concat "[ \t]*" org-clock-string
6505 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
6506 "\\([ \t]*=>.*\\)?"))
6507 ts te h m s)
6508 (if (not (looking-at re))
6510 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
6511 (end-of-line 1)
6512 (setq ts (match-string 1)
6513 te (match-string 2))
6514 (setq s (- (time-to-seconds
6515 (apply 'encode-time (org-parse-time-string te)))
6516 (time-to-seconds
6517 (apply 'encode-time (org-parse-time-string ts))))
6518 h (floor (/ s 3600))
6519 s (- s (* 3600 h))
6520 m (floor (/ s 60))
6521 s (- s (* 60 s)))
6522 (insert " => " (format "%2d:%02d" h m))
6523 t)))))
6525 (defun org-clock-special-range (key &optional time as-strings)
6526 "Return two times bordering a special time range.
6527 Key is a symbol specifying the range and can be one of `today', `yesterday',
6528 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
6529 A week starts Monday 0:00 and ends Sunday 24:00.
6530 The range is determined relative to TIME. TIME defaults to the current time.
6531 The return value is a cons cell with two internal times like the ones
6532 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
6533 the returned times will be formatted strings."
6534 (let* ((tm (decode-time (or time (current-time))))
6535 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
6536 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
6537 (dow (nth 6 tm))
6538 s1 m1 h1 d1 month1 y1 diff ts te fm)
6539 (cond
6540 ((eq key 'today)
6541 (setq h 0 m 0 h1 24 m1 0))
6542 ((eq key 'yesterday)
6543 (setq d (1- d) h 0 m 0 h1 24 m1 0))
6544 ((eq key 'thisweek)
6545 (setq diff (if (= dow 0) 6 (1- dow))
6546 m 0 h 0 d (- d diff) d1 (+ 7 d)))
6547 ((eq key 'lastweek)
6548 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
6549 m 0 h 0 d (- d diff) d1 (+ 7 d)))
6550 ((eq key 'thismonth)
6551 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
6552 ((eq key 'lastmonth)
6553 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
6554 ((eq key 'thisyear)
6555 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
6556 ((eq key 'lastyear)
6557 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
6558 (t (error "No such time block %s" key)))
6559 (setq ts (encode-time s m h d month y)
6560 te (encode-time (or s1 s) (or m1 m) (or h1 h)
6561 (or d1 d) (or month1 month) (or y1 y)))
6562 (setq fm (cdr org-time-stamp-formats))
6563 (if as-strings
6564 (cons (format-time-string fm ts) (format-time-string fm te))
6565 (cons ts te))))
6567 (defun org-dblock-write:clocktable (params)
6568 "Write the standard clocktable."
6569 (let ((hlchars '((1 . "*") (2 . ?/)))
6570 (emph nil)
6571 (ins (make-marker))
6572 ipos time h m p level hlc hdl maxlevel
6573 ts te cc block)
6574 (setq maxlevel (or (plist-get params :maxlevel) 3)
6575 emph (plist-get params :emphasize)
6576 ts (plist-get params :tstart)
6577 te (plist-get params :tend)
6578 block (plist-get params :block))
6579 (when block
6580 (setq cc (org-clock-special-range block nil t)
6581 ts (car cc) te (cdr cc)))
6582 (if ts (setq ts (time-to-seconds
6583 (apply 'encode-time (org-parse-time-string ts)))))
6584 (if te (setq te (time-to-seconds
6585 (apply 'encode-time (org-parse-time-string te)))))
6586 (move-marker ins (point))
6587 (setq ipos (point))
6588 (insert-before-markers "Clock summary at ["
6589 (substring
6590 (format-time-string (cdr org-time-stamp-formats))
6591 1 -1)
6592 "]."
6593 (if block
6594 (format " Considered range is /%s/." block)
6596 "\n\n|L|Headline|Time|\n")
6597 (org-clock-sum ts te)
6598 (setq h (/ org-clock-file-total-minutes 60)
6599 m (- org-clock-file-total-minutes (* 60 h)))
6600 (insert-before-markers "|-\n|0|" "*Total file time*| "
6601 (format "*%d:%02d*" h m)
6602 "|\n")
6603 (goto-char (point-min))
6604 (while (setq p (next-single-property-change (point) :org-clock-minutes))
6605 (goto-char p)
6606 (when (setq time (get-text-property p :org-clock-minutes))
6607 (save-excursion
6608 (beginning-of-line 1)
6609 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[0-9a-zA-Z_@:]+:\\)?[ \t]*$")
6610 (setq level (- (match-end 1) (match-beginning 1)))
6611 (<= level maxlevel))
6612 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
6613 hdl (match-string 2)
6614 h (/ time 60)
6615 m (- time (* 60 h)))
6616 (goto-char ins)
6617 (if (= level 1) (insert-before-markers "|-\n"))
6618 (insert-before-markers
6619 "| " (int-to-string level) "|" hlc hdl hlc " |"
6620 (make-string (1- level) ?|)
6622 (format "%d:%02d" h m)
6624 " |\n")))))
6625 (goto-char ins)
6626 (backward-delete-char 1)
6627 (goto-char ipos)
6628 (skip-chars-forward "^|")
6629 (org-table-align)))
6631 (defun org-collect-clock-time-entries ()
6632 "Return an internal list with clocking information.
6633 This list has one entry for each CLOCK interval.
6634 FIXME: describe the elements."
6635 (interactive)
6636 (let ((re (concat "^[ \t]*" org-clock-string
6637 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
6638 rtn beg end next cont level title total closedp leafp
6639 clockpos titlepos h m donep)
6640 (save-excursion
6641 (org-clock-sum)
6642 (goto-char (point-min))
6643 (while (re-search-forward re nil t)
6644 (setq clockpos (match-beginning 0)
6645 beg (match-string 1) end (match-string 2)
6646 cont (match-end 0))
6647 (setq beg (apply 'encode-time (org-parse-time-string beg))
6648 end (apply 'encode-time (org-parse-time-string end)))
6649 (org-back-to-heading t)
6650 (setq donep (org-entry-is-done-p))
6651 (setq titlepos (point)
6652 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
6653 h (/ total 60) m (- total (* 60 h))
6654 total (cons h m))
6655 (looking-at "\\(\\*+\\) +\\(.*\\)")
6656 (setq level (- (match-end 1) (match-beginning 1))
6657 title (org-match-string-no-properties 2))
6658 (save-excursion (outline-next-heading) (setq next (point)))
6659 (setq closedp (re-search-forward org-closed-time-regexp next t))
6660 (goto-char next)
6661 (setq leafp (and (looking-at "^\\*+ ")
6662 (<= (- (match-end 0) (point)) level)))
6663 (push (list beg end clockpos closedp donep
6664 total title titlepos level leafp)
6665 rtn)
6666 (goto-char cont)))
6667 (nreverse rtn)))
6669 ;;; Agenda, and Diary Integration
6671 ;;; Define the mode
6673 (defvar org-agenda-mode-map (make-sparse-keymap)
6674 "Keymap for `org-agenda-mode'.")
6676 (defvar org-agenda-menu) ; defined later in this file.
6677 (defvar org-agenda-follow-mode nil)
6678 (defvar org-agenda-show-log nil)
6679 (defvar org-agenda-redo-command nil)
6680 (defvar org-agenda-mode-hook nil)
6681 (defvar org-agenda-type nil)
6682 (defvar org-agenda-force-single-file nil)
6684 (defun org-agenda-mode ()
6685 "Mode for time-sorted view on action items in Org-mode files.
6687 The following commands are available:
6689 \\{org-agenda-mode-map}"
6690 (interactive)
6691 (kill-all-local-variables)
6692 (setq major-mode 'org-agenda-mode)
6693 (setq mode-name "Org-Agenda")
6694 (use-local-map org-agenda-mode-map)
6695 (easy-menu-add org-agenda-menu)
6696 (if org-startup-truncated (setq truncate-lines t))
6697 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
6698 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
6699 (unless org-agenda-keep-modes
6700 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
6701 org-agenda-show-log nil))
6702 (easy-menu-change
6703 '("Agenda") "Agenda Files"
6704 (append
6705 (list
6706 (vector
6707 (if (get 'org-agenda-files 'org-restrict)
6708 "Restricted to single file"
6709 "Edit File List")
6710 '(org-edit-agenda-file-list)
6711 (not (get 'org-agenda-files 'org-restrict)))
6712 "--")
6713 (mapcar 'org-file-menu-entry (org-agenda-files))))
6714 (org-agenda-set-mode-name)
6715 (apply
6716 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
6717 (list 'org-agenda-mode-hook)))
6719 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
6720 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
6721 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
6722 (define-key org-agenda-mode-map " " 'org-agenda-show)
6723 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
6724 (define-key org-agenda-mode-map "o" 'delete-other-windows)
6725 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
6726 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
6727 (define-key org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
6728 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
6729 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
6730 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
6731 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
6732 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
6733 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
6734 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
6735 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
6737 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
6738 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
6739 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
6740 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
6741 (while l (define-key org-agenda-mode-map
6742 (int-to-string (pop l)) 'digit-argument)))
6744 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
6745 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
6746 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
6747 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
6748 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
6749 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
6750 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
6751 (define-key org-agenda-mode-map "s" 'org-save-all-org-buffers)
6752 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
6753 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
6754 (define-key org-agenda-mode-map "n" 'next-line)
6755 (define-key org-agenda-mode-map "p" 'previous-line)
6756 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
6757 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
6758 (define-key org-agenda-mode-map "," 'org-agenda-priority)
6759 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
6760 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
6761 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
6762 (eval-after-load "calendar"
6763 '(define-key calendar-mode-map org-calendar-to-agenda-key
6764 'org-calendar-goto-agenda))
6765 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
6766 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
6767 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
6768 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
6769 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
6770 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
6771 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
6772 (define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
6773 (define-key org-agenda-mode-map "O" 'org-clock-out)
6774 (define-key org-agenda-mode-map "X" 'org-clock-cancel)
6775 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
6776 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
6777 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
6778 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
6779 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
6780 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
6781 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
6782 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
6783 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
6784 "Local keymap for agenda entries from Org-mode.")
6786 (define-key org-agenda-keymap
6787 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
6788 (define-key org-agenda-keymap
6789 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
6790 (when org-agenda-mouse-1-follows-link
6791 (define-key org-agenda-keymap [follow-link] 'mouse-face))
6792 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
6793 '("Agenda"
6794 ("Agenda Files")
6795 "--"
6796 ["Show" org-agenda-show t]
6797 ["Go To (other window)" org-agenda-goto t]
6798 ["Go To (this window)" org-agenda-switch-to t]
6799 ["Follow Mode" org-agenda-follow-mode
6800 :style toggle :selected org-agenda-follow-mode :active t]
6801 "--"
6802 ["Cycle TODO" org-agenda-todo t]
6803 ("Tags"
6804 ["Show all Tags" org-agenda-show-tags t]
6805 ["Set Tags" org-agenda-set-tags t])
6806 ("Schedule"
6807 ["Schedule" org-agenda-schedule t]
6808 ["Set Deadline" org-agenda-deadline t]
6809 "--"
6810 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
6811 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
6812 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
6813 ("Priority"
6814 ["Set Priority" org-agenda-priority t]
6815 ["Increase Priority" org-agenda-priority-up t]
6816 ["Decrease Priority" org-agenda-priority-down t]
6817 ["Show Priority" org-agenda-show-priority t])
6818 "--"
6819 ;; ["New agenda command" org-agenda t]
6820 ["Rebuild buffer" org-agenda-redo t]
6821 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
6822 "--"
6823 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
6824 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
6825 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
6826 "--"
6827 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
6828 :style radio :selected (equal org-agenda-ndays 1)]
6829 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
6830 :style radio :selected (equal org-agenda-ndays 7)]
6831 "--"
6832 ["Show Logbook entries" org-agenda-log-mode
6833 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
6834 ["Include Diary" org-agenda-toggle-diary
6835 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
6836 ["Use Time Grid" org-agenda-toggle-time-grid
6837 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
6838 "--"
6839 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
6840 ("Calendar Commands"
6841 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
6842 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
6843 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
6844 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
6845 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
6846 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
6847 "--"
6848 ["Quit" org-agenda-quit t]
6849 ["Exit and Release Buffers" org-agenda-exit t]
6852 (defvar org-agenda-restrict nil)
6853 (defvar org-agenda-restrict-begin (make-marker))
6854 (defvar org-agenda-restrict-end (make-marker))
6855 (defvar org-agenda-last-dispatch-buffer nil)
6857 ;;;###autoload
6858 (defun org-agenda (arg)
6859 "Dispatch agenda commands to collect entries to the agenda buffer.
6860 Prompts for a character to select a command. Any prefix arg will be passed
6861 on to the selected command. The default selections are:
6863 a Call `org-agenda-list' to display the agenda for current day or week.
6864 t Call `org-todo-list' to display the global todo list.
6865 T Call `org-todo-list' to display the global todo list, select only
6866 entries with a specific TODO keyword (the user gets a prompt).
6867 m Call `org-tags-view' to display headlines with tags matching
6868 a condition (the user is prompted for the condition).
6869 M Like `m', but select only TODO entries, no ordinary headlines.
6870 l Create a timeeline for the current buffer.
6872 More commands can be added by configuring the variable
6873 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
6874 searches can be pre-defined in this way.
6876 If the current buffer is in Org-mode and visiting a file, you can also
6877 first press `1' to indicate that the agenda should be temporarily (until the
6878 next use of \\[org-agenda]) restricted to the current file."
6879 (interactive "P")
6880 (catch 'exit
6881 (let ((restrict-ok (and buffer-file-name (org-mode-p)))
6882 (buf (current-buffer))
6883 (bfn buffer-file-name)
6884 (custom org-agenda-custom-commands)
6885 c entry key type match lprops)
6886 ;; Turn off restriction
6887 (put 'org-agenda-files 'org-restrict nil)
6888 (setq org-agenda-restrict nil)
6889 (move-marker org-agenda-restrict-begin nil)
6890 (move-marker org-agenda-restrict-end nil)
6891 ;; Remember where this call originated
6892 (setq org-agenda-last-dispatch-buffer (current-buffer))
6893 (save-window-excursion
6894 (delete-other-windows)
6895 (switch-to-buffer-other-window " *Agenda Commands*")
6896 (erase-buffer)
6897 (insert
6898 "Press key for an agenda command:
6899 --------------------------------
6900 a Agenda for current week or day
6901 t List of all TODO entries T Entries with special TODO kwd
6902 m Match a TAGS query M Like m, but only TODO entries
6903 L Timeline for current buffer C Configure custom agenda commands")
6904 (while (setq entry (pop custom))
6905 (setq key (car entry) type (nth 1 entry) match (nth 2 entry))
6906 (insert (format "\n%-4s%-14s: %s"
6908 (cond
6909 ((stringp type) type)
6910 ((eq type 'tags) "Tags query")
6911 ((eq type 'todo) "TODO keyword")
6912 ((eq type 'tags-tree) "Tags tree")
6913 ((eq type 'todo-tree) "TODO kwd tree")
6914 ((eq type 'occur-tree) "Occur tree")
6915 (t "???"))
6916 (if (stringp match)
6917 (org-add-props match nil 'face 'org-warning)
6918 (format "set of %d commands" (+ -2 (length entry)))))))
6919 (if restrict-ok
6920 (insert "\n"
6921 (org-add-props "1 Restrict call to current buffer 0 Restrict call to region or subtree" nil 'face 'org-table)))
6923 (goto-char (point-min))
6924 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
6925 (message "Press key for agenda command%s"
6926 (if restrict-ok ", or [1] or [0] to restrict" ""))
6927 (setq c (read-char-exclusive))
6928 (message "")
6929 (when (memq c '(?L ?1 ?0))
6930 (if restrict-ok
6931 (put 'org-agenda-files 'org-restrict (list bfn))
6932 (error "Cannot restrict agenda to current buffer"))
6933 (with-current-buffer " *Agenda Commands*"
6934 (goto-char (point-max))
6935 (delete-region (point-at-bol) (point))
6936 (goto-char (point-min)))
6937 (when (eq c ?0)
6938 (setq org-agenda-restrict t)
6939 (with-current-buffer buf
6940 (if (org-region-active-p)
6941 (progn
6942 (move-marker org-agenda-restrict-begin (region-beginning))
6943 (move-marker org-agenda-restrict-end (region-end)))
6944 (save-excursion
6945 (org-back-to-heading t)
6946 (move-marker org-agenda-restrict-begin (point))
6947 (move-marker org-agenda-restrict-end
6948 (progn (org-end-of-subtree t)))))))
6949 (unless (eq c ?L)
6950 (message "Press key for agenda command%s"
6951 (if restrict-ok " (restricted to current file)" ""))
6952 (setq c (read-char-exclusive)))
6953 (message "")))
6954 (require 'calendar) ; FIXME: can we avoid this for some commands?
6955 ;; For example the todo list should not need it (but does...)
6956 (cond
6957 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
6958 ((equal c ?a) (call-interactively 'org-agenda-list))
6959 ((equal c ?t) (call-interactively 'org-todo-list))
6960 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
6961 ((equal c ?m) (call-interactively 'org-tags-view))
6962 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
6963 ((equal c ?L)
6964 (unless restrict-ok
6965 (error "This is not an Org-mode file"))
6966 (org-call-with-arg 'org-timeline arg))
6967 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
6968 (if (symbolp (nth 1 entry))
6969 (progn
6970 (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
6971 lprops (nth 3 entry))
6972 (cond
6973 ((eq type 'tags)
6974 (org-let lprops '(org-tags-view current-prefix-arg match)))
6975 ((eq type 'tags-todo)
6976 (org-let lprops '(org-tags-view '(4) match)))
6977 ((eq type 'todo)
6978 (org-let lprops '(org-todo-list match)))
6979 ((eq type 'tags-tree)
6980 (org-check-for-org-mode)
6981 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
6982 ((eq type 'todo-tree)
6983 (org-check-for-org-mode)
6984 (org-let lprops
6985 '(org-occur (concat "^" outline-regexp "[ \t]*"
6986 (regexp-quote match) "\\>"))))
6987 ((eq type 'occur-tree)
6988 (org-check-for-org-mode)
6989 (org-let lprops '(org-occur match)))
6990 (t (error "Invalid custom agenda command type %s" type))))
6991 (org-run-agenda-series (cddr entry))))
6992 (t (error "Invalid key"))))))
6994 ;; FIXME: what is the meaning of WINDOW?????
6995 (defun org-run-agenda-series (series &optional window)
6996 (org-prepare-agenda)
6997 (let* ((org-agenda-multi t)
6998 (redo (list 'org-run-agenda-series (list 'quote series)))
6999 (org-select-agenda-window t)
7000 (cmds (car series))
7001 (gprops (nth 1 series))
7002 cmd type match lprops)
7003 (while (setq cmd (pop cmds))
7004 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
7005 (cond
7006 ((eq type 'agenda)
7007 (call-interactively 'org-agenda-list))
7008 ((eq type 'alltodo)
7009 (call-interactively 'org-todo-list))
7010 ((eq type 'tags)
7011 (org-let2 gprops lprops
7012 '(org-tags-view current-prefix-arg match)))
7013 ((eq type 'tags-todo)
7014 (org-let2 gprops lprops
7015 '(org-tags-view '(4) match)))
7016 ((eq type 'todo)
7017 (org-let2 gprops lprops
7018 '(org-todo-list match)))
7019 (t (error "Invalid type in command series"))))
7020 (widen)
7021 (setq org-agenda-redo-command redo)
7022 (goto-char (point-min)))
7023 (org-finalize-agenda))
7025 ;;;###autoload
7026 (defmacro org-batch-agenda (cmd-key &rest parameters)
7027 "Run an agenda command in batch mode, send result to STDOUT.
7028 CMD-KEY is a string that is also a key in `org-agenda-custom-commands'.
7029 Paramters are alternating variable names and values that will be bound
7030 before running the agenda command."
7031 (let (pars)
7032 (while parameters
7033 (push (list (pop parameters) (if parameters (pop parameters))) pars))
7034 (flet ((read-char-exclusive () (string-to-char cmd-key)))
7035 (eval (list 'let (nreverse pars) '(org-agenda nil))))
7036 (set-buffer "*Org Agenda*")
7037 (princ (buffer-string))))
7039 (defun org-check-for-org-mode ()
7040 "Make sure current buffer is in org-mode. Error if not."
7041 (or (org-mode-p)
7042 (error "Cannot execute org-mode agenda command on buffer in %s."
7043 major-mode)))
7045 (defun org-fit-agenda-window ()
7046 "Fit the window to the buffer size."
7047 (and org-fit-agenda-window
7048 (memq org-agenda-window-setup '(reorganize-frame))
7049 (fboundp 'fit-window-to-buffer)
7050 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
7051 (/ (frame-height) 2))))
7053 (defun org-agenda-files (&optional unrestricted)
7054 "Get the list of agenda files.
7055 Optional UNRESTRICTED means return the full list even if a restriction
7056 is currently in place."
7057 (cond
7058 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
7059 ((stringp org-agenda-files) (org-read-agenda-file-list))
7060 ((listp org-agenda-files) org-agenda-files)
7061 (t (error "Invalid value of `org-agenda-files'"))))
7063 (defvar org-window-configuration)
7065 (defun org-edit-agenda-file-list ()
7066 "Edit the list of agenda files.
7067 Depending on setup, this either uses customize to edit the variable
7068 `org-agenda-files', or it visits the file that is holding the list. In the
7069 latter case, the buffer is set up in a way that saving it automatically kills
7070 the buffer and restores the previous window configuration."
7071 (interactive)
7072 (if (stringp org-agenda-files)
7073 (let ((cw (current-window-configuration)))
7074 (find-file org-agenda-files)
7075 (org-set-local 'org-window-configuration cw)
7076 (org-add-hook 'after-save-hook
7077 (lambda ()
7078 (set-window-configuration
7079 (prog1 org-window-configuration
7080 (kill-buffer (current-buffer))))
7081 (org-install-agenda-files-menu)
7082 (message "New agenda file list installed"))
7083 nil 'local)
7084 (message (substitute-command-keys
7085 "Edit list and finish with \\[save-buffer]")))
7086 (customize-variable 'org-agenda-files)))
7088 (defun org-store-new-agenda-file-list (list)
7089 "Set new value for the agenda file list and save it correcly."
7090 (if (stringp org-agenda-files)
7091 (let ((f org-agenda-files) b)
7092 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
7093 (with-temp-file f
7094 (insert (mapconcat 'identity list "\n") "\n")))
7095 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
7096 (setq org-agenda-files list)
7097 (customize-save-variable 'org-agenda-files org-agenda-files))))
7099 (defun org-read-agenda-file-list ()
7100 "Read the list of agenda files from a file."
7101 (when (stringp org-agenda-files)
7102 (with-temp-buffer
7103 (insert-file-contents org-agenda-files)
7104 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
7106 (defvar org-agenda-markers nil
7107 "List of all currently active markers created by `org-agenda'.")
7108 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
7109 "Creation time of the last agenda marker.")
7111 (defun org-agenda-new-marker (&optional pos)
7112 "Return a new agenda marker.
7113 Org-mode keeps a list of these markers and resets them when they are
7114 no longer in use."
7115 (let ((m (copy-marker (or pos (point)))))
7116 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
7117 (push m org-agenda-markers)
7120 (defun org-agenda-maybe-reset-markers (&optional force)
7121 "Reset markers created by `org-agenda'. But only if they are old enough."
7122 (if (or (and force (not org-agenda-multi))
7123 (> (- (time-to-seconds (current-time))
7124 org-agenda-last-marker-time)
7126 (while org-agenda-markers
7127 (move-marker (pop org-agenda-markers) nil))))
7129 (defvar org-agenda-new-buffers nil
7130 "Buffers created to visit agenda files.")
7132 (defun org-get-agenda-file-buffer (file)
7133 "Get a buffer visiting FILE. If the buffer needs to be created, add
7134 it to the list of buffers which might be released later."
7135 (let ((buf (find-buffer-visiting file)))
7136 (if buf
7137 buf ; just return it
7138 ;; Make a new buffer and remember it
7139 (setq buf (find-file-noselect file))
7140 (if buf (push buf org-agenda-new-buffers))
7141 buf)))
7143 (defun org-release-buffers (blist)
7144 "Release all buffers in list, asking the user for confirmation when needed.
7145 When a buffer is unmodified, it is just killed. When modified, it is saved
7146 \(if the user agrees) and then killed."
7147 (let (buf file)
7148 (while (setq buf (pop blist))
7149 (setq file (buffer-file-name buf))
7150 (when (and (buffer-modified-p buf)
7151 file
7152 (y-or-n-p (format "Save file %s? " file)))
7153 (with-current-buffer buf (save-buffer)))
7154 (kill-buffer buf))))
7156 (defun org-timeline (&optional include-all)
7157 "Show a time-sorted view of the entries in the current org file.
7158 Only entries with a time stamp of today or later will be listed. With
7159 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
7160 under the current date.
7161 If the buffer contains an active region, only check the region for
7162 dates."
7163 (interactive "P")
7164 (require 'calendar)
7165 (org-compile-prefix-format 'timeline)
7166 (org-set-sorting-strategy 'timeline)
7167 (let* ((dopast t)
7168 (dotodo include-all)
7169 (doclosed org-agenda-show-log)
7170 (entry buffer-file-name)
7171 (date (calendar-current-date))
7172 (win (selected-window))
7173 (pos1 (point))
7174 (beg (if (org-region-active-p) (region-beginning) (point-min)))
7175 (end (if (org-region-active-p) (region-end) (point-max)))
7176 (day-numbers (org-get-all-dates beg end 'no-ranges
7177 t doclosed ; always include today
7178 org-timeline-show-empty-dates))
7179 (today (time-to-days (current-time)))
7180 (past t)
7181 args
7182 s e rtn d emptyp)
7183 (setq org-agenda-redo-command
7184 (list 'progn
7185 (list 'switch-to-buffer-other-window (current-buffer))
7186 (list 'org-timeline (list 'quote include-all))))
7187 (if (not dopast)
7188 ;; Remove past dates from the list of dates.
7189 (setq day-numbers (delq nil (mapcar (lambda(x)
7190 (if (>= x today) x nil))
7191 day-numbers))))
7192 (org-prepare-agenda)
7193 (if doclosed (push :closed args))
7194 (push :timestamp args)
7195 (if dotodo (push :todo args))
7196 (while (setq d (pop day-numbers))
7197 (if (and (listp d) (eq (car d) :omitted))
7198 (progn
7199 (setq s (point))
7200 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
7201 (put-text-property s (1- (point)) 'face 'org-level-3))
7202 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
7203 (if (and (>= d today)
7204 dopast
7205 past)
7206 (progn
7207 (setq past nil)
7208 (insert (make-string 79 ?-) "\n")))
7209 (setq date (calendar-gregorian-from-absolute d))
7210 (setq s (point))
7211 (setq rtn (and (not emptyp)
7212 (apply 'org-agenda-get-day-entries
7213 entry date args)))
7214 (if (or rtn (equal d today) org-timeline-show-empty-dates)
7215 (progn
7216 (insert (calendar-day-name date) " "
7217 (number-to-string (extract-calendar-day date)) " "
7218 (calendar-month-name (extract-calendar-month date)) " "
7219 (number-to-string (extract-calendar-year date)) "\n")
7220 (put-text-property s (1- (point)) 'face
7221 'org-level-3)
7222 (if (equal d today)
7223 (put-text-property s (1- (point)) 'org-today t))
7224 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
7225 (put-text-property s (1- (point)) 'day d)))))
7226 (goto-char (point-min))
7227 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
7228 (point-min)))
7229 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
7230 (org-finalize-agenda)
7231 (setq buffer-read-only t)
7232 (when (not org-select-agenda-window)
7233 (select-window win)
7234 (goto-char pos1))))
7236 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
7237 (defvar org-agenda-last-arguments nil
7238 "The arguments of the previous call to org-agenda")
7240 ;;;###autoload
7241 (defun org-agenda-list (&optional include-all start-day ndays)
7242 "Produce a weekly view from all files in variable `org-agenda-files'.
7243 The view will be for the current week, but from the overview buffer you
7244 will be able to go to other weeks.
7245 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
7246 also be shown, under the current date.
7247 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
7248 on the days are also shown. See the variable `org-log-done' for how
7249 to turn on logging.
7250 START-DAY defaults to TODAY, or to the most recent match for the weekday
7251 given in `org-agenda-start-on-weekday'.
7252 NDAYS defaults to `org-agenda-ndays'."
7253 (interactive "P")
7254 (if org-agenda-overriding-arguments
7255 (setq include-all (car org-agenda-overriding-arguments)
7256 start-day (nth 1 org-agenda-overriding-arguments)
7257 ndays (nth 2 org-agenda-overriding-arguments)))
7258 (setq org-agenda-last-arguments (list include-all start-day ndays))
7259 (org-compile-prefix-format 'agenda)
7260 (org-set-sorting-strategy 'agenda)
7261 (require 'calendar)
7262 (let* ((org-agenda-start-on-weekday
7263 (if (or (equal ndays 1)
7264 (and (null ndays) (equal 1 org-agenda-ndays)))
7265 nil org-agenda-start-on-weekday))
7266 (thefiles (org-agenda-files))
7267 (files thefiles)
7268 (win (selected-window))
7269 (today (time-to-days (current-time)))
7270 (sd (or start-day today))
7271 (start (if (or (null org-agenda-start-on-weekday)
7272 (< org-agenda-ndays 7))
7274 (let* ((nt (calendar-day-of-week
7275 (calendar-gregorian-from-absolute sd)))
7276 (n1 org-agenda-start-on-weekday)
7277 (d (- nt n1)))
7278 (- sd (+ (if (< d 0) 7 0) d)))))
7279 (day-numbers (list start))
7280 ;FIXME (inhibit-redisplay t)
7281 s e rtn rtnall file date d start-pos end-pos todayp nd)
7282 (setq org-agenda-redo-command
7283 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
7284 ;; Make the list of days
7285 (setq ndays (or ndays org-agenda-ndays)
7286 nd ndays)
7287 (while (> ndays 1)
7288 (push (1+ (car day-numbers)) day-numbers)
7289 (setq ndays (1- ndays)))
7290 (setq day-numbers (nreverse day-numbers))
7291 (org-prepare-agenda)
7292 (org-set-local 'starting-day (car day-numbers))
7293 (org-set-local 'include-all-loc include-all)
7294 (when (and (or include-all org-agenda-include-all-todo)
7295 (member today day-numbers))
7296 (setq files thefiles
7297 rtnall nil)
7298 (while (setq file (pop files))
7299 (catch 'nextfile
7300 (org-check-agenda-file file)
7301 (setq date (calendar-gregorian-from-absolute today)
7302 rtn (org-agenda-get-day-entries
7303 file date :todo))
7304 (setq rtnall (append rtnall rtn))))
7305 (when rtnall
7306 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
7307 (add-text-properties (point-min) (1- (point))
7308 (list 'face 'org-level-3))
7309 (insert (org-finalize-agenda-entries rtnall) "\n")))
7310 (setq s (point))
7311 (insert (if (= nd 7) "Week-" "Day-") "agenda:\n")
7312 (add-text-properties s (1- (point)) (list 'face 'org-level-3))
7313 (while (setq d (pop day-numbers))
7314 (setq date (calendar-gregorian-from-absolute d)
7315 s (point))
7316 (if (or (setq todayp (= d today))
7317 (and (not start-pos) (= d sd)))
7318 (setq start-pos (point))
7319 (if (and start-pos (not end-pos))
7320 (setq end-pos (point))))
7321 (setq files thefiles
7322 rtnall nil)
7323 (while (setq file (pop files))
7324 (catch 'nextfile
7325 (org-check-agenda-file file)
7326 (if org-agenda-show-log
7327 (setq rtn (org-agenda-get-day-entries
7328 file date
7329 :deadline :scheduled :timestamp :closed))
7330 (setq rtn (org-agenda-get-day-entries
7331 file date
7332 :deadline :scheduled :timestamp)))
7333 (setq rtnall (append rtnall rtn))))
7334 (if org-agenda-include-diary
7335 (progn
7336 (require 'diary-lib)
7337 (setq rtn (org-get-entries-from-diary date))
7338 (setq rtnall (append rtnall rtn))))
7339 (if (or rtnall org-agenda-show-all-dates)
7340 (progn
7341 (insert (format "%-9s %2d %s %4d\n"
7342 (calendar-day-name date)
7343 (extract-calendar-day date)
7344 (calendar-month-name (extract-calendar-month date))
7345 (extract-calendar-year date)))
7346 (put-text-property s (1- (point)) 'face
7347 'org-level-3)
7348 (if todayp (put-text-property s (1- (point)) 'org-today t))
7350 (if rtnall (insert
7351 (org-finalize-agenda-entries
7352 (org-agenda-add-time-grid-maybe
7353 rtnall nd todayp))
7354 "\n"))
7355 (put-text-property s (1- (point)) 'day d))))
7356 (goto-char (point-min))
7357 (org-fit-agenda-window)
7358 (unless (and (pos-visible-in-window-p (point-min))
7359 (pos-visible-in-window-p (point-max)))
7360 (goto-char (1- (point-max)))
7361 (recenter -1)
7362 (if (not (pos-visible-in-window-p (or start-pos 1)))
7363 (progn
7364 (goto-char (or start-pos 1))
7365 (recenter 1))))
7366 (goto-char (or start-pos 1))
7367 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
7368 (org-finalize-agenda)
7369 (setq buffer-read-only t)
7370 (if (not org-select-agenda-window) (select-window win))
7371 (message "")))
7373 (defvar org-select-this-todo-keyword nil)
7375 ;;;###autoload
7376 (defun org-todo-list (arg)
7377 "Show all TODO entries from all agenda file in a single list.
7378 The prefix arg can be used to select a specific TODO keyword and limit
7379 the list to these. When using \\[universal-argument], you will be prompted
7380 for a keyword. A numeric prefix directly selects the Nth keyword in
7381 `org-todo-keywords'."
7382 (interactive "P")
7383 (org-compile-prefix-format 'todo)
7384 (org-set-sorting-strategy 'todo)
7385 (let* ((today (time-to-days (current-time)))
7386 (date (calendar-gregorian-from-absolute today))
7387 (win (selected-window))
7388 (kwds org-todo-keywords)
7389 (completion-ignore-case t)
7390 (org-select-this-todo-keyword
7391 (if (stringp arg) arg
7392 (and arg (integerp arg) (> arg 0)
7393 (nth (1- arg) org-todo-keywords))))
7394 rtn rtnall files file pos)
7395 (when (equal arg '(4))
7396 (setq org-select-this-todo-keyword
7397 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
7398 nil t)))
7399 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
7400 (org-prepare-agenda)
7401 (org-set-local 'last-arg arg)
7402 (org-set-local 'org-todo-keywords kwds)
7403 (setq org-agenda-redo-command
7404 '(org-todo-list (or current-prefix-arg last-arg)))
7405 (setq files (org-agenda-files)
7406 rtnall nil)
7407 (while (setq file (pop files))
7408 (catch 'nextfile
7409 (org-check-agenda-file file)
7410 (setq rtn (org-agenda-get-day-entries file date :todo))
7411 (setq rtnall (append rtnall rtn))))
7412 (insert "Global list of TODO items of type: ")
7413 (add-text-properties (point-min) (1- (point))
7414 (list 'face 'org-level-3))
7415 (setq pos (point))
7416 (insert (or org-select-this-todo-keyword "ALL") "\n")
7417 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
7418 (setq pos (point))
7419 (unless org-agenda-multi
7420 (insert
7421 "Available with `N r': (0)ALL "
7422 (let ((n 0))
7423 (mapconcat (lambda (x)
7424 (format "(%d)%s" (setq n (1+ n)) x))
7425 org-todo-keywords " "))
7426 "\n"))
7427 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
7428 (when rtnall
7429 (insert (org-finalize-agenda-entries rtnall) "\n"))
7430 (goto-char (point-min))
7431 (org-fit-agenda-window)
7432 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
7433 (org-finalize-agenda)
7434 (setq buffer-read-only t)
7435 (if (not org-select-agenda-window) (select-window win))))
7437 (defun org-check-agenda-file (file)
7438 "Make sure FILE exists. If not, ask user what to do."
7439 (when (not (file-exists-p file))
7440 (message "non-existent file %s. [R]emove from list or [A]bort?"
7441 (abbreviate-file-name file))
7442 (let ((r (downcase (read-char-exclusive))))
7443 (cond
7444 ((equal r ?r)
7445 (org-remove-file file)
7446 (throw 'nextfile t))
7447 (t (error "Abort"))))))
7449 (defun org-agenda-check-type (error &rest types)
7450 "Check if agenda buffer is of allowed type.
7451 If ERROR is non-nil, throw an error, otherwise just return nil."
7452 (if (memq org-agenda-type types)
7454 (if error
7455 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
7456 nil)))
7458 (defun org-agenda-quit ()
7459 "Exit agenda by removing the window or the buffer."
7460 (interactive)
7461 (let ((buf (current-buffer)))
7462 (if (not (one-window-p)) (delete-window))
7463 (kill-buffer buf)
7464 (org-agenda-maybe-reset-markers 'force))
7465 ;; Maybe restore the pre-agenda window configuration.
7466 (and org-agenda-restore-windows-after-quit
7467 (not (eq org-agenda-window-setup 'other-frame))
7468 org-pre-agenda-window-conf
7469 (set-window-configuration org-pre-agenda-window-conf)))
7471 (defun org-agenda-exit ()
7472 "Exit agenda by removing the window or the buffer.
7473 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
7474 Org-mode buffers visited directly by the user will not be touched."
7475 (interactive)
7476 (org-release-buffers org-agenda-new-buffers)
7477 (setq org-agenda-new-buffers nil)
7478 (org-agenda-quit))
7480 (defun org-save-all-org-buffers ()
7481 "Save all Org-mode buffers without user confirmation."
7482 (interactive)
7483 (message "Saving all Org-mode buffers...")
7484 (save-some-buffers t 'org-mode-p)
7485 (message "Saving all Org-mode buffers... done"))
7487 (defun org-agenda-redo ()
7488 "Rebuild Agenda.
7489 When this is the global TODO list, a prefix argument will be interpreted."
7490 (interactive)
7491 (let* ((org-agenda-keep-modes t)
7492 (line (org-current-line))
7493 (window-line (- line (org-current-line (window-start)))))
7494 (message "Rebuilding agenda buffer...")
7495 (eval org-agenda-redo-command)
7496 (message "Rebuilding agenda buffer...done")
7497 (goto-line line)
7498 (recenter window-line)))
7500 (defun org-agenda-goto-today ()
7501 "Go to today."
7502 (interactive)
7503 (org-agenda-check-type t 'timeline 'agenda)
7504 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
7505 (cond
7506 (tdpos (goto-char tdpos))
7507 ((eq org-agenda-type 'agenda)
7508 (let ((org-agenda-overriding-arguments org-agenda-last-arguments))
7509 (setf (nth 1 org-agenda-overriding-arguments) nil)
7510 (org-agenda-redo)
7511 (org-agenda-find-today-or-agenda)))
7512 (t (error "Cannot find today")))))
7514 (defun org-agenda-find-today-or-agenda ()
7515 (goto-char
7516 (or (text-property-any (point-min) (point-max) 'org-today t)
7517 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
7518 (point-min))))
7520 (defun org-agenda-later (arg)
7521 "Go forward in time by `org-agenda-ndays' days.
7522 With prefix ARG, go forward that many times `org-agenda-ndays'."
7523 (interactive "p")
7524 (org-agenda-check-type t 'agenda)
7525 (let ((org-agenda-overriding-arguments
7526 (list (car org-agenda-last-arguments)
7527 (+ starting-day (* arg org-agenda-ndays))
7528 nil t)))
7529 (org-agenda-redo)
7530 (org-agenda-find-today-or-agenda)))
7532 (defun org-agenda-earlier (arg)
7533 "Go back in time by `org-agenda-ndays' days.
7534 With prefix ARG, go back that many times `org-agenda-ndays'."
7535 (interactive "p")
7536 (org-agenda-check-type t 'agenda)
7537 (let ((org-agenda-overriding-arguments
7538 (list (car org-agenda-last-arguments)
7539 (- starting-day (* arg org-agenda-ndays))
7540 nil t)))
7541 (org-agenda-redo)
7542 (org-agenda-find-today-or-agenda)))
7544 (defun org-agenda-week-view ()
7545 "Switch to weekly view for agenda."
7546 (interactive)
7547 (org-agenda-check-type t 'agenda)
7548 (if (= org-agenda-ndays 7)
7549 (error "This is already the week view"))
7550 (setq org-agenda-ndays 7)
7551 (let ((org-agenda-overriding-arguments
7552 (list (car org-agenda-last-arguments)
7553 (or (get-text-property (point) 'day)
7554 starting-day)
7555 nil t)))
7556 (org-agenda-redo)
7557 (org-agenda-find-today-or-agenda))
7558 (org-agenda-set-mode-name)
7559 (message "Switched to week view"))
7561 (defun org-agenda-day-view ()
7562 "Switch to daily view for agenda."
7563 (interactive)
7564 (org-agenda-check-type t 'agenda)
7565 (if (= org-agenda-ndays 1)
7566 (error "This is already the day view"))
7567 (setq org-agenda-ndays 1)
7568 (let ((org-agenda-overriding-arguments
7569 (list (car org-agenda-last-arguments)
7570 (or (get-text-property (point) 'day)
7571 starting-day)
7572 nil t)))
7573 (org-agenda-redo)
7574 (org-agenda-find-today-or-agenda))
7575 (org-agenda-set-mode-name)
7576 (message "Switched to day view"))
7578 (defun org-agenda-next-date-line (&optional arg)
7579 "Jump to the next line indicating a date in agenda buffer."
7580 (interactive "p")
7581 (org-agenda-check-type t 'agenda 'timeline)
7582 (beginning-of-line 1)
7583 (if (looking-at "^\\S-") (forward-char 1))
7584 (if (not (re-search-forward "^\\S-" nil t arg))
7585 (progn
7586 (backward-char 1)
7587 (error "No next date after this line in this buffer")))
7588 (goto-char (match-beginning 0)))
7590 (defun org-agenda-previous-date-line (&optional arg)
7591 "Jump to the previous line indicating a date in agenda buffer."
7592 (interactive "p")
7593 (org-agenda-check-type t 'agenda 'timeline)
7594 (beginning-of-line 1)
7595 (if (not (re-search-backward "^\\S-" nil t arg))
7596 (error "No previous date before this line in this buffer")))
7598 ;; Initialize the highlight
7599 (defvar org-hl (org-make-overlay 1 1))
7600 (org-overlay-put org-hl 'face 'highlight)
7602 (defun org-highlight (begin end &optional buffer)
7603 "Highlight a region with overlay."
7604 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
7605 org-hl begin end (or buffer (current-buffer))))
7607 (defun org-unhighlight ()
7608 "Detach overlay INDEX."
7609 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
7612 (defun org-agenda-follow-mode ()
7613 "Toggle follow mode in an agenda buffer."
7614 (interactive)
7615 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
7616 (org-agenda-set-mode-name)
7617 (message "Follow mode is %s"
7618 (if org-agenda-follow-mode "on" "off")))
7620 (defun org-agenda-log-mode ()
7621 "Toggle log mode in an agenda buffer."
7622 (interactive)
7623 (org-agenda-check-type t 'agenda 'timeline)
7624 (setq org-agenda-show-log (not org-agenda-show-log))
7625 (org-agenda-set-mode-name)
7626 (org-agenda-redo)
7627 (message "Log mode is %s"
7628 (if org-agenda-show-log "on" "off")))
7630 (defun org-agenda-toggle-diary ()
7631 "Toggle diary inclusion in an agenda buffer."
7632 (interactive)
7633 (org-agenda-check-type t 'agenda)
7634 (setq org-agenda-include-diary (not org-agenda-include-diary))
7635 (org-agenda-redo)
7636 (org-agenda-set-mode-name)
7637 (message "Diary inclusion turned %s"
7638 (if org-agenda-include-diary "on" "off")))
7640 (defun org-agenda-toggle-time-grid ()
7641 "Toggle time grid in an agenda buffer."
7642 (interactive)
7643 (org-agenda-check-type t 'agenda)
7644 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
7645 (org-agenda-redo)
7646 (org-agenda-set-mode-name)
7647 (message "Time-grid turned %s"
7648 (if org-agenda-use-time-grid "on" "off")))
7650 (defun org-agenda-set-mode-name ()
7651 "Set the mode name to indicate all the small mode settings."
7652 (setq mode-name
7653 (concat "Org-Agenda"
7654 (if (equal org-agenda-ndays 1) " Day" "")
7655 (if (equal org-agenda-ndays 7) " Week" "")
7656 (if org-agenda-follow-mode " Follow" "")
7657 (if org-agenda-include-diary " Diary" "")
7658 (if org-agenda-use-time-grid " Grid" "")
7659 (if org-agenda-show-log " Log" "")))
7660 (force-mode-line-update))
7662 (defun org-agenda-post-command-hook ()
7663 (and (eolp) (not (bolp)) (backward-char 1))
7664 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
7665 (if (and org-agenda-follow-mode
7666 (get-text-property (point) 'org-marker))
7667 (org-agenda-show)))
7669 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
7671 (defun org-get-entries-from-diary (date)
7672 "Get the (Emacs Calendar) diary entries for DATE."
7673 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
7674 (diary-display-hook '(fancy-diary-display))
7675 (list-diary-entries-hook
7676 (cons 'org-diary-default-entry list-diary-entries-hook))
7677 (diary-file-name-prefix-function nil) ; turn this feature off
7678 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
7679 entries
7680 (org-disable-agenda-to-diary t))
7681 (save-excursion
7682 (save-window-excursion
7683 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
7684 (if (not (get-buffer fancy-diary-buffer))
7685 (setq entries nil)
7686 (with-current-buffer fancy-diary-buffer
7687 (setq buffer-read-only nil)
7688 (if (= (point-max) 1)
7689 ;; No entries
7690 (setq entries nil)
7691 ;; Omit the date and other unnecessary stuff
7692 (org-agenda-cleanup-fancy-diary)
7693 ;; Add prefix to each line and extend the text properties
7694 (if (= (point-max) 1)
7695 (setq entries nil)
7696 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
7697 (set-buffer-modified-p nil)
7698 (kill-buffer fancy-diary-buffer)))
7699 (when entries
7700 (setq entries (org-split-string entries "\n"))
7701 (setq entries
7702 (mapcar
7703 (lambda (x)
7704 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
7705 ;; Extend the text properties to the beginning of the line
7706 (org-add-props x (text-properties-at (1- (length x)) x)))
7707 entries)))))
7709 (defun org-agenda-cleanup-fancy-diary ()
7710 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
7711 This gets rid of the date, the underline under the date, and
7712 the dummy entry installed by `org-mode' to ensure non-empty diary for each
7713 date. It also removes lines that contain only whitespace."
7714 (goto-char (point-min))
7715 (if (looking-at ".*?:[ \t]*")
7716 (progn
7717 (replace-match "")
7718 (re-search-forward "\n=+$" nil t)
7719 (replace-match "")
7720 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
7721 (re-search-forward "\n=+$" nil t)
7722 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
7723 (goto-char (point-min))
7724 (while (re-search-forward "^ +\n" nil t)
7725 (replace-match ""))
7726 (goto-char (point-min))
7727 (if (re-search-forward "^Org-mode dummy\n?" nil t)
7728 (replace-match "")))
7730 ;; Make sure entries from the diary have the right text properties.
7731 (eval-after-load "diary-lib"
7732 '(if (boundp 'diary-modify-entry-list-string-function)
7733 ;; We can rely on the hook, nothing to do
7735 ;; Hook not avaiable, must use advice to make this work
7736 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
7737 "Make the position visible."
7738 (if (and org-disable-agenda-to-diary ;; called from org-agenda
7739 (stringp string)
7740 buffer-file-name)
7741 (setq string (org-modify-diary-entry-string string))))))
7743 (defun org-modify-diary-entry-string (string)
7744 "Add text properties to string, allowing org-mode to act on it."
7745 (org-add-props string nil
7746 'mouse-face 'highlight
7747 'keymap org-agenda-keymap
7748 'help-echo (format "mouse-2 or RET jump to diary file %s"
7749 (abbreviate-file-name buffer-file-name))
7750 'org-agenda-diary-link t
7751 'org-marker (org-agenda-new-marker (point-at-bol))))
7753 (defun org-diary-default-entry ()
7754 "Add a dummy entry to the diary.
7755 Needed to avoid empty dates which mess up holiday display."
7756 ;; Catch the error if dealing with the new add-to-diary-alist
7757 (when org-disable-agenda-to-diary
7758 (condition-case nil
7759 (add-to-diary-list original-date "Org-mode dummy" "")
7760 (error
7761 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
7763 (defun org-cycle-agenda-files ()
7764 "Cycle through the files in `org-agenda-files'.
7765 If the current buffer visits an agenda file, find the next one in the list.
7766 If the current buffer does not, find the first agenda file."
7767 (interactive)
7768 (let* ((fs (org-agenda-files t))
7769 (files (append fs (list (car fs))))
7770 (tcf (if buffer-file-name (file-truename buffer-file-name)))
7771 file)
7772 (unless files (error "No agenda files"))
7773 (catch 'exit
7774 (while (setq file (pop files))
7775 (if (equal (file-truename file) tcf)
7776 (when (car files)
7777 (find-file (car files))
7778 (throw 'exit t))))
7779 (find-file (car fs)))))
7781 (defun org-agenda-file-to-end ()
7782 "Move/add the current file to the end of the agenda file list.
7783 If the file is not present in the list, it is appended to the list. If it is
7784 present, it is moved there."
7785 (interactive)
7786 (org-agenda-file-to-front 'to-end))
7788 (defun org-agenda-file-to-front (&optional to-end)
7789 "Move/add the current file to the top of the agenda file list.
7790 If the file is not present in the list, it is added to the front. If it is
7791 present, it is moved there. With optional argument TO-END, add/move to the
7792 end of the list."
7793 (interactive "P")
7794 (let ((file-alist (mapcar (lambda (x)
7795 (cons (file-truename x) x))
7796 (org-agenda-files t)))
7797 (ctf (file-truename buffer-file-name))
7798 x had)
7799 (setq x (assoc ctf file-alist) had x)
7801 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
7802 (if to-end
7803 (setq file-alist (append (delq x file-alist) (list x)))
7804 (setq file-alist (cons x (delq x file-alist))))
7805 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
7806 (org-install-agenda-files-menu)
7807 (message "File %s to %s of agenda file list"
7808 (if had "moved" "added") (if to-end "end" "front"))))
7810 (defun org-remove-file (&optional file)
7811 "Remove current file from the list of files in variable `org-agenda-files'.
7812 These are the files which are being checked for agenda entries.
7813 Optional argument FILE means, use this file instead of the current."
7814 (interactive)
7815 (let* ((file (or file buffer-file-name))
7816 (true-file (file-truename file))
7817 (afile (abbreviate-file-name file))
7818 (files (delq nil (mapcar
7819 (lambda (x)
7820 (if (equal true-file
7821 (file-truename x))
7822 nil x))
7823 (org-agenda-files t)))))
7824 (if (not (= (length files) (length (org-agenda-files t))))
7825 (progn
7826 (org-store-new-agenda-file-list files)
7827 (org-install-agenda-files-menu)
7828 (message "Removed file: %s" afile))
7829 (message "File was not in list: %s" afile))))
7831 (defun org-file-menu-entry (file)
7832 (vector file (list 'find-file file) t))
7834 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
7835 "Return a list of all relevant day numbers from BEG to END buffer positions.
7836 If NO-RANGES is non-nil, include only the start and end dates of a range,
7837 not every single day in the range. If FORCE-TODAY is non-nil, make
7838 sure that TODAY is included in the list. If INACTIVE is non-nil, also
7839 inactive time stamps (those in square brackets) are included.
7840 When EMPTY is non-nil, also include days without any entries."
7841 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
7842 dates dates1 date day day1 day2 ts1 ts2)
7843 (if force-today
7844 (setq dates (list (time-to-days (current-time)))))
7845 (save-excursion
7846 (goto-char beg)
7847 (while (re-search-forward re end t)
7848 (setq day (time-to-days (org-time-string-to-time
7849 (substring (match-string 1) 0 10))))
7850 (or (memq day dates) (push day dates)))
7851 (unless no-ranges
7852 (goto-char beg)
7853 (while (re-search-forward org-tr-regexp end t)
7854 (setq ts1 (substring (match-string 1) 0 10)
7855 ts2 (substring (match-string 2) 0 10)
7856 day1 (time-to-days (org-time-string-to-time ts1))
7857 day2 (time-to-days (org-time-string-to-time ts2)))
7858 (while (< (setq day1 (1+ day1)) day2)
7859 (or (memq day1 dates) (push day1 dates)))))
7860 (setq dates (sort dates '<))
7861 (when empty
7862 (while (setq day (pop dates))
7863 (setq day2 (car dates))
7864 (push day dates1)
7865 (when (and day2 empty)
7866 (if (or (eq empty t)
7867 (and (numberp empty) (<= (- day2 day) empty)))
7868 (while (< (setq day (1+ day)) day2)
7869 (push (list day) dates1))
7870 (push (cons :omitted (- day2 day)) dates1))))
7871 (setq dates (nreverse dates1)))
7872 dates)))
7874 ;;;###autoload
7875 (defun org-diary (&rest args)
7876 "Return diary information from org-files.
7877 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
7878 It accesses org files and extracts information from those files to be
7879 listed in the diary. The function accepts arguments specifying what
7880 items should be listed. The following arguments are allowed:
7882 :timestamp List the headlines of items containing a date stamp or
7883 date range matching the selected date. Deadlines will
7884 also be listed, on the expiration day.
7886 :deadline List any deadlines past due, or due within
7887 `org-deadline-warning-days'. The listing occurs only
7888 in the diary for *today*, not at any other date. If
7889 an entry is marked DONE, it is no longer listed.
7891 :scheduled List all items which are scheduled for the given date.
7892 The diary for *today* also contains items which were
7893 scheduled earlier and are not yet marked DONE.
7895 :todo List all TODO items from the org-file. This may be a
7896 long list - so this is not turned on by default.
7897 Like deadlines, these entries only show up in the
7898 diary for *today*, not at any other date.
7900 The call in the diary file should look like this:
7902 &%%(org-diary) ~/path/to/some/orgfile.org
7904 Use a separate line for each org file to check. Or, if you omit the file name,
7905 all files listed in `org-agenda-files' will be checked automatically:
7907 &%%(org-diary)
7909 If you don't give any arguments (as in the example above), the default
7910 arguments (:deadline :scheduled :timestamp) are used. So the example above may
7911 also be written as
7913 &%%(org-diary :deadline :timestamp :scheduled)
7915 The function expects the lisp variables `entry' and `date' to be provided
7916 by the caller, because this is how the calendar works. Don't use this
7917 function from a program - use `org-agenda-get-day-entries' instead."
7918 (org-agenda-maybe-reset-markers)
7919 (org-compile-prefix-format 'agenda)
7920 (org-set-sorting-strategy 'agenda)
7921 (setq args (or args '(:deadline :scheduled :timestamp)))
7922 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
7923 (list entry)
7924 (org-agenda-files t)))
7925 file rtn results)
7926 ;; If this is called during org-agenda, don't return any entries to
7927 ;; the calendar. Org Agenda will list these entries itself.
7928 (if org-disable-agenda-to-diary (setq files nil))
7929 (while (setq file (pop files))
7930 (setq rtn (apply 'org-agenda-get-day-entries file date args))
7931 (setq results (append results rtn)))
7932 (if results
7933 (concat (org-finalize-agenda-entries results) "\n"))))
7934 (defvar org-category-table nil)
7935 (defun org-get-category-table ()
7936 "Get the table of categories and positions in current buffer."
7937 (let (tbl)
7938 (save-excursion
7939 (goto-char (point-min))
7940 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
7941 (push (cons (point) (org-trim (match-string 2))) tbl)))
7942 tbl))
7943 (defun org-get-category (&optional pos)
7944 "Get the category applying to position POS."
7945 (if (not org-category-table)
7946 (cond
7947 ((null org-category)
7948 (setq org-category
7949 (if buffer-file-name
7950 (file-name-sans-extension
7951 (file-name-nondirectory buffer-file-name))
7952 "???")))
7953 ((symbolp org-category) (symbol-name org-category))
7954 (t org-category))
7955 (let ((tbl org-category-table)
7956 (pos (or pos (point))))
7957 (while (and tbl (> (caar tbl) pos))
7958 (pop tbl))
7959 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
7960 org-category-table))))))
7962 (defun org-agenda-get-day-entries (file date &rest args)
7963 "Does the work for `org-diary' and `org-agenda'.
7964 FILE is the path to a file to be checked for entries. DATE is date like
7965 the one returned by `calendar-current-date'. ARGS are symbols indicating
7966 which kind of entries should be extracted. For details about these, see
7967 the documentation of `org-diary'."
7968 (setq args (or args '(:deadline :scheduled :timestamp)))
7969 (let* ((org-startup-with-deadline-check nil)
7970 (org-startup-folded nil)
7971 (org-startup-align-all-tables nil)
7972 (buffer (if (file-exists-p file)
7973 (org-get-agenda-file-buffer file)
7974 (error "No such file %s" file)))
7975 arg results rtn)
7976 (if (not buffer)
7977 ;; If file does not exist, make sure an error message ends up in diary
7978 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
7979 (with-current-buffer buffer
7980 (unless (org-mode-p)
7981 (error "Agenda file %s is not in `org-mode'" file))
7982 (setq org-category-table (org-get-category-table))
7983 (let ((case-fold-search nil))
7984 (save-excursion
7985 (save-restriction
7986 (if org-agenda-restrict
7987 (narrow-to-region org-agenda-restrict-begin
7988 org-agenda-restrict-end)
7989 (widen))
7990 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
7991 (while (setq arg (pop args))
7992 (cond
7993 ((and (eq arg :todo)
7994 (equal date (calendar-current-date)))
7995 (setq rtn (org-agenda-get-todos))
7996 (setq results (append results rtn)))
7997 ((eq arg :timestamp)
7998 (setq rtn (org-agenda-get-blocks))
7999 (setq results (append results rtn))
8000 (setq rtn (org-agenda-get-timestamps))
8001 (setq results (append results rtn)))
8002 ((eq arg :scheduled)
8003 (setq rtn (org-agenda-get-scheduled))
8004 (setq results (append results rtn)))
8005 ((eq arg :closed)
8006 (setq rtn (org-agenda-get-closed))
8007 (setq results (append results rtn)))
8008 ((and (eq arg :deadline)
8009 (equal date (calendar-current-date)))
8010 (setq rtn (org-agenda-get-deadlines))
8011 (setq results (append results rtn))))))))
8012 results))))
8014 (defun org-entry-is-done-p ()
8015 "Is the current entry marked DONE?"
8016 (save-excursion
8017 (and (re-search-backward "[\r\n]\\*" nil t)
8018 (looking-at org-nl-done-regexp))))
8020 (defun org-at-date-range-p ()
8021 "Is the cursor inside a date range?"
8022 (interactive)
8023 (save-excursion
8024 (catch 'exit
8025 (let ((pos (point)))
8026 (skip-chars-backward "^<\r\n")
8027 (skip-chars-backward "<")
8028 (and (looking-at org-tr-regexp)
8029 (>= (match-end 0) pos)
8030 (throw 'exit t))
8031 (skip-chars-backward "^<\r\n")
8032 (skip-chars-backward "<")
8033 (and (looking-at org-tr-regexp)
8034 (>= (match-end 0) pos)
8035 (throw 'exit t)))
8036 nil)))
8038 (defun org-agenda-get-todos ()
8039 "Return the TODO information for agenda display."
8040 (let* ((props (list 'face nil
8041 'done-face 'org-done
8042 'org-not-done-regexp org-not-done-regexp
8043 'mouse-face 'highlight
8044 'keymap org-agenda-keymap
8045 'help-echo
8046 (format "mouse-2 or RET jump to org file %s"
8047 (abbreviate-file-name buffer-file-name))))
8048 (regexp (concat "[\n\r]\\*+ *\\("
8049 (if org-select-this-todo-keyword
8050 (concat "\\<\\(" org-select-this-todo-keyword
8051 "\\)\\>")
8052 org-not-done-regexp)
8053 "[^\n\r]*\\)"))
8054 (sched-re (concat ".*\n?.*?" org-scheduled-time-regexp))
8055 marker priority category tags
8056 ee txt)
8057 (goto-char (point-min))
8058 (while (re-search-forward regexp nil t)
8059 (catch :skip
8060 (when (and org-agenda-todo-ignore-scheduled
8061 (looking-at sched-re))
8062 ;; FIXME: the following test also happens below, but we need it here
8063 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
8064 (throw :skip nil))
8065 (org-agenda-skip)
8066 (goto-char (match-beginning 1))
8067 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
8068 category (org-get-category)
8069 tags (org-get-tags-at (point))
8070 txt (org-format-agenda-item "" (match-string 1) category tags)
8071 priority
8072 (+ (org-get-priority txt)
8073 (if org-todo-kwd-priority-p
8074 (- org-todo-kwd-max-priority -2
8075 (length
8076 (member (match-string 2) org-todo-keywords)))
8077 1)))
8078 (org-add-props txt props
8079 'org-marker marker 'org-hd-marker marker
8080 'priority priority 'category category)
8081 (push txt ee)
8082 (if org-agenda-todo-list-sublevels
8083 (goto-char (match-end 1))
8084 (org-end-of-subtree 'invisible))))
8085 (nreverse ee)))
8087 (defconst org-agenda-no-heading-message
8088 "No heading for this item in buffer or region.")
8090 (defun org-agenda-get-timestamps ()
8091 "Return the date stamp information for agenda display."
8092 (let* ((props (list 'face nil
8093 'org-not-done-regexp org-not-done-regexp
8094 'mouse-face 'highlight
8095 'keymap org-agenda-keymap
8096 'help-echo
8097 (format "mouse-2 or RET jump to org file %s"
8098 (abbreviate-file-name buffer-file-name))))
8099 (regexp (regexp-quote
8100 (substring
8101 (format-time-string
8102 (car org-time-stamp-formats)
8103 (apply 'encode-time ; DATE bound by calendar
8104 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
8105 0 11)))
8106 marker hdmarker deadlinep scheduledp donep tmp priority category
8107 ee txt timestr tags)
8108 (goto-char (point-min))
8109 (while (re-search-forward regexp nil t)
8110 (catch :skip
8111 (and (save-match-data (org-at-date-range-p)) (throw :skip nil))
8112 (org-agenda-skip)
8113 (setq marker (org-agenda-new-marker (match-beginning 0))
8114 category (org-get-category (match-beginning 0))
8115 tmp (buffer-substring (max (point-min)
8116 (- (match-beginning 0)
8117 org-ds-keyword-length))
8118 (match-beginning 0))
8119 timestr (buffer-substring (match-beginning 0) (point-at-eol))
8120 deadlinep (string-match org-deadline-regexp tmp)
8121 scheduledp (string-match org-scheduled-regexp tmp)
8122 donep (org-entry-is-done-p))
8123 (if (string-match ">" timestr)
8124 ;; substring should only run to end of time stamp
8125 (setq timestr (substring timestr 0 (match-end 0))))
8126 (save-excursion
8127 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
8128 (progn
8129 (goto-char (match-end 1))
8130 (setq hdmarker (org-agenda-new-marker)
8131 tags (org-get-tags-at))
8132 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
8133 (setq txt (org-format-agenda-item
8134 (format "%s%s"
8135 (if deadlinep "Deadline: " "")
8136 (if scheduledp "Scheduled: " ""))
8137 (match-string 1) category tags timestr)))
8138 (setq txt org-agenda-no-heading-message))
8139 (setq priority (org-get-priority txt))
8140 (org-add-props txt props
8141 'org-marker marker 'org-hd-marker hdmarker)
8142 (if deadlinep
8143 (org-add-props txt nil
8144 'face (if donep 'org-done 'org-warning)
8145 'undone-face 'org-warning 'done-face 'org-done
8146 'category category 'priority (+ 100 priority))
8147 (if scheduledp
8148 (org-add-props txt nil
8149 'face 'org-scheduled-today
8150 'undone-face 'org-scheduled-today 'done-face 'org-done
8151 'category category 'priority (+ 99 priority))
8152 (org-add-props txt nil 'priority priority 'category category)))
8153 (push txt ee))
8154 (outline-next-heading)))
8155 (nreverse ee)))
8157 (defun org-agenda-get-closed ()
8158 "Return the logged TODO entries for agenda display."
8159 (let* ((props (list 'mouse-face 'highlight
8160 'org-not-done-regexp org-not-done-regexp
8161 'keymap org-agenda-keymap
8162 'help-echo
8163 (format "mouse-2 or RET jump to org file %s"
8164 (abbreviate-file-name buffer-file-name))))
8165 (regexp (concat
8166 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
8167 (regexp-quote
8168 (substring
8169 (format-time-string
8170 (car org-time-stamp-formats)
8171 (apply 'encode-time ; DATE bound by calendar
8172 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
8173 1 11))))
8174 marker hdmarker priority category tags closedp
8175 ee txt timestr)
8176 (goto-char (point-min))
8177 (while (re-search-forward regexp nil t)
8178 (catch :skip
8179 (org-agenda-skip)
8180 (setq marker (org-agenda-new-marker (match-beginning 0))
8181 closedp (equal (match-string 1) org-closed-string)
8182 category (org-get-category (match-beginning 0))
8183 timestr (buffer-substring (match-beginning 0) (point-at-eol))
8184 ;; donep (org-entry-is-done-p)
8186 (if (string-match "\\]" timestr)
8187 ;; substring should only run to end of time stamp
8188 (setq timestr (substring timestr 0 (match-end 0))))
8189 (save-excursion
8190 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
8191 (progn
8192 (goto-char (match-end 1))
8193 (setq hdmarker (org-agenda-new-marker)
8194 tags (org-get-tags-at))
8195 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
8196 (setq txt (org-format-agenda-item
8197 (if closedp "Closed: " "Clocked: ")
8198 (match-string 1) category tags timestr)))
8199 (setq txt org-agenda-no-heading-message))
8200 (setq priority 100000)
8201 (org-add-props txt props
8202 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
8203 'priority priority 'category category
8204 'undone-face 'org-warning 'done-face 'org-done)
8205 (push txt ee))
8206 (outline-next-heading)))
8207 (nreverse ee)))
8209 (defun org-agenda-get-deadlines ()
8210 "Return the deadline information for agenda display."
8211 (let* ((wdays org-deadline-warning-days)
8212 (props (list 'mouse-face 'highlight
8213 'org-not-done-regexp org-not-done-regexp
8214 'keymap org-agenda-keymap
8215 'help-echo
8216 (format "mouse-2 or RET jump to org file %s"
8217 (abbreviate-file-name buffer-file-name))))
8218 (regexp org-deadline-time-regexp)
8219 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
8220 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
8221 d2 diff pos pos1 category tags
8222 ee txt head face)
8223 (goto-char (point-min))
8224 (while (re-search-forward regexp nil t)
8225 (catch :skip
8226 (org-agenda-skip)
8227 (setq pos (1- (match-beginning 1))
8228 d2 (time-to-days
8229 (org-time-string-to-time (match-string 1)))
8230 diff (- d2 d1))
8231 ;; When to show a deadline in the calendar:
8232 ;; If the expiration is within wdays warning time.
8233 ;; Past-due deadlines are only shown on the current date
8234 (if (and (< diff wdays) todayp (not (= diff 0)))
8235 (save-excursion
8236 (setq category (org-get-category))
8237 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
8238 (progn
8239 (goto-char (match-end 0))
8240 (setq pos1 (match-end 1))
8241 (setq tags (org-get-tags-at pos1))
8242 (setq head (buffer-substring-no-properties
8243 (point)
8244 (progn (skip-chars-forward "^\r\n")
8245 (point))))
8246 (if (string-match org-looking-at-done-regexp head)
8247 (setq txt nil)
8248 (setq txt (org-format-agenda-item
8249 (format "In %3d d.: " diff) head category tags))))
8250 (setq txt org-agenda-no-heading-message))
8251 (when txt
8252 (setq face (cond ((<= diff 0) 'org-warning)
8253 ((<= diff 5) 'org-upcoming-deadline)
8254 (t nil)))
8255 (org-add-props txt props
8256 'org-marker (org-agenda-new-marker pos)
8257 'org-hd-marker (org-agenda-new-marker pos1)
8258 'priority (+ (- 10 diff) (org-get-priority txt))
8259 'category category
8260 'face face 'undone-face face 'done-face 'org-done)
8261 (push txt ee))))))
8262 ee))
8264 (defun org-agenda-get-scheduled ()
8265 "Return the scheduled information for agenda display."
8266 (let* ((props (list 'face 'org-scheduled-previously
8267 'org-not-done-regexp org-not-done-regexp
8268 'undone-face 'org-scheduled-previously
8269 'done-face 'org-done
8270 'mouse-face 'highlight
8271 'keymap org-agenda-keymap
8272 'help-echo
8273 (format "mouse-2 or RET jump to org file %s"
8274 (abbreviate-file-name buffer-file-name))))
8275 (regexp org-scheduled-time-regexp)
8276 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
8277 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
8278 d2 diff pos pos1 category tags
8279 ee txt head)
8280 (goto-char (point-min))
8281 (while (re-search-forward regexp nil t)
8282 (catch :skip
8283 (org-agenda-skip)
8284 (setq pos (1- (match-beginning 1))
8285 d2 (time-to-days
8286 (org-time-string-to-time (match-string 1)))
8287 diff (- d2 d1))
8288 ;; When to show a scheduled item in the calendar:
8289 ;; If it is on or past the date.
8290 (if (and (< diff 0) todayp)
8291 (save-excursion
8292 (setq category (org-get-category))
8293 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
8294 (progn
8295 (goto-char (match-end 0))
8296 (setq pos1 (match-end 1))
8297 (setq tags (org-get-tags-at))
8298 (setq head (buffer-substring-no-properties
8299 (point)
8300 (progn (skip-chars-forward "^\r\n") (point))))
8301 (if (string-match org-looking-at-done-regexp head)
8302 (setq txt nil)
8303 (setq txt (org-format-agenda-item
8304 (format "Sched.%2dx: " (- 1 diff)) head
8305 category tags))))
8306 (setq txt org-agenda-no-heading-message))
8307 (when txt
8308 (org-add-props txt props
8309 'org-marker (org-agenda-new-marker pos)
8310 'org-hd-marker (org-agenda-new-marker pos1)
8311 'priority (+ (- 5 diff) (org-get-priority txt))
8312 'category category)
8313 (push txt ee))))))
8314 ee))
8316 (defun org-agenda-get-blocks ()
8317 "Return the date-range information for agenda display."
8318 (let* ((props (list 'face nil
8319 'org-not-done-regexp org-not-done-regexp
8320 'mouse-face 'highlight
8321 'keymap org-agenda-keymap
8322 'help-echo
8323 (format "mouse-2 or RET jump to org file %s"
8324 (abbreviate-file-name buffer-file-name))))
8325 (regexp org-tr-regexp)
8326 (d0 (calendar-absolute-from-gregorian date))
8327 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
8328 (goto-char (point-min))
8329 (while (re-search-forward regexp nil t)
8330 (catch :skip
8331 (org-agenda-skip)
8332 (setq pos (point))
8333 (setq timestr (match-string 0)
8334 s1 (match-string 1)
8335 s2 (match-string 2)
8336 d1 (time-to-days (org-time-string-to-time s1))
8337 d2 (time-to-days (org-time-string-to-time s2)))
8338 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
8339 ;; Only allow days between the limits, because the normal
8340 ;; date stamps will catch the limits.
8341 (save-excursion
8342 (setq marker (org-agenda-new-marker (point)))
8343 (setq category (org-get-category))
8344 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
8345 (progn
8346 (setq hdmarker (org-agenda-new-marker (match-end 1)))
8347 (goto-char (match-end 1))
8348 (setq tags (org-get-tags-at))
8349 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
8350 (setq txt (org-format-agenda-item
8351 (format (if (= d1 d2) "" "(%d/%d): ")
8352 (1+ (- d0 d1)) (1+ (- d2 d1)))
8353 (match-string 1) category tags
8354 (if (= d0 d1) timestr))))
8355 (setq txt org-agenda-no-heading-message))
8356 (org-add-props txt props
8357 'org-marker marker 'org-hd-marker hdmarker
8358 'priority (org-get-priority txt) 'category category)
8359 (push txt ee)))
8360 (goto-char pos)))
8361 ;; Sort the entries by expiration date.
8362 (nreverse ee)))
8364 (defconst org-plain-time-of-day-regexp
8365 (concat
8366 "\\(\\<[012]?[0-9]"
8367 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
8368 "\\(--?"
8369 "\\(\\<[012]?[0-9]"
8370 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
8371 "\\)?")
8372 "Regular expression to match a plain time or time range.
8373 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
8374 groups carry important information:
8375 0 the full match
8376 1 the first time, range or not
8377 8 the second time, if it is a range.")
8379 (defconst org-stamp-time-of-day-regexp
8380 (concat
8381 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
8382 "\\([012][0-9]:[0-5][0-9]\\)>"
8383 "\\(--?"
8384 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
8385 "Regular expression to match a timestamp time or time range.
8386 After a match, the following groups carry important information:
8387 0 the full match
8388 1 date plus weekday, for backreferencing to make sure both times on same day
8389 2 the first time, range or not
8390 4 the second time, if it is a range.")
8392 (defvar org-prefix-has-time nil
8393 "A flag, set by `org-compile-prefix-format'.
8394 The flag is set if the currently compiled format contains a `%t'.")
8395 (defvar org-prefix-has-tag nil
8396 "A flag, set by `org-compile-prefix-format'.
8397 The flag is set if the currently compiled format contains a `%T'.")
8399 (defun org-format-agenda-item (extra txt &optional category tags dotime
8400 noprefix)
8401 "Format TXT to be inserted into the agenda buffer.
8402 In particular, it adds the prefix and corresponding text properties. EXTRA
8403 must be a string and replaces the `%s' specifier in the prefix format.
8404 CATEGORY (string, symbol or nil) may be used to overrule the default
8405 category taken from local variable or file name. It will replace the `%c'
8406 specifier in the format. DOTIME, when non-nil, indicates that a
8407 time-of-day should be extracted from TXT for sorting of this entry, and for
8408 the `%t' specifier in the format. When DOTIME is a string, this string is
8409 searched for a time before TXT is. NOPREFIX is a flag and indicates that
8410 only the correctly processes TXT should be returned - this is used by
8411 `org-agenda-change-all-lines'. TAGS can be the tags of the headline."
8412 (save-match-data
8413 ;; Diary entries sometimes have extra whitespace at the beginning
8414 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
8415 (let* ((category (or category
8416 org-category
8417 (if buffer-file-name
8418 (file-name-sans-extension
8419 (file-name-nondirectory buffer-file-name))
8420 "")))
8421 (tag (if tags (nth (1- (length tags)) tags) ""))
8422 time ;; needed for the eval of the prefix format
8423 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
8424 (time-of-day (and dotime (org-get-time-of-day ts)))
8425 stamp plain s0 s1 s2 rtn)
8426 (when (and dotime time-of-day org-prefix-has-time)
8427 ;; Extract starting and ending time and move them to prefix
8428 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
8429 (setq plain (string-match org-plain-time-of-day-regexp ts)))
8430 (setq s0 (match-string 0 ts)
8431 s1 (match-string (if plain 1 2) ts)
8432 s2 (match-string (if plain 8 4) ts))
8434 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
8435 ;; them, we might want to remove them there to avoid duplication.
8436 ;; The user can turn this off with a variable.
8437 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
8438 (string-match (concat (regexp-quote s0) " *") txt)
8439 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
8440 (= (match-beginning 0) 0)
8442 (setq txt (replace-match "" nil nil txt))))
8443 ;; Normalize the time(s) to 24 hour
8444 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
8445 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
8447 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
8448 ;; Tags are in the string
8449 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
8450 (and org-agenda-remove-tags-when-in-prefix
8451 org-prefix-has-tag))
8452 (setq txt (replace-match "" t t txt))
8453 (setq txt (replace-match
8454 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
8455 (match-string 2 txt))
8456 t t txt))))
8458 ;; Create the final string
8459 (if noprefix
8460 (setq rtn txt)
8461 ;; Prepare the variables needed in the eval of the compiled format
8462 (setq time (cond (s2 (concat s1 "-" s2))
8463 (s1 (concat s1 "......"))
8464 (t ""))
8465 extra (or extra "")
8466 category (if (symbolp category) (symbol-name category) category))
8467 ;; Evaluate the compiled format
8468 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
8470 ;; And finally add the text properties
8471 (org-add-props rtn nil
8472 'category (downcase category) 'tags tags
8473 'prefix-length (- (length rtn) (length txt))
8474 'time-of-day time-of-day
8475 'dotime dotime))))
8477 (defvar org-agenda-sorting-strategy)
8478 (defvar org-agenda-sorting-strategy-selected nil)
8480 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
8481 (catch 'exit
8482 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
8483 ((and todayp (member 'today (car org-agenda-time-grid))))
8484 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
8485 ((member 'weekly (car org-agenda-time-grid)))
8486 (t (throw 'exit list)))
8487 (let* ((have (delq nil (mapcar
8488 (lambda (x) (get-text-property 1 'time-of-day x))
8489 list)))
8490 (string (nth 1 org-agenda-time-grid))
8491 (gridtimes (nth 2 org-agenda-time-grid))
8492 (req (car org-agenda-time-grid))
8493 (remove (member 'remove-match req))
8494 new time)
8495 (if (and (member 'require-timed req) (not have))
8496 ;; don't show empty grid
8497 (throw 'exit list))
8498 (while (setq time (pop gridtimes))
8499 (unless (and remove (member time have))
8500 (setq time (int-to-string time))
8501 (push (org-format-agenda-item
8502 nil string "" nil
8503 (concat (substring time 0 -2) ":" (substring time -2)))
8504 new)
8505 (put-text-property
8506 1 (length (car new)) 'face 'org-time-grid (car new))))
8507 (if (member 'time-up org-agenda-sorting-strategy-selected)
8508 (append new list)
8509 (append list new)))))
8511 (defun org-compile-prefix-format (key)
8512 "Compile the prefix format into a Lisp form that can be evaluated.
8513 The resulting form is returned and stored in the variable
8514 `org-prefix-format-compiled'."
8515 (setq org-prefix-has-time nil org-prefix-has-tag nil)
8516 (let ((s (cond
8517 ((stringp org-agenda-prefix-format)
8518 org-agenda-prefix-format)
8519 ((assq key org-agenda-prefix-format)
8520 (cdr (assq key org-agenda-prefix-format)))
8521 (t " %-12:c%?-12t% s")))
8522 (start 0)
8523 varform vars var e c f opt)
8524 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
8525 s start)
8526 (setq var (cdr (assoc (match-string 4 s)
8527 '(("c" . category) ("t" . time) ("s" . extra)
8528 ("T" . tag))))
8529 c (or (match-string 3 s) "")
8530 opt (match-beginning 1)
8531 start (1+ (match-beginning 0)))
8532 (if (equal var 'time) (setq org-prefix-has-time t))
8533 (if (equal var 'tag) (setq org-prefix-has-tag t))
8534 (setq f (concat "%" (match-string 2 s) "s"))
8535 (if opt
8536 (setq varform
8537 `(if (equal "" ,var)
8539 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
8540 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
8541 (setq s (replace-match "%s" t nil s))
8542 (push varform vars))
8543 (setq vars (nreverse vars))
8544 (setq org-prefix-format-compiled `(format ,s ,@vars))))
8546 (defun org-set-sorting-strategy (key)
8547 (if (symbolp (car org-agenda-sorting-strategy))
8548 ;; the old format
8549 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
8550 (setq org-agenda-sorting-strategy-selected
8551 (or (cdr (assq key org-agenda-sorting-strategy))
8552 (cdr (assq 'agenda org-agenda-sorting-strategy))
8553 '(time-up category-keep priority-down)))))
8555 (defun org-get-time-of-day (s &optional string mod24)
8556 "Check string S for a time of day.
8557 If found, return it as a military time number between 0 and 2400.
8558 If not found, return nil.
8559 The optional STRING argument forces conversion into a 5 character wide string
8560 HH:MM."
8561 (save-match-data
8562 (when
8564 (string-match
8565 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
8566 (string-match
8567 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
8568 (let* ((h (string-to-number (match-string 1 s)))
8569 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
8570 (ampm (if (match-end 4) (downcase (match-string 4 s))))
8571 (am-p (equal ampm "am"))
8572 (h1 (cond ((not ampm) h)
8573 ((= h 12) (if am-p 0 12))
8574 (t (+ h (if am-p 0 12)))))
8575 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
8576 (mod h1 24) h1))
8577 (t0 (+ (* 100 h2) m))
8578 (t1 (concat (if (>= h1 24) "+" " ")
8579 (if (< t0 100) "0" "")
8580 (if (< t0 10) "0" "")
8581 (int-to-string t0))))
8582 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
8584 (defun org-finalize-agenda-entries (list &optional nosort)
8585 "Sort and concatenate the agenda items."
8586 (setq list (mapcar 'org-agenda-highlight-todo list))
8587 (if nosort
8588 list
8589 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
8591 (defun org-agenda-highlight-todo (x)
8592 (let (re pl)
8593 (if (eq x 'line)
8594 (save-excursion
8595 (beginning-of-line 1)
8596 (setq re (get-text-property (point) 'org-not-done-regexp))
8597 (goto-char (+ (point) (get-text-property (point) 'prefix-length)))
8598 (and (looking-at (concat "[ \t]*\\.*" re))
8599 (add-text-properties (match-beginning 0) (match-end 0)
8600 '(face org-todo))))
8601 (setq re (concat (get-text-property 0 'org-not-done-regexp x))
8602 pl (get-text-property 0 'prefix-length x))
8603 (and re (equal (string-match (concat "\\(\\.*\\)" re) x pl) pl)
8604 (add-text-properties (match-end 1) (match-end 0)
8605 '(face org-todo) x))
8606 x)))
8608 (defsubst org-cmp-priority (a b)
8609 "Compare the priorities of string A and B."
8610 (let ((pa (or (get-text-property 1 'priority a) 0))
8611 (pb (or (get-text-property 1 'priority b) 0)))
8612 (cond ((> pa pb) +1)
8613 ((< pa pb) -1)
8614 (t nil))))
8616 (defsubst org-cmp-category (a b)
8617 "Compare the string values of categories of strings A and B."
8618 (let ((ca (or (get-text-property 1 'category a) ""))
8619 (cb (or (get-text-property 1 'category b) "")))
8620 (cond ((string-lessp ca cb) -1)
8621 ((string-lessp cb ca) +1)
8622 (t nil))))
8624 (defsubst org-cmp-tag (a b)
8625 "Compare the string values of categories of strings A and B."
8626 (let ((ta (car (last (get-text-property 1 'tags a))))
8627 (tb (car (last (get-text-property 1 'tags b)))))
8628 (cond ((not ta) +1)
8629 ((not tb) -1)
8630 ((string-lessp ta tb) -1)
8631 ((string-lessp tb ta) +1)
8632 (t nil))))
8634 (defsubst org-cmp-time (a b)
8635 "Compare the time-of-day values of strings A and B."
8636 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
8637 (ta (or (get-text-property 1 'time-of-day a) def))
8638 (tb (or (get-text-property 1 'time-of-day b) def)))
8639 (cond ((< ta tb) -1)
8640 ((< tb ta) +1)
8641 (t nil))))
8643 (defun org-entries-lessp (a b)
8644 "Predicate for sorting agenda entries."
8645 ;; The following variables will be used when the form is evaluated.
8646 (let* ((time-up (org-cmp-time a b))
8647 (time-down (if time-up (- time-up) nil))
8648 (priority-up (org-cmp-priority a b))
8649 (priority-down (if priority-up (- priority-up) nil))
8650 (category-up (org-cmp-category a b))
8651 (category-down (if category-up (- category-up) nil))
8652 (category-keep (if category-up +1 nil))
8653 (tag-up (org-cmp-tag a b))
8654 (tag-down (if tag-up (- tag-up) nil)))
8655 (cdr (assoc
8656 (eval (cons 'or org-agenda-sorting-strategy-selected))
8657 '((-1 . t) (1 . nil) (nil . nil))))))
8659 (defun org-agenda-show-priority ()
8660 "Show the priority of the current item.
8661 This priority is composed of the main priority given with the [#A] cookies,
8662 and by additional input from the age of a schedules or deadline entry."
8663 (interactive)
8664 (let* ((pri (get-text-property (point-at-bol) 'priority)))
8665 (message "Priority is %d" (if pri pri -1000))))
8667 (defun org-agenda-show-tags ()
8668 "Show the tags applicable to the current item."
8669 (interactive)
8670 (let* ((tags (get-text-property (point-at-bol) 'tags)))
8671 (if tags
8672 (message "Tags are :%s:"
8673 (org-no-properties (mapconcat 'identity tags ":")))
8674 (message "No tags associated with this line"))))
8676 (defun org-agenda-goto (&optional highlight)
8677 "Go to the Org-mode file which contains the item at point."
8678 (interactive)
8679 (let* ((marker (or (get-text-property (point) 'org-marker)
8680 (org-agenda-error)))
8681 (buffer (marker-buffer marker))
8682 (pos (marker-position marker)))
8683 (switch-to-buffer-other-window buffer)
8684 (widen)
8685 (goto-char pos)
8686 (when (org-mode-p)
8687 (org-show-hierarchy-above 'agenda)
8688 (save-excursion
8689 (and (outline-next-heading)
8690 (org-flag-heading nil)))) ; show the next heading
8691 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
8693 (defun org-agenda-switch-to (&optional delete-other-windows)
8694 "Go to the Org-mode file which contains the item at point."
8695 (interactive)
8696 (let* ((marker (or (get-text-property (point) 'org-marker)
8697 (org-agenda-error)))
8698 (buffer (marker-buffer marker))
8699 (pos (marker-position marker)))
8700 (switch-to-buffer buffer)
8701 (and delete-other-windows (delete-other-windows))
8702 (widen)
8703 (goto-char pos)
8704 (when (org-mode-p)
8705 (org-show-hierarchy-above 'agenda)
8706 (save-excursion
8707 (and (outline-next-heading)
8708 (org-flag-heading nil)))))) ; show the next heading
8710 (defun org-agenda-goto-mouse (ev)
8711 "Go to the Org-mode file which contains the item at the mouse click."
8712 (interactive "e")
8713 (mouse-set-point ev)
8714 (org-agenda-goto))
8716 (defun org-agenda-show ()
8717 "Display the Org-mode file which contains the item at point."
8718 (interactive)
8719 (let ((win (selected-window)))
8720 (org-agenda-goto t)
8721 (select-window win)))
8723 (defun org-agenda-recenter (arg)
8724 "Display the Org-mode file which contains the item at point and recenter."
8725 (interactive "P")
8726 (let ((win (selected-window)))
8727 (org-agenda-goto t)
8728 (recenter arg)
8729 (select-window win)))
8731 (defun org-agenda-show-mouse (ev)
8732 "Display the Org-mode file which contains the item at the mouse click."
8733 (interactive "e")
8734 (mouse-set-point ev)
8735 (org-agenda-show))
8737 (defun org-agenda-check-no-diary ()
8738 "Check if the entry is a diary link and abort if yes."
8739 (if (get-text-property (point) 'org-agenda-diary-link)
8740 (org-agenda-error)))
8742 (defun org-agenda-error ()
8743 (error "Command not allowed in this line"))
8745 (defvar org-last-heading-marker (make-marker)
8746 "Marker pointing to the headline that last changed its TODO state
8747 by a remote command from the agenda.")
8749 (defun org-agenda-todo (&optional arg)
8750 "Cycle TODO state of line at point, also in Org-mode file.
8751 This changes the line at point, all other lines in the agenda referring to
8752 the same tree node, and the headline of the tree node in the Org-mode file."
8753 (interactive "P")
8754 (org-agenda-check-no-diary)
8755 (let* ((col (current-column))
8756 (marker (or (get-text-property (point) 'org-marker)
8757 (org-agenda-error)))
8758 (buffer (marker-buffer marker))
8759 (pos (marker-position marker))
8760 (hdmarker (get-text-property (point) 'org-hd-marker))
8761 (buffer-read-only nil)
8762 newhead)
8763 (with-current-buffer buffer
8764 (widen)
8765 (goto-char pos)
8766 (org-show-hierarchy-above 'agenda)
8767 (save-excursion
8768 (and (outline-next-heading)
8769 (org-flag-heading nil))) ; show the next heading
8770 (org-todo arg)
8771 (and (bolp) (forward-char 1))
8772 (setq newhead (org-get-heading))
8773 (save-excursion
8774 (org-back-to-heading)
8775 (move-marker org-last-heading-marker (point))))
8776 (beginning-of-line 1)
8777 (save-excursion
8778 (org-agenda-change-all-lines newhead hdmarker 'fixface))
8779 (move-to-column col)))
8781 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
8782 "Change all lines in the agenda buffer which match HDMARKER.
8783 The new content of the line will be NEWHEAD (as modified by
8784 `org-format-agenda-item'). HDMARKER is checked with
8785 `equal' against all `org-hd-marker' text properties in the file.
8786 If FIXFACE is non-nil, the face of each item is modified acording to
8787 the new TODO state."
8788 (let* (props m pl undone-face done-face finish new dotime cat tags)
8789 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
8790 (save-excursion
8791 (goto-char (point-max))
8792 (beginning-of-line 1)
8793 (while (not finish)
8794 (setq finish (bobp))
8795 (when (and (setq m (get-text-property (point) 'org-hd-marker))
8796 (equal m hdmarker))
8797 (setq props (text-properties-at (point))
8798 dotime (get-text-property (point) 'dotime)
8799 cat (get-text-property (point) 'category)
8800 tags (get-text-property (point) 'tags)
8801 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
8802 pl (get-text-property (point) 'prefix-length)
8803 undone-face (get-text-property (point) 'undone-face)
8804 done-face (get-text-property (point) 'done-face))
8805 (move-to-column pl)
8806 (if (looking-at ".*")
8807 (progn
8808 (replace-match new t t)
8809 (beginning-of-line 1)
8810 (add-text-properties (point-at-bol) (point-at-eol) props)
8811 (when fixface
8812 (add-text-properties
8813 (point-at-bol) (point-at-eol)
8814 (list 'face
8815 (if org-last-todo-state-is-todo
8816 undone-face done-face)))
8817 (org-agenda-highlight-todo 'line))
8818 ;; (org-agenda-align-tags 'line) ;; done below by finalize
8819 (beginning-of-line 1))
8820 (error "Line update did not work")))
8821 (beginning-of-line 0)))
8822 (org-finalize-agenda)))
8824 (defun org-agenda-align-tags (&optional line)
8825 "Align all tags in agenda items to `org-agenda-align-tags-to-column'."
8826 (let ((buffer-read-only))
8827 (save-excursion
8828 (goto-char (if line (point-at-bol) (point-min)))
8829 (while (re-search-forward "\\([ \t]+\\):[a-zA-Z0-9_@:]+:[ \t]*$"
8830 (if line (point-at-eol) nil) t)
8831 (delete-region (match-beginning 1) (match-end 1))
8832 (goto-char (match-beginning 1))
8833 (insert (org-add-props
8834 (make-string (max 1 (- org-agenda-align-tags-to-column
8835 (current-column))) ?\ )
8836 (text-properties-at (point))))))))
8838 (defun org-agenda-priority-up ()
8839 "Increase the priority of line at point, also in Org-mode file."
8840 (interactive)
8841 (org-agenda-priority 'up))
8843 (defun org-agenda-priority-down ()
8844 "Decrease the priority of line at point, also in Org-mode file."
8845 (interactive)
8846 (org-agenda-priority 'down))
8848 (defun org-agenda-priority (&optional force-direction)
8849 "Set the priority of line at point, also in Org-mode file.
8850 This changes the line at point, all other lines in the agenda referring to
8851 the same tree node, and the headline of the tree node in the Org-mode file."
8852 (interactive)
8853 (org-agenda-check-no-diary)
8854 (let* ((marker (or (get-text-property (point) 'org-marker)
8855 (org-agenda-error)))
8856 (buffer (marker-buffer marker))
8857 (pos (marker-position marker))
8858 (hdmarker (get-text-property (point) 'org-hd-marker))
8859 (buffer-read-only nil)
8860 newhead)
8861 (with-current-buffer buffer
8862 (widen)
8863 (goto-char pos)
8864 (org-show-hierarchy-above 'agenda)
8865 (save-excursion
8866 (and (outline-next-heading)
8867 (org-flag-heading nil))) ; show the next heading
8868 (funcall 'org-priority force-direction)
8869 (end-of-line 1)
8870 (setq newhead (org-get-heading)))
8871 (org-agenda-change-all-lines newhead hdmarker)
8872 (beginning-of-line 1)))
8874 (defun org-get-tags-at (&optional pos)
8875 "Get a list of all headline tags applicable at POS.
8876 POS defaults to point. If tags are inherited, the list contains
8877 the targets in the same sequence as the headlines appear, i.e.
8878 the tags of the current headline come last."
8879 (interactive)
8880 (let (tags)
8881 (save-excursion
8882 (goto-char (or pos (point)))
8883 (save-match-data
8884 (org-back-to-heading t)
8885 (condition-case nil
8886 (while t
8887 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
8888 (setq tags (append (org-split-string
8889 (org-match-string-no-properties 1) ":")
8890 tags)))
8891 (or org-use-tag-inheritance (error ""))
8892 (org-up-heading-all 1))
8893 (error nil))))
8894 tags))
8896 (defun org-agenda-set-tags ()
8897 "Set tags for the current headline."
8898 (interactive)
8899 (org-agenda-check-no-diary)
8900 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
8901 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
8902 (org-agenda-error)))
8903 (buffer (marker-buffer hdmarker))
8904 (pos (marker-position hdmarker))
8905 (buffer-read-only nil)
8906 newhead)
8907 (with-current-buffer buffer
8908 (widen)
8909 (goto-char pos)
8910 (org-show-hierarchy-above 'agenda)
8911 (save-excursion
8912 (and (outline-next-heading)
8913 (org-flag-heading nil))) ; show the next heading
8914 (call-interactively 'org-set-tags)
8915 (end-of-line 1)
8916 (setq newhead (org-get-heading)))
8917 (org-agenda-change-all-lines newhead hdmarker)
8918 (beginning-of-line 1)))
8920 (defun org-agenda-date-later (arg &optional what)
8921 "Change the date of this item to one day later."
8922 (interactive "p")
8923 (org-agenda-check-type t 'agenda 'timeline)
8924 (org-agenda-check-no-diary)
8925 (let* ((marker (or (get-text-property (point) 'org-marker)
8926 (org-agenda-error)))
8927 (buffer (marker-buffer marker))
8928 (pos (marker-position marker)))
8929 (with-current-buffer buffer
8930 (widen)
8931 (goto-char pos)
8932 (if (not (org-at-timestamp-p))
8933 (error "Cannot find time stamp"))
8934 (org-timestamp-change arg (or what 'day))
8935 (message "Time stamp changed to %s" org-last-changed-timestamp))))
8937 (defun org-agenda-date-earlier (arg &optional what)
8938 "Change the date of this item to one day earlier."
8939 (interactive "p")
8940 (org-agenda-date-later (- arg) what))
8942 (defun org-agenda-date-prompt (arg)
8943 "Change the date of this item. Date is prompted for, with default today.
8944 The prefix ARG is passed to the `org-time-stamp' command and can therefore
8945 be used to request time specification in the time stamp."
8946 (interactive "P")
8947 (org-agenda-check-type t 'agenda 'timeline)
8948 (org-agenda-check-no-diary)
8949 (let* ((marker (or (get-text-property (point) 'org-marker)
8950 (org-agenda-error)))
8951 (buffer (marker-buffer marker))
8952 (pos (marker-position marker)))
8953 (with-current-buffer buffer
8954 (widen)
8955 (goto-char pos)
8956 (if (not (org-at-timestamp-p))
8957 (error "Cannot find time stamp"))
8958 (org-time-stamp arg)
8959 (message "Time stamp changed to %s" org-last-changed-timestamp))))
8961 (defun org-agenda-schedule (arg)
8962 "Schedule the item at point."
8963 (interactive "P")
8964 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
8965 (org-agenda-check-no-diary)
8966 (let* ((marker (or (get-text-property (point) 'org-marker)
8967 (org-agenda-error)))
8968 (buffer (marker-buffer marker))
8969 (pos (marker-position marker))
8970 (org-insert-labeled-timestamps-at-point nil)
8972 (with-current-buffer buffer
8973 (widen)
8974 (goto-char pos)
8975 (setq ts (org-schedule))
8976 (message "Item scheduled for %s" ts))))
8978 (defun org-agenda-deadline (arg)
8979 "Schedule the item at point."
8980 (interactive "P")
8981 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
8982 (org-agenda-check-no-diary)
8983 (let* ((marker (or (get-text-property (point) 'org-marker)
8984 (org-agenda-error)))
8985 (buffer (marker-buffer marker))
8986 (pos (marker-position marker))
8987 (org-insert-labeled-timestamps-at-point nil)
8989 (with-current-buffer buffer
8990 (widen)
8991 (goto-char pos)
8992 (setq ts (org-deadline))
8993 (message "Deadline for this item set to %s" ts))))
8995 (defun org-get-heading ()
8996 "Return the heading of the current entry, without the stars."
8997 (save-excursion
8998 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
8999 (if (and (re-search-backward "[\r\n]\\*" nil t)
9000 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
9001 (match-string 1)
9002 "")))
9004 (defun org-agenda-clock-in (&optional arg)
9005 "Start the clock on the currently selected item."
9006 (interactive "P")
9007 (org-agenda-check-no-diary)
9008 (let* ((marker (or (get-text-property (point) 'org-marker)
9009 (org-agenda-error)))
9010 (pos (marker-position marker)))
9011 (with-current-buffer (marker-buffer marker)
9012 (widen)
9013 (goto-char pos)
9014 (org-clock-in))))
9016 (defun org-agenda-diary-entry ()
9017 "Make a diary entry, like the `i' command from the calendar.
9018 All the standard commands work: block, weekly etc."
9019 (interactive)
9020 (org-agenda-check-type t 'agenda 'timeline)
9021 (require 'diary-lib)
9022 (let* ((char (progn
9023 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
9024 (read-char-exclusive)))
9025 (cmd (cdr (assoc char
9026 '((?d . insert-diary-entry)
9027 (?w . insert-weekly-diary-entry)
9028 (?m . insert-monthly-diary-entry)
9029 (?y . insert-yearly-diary-entry)
9030 (?a . insert-anniversary-diary-entry)
9031 (?b . insert-block-diary-entry)
9032 (?c . insert-cyclic-diary-entry)))))
9033 (oldf (symbol-function 'calendar-cursor-to-date))
9034 (point (point))
9035 (mark (or (mark t) (point))))
9036 (unless cmd
9037 (error "No command associated with <%c>" char))
9038 (unless (and (get-text-property point 'day)
9039 (or (not (equal ?b char))
9040 (get-text-property mark 'day)))
9041 (error "Don't know which date to use for diary entry"))
9042 ;; We implement this by hacking the `calendar-cursor-to-date' function
9043 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
9044 (let ((calendar-mark-ring
9045 (list (calendar-gregorian-from-absolute
9046 (or (get-text-property mark 'day)
9047 (get-text-property point 'day))))))
9048 (unwind-protect
9049 (progn
9050 (fset 'calendar-cursor-to-date
9051 (lambda (&optional error)
9052 (calendar-gregorian-from-absolute
9053 (get-text-property point 'day))))
9054 (call-interactively cmd))
9055 (fset 'calendar-cursor-to-date oldf)))))
9058 (defun org-agenda-execute-calendar-command (cmd)
9059 "Execute a calendar command from the agenda, with the date associated to
9060 the cursor position."
9061 (org-agenda-check-type t 'agenda 'timeline)
9062 (require 'diary-lib)
9063 (unless (get-text-property (point) 'day)
9064 (error "Don't know which date to use for calendar command"))
9065 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
9066 (point (point))
9067 (date (calendar-gregorian-from-absolute
9068 (get-text-property point 'day)))
9069 (displayed-day (extract-calendar-day date))
9070 (displayed-month (extract-calendar-month date))
9071 (displayed-year (extract-calendar-year date)))
9072 (unwind-protect
9073 (progn
9074 (fset 'calendar-cursor-to-date
9075 (lambda (&optional error)
9076 (calendar-gregorian-from-absolute
9077 (get-text-property point 'day))))
9078 (call-interactively cmd))
9079 (fset 'calendar-cursor-to-date oldf))))
9081 (defun org-agenda-phases-of-moon ()
9082 "Display the phases of the moon for the 3 months around the cursor date."
9083 (interactive)
9084 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
9086 (defun org-agenda-holidays ()
9087 "Display the holidays for the 3 months around the cursor date."
9088 (interactive)
9089 (org-agenda-execute-calendar-command 'list-calendar-holidays))
9091 (defun org-agenda-sunrise-sunset (arg)
9092 "Display sunrise and sunset for the cursor date.
9093 Latitude and longitude can be specified with the variables
9094 `calendar-latitude' and `calendar-longitude'. When called with prefix
9095 argument, latitude and longitude will be prompted for."
9096 (interactive "P")
9097 (let ((calendar-longitude (if arg nil calendar-longitude))
9098 (calendar-latitude (if arg nil calendar-latitude))
9099 (calendar-location-name
9100 (if arg "the given coordinates" calendar-location-name)))
9101 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
9103 (defun org-agenda-goto-calendar ()
9104 "Open the Emacs calendar with the date at the cursor."
9105 (interactive)
9106 (org-agenda-check-type t 'agenda 'timeline)
9107 (let* ((day (or (get-text-property (point) 'day)
9108 (error "Don't know which date to open in calendar")))
9109 (date (calendar-gregorian-from-absolute day))
9110 (calendar-move-hook nil)
9111 (view-calendar-holidays-initially nil)
9112 (view-diary-entries-initially nil))
9113 (calendar)
9114 (calendar-goto-date date)))
9116 (defun org-calendar-goto-agenda ()
9117 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
9118 This is a command that has to be installed in `calendar-mode-map'."
9119 (interactive)
9120 (org-agenda-list nil (calendar-absolute-from-gregorian
9121 (calendar-cursor-to-date))
9122 nil))
9124 (defun org-agenda-convert-date ()
9125 (interactive)
9126 (org-agenda-check-type t 'agenda 'timeline)
9127 (let ((day (get-text-property (point) 'day))
9128 date s)
9129 (unless day
9130 (error "Don't know which date to convert"))
9131 (setq date (calendar-gregorian-from-absolute day))
9132 (setq s (concat
9133 "Gregorian: " (calendar-date-string date) "\n"
9134 "ISO: " (calendar-iso-date-string date) "\n"
9135 "Day of Yr: " (calendar-day-of-year-string date) "\n"
9136 "Julian: " (calendar-julian-date-string date) "\n"
9137 "Astron. JD: " (calendar-astro-date-string date)
9138 " (Julian date number at noon UTC)\n"
9139 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
9140 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
9141 "French: " (calendar-french-date-string date) "\n"
9142 "Mayan: " (calendar-mayan-date-string date) "\n"
9143 "Coptic: " (calendar-coptic-date-string date) "\n"
9144 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
9145 "Persian: " (calendar-persian-date-string date) "\n"
9146 "Chinese: " (calendar-chinese-date-string date) "\n"))
9147 (with-output-to-temp-buffer "*Dates*"
9148 (princ s))
9149 (if (fboundp 'fit-window-to-buffer)
9150 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
9152 ;;; Tags
9154 (defun org-scan-tags (action matcher &optional todo-only)
9155 "Scan headline tags with inheritance and produce output ACTION.
9156 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
9157 evaluated, testing if a given set of tags qualifies a headline for
9158 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
9159 are included in the output."
9160 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9161 (mapconcat 'regexp-quote
9162 (nreverse (cdr (reverse org-todo-keywords)))
9163 "\\|")
9164 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
9165 (props (list 'face nil
9166 'done-face 'org-done
9167 'undone-face nil
9168 'mouse-face 'highlight
9169 'org-not-done-regexp org-not-done-regexp
9170 'keymap org-agenda-keymap
9171 'help-echo
9172 (format "mouse-2 or RET jump to org file %s"
9173 (abbreviate-file-name buffer-file-name))))
9174 lspos
9175 tags tags-list tags-alist (llast 0) rtn level category i txt
9176 todo marker)
9177 (save-excursion
9178 (goto-char (point-min))
9179 (when (eq action 'sparse-tree) (org-overview))
9180 (while (re-search-forward re nil t)
9181 (catch :skip
9182 (and (eq action 'agenda) (org-agenda-skip))
9183 (setq todo (if (match-end 1) (match-string 2))
9184 tags (if (match-end 4) (match-string 4)))
9185 (goto-char (setq lspos (1+ (match-beginning 0))))
9186 (setq level (funcall outline-level)
9187 category (org-get-category))
9188 (setq i llast llast level)
9189 ;; remove tag lists from same and sublevels
9190 (while (>= i level)
9191 (when (setq entry (assoc i tags-alist))
9192 (setq tags-alist (delete entry tags-alist)))
9193 (setq i (1- i)))
9194 ;; add the nex tags
9195 (when tags
9196 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9197 tags-alist
9198 (cons (cons level tags) tags-alist)))
9199 ;; compile tags for current headline
9200 (setq tags-list
9201 (if org-use-tag-inheritance
9202 (apply 'append (mapcar 'cdr tags-alist))
9203 tags))
9204 (when (and (or (not todo-only) todo)
9205 (eval matcher)
9206 (or (not org-agenda-skip-archived-trees)
9207 (not (member org-archive-tag tags-list))))
9208 ;; list this headline
9209 (if (eq action 'sparse-tree)
9210 (progn
9211 (org-show-hierarchy-above 'tags-tree))
9212 (setq txt (org-format-agenda-item
9214 (concat
9215 (if org-tags-match-list-sublevels
9216 (make-string (1- level) ?.) "")
9217 (org-get-heading))
9218 category tags-list))
9219 (goto-char lspos)
9220 (setq marker (org-agenda-new-marker))
9221 (org-add-props txt props
9222 'org-marker marker 'org-hd-marker marker 'category category)
9223 (push txt rtn))
9224 ;; if we are to skip sublevels, jump to end of subtree
9225 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9226 (when (and (eq action 'sparse-tree)
9227 (not org-sparse-tree-open-archived-trees))
9228 (org-hide-archived-subtrees (point-min) (point-max)))
9229 (nreverse rtn)))
9231 (defun org-tags-sparse-tree (&optional arg match)
9232 "Create a sparse tree according to tags search string MATCH.
9233 MATCH can contain positive and negative selection of tags, like
9234 \"+WORK+URGENT-WITHBOSS\"."
9235 (interactive "P")
9236 (let ((org-show-following-heading nil)
9237 (org-show-hierarchy-above nil))
9238 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
9240 (defun org-make-tags-matcher (match)
9241 "Create the TAGS matcher form for the tags-selecting string MATCH."
9242 (unless match
9243 ;; Get a new match request, with completion
9244 (setq org-last-tags-completion-table
9245 (or org-tag-alist
9246 org-last-tags-completion-table))
9247 (setq match (completing-read
9248 "Tags: " 'org-tags-completion-function nil nil nil
9249 'org-tags-history)))
9250 ;; parse the string and create a lisp form
9251 (let ((match0 match) minus tag mm matcher orterms term orlist)
9252 (setq orterms (org-split-string match "|"))
9253 (while (setq term (pop orterms))
9254 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
9255 (setq minus (and (match-end 1)
9256 (equal (match-string 1 term) "-"))
9257 tag (match-string 2 term)
9258 term (substring term (match-end 0))
9259 mm (list 'member (downcase tag) 'tags-list)
9260 mm (if minus (list 'not mm) mm))
9261 (push mm matcher))
9262 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
9263 orlist)
9264 (setq matcher nil))
9265 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9266 ;; Return the string and lisp forms of the matcher
9267 (cons match0 matcher)))
9269 ;;;###autoload
9270 (defun org-tags-view (&optional todo-only match)
9271 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
9272 The prefix arg TODO-ONLY limits the search to TODO entries."
9273 (interactive "P")
9274 (org-compile-prefix-format 'tags)
9275 (org-set-sorting-strategy 'tags)
9276 (let* ((org-tags-match-list-sublevels
9277 (if todo-only t org-tags-match-list-sublevels))
9278 (win (selected-window))
9279 (completion-ignore-case t)
9280 rtn rtnall files file pos matcher
9281 buffer)
9282 (setq matcher (org-make-tags-matcher match)
9283 match (car matcher) matcher (cdr matcher))
9284 (org-prepare-agenda)
9285 (setq org-agenda-redo-command
9286 (list 'org-tags-view (list 'quote todo-only)
9287 (list 'if 'current-prefix-arg nil match)))
9288 (setq files (org-agenda-files)
9289 rtnall nil)
9290 (while (setq file (pop files))
9291 (catch 'nextfile
9292 (org-check-agenda-file file)
9293 (setq buffer (if (file-exists-p file)
9294 (org-get-agenda-file-buffer file)
9295 (error "No such file %s" file)))
9296 (if (not buffer)
9297 ;; If file does not exist, merror message to agenda
9298 (setq rtn (list
9299 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
9300 rtnall (append rtnall rtn))
9301 (with-current-buffer buffer
9302 (unless (org-mode-p)
9303 (error "Agenda file %s is not in `org-mode'" file))
9304 (setq org-category-table (org-get-category-table))
9305 (save-excursion
9306 (save-restriction
9307 (if org-agenda-restrict
9308 (narrow-to-region org-agenda-restrict-begin
9309 org-agenda-restrict-end)
9310 (widen))
9311 (setq rtn (org-scan-tags 'agenda matcher todo-only))
9312 (setq rtnall (append rtnall rtn))))))))
9313 (insert "Headlines with TAGS match: ")
9314 (add-text-properties (point-min) (1- (point))
9315 (list 'face 'org-level-3))
9316 (setq pos (point))
9317 (insert match "\n")
9318 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
9319 (setq pos (point))
9320 (unless org-agenda-multi
9321 (insert "Press `C-u r' to search again with new search string\n"))
9322 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
9323 (when rtnall
9324 (insert (org-finalize-agenda-entries rtnall) "\n"))
9325 (goto-char (point-min))
9326 (org-fit-agenda-window)
9327 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
9328 (org-finalize-agenda)
9329 (setq buffer-read-only t)
9330 (if (not org-select-agenda-window) (select-window win))))
9332 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9333 (defun org-set-tags (&optional arg just-align)
9334 "Set the tags for the current headline.
9335 With prefix ARG, realign all tags in headings in the current buffer."
9336 (interactive "P")
9337 (let* ((re (concat "^" outline-regexp))
9338 (col (current-column))
9339 (current (org-get-tags))
9340 table current-tags inherited-tags ; computed below when needed
9341 tags hd empty invis)
9342 (if arg
9343 (save-excursion
9344 (goto-char (point-min))
9345 (while (re-search-forward re nil t)
9346 (org-set-tags nil t))
9347 (message "All tags realigned to column %d" org-tags-column))
9348 (if just-align
9349 (setq tags current)
9350 (setq table (or org-tag-alist (org-get-buffer-tags))
9351 org-last-tags-completion-table table
9352 current-tags (org-split-string current ":")
9353 inherited-tags (nreverse
9354 (nthcdr (length current-tags)
9355 (nreverse (org-get-tags-at))))
9356 tags
9357 (if (or (eq t org-use-fast-tag-selection)
9358 (and org-use-fast-tag-selection
9359 (delq nil (mapcar 'cdr table))))
9360 (org-fast-tag-selection current-tags inherited-tags table)
9361 (let ((org-add-colon-after-tag-completion t))
9362 (completing-read "Tags: " 'org-tags-completion-function
9363 nil nil current 'org-tags-history))))
9364 (while (string-match "[-+&]+" tags)
9365 (setq tags (replace-match ":" t t tags))))
9366 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
9367 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9368 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9369 (if (equal current "")
9370 (progn
9371 (end-of-line 1)
9372 (or empty (insert " ")))
9373 (beginning-of-line 1)
9374 (setq invis (org-invisible-p))
9375 (looking-at (concat ".*?\\([ \t]*" (regexp-quote current) "\\)[ \t]*"))
9376 (delete-region (match-beginning 1) (match-end 1))
9377 (goto-char (match-beginning 1))
9378 (insert (if empty "" " ")))
9379 (if (equal tags "")
9380 (save-excursion
9381 (beginning-of-line 1)
9382 (skip-chars-forward "*")
9383 (if (= (char-after) ?\ ) (forward-char 1))
9384 (and (re-search-forward "[ \t]+$" (point-at-eol) t)
9385 (replace-match "")))
9386 (let (buffer-invisibility-spec) ; Emacs 21 compatibility
9387 (move-to-column (max (current-column)
9388 (if (> org-tags-column 0)
9389 org-tags-column
9390 (- (- org-tags-column) (length tags))))
9392 (insert tags)
9393 (if (and (not invis) (org-invisible-p))
9394 (outline-flag-region (point) (point-at-bol) nil))) ; show
9395 (move-to-column col))))
9397 (defun org-tags-completion-function (string predicate &optional flag)
9398 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9399 (confirm (lambda (x) (stringp (car x)))))
9400 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9401 (setq s1 (match-string 1 string)
9402 s2 (match-string 2 string))
9403 (setq s1 "" s2 string))
9404 (cond
9405 ((eq flag nil)
9406 ;; try completion
9407 (setq rtn (try-completion s2 ctable confirm))
9408 (if (stringp rtn)
9409 (concat s1 s2 (substring rtn (length s2))
9410 (if (and org-add-colon-after-tag-completion
9411 (assoc rtn ctable))
9412 ":" "")))
9414 ((eq flag t)
9415 ;; all-completions
9416 (all-completions s2 ctable confirm)
9418 ((eq flag 'lambda)
9419 ;; exact match?
9420 (assoc s2 ctable)))
9423 (defun org-fast-tag-insert (kwd tags face &optional end)
9424 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9425 (insert (format "%-12s" (concat kwd ":"))
9426 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9427 (or end "")))
9429 (defun org-fast-tag-selection (current inherited table)
9430 "Fast tag selection with single keys.
9431 CURRENT is the current list of tags in the headline, INHERITED is the
9432 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9433 possibly with grouping information.
9434 If the keys are nil, a-z are automatically assigned.
9435 Returns the new tags string, or nil to not change the current settings."
9436 (let* ((maxlen (apply 'max (mapcar
9437 (lambda (x)
9438 (if (stringp (car x)) (string-width (car x)) 0))
9439 table)))
9440 (fwidth (+ maxlen 3 1 3))
9441 (ncol (/ (- (window-width) 4) fwidth))
9442 (i-face 'org-done)
9443 (c-face 'org-tag)
9444 tg cnt e c char c1 c2 ntable tbl rtn
9445 groups ingroup)
9446 (save-window-excursion
9447 (delete-other-windows)
9448 (split-window-vertically)
9449 (switch-to-buffer-other-window (get-buffer-create " *Org tags*"))
9450 (erase-buffer)
9451 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9452 (org-fast-tag-insert "Current" current c-face "\n\n")
9453 (setq tbl table char ?a cnt 0)
9454 (while (setq e (pop tbl))
9455 (cond
9456 ((equal e '(:startgroup))
9457 (push '() groups) (setq ingroup t)
9458 (when (not (= cnt 0))
9459 (setq cnt 0)
9460 (insert "\n"))
9461 (insert "{ "))
9462 ((equal e '(:endgroup))
9463 (setq ingroup nil cnt 0)
9464 (insert "}\n"))
9466 (setq tg (car e) c2 nil)
9467 (if (cdr e)
9468 (setq c (cdr e))
9469 ;; automatically assign a character.
9470 (setq c1 (string-to-char
9471 (downcase (substring
9472 tg (if (= (string-to-char tg) ?@) 1 0)))))
9473 (if (or (rassoc c1 ntable) (rassoc c1 table))
9474 (while (or (rassoc char ntable) (rassoc char table))
9475 (setq char (1+ char)))
9476 (setq c2 c1))
9477 (setq c (or c2 char)))
9478 (if ingroup (push tg (car groups)))
9479 (setq tg (org-add-props tg nil 'face
9480 (cond
9481 ((member tg current) c-face)
9482 ((member tg inherited) i-face)
9483 (t nil))))
9484 (if (and (= cnt 0) (not ingroup)) (insert " "))
9485 (insert "[" c "] " tg (make-string
9486 (- fwidth 4 (length tg)) ?\ ))
9487 (push (cons tg c) ntable)
9488 (when (= (setq cnt (1+ cnt)) ncol)
9489 (insert "\n")
9490 (if ingroup (insert " "))
9491 (setq cnt 0)))))
9492 (setq ntable (nreverse ntable))
9493 (insert "\n")
9494 (goto-char (point-min))
9495 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
9496 (setq rtn
9497 (catch 'exit
9498 (while t
9499 (message "[key]:Toggle SPC: clear current RET accept%s"
9500 (if groups " [!] ignore goups" ""))
9501 (setq c (read-char-exclusive))
9502 (cond
9503 ((= c ?\r) (throw 'exit t))
9504 ((= c ?!)
9505 (setq groups nil)
9506 (goto-char (point-min))
9507 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9508 ((or (= c ?\C-g)
9509 (and (= c ?q) (not (rassoc c ntable))))
9510 (setq quit-flag t))
9511 ((= c ?\ ) (setq current nil))
9512 ((setq e (rassoc c ntable) tg (car e))
9513 (if (member tg current)
9514 (setq current (delete tg current))
9515 (loop for g in groups do
9516 (if (member tg g)
9517 (mapcar (lambda (x)
9518 (setq current (delete x current)))
9519 g)))
9520 (setq current (cons tg current)))))
9521 ;; Create a sorted list
9522 (setq current
9523 (sort current
9524 (lambda (a b)
9525 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9526 (goto-char (point-min))
9527 (beginning-of-line 2)
9528 (delete-region (point) (point-at-eol))
9529 (org-fast-tag-insert "Current" current c-face)
9530 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
9531 (setq tg (match-string 1))
9532 (add-text-properties (match-beginning 1) (match-end 1)
9533 (list 'face
9534 (cond
9535 ((member tg current) c-face)
9536 ((member tg inherited) i-face)
9537 (t nil)))))
9538 (goto-char (point-min)))))
9539 (if rtn
9540 (mapconcat 'identity current ":")
9541 nil))))
9543 (defun org-get-tags ()
9544 "Get the TAGS string in the current headline."
9545 (unless (org-on-heading-p t)
9546 (error "Not on a heading"))
9547 (save-excursion
9548 (beginning-of-line 1)
9549 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
9550 (org-match-string-no-properties 1)
9551 "")))
9553 (defun org-get-buffer-tags ()
9554 "Get a table of all tags used in the buffer, for completion."
9555 (let (tags)
9556 (save-excursion
9557 (goto-char (point-min))
9558 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
9559 (mapc (lambda (x) (add-to-list 'tags x))
9560 (org-split-string (org-match-string-no-properties 1) ":"))))
9561 (mapcar 'list tags)))
9563 ;;; Link Stuff
9565 (defvar org-create-file-search-functions nil
9566 "List of functions to construct the right search string for a file link.
9567 These functions are called in turn with point at the location to
9568 which the link should point.
9570 A function in the hook should first test if it would like to
9571 handle this file type, for example by checking the major-mode or
9572 the file extension. If it decides not to handle this file, it
9573 should just return nil to give other functions a chance. If it
9574 does handle the file, it must return the search string to be used
9575 when following the link. The search string will be part of the
9576 file link, given after a double colon, and `org-open-at-point'
9577 will automatically search for it. If special measures must be
9578 taken to make the search successful, another function should be
9579 added to the companion hook `org-execute-file-search-functions',
9580 which see.
9582 A function in this hook may also use `setq' to set the variable
9583 `description' to provide a suggestion for the descriptive text to
9584 be used for this link when it gets inserted into an Org-mode
9585 buffer with \\[org-insert-link].")
9587 (defvar org-execute-file-search-functions nil
9588 "List of functions to execute a file search triggered by a link.
9590 Functions added to this hook must accept a single argument, the
9591 search string that was part of the file link, the part after the
9592 double colon. The function must first check if it would like to
9593 handle this search, for example by checking the major-mode or the
9594 file extension. If it decides not to handle this search, it
9595 should just return nil to give other functions a chance. If it
9596 does handle the search, it must return a non-nil value to keep
9597 other functions from trying.
9599 Each function can access the current prefix argument through the
9600 variable `current-prefix-argument'. Note that a single prefix is
9601 used to force opening a link in Emacs, so it may be good to only
9602 use a numeric or double prefix to guide the search function.
9604 In case this is needed, a function in this hook can also restore
9605 the window configuration before `org-open-at-point' was called using:
9607 (set-window-configuration org-window-config-before-follow-link)")
9609 (defun org-find-file-at-mouse (ev)
9610 "Open file link or URL at mouse."
9611 (interactive "e")
9612 (mouse-set-point ev)
9613 (org-open-at-point 'in-emacs))
9615 (defun org-open-at-mouse (ev)
9616 "Open file link or URL at mouse."
9617 (interactive "e")
9618 (mouse-set-point ev)
9619 (org-open-at-point))
9621 (defvar org-window-config-before-follow-link nil
9622 "The window configuration before following a link.
9623 This is saved in case the need arises to restore it.")
9625 ;; FIXME: IN-EMACS is used for many purposes, maybe rename this argument???
9626 (defun org-open-at-point (&optional in-emacs)
9627 "Open link at or after point.
9628 If there is no link at point, this function will search forward up to
9629 the end of the current subtree.
9630 Normally, files will be opened by an appropriate application. If the
9631 optional argument IN-EMACS is non-nil, Emacs will visit the file."
9632 (interactive "P")
9633 (setq org-window-config-before-follow-link (current-window-configuration))
9634 (org-remove-occur-highlights nil nil t)
9635 (if (org-at-timestamp-p)
9636 (org-follow-timestamp-link)
9637 (let (type path link line search (pos (point)))
9638 (catch 'match
9639 (save-excursion
9640 (skip-chars-forward "^]\n\r")
9641 (when (and (re-search-backward "\\[\\[" nil t)
9642 (looking-at org-bracket-link-regexp)
9643 (<= (match-beginning 0) pos)
9644 (>= (match-end 0) pos))
9645 (setq link (org-link-unescape (org-match-string-no-properties 1)))
9646 (while (string-match " *\n *" link)
9647 (setq link (replace-match " " t t link)))
9648 (setq link (org-link-expand-abbrev link))
9649 (if (string-match org-link-re-with-space2 link)
9650 (setq type (match-string 1 link)
9651 path (match-string 2 link))
9652 (setq type "thisfile"
9653 path link))
9654 (throw 'match t)))
9656 (when (get-text-property (point) 'org-linked-text)
9657 (setq type "thisfile"
9658 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9659 (1+ (point)) (point))
9660 path (buffer-substring
9661 (previous-single-property-change pos 'org-linked-text)
9662 (next-single-property-change pos 'org-linked-text)))
9663 (throw 'match t))
9665 (save-excursion
9666 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
9667 (if (equal (char-before) ?<) (backward-char 1))
9668 (when (or (looking-at org-angle-link-re)
9669 (looking-at org-plain-link-re)
9670 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
9671 (re-search-forward org-plain-link-re (point-at-eol) t))
9672 (<= (match-beginning 0) pos)
9673 (>= (match-end 0) pos)))
9674 (setq type (match-string 1)
9675 path (match-string 2))
9676 (throw 'match t)))
9677 (save-excursion
9678 (skip-chars-backward "^ \t\n\r")
9679 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
9680 (setq type "tags"
9681 path (match-string 1))
9682 (while (string-match ":" path)
9683 (setq path (replace-match "+" t t path)))
9684 (throw 'match t)))
9685 (save-excursion
9686 (skip-chars-backward "a-zA-Z_")
9687 (when (and (memq 'camel org-activate-links)
9688 (looking-at org-camel-regexp))
9689 (setq type "camel" path (match-string 0))
9690 (if (equal (char-before) ?*)
9691 (setq path (concat "*" path))))
9692 (throw 'match t)))
9693 (unless path
9694 (error "No link found"))
9695 ;; Remove any trailing spaces in path
9696 (if (string-match " +\\'" path)
9697 (setq path (replace-match "" t t path)))
9699 (cond
9701 ((equal type "mailto")
9702 (let ((cmd (car org-link-mailto-program))
9703 (args (cdr org-link-mailto-program)) args1
9704 (address path) (subject "") a)
9705 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9706 (setq address (match-string 1 path)
9707 subject (org-link-escape (match-string 2 path))))
9708 (while args
9709 (cond
9710 ((not (stringp (car args))) (push (pop args) args1))
9711 (t (setq a (pop args))
9712 (if (string-match "%a" a)
9713 (setq a (replace-match address t t a)))
9714 (if (string-match "%s" a)
9715 (setq a (replace-match subject t t a)))
9716 (push a args1))))
9717 (apply cmd (nreverse args1))))
9719 ((member type '("http" "https" "ftp" "news"))
9720 (browse-url (concat type ":" path)))
9722 ((string= type "tags")
9723 (org-tags-view in-emacs path))
9724 ((or (string= type "camel")
9725 (string= type "thisfile"))
9726 (if in-emacs
9727 (switch-to-buffer-other-window
9728 (org-get-buffer-for-internal-link (current-buffer)))
9729 (org-mark-ring-push))
9730 (org-link-search
9731 path
9732 (cond ((equal in-emacs '(4)) 'occur)
9733 ((equal in-emacs '(16)) 'org-occur)
9734 (t nil))))
9736 ((string= type "file")
9737 (if (string-match "::\\([0-9]+\\)\\'" path)
9738 (setq line (string-to-number (match-string 1 path))
9739 path (substring path 0 (match-beginning 0)))
9740 (if (string-match "::\\(.+\\)\\'" path)
9741 (setq search (match-string 1 path)
9742 path (substring path 0 (match-beginning 0)))))
9743 (org-open-file path in-emacs line search))
9745 ((string= type "news")
9746 (org-follow-gnus-link path))
9748 ((string= type "bbdb")
9749 (org-follow-bbdb-link path))
9751 ((string= type "info")
9752 (org-follow-info-link path))
9754 ((string= type "gnus")
9755 (let (group article)
9756 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9757 (error "Error in Gnus link"))
9758 (setq group (match-string 1 path)
9759 article (match-string 3 path))
9760 (org-follow-gnus-link group article)))
9762 ((string= type "vm")
9763 (let (folder article)
9764 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9765 (error "Error in VM link"))
9766 (setq folder (match-string 1 path)
9767 article (match-string 3 path))
9768 ;; in-emacs is the prefix arg, will be interpreted as read-only
9769 (org-follow-vm-link folder article in-emacs)))
9771 ((string= type "wl")
9772 (let (folder article)
9773 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9774 (error "Error in Wanderlust link"))
9775 (setq folder (match-string 1 path)
9776 article (match-string 3 path))
9777 (org-follow-wl-link folder article)))
9779 ((string= type "mhe")
9780 (let (folder article)
9781 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9782 (error "Error in MHE link"))
9783 (setq folder (match-string 1 path)
9784 article (match-string 3 path))
9785 (org-follow-mhe-link folder article)))
9787 ((string= type "rmail")
9788 (let (folder article)
9789 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9790 (error "Error in RMAIL link"))
9791 (setq folder (match-string 1 path)
9792 article (match-string 3 path))
9793 (org-follow-rmail-link folder article)))
9795 ((string= type "shell")
9796 (let ((cmd path))
9797 (while (string-match "@{" cmd)
9798 (setq cmd (replace-match "<" t t cmd)))
9799 (while (string-match "@}" cmd)
9800 (setq cmd (replace-match ">" t t cmd)))
9801 (if (or (not org-confirm-shell-link-function)
9802 (funcall org-confirm-shell-link-function
9803 (format "Execute \"%s\" in shell? "
9804 (org-add-props cmd nil
9805 'face 'org-warning))))
9806 (progn
9807 (message "Executing %s" cmd)
9808 (shell-command cmd))
9809 (error "Abort"))))
9811 ((string= type "elisp")
9812 (let ((cmd path))
9813 (if (or (not org-confirm-elisp-link-function)
9814 (funcall org-confirm-elisp-link-function
9815 (format "Execute \"%s\" as elisp? "
9816 (org-add-props cmd nil
9817 'face 'org-warning))))
9818 (message "%s => %s" cmd (eval (read cmd)))
9819 (error "Abort"))))
9822 (browse-url-at-point))))))
9825 (defun org-link-expand-abbrev (link)
9826 "Apply replacements as defined in `org-link-abbrev-alist."
9827 (if (string-match "^\\([a-zA-Z]+\\)\\(::\\(.*\\)\\)?$" link)
9828 (let* ((key (match-string 1 link))
9829 (as (or (assoc key org-link-abbrev-alist-local)
9830 (assoc key org-link-abbrev-alist)))
9831 (tag (and (match-end 2) (match-string 3 link)))
9832 rpl)
9833 (if (not as)
9834 link
9835 (setq rpl (cdr as))
9836 (cond
9837 ((symbolp rpl) (funcall rpl tag))
9838 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9839 (t (concat rpl tag)))))
9840 link))
9842 (defun org-link-search (s &optional type)
9843 "Search for a link search option.
9844 When S is a CamelCaseWord, search for a target, or for a sentence containing
9845 the words. If S is surrounded by forward slashes, it is interpreted as a
9846 regular expression. In org-mode files, this will create an `org-occur'
9847 sparse tree. In ordinary files, `occur' will be used to list matches.
9848 If the current buffer is in `dired-mode', grep will be used to search
9849 in all files."
9850 (let ((case-fold-search t)
9851 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9852 (pos (point))
9853 (pre "") (post "")
9854 words re0 re1 re2 re3 re4 re5 re2a reall camel)
9855 (cond
9856 ;; First check if there are any special
9857 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9858 ;; Now try the builtin stuff
9859 ((save-excursion
9860 (goto-char (point-min))
9861 (and
9862 (re-search-forward
9863 (concat "<<" (regexp-quote s0) ">>") nil t)
9864 (setq pos (match-beginning 0))))
9865 ;; There is an exact target for this
9866 (goto-char pos))
9867 ((string-match "^/\\(.*\\)/$" s)
9868 ;; A regular expression
9869 (cond
9870 ((org-mode-p)
9871 (org-occur (match-string 1 s)))
9872 ;;((eq major-mode 'dired-mode)
9873 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9874 (t (org-do-occur (match-string 1 s)))))
9875 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
9877 ;; A camel or a normal search string
9878 (when (equal (string-to-char s) ?*)
9879 ;; Anchor on headlines, post may include tags.
9880 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
9881 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
9882 s (substring s 1)))
9883 (remove-text-properties
9884 0 (length s)
9885 '(face nil mouse-face nil keymap nil fontified nil) s)
9886 ;; Make a series of regular expressions to find a match
9887 (setq words
9888 (if camel
9889 (org-camel-to-words s)
9890 (org-split-string s "[ \n\r\t]+"))
9891 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9892 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
9893 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9894 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9895 re1 (concat pre re2 post)
9896 re3 (concat pre re4 post)
9897 re5 (concat pre ".*" re4)
9898 re2 (concat pre re2)
9899 re2a (concat pre re2a)
9900 re4 (concat pre re4)
9901 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9902 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9903 re5 "\\)"
9905 (cond
9906 ((eq type 'org-occur) (org-occur reall))
9907 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9908 (t (goto-char (point-min))
9909 (if (or (org-search-not-link re0 nil t)
9910 (org-search-not-link re1 nil t)
9911 (org-search-not-link re2 nil t)
9912 (org-search-not-link re2a nil t)
9913 (org-search-not-link re3 nil t)
9914 (org-search-not-link re4 nil t)
9915 (org-search-not-link re5 nil t)
9917 (goto-char (match-beginning 1))
9918 (goto-char pos)
9919 (error "No match")))))
9921 ;; Normal string-search
9922 (goto-char (point-min))
9923 (if (search-forward s nil t)
9924 (goto-char (match-beginning 0))
9925 (error "No match"))))
9926 (and (org-mode-p) (org-show-hierarchy-above 'link-search))))
9928 (defun org-search-not-link (&rest args)
9929 "Execute `re-search-forward', but only accept matches that are not a link."
9930 (catch 'exit
9931 (let (p1)
9932 (while (apply 're-search-forward args)
9933 (setq p1 (point))
9934 (if (not (save-match-data
9935 (and (re-search-backward "\\[\\[" nil t)
9936 (looking-at org-bracket-link-regexp)
9937 (<= (match-beginning 0) p1)
9938 (>= (match-end 0) p1))))
9939 (progn (goto-char (match-end 0))
9940 (throw 'exit (point)))
9941 (goto-char (match-end 0)))))))
9943 (defun org-get-buffer-for-internal-link (buffer)
9944 "Return a buffer to be used for displaying the link target of internal links."
9945 (cond
9946 ((not org-display-internal-link-with-indirect-buffer)
9947 buffer)
9948 ((string-match "(Clone)$" (buffer-name buffer))
9949 (message "Buffer is already a clone, not making another one")
9950 ;; we also do not modify visibility in this case
9951 buffer)
9952 (t ; make a new indirect buffer for displaying the link
9953 (let* ((bn (buffer-name buffer))
9954 (ibn (concat bn "(Clone)"))
9955 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9956 (with-current-buffer ib (org-overview))
9957 ib))))
9959 (defun org-do-occur (regexp &optional cleanup)
9960 "Call the Emacs command `occur'.
9961 If CLEANUP is non-nil, remove the printout of the regular expression
9962 in the *Occur* buffer. This is useful if the regex is long and not useful
9963 to read."
9964 (occur regexp)
9965 (when cleanup
9966 (let ((cwin (selected-window)) win beg end)
9967 (when (setq win (get-buffer-window "*Occur*"))
9968 (select-window win))
9969 (goto-char (point-min))
9970 (when (re-search-forward "match[a-z]+" nil t)
9971 (setq beg (match-end 0))
9972 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9973 (setq end (1- (match-beginning 0)))))
9974 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
9975 (goto-char (point-min))
9976 (select-window cwin))))
9978 (defvar org-mark-ring nil
9979 "Mark ring for positions before jumps in Org-mode.")
9980 (defvar org-mark-ring-last-goto nil
9981 "Last position in the mark ring used to go back.")
9982 ;; Fill and close the ring
9983 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9984 (loop for i from 1 to org-mark-ring-length do
9985 (push (make-marker) org-mark-ring))
9986 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9987 org-mark-ring)
9989 (defun org-mark-ring-push (&optional pos buffer)
9990 "Put the current position or POS into the mark ring and rotate it."
9991 (interactive)
9992 (setq pos (or pos (point)))
9993 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9994 (move-marker (car org-mark-ring)
9995 (or pos (point))
9996 (or buffer (current-buffer)))
9997 (message
9998 (substitute-command-keys
9999 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10001 (defun org-mark-ring-goto (&optional n)
10002 "Jump to the previous position in the mark ring.
10003 With prefix arg N, jump back that many stored positions. When
10004 called several times in succession, walk through the entire ring.
10005 Org-mode commands jumping to a different position in the current file,
10006 or to another Org-mode file, automatically push the old position
10007 onto the ring."
10008 (interactive "p")
10009 (let (p m)
10010 (if (eq last-command this-command)
10011 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10012 (setq p org-mark-ring))
10013 (setq org-mark-ring-last-goto p)
10014 (setq m (car p))
10015 (switch-to-buffer (marker-buffer m))
10016 (goto-char m)
10017 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above 'mark-goto))))
10019 (defun org-camel-to-words (s)
10020 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
10021 (let ((case-fold-search nil)
10022 words)
10023 (while (string-match "[a-z][A-Z]" s)
10024 (push (substring s 0 (1+ (match-beginning 0))) words)
10025 (setq s (substring s (1+ (match-beginning 0)))))
10026 (nreverse (cons s words))))
10028 (defun org-remove-angle-brackets (s)
10029 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10030 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10032 (defun org-add-angle-brackets (s)
10033 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10034 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10037 (defun org-follow-timestamp-link ()
10038 (cond
10039 ((org-at-date-range-p)
10040 (let ((org-agenda-start-on-weekday)
10041 (t1 (match-string 1))
10042 (t2 (match-string 2)))
10043 (setq t1 (time-to-days (org-time-string-to-time t1))
10044 t2 (time-to-days (org-time-string-to-time t2)))
10045 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10046 ((org-at-timestamp-p)
10047 (org-agenda-list nil (time-to-days (org-time-string-to-time
10048 (substring (match-string 1) 0 10)))
10050 (t (error "This should not happen"))))
10053 (defun org-follow-bbdb-link (name)
10054 "Follow a BBDB link to NAME."
10055 (require 'bbdb)
10056 (let ((inhibit-redisplay t)
10057 (bbdb-electric-p nil))
10058 (catch 'exit
10059 ;; Exact match on name
10060 (bbdb-name (concat "\\`" name "\\'") nil)
10061 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10062 ;; Exact match on name
10063 (bbdb-company (concat "\\`" name "\\'") nil)
10064 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10065 ;; Partial match on name
10066 (bbdb-name name nil)
10067 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10068 ;; Partial match on company
10069 (bbdb-company name nil)
10070 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10071 ;; General match including network address and notes
10072 (bbdb name nil)
10073 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
10074 (delete-window (get-buffer-window "*BBDB*"))
10075 (error "No matching BBDB record")))))
10078 (defun org-follow-info-link (name)
10079 "Follow an info file & node link to NAME."
10080 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
10081 (string-match "\\(.*\\)" name))
10082 (progn
10083 (require 'info)
10084 (if (match-string 2 name) ; If there isn't a node, choose "Top"
10085 (Info-find-node (match-string 1 name) (match-string 2 name))
10086 (Info-find-node (match-string 1 name) "Top")))
10087 (message (concat "Could not open: " name))))
10089 (defun org-follow-gnus-link (&optional group article)
10090 "Follow a Gnus link to GROUP and ARTICLE."
10091 (require 'gnus)
10092 (funcall (cdr (assq 'gnus org-link-frame-setup)))
10093 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
10094 (if group (gnus-fetch-group group))
10095 (if article
10096 (or (gnus-summary-goto-article article nil 'force)
10097 (if (fboundp 'gnus-summary-insert-cached-articles)
10098 (progn
10099 (gnus-summary-insert-cached-articles)
10100 (gnus-summary-goto-article article nil 'force))
10101 (message "Message could not be found.")))))
10103 (defun org-follow-vm-link (&optional folder article readonly)
10104 "Follow a VM link to FOLDER and ARTICLE."
10105 (require 'vm)
10106 (setq article (org-add-angle-brackets article))
10107 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
10108 ;; ange-ftp or efs or tramp access
10109 (let ((user (or (match-string 1 folder) (user-login-name)))
10110 (host (match-string 2 folder))
10111 (file (match-string 3 folder)))
10112 (cond
10113 ((featurep 'tramp)
10114 ;; use tramp to access the file
10115 (if (featurep 'xemacs)
10116 (setq folder (format "[%s@%s]%s" user host file))
10117 (setq folder (format "/%s@%s:%s" user host file))))
10119 ;; use ange-ftp or efs
10120 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
10121 (setq folder (format "/%s@%s:%s" user host file))))))
10122 (when folder
10123 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
10124 (sit-for 0.1)
10125 (when article
10126 (vm-select-folder-buffer)
10127 (widen)
10128 (let ((case-fold-search t))
10129 (goto-char (point-min))
10130 (if (not (re-search-forward
10131 (concat "^" "message-id: *" (regexp-quote article))))
10132 (error "Could not find the specified message in this folder"))
10133 (vm-isearch-update)
10134 (vm-isearch-narrow)
10135 (vm-beginning-of-message)
10136 (vm-summarize)))))
10138 (defun org-follow-wl-link (folder article)
10139 "Follow a Wanderlust link to FOLDER and ARTICLE."
10140 (setq article (org-add-angle-brackets article))
10141 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
10142 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
10143 (wl-summary-redisplay))
10145 (defun org-follow-rmail-link (folder article)
10146 "Follow an RMAIL link to FOLDER and ARTICLE."
10147 (setq article (org-add-angle-brackets article))
10148 (let (message-number)
10149 (save-excursion
10150 (save-window-excursion
10151 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
10152 (setq message-number
10153 (save-restriction
10154 (widen)
10155 (goto-char (point-max))
10156 (if (re-search-backward
10157 (concat "^Message-ID:\\s-+" (regexp-quote
10158 (or article "")))
10159 nil t)
10160 (rmail-what-message))))))
10161 (if message-number
10162 (progn
10163 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
10164 (rmail-show-message message-number)
10165 message-number)
10166 (error "Message not found"))))
10168 ;; mh-e integration based on planner-mode
10169 (defun org-mhe-get-message-real-folder ()
10170 "Return the name of the current message real folder, so if you use
10171 sequences, it will now work."
10172 (save-excursion
10173 (let* ((folder
10174 (if (equal major-mode 'mh-folder-mode)
10175 mh-current-folder
10176 ;; Refer to the show buffer
10177 mh-show-folder-buffer))
10178 (end-index
10179 (if (boundp 'mh-index-folder)
10180 (min (length mh-index-folder) (length folder))))
10182 ;; a simple test on mh-index-data does not work, because
10183 ;; mh-index-data is always nil in a show buffer.
10184 (if (and (boundp 'mh-index-folder)
10185 (string= mh-index-folder (substring folder 0 end-index)))
10186 (if (equal major-mode 'mh-show-mode)
10187 (save-window-excursion
10188 (when (buffer-live-p (get-buffer folder))
10189 (progn
10190 (pop-to-buffer folder)
10191 (org-mhe-get-message-folder-from-index)
10194 (org-mhe-get-message-folder-from-index)
10196 folder
10200 (defun org-mhe-get-message-folder-from-index ()
10201 "Returns the name of the message folder in a index folder buffer."
10202 (save-excursion
10203 (mh-index-previous-folder)
10204 (re-search-forward "^\\(+.*\\)$" nil t)
10205 (message (match-string 1))))
10207 (defun org-mhe-get-message-folder ()
10208 "Return the name of the current message folder. Be careful if you
10209 use sequences."
10210 (save-excursion
10211 (if (equal major-mode 'mh-folder-mode)
10212 mh-current-folder
10213 ;; Refer to the show buffer
10214 mh-show-folder-buffer)))
10216 (defun org-mhe-get-message-num ()
10217 "Return the number of the current message. Be careful if you
10218 use sequences."
10219 (save-excursion
10220 (if (equal major-mode 'mh-folder-mode)
10221 (mh-get-msg-num nil)
10222 ;; Refer to the show buffer
10223 (mh-show-buffer-message-number))))
10225 (defun org-mhe-get-header (header)
10226 "Return a header of the message in folder mode. This will create a
10227 show buffer for the corresponding message. If you have a more clever
10228 idea..."
10229 (let* ((folder (org-mhe-get-message-folder))
10230 (num (org-mhe-get-message-num))
10231 (buffer (get-buffer-create (concat "show-" folder)))
10232 (header-field))
10233 (with-current-buffer buffer
10234 (mh-display-msg num folder)
10235 (if (equal major-mode 'mh-folder-mode)
10236 (mh-header-display)
10237 (mh-show-header-display))
10238 (set-buffer buffer)
10239 (setq header-field (mh-get-header-field header))
10240 (if (equal major-mode 'mh-folder-mode)
10241 (mh-show)
10242 (mh-show-show))
10243 header-field)))
10245 (defun org-follow-mhe-link (folder article)
10246 "Follow an MHE link to FOLDER and ARTICLE.
10247 If ARTICLE is nil FOLDER is shown. If the configuration variable
10248 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
10249 ARTICLE is searched in all folders. Indexed searches (swish++,
10250 namazu, and others supported by MH-E) will always search in all
10251 folders."
10252 (require 'mh-e)
10253 (require 'mh-search)
10254 (require 'mh-utils)
10255 (mh-find-path)
10256 (if (not article)
10257 (mh-visit-folder (mh-normalize-folder-name folder))
10258 (setq article (org-add-angle-brackets article))
10259 (mh-search-choose)
10260 (if (equal mh-searcher 'pick)
10261 (progn
10262 (mh-search folder (list "--message-id" article))
10263 (when (and org-mhe-search-all-folders
10264 (not (org-mhe-get-message-real-folder)))
10265 (kill-this-buffer)
10266 (mh-search "+" (list "--message-id" article))))
10267 (mh-search "+" article))
10268 (if (org-mhe-get-message-real-folder)
10269 (mh-show-msg 1)
10270 (kill-this-buffer)
10271 (error "Message not found"))))
10273 ;; BibTeX links
10275 ;; Use the custom search meachnism to construct and use search strings for
10276 ;; file links to BibTeX database entries.
10278 (defun org-create-file-search-in-bibtex ()
10279 "Create the search string and description for a BibTeX database entry."
10280 (when (eq major-mode 'bibtex-mode)
10281 ;; yes, we want to construct this search string.
10282 ;; Make a good description for this entry, using names, year and the title
10283 ;; Put it into the `description' variable which is dynamically scoped.
10284 (let ((bibtex-autokey-names 1)
10285 (bibtex-autokey-names-stretch 1)
10286 (bibtex-autokey-name-case-convert-function 'identity)
10287 (bibtex-autokey-name-separator " & ")
10288 (bibtex-autokey-additional-names " et al.")
10289 (bibtex-autokey-year-length 4)
10290 (bibtex-autokey-name-year-separator " ")
10291 (bibtex-autokey-titlewords 3)
10292 (bibtex-autokey-titleword-separator " ")
10293 (bibtex-autokey-titleword-case-convert-function 'identity)
10294 (bibtex-autokey-titleword-length 'infty)
10295 (bibtex-autokey-year-title-separator ": "))
10296 (setq description (bibtex-generate-autokey)))
10297 ;; Now parse the entry, get the key and return it.
10298 (save-excursion
10299 (bibtex-beginning-of-entry)
10300 (cdr (assoc "=key=" (bibtex-parse-entry))))))
10302 (defun org-execute-file-search-in-bibtex (s)
10303 "Find the link search string S as a key for a database entry."
10304 (when (eq major-mode 'bibtex-mode)
10305 ;; Yes, we want to do the search in this file.
10306 ;; We construct a regexp that searches for "@entrytype{" followed by the key
10307 (goto-char (point-min))
10308 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
10309 (regexp-quote s) "[ \t\n]*,") nil t)
10310 (goto-char (match-beginning 0)))
10311 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
10312 ;; Use double prefix to indicate that any web link should be browsed
10313 (let ((b (current-buffer)) (p (point)))
10314 ;; Restore the window configuration because we just use the web link
10315 (set-window-configuration org-window-config-before-follow-link)
10316 (save-excursion (set-buffer b) (goto-char p)
10317 (bibtex-url)))
10318 (recenter 0)) ; Move entry start to beginning of window
10319 ;; return t to indicate that the search is done.
10322 ;; Finally add the functions to the right hooks.
10323 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
10324 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
10326 ;; end of Bibtex link setup
10328 (defun org-upgrade-old-links (&optional query-description)
10329 "Transfer old <...> style links to new [[...]] style links.
10330 With arg query-description, ask at each match for a description text to use
10331 for this link."
10332 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
10333 (save-excursion
10334 (goto-char (point-min))
10335 (let ((re (concat "\\([^[]\\)<\\("
10336 "\\(" (mapconcat 'identity org-link-types "\\|")
10337 "\\):"
10338 "[^" org-non-link-chars "]+\\)>"))
10339 l1 l2 (cnt 0))
10340 (while (re-search-forward re nil t)
10341 (setq cnt (1+ cnt)
10342 l1 (org-match-string-no-properties 2)
10343 l2 (save-match-data (org-link-escape l1)))
10344 (when query-description (setq l1 (read-string "Desc: " l1)))
10345 (if (equal l1 l2)
10346 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
10347 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
10348 (message "%d matches have beed treated" cnt))))
10350 (defun org-open-file (path &optional in-emacs line search)
10351 "Open the file at PATH.
10352 First, this expands any special file name abbreviations. Then the
10353 configuration variable `org-file-apps' is checked if it contains an
10354 entry for this file type, and if yes, the corresponding command is launched.
10355 If no application is found, Emacs simply visits the file.
10356 With optional argument IN-EMACS, Emacs will visit the file.
10357 Optional LINE specifies a line to go to, optional SEARCH a string to
10358 search for. If LINE or SEARCH is given, the file will always be
10359 opened in Emacs.
10360 If the file does not exist, an error is thrown."
10361 (setq in-emacs (or in-emacs line search))
10362 (let* ((file (if (equal path "")
10363 buffer-file-name
10364 (substitute-in-file-name (expand-file-name path))))
10365 (apps (append org-file-apps (org-default-apps)))
10366 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10367 (dirp (if remp nil (file-directory-p file)))
10368 (dfile (downcase file))
10369 (old-buffer (current-buffer))
10370 (old-pos (point))
10371 (old-mode major-mode)
10372 ext cmd)
10373 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10374 (setq ext (match-string 1 dfile))
10375 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10376 (setq ext (match-string 1 dfile))))
10377 (if in-emacs
10378 (setq cmd 'emacs)
10379 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10380 (and dirp (cdr (assoc 'directory apps)))
10381 (cdr (assoc ext apps))
10382 (cdr (assoc t apps)))))
10383 (when (eq cmd 'mailcap)
10384 (require 'mailcap)
10385 (mailcap-parse-mailcaps)
10386 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10387 (command (mailcap-mime-info mime-type)))
10388 (if (stringp command)
10389 (setq cmd command)
10390 (setq cmd 'emacs))))
10391 (if (and (not (eq cmd 'emacs)) ; Emacs has not problems with non-ex files
10392 (not (file-exists-p file))
10393 (not org-open-non-existing-files))
10394 (error "No such file: %s" file))
10395 (cond
10396 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10397 ;; Normalize use of quote, this can vary.
10398 (if (string-match "['\"]%s['\"]" cmd)
10399 (setq cmd (replace-match "'%s'" t t cmd)))
10400 (setq cmd (format cmd file))
10401 (save-window-excursion
10402 (shell-command (concat cmd " &"))))
10403 ((or (stringp cmd)
10404 (eq cmd 'emacs))
10405 ; (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
10406 ; (funcall (cdr (assq 'file org-link-frame-setup)) file))
10407 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10408 (if line (goto-line line)
10409 (if search (org-link-search search))))
10410 ((consp cmd)
10411 (eval cmd))
10412 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10413 (and (org-mode-p) (eq old-mode 'org-mode)
10414 (or (not (equal old-buffer (current-buffer)))
10415 (not (equal old-pos (point))))
10416 (org-mark-ring-push old-pos old-buffer))))
10418 (defun org-default-apps ()
10419 "Return the default applications for this operating system."
10420 (cond
10421 ((eq system-type 'darwin)
10422 org-file-apps-defaults-macosx)
10423 ((eq system-type 'windows-nt)
10424 org-file-apps-defaults-windowsnt)
10425 (t org-file-apps-defaults-gnu)))
10427 (defun org-expand-file-name (path)
10428 "Replace special path abbreviations and expand the file name."
10429 (expand-file-name path))
10431 (defun org-file-remote-p (file)
10432 "Test whether FILE specifies a location on a remote system.
10433 Return non-nil if the location is indeed remote.
10435 For example, the filename \"/user@host:/foo\" specifies a location
10436 on the system \"/user@host:\"."
10437 (cond ((fboundp 'file-remote-p)
10438 (file-remote-p file))
10439 ((fboundp 'tramp-handle-file-remote-p)
10440 (tramp-handle-file-remote-p file))
10441 ((and (boundp 'ange-ftp-name-format)
10442 (string-match (car ange-ftp-name-format) file))
10444 (t nil)))
10446 (defvar org-insert-link-history nil
10447 "Minibuffer history for links inserted with `org-insert-link'.")
10449 (defvar org-stored-links nil
10450 "Contains the links stored with `org-store-link'.")
10452 ;;;###autoload
10453 (defun org-store-link (arg)
10454 "\\<org-mode-map>Store an org-link to the current location.
10455 This link can later be inserted into an org-buffer with
10456 \\[org-insert-link].
10457 For some link types, a prefix arg is interpreted:
10458 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
10459 For file links, arg negates `org-context-in-file-links'."
10460 (interactive "P")
10461 (let (link cpltxt desc description search txt (pos (point)))
10462 (cond
10464 ((eq major-mode 'bbdb-mode)
10465 (setq cpltxt (concat
10466 "bbdb:"
10467 (or (bbdb-record-name (bbdb-current-record))
10468 (bbdb-record-company (bbdb-current-record))))
10469 link (org-make-link cpltxt)))
10471 ((eq major-mode 'Info-mode)
10472 (setq link (org-make-link "info:"
10473 (file-name-nondirectory Info-current-file)
10474 ":" Info-current-node))
10475 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
10476 ":" Info-current-node)))
10478 ((eq major-mode 'calendar-mode)
10479 (let ((cd (calendar-cursor-to-date)))
10480 (setq link
10481 (format-time-string
10482 (car org-time-stamp-formats)
10483 (apply 'encode-time
10484 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
10485 nil nil nil))))))
10487 ((or (eq major-mode 'vm-summary-mode)
10488 (eq major-mode 'vm-presentation-mode))
10489 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
10490 (vm-follow-summary-cursor)
10491 (save-excursion
10492 (vm-select-folder-buffer)
10493 (let* ((message (car vm-message-pointer))
10494 (folder buffer-file-name)
10495 (subject (vm-su-subject message))
10496 (author (vm-su-full-name message))
10497 (message-id (vm-su-message-id message)))
10498 (setq message-id (org-remove-angle-brackets message-id))
10499 (setq folder (abbreviate-file-name folder))
10500 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
10501 folder)
10502 (setq folder (replace-match "" t t folder)))
10503 (setq cpltxt (concat author " on: " subject))
10504 (setq link (org-make-link "vm:" folder "#" message-id)))))
10506 ((eq major-mode 'wl-summary-mode)
10507 (let* ((msgnum (wl-summary-message-number))
10508 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
10509 msgnum 'message-id))
10510 (wl-message-entity (elmo-msgdb-overview-get-entity
10511 msgnum (wl-summary-buffer-msgdb)))
10512 (author (wl-summary-line-from)) ; FIXME: correct?
10513 (subject "???")) ; FIXME:
10514 (setq message-id (org-remove-angle-brackets message-id))
10515 (setq cpltxt (concat author " on: " subject))
10516 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
10517 "#" message-id))))
10519 ((or (equal major-mode 'mh-folder-mode)
10520 (equal major-mode 'mh-show-mode))
10521 (let ((from-header (org-mhe-get-header "From:"))
10522 (to-header (org-mhe-get-header "To:"))
10523 (subject (org-mhe-get-header "Subject:")))
10524 (setq cpltxt (concat from-header " on: " subject))
10525 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
10526 (org-remove-angle-brackets
10527 (org-mhe-get-header "Message-Id:"))))))
10529 ((eq major-mode 'rmail-mode)
10530 (save-excursion
10531 (save-restriction
10532 (rmail-narrow-to-non-pruned-header)
10533 (let ((folder buffer-file-name)
10534 (message-id (mail-fetch-field "message-id"))
10535 (author (mail-fetch-field "from"))
10536 (subject (mail-fetch-field "subject")))
10537 (setq message-id (org-remove-angle-brackets message-id))
10538 (setq cpltxt (concat author " on: " subject))
10539 (setq link (org-make-link "rmail:" folder "#" message-id))))))
10541 ((eq major-mode 'gnus-group-mode)
10542 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
10543 (gnus-group-group-name)) ; version
10544 ((fboundp 'gnus-group-name)
10545 (gnus-group-name))
10546 (t "???"))))
10547 (setq cpltxt (concat
10548 (if (org-xor arg org-usenet-links-prefer-google)
10549 "http://groups.google.com/groups?group="
10550 "gnus:")
10551 group)
10552 link (org-make-link cpltxt))))
10554 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
10555 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
10556 (gnus-summary-beginning-of-article)
10557 (let* ((group (car gnus-article-current))
10558 (article (cdr gnus-article-current))
10559 (header (gnus-summary-article-header article))
10560 (author (mail-header-from header))
10561 (message-id (mail-header-id header))
10562 (date (mail-header-date header))
10563 (subject (gnus-summary-subject-string)))
10564 (setq cpltxt (concat author " on: " subject))
10565 (if (org-xor arg org-usenet-links-prefer-google)
10566 (setq link
10567 (concat
10568 cpltxt "\n "
10569 (format "http://groups.google.com/groups?as_umsgid=%s"
10570 (org-fixup-message-id-for-http message-id))))
10571 (setq link (org-make-link "gnus:" group
10572 "#" (number-to-string article))))))
10574 ((eq major-mode 'w3-mode)
10575 (setq cpltxt (url-view-url t)
10576 link (org-make-link cpltxt)))
10577 ((eq major-mode 'w3m-mode)
10578 (setq cpltxt (or w3m-current-title w3m-current-url)
10579 link (org-make-link w3m-current-url)))
10581 ((setq search (run-hook-with-args-until-success
10582 'org-create-file-search-functions))
10583 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
10584 "::" search))
10585 (setq cpltxt (or description link)))
10587 ((eq major-mode 'image-mode)
10588 (setq cpltxt (concat "file:"
10589 (abbreviate-file-name buffer-file-name))
10590 link (org-make-link cpltxt)))
10592 ((eq major-mode 'dired-mode)
10593 ;; link to the file in the current line
10594 (setq cpltxt (concat "file:"
10595 (abbreviate-file-name
10596 (expand-file-name
10597 (dired-get-filename nil t))))
10598 link (org-make-link cpltxt)))
10600 ((org-mode-p)
10601 ;; Just link to current headline
10602 (setq cpltxt (concat "file:"
10603 (abbreviate-file-name buffer-file-name)))
10604 ;; Add a context search string
10605 (when (org-xor org-context-in-file-links arg)
10606 ;; Check if we are on a target
10607 (if (save-excursion
10608 (skip-chars-forward "^>\n\r")
10609 (and (re-search-backward "<<" nil t)
10610 (looking-at "<<\\(.*?\\)>>")
10611 (<= (match-beginning 0) pos)
10612 (>= (match-end 0) pos)))
10613 (setq cpltxt (concat cpltxt "::" (match-string 1)))
10614 (setq txt (cond
10615 ((org-on-heading-p) nil)
10616 ((org-region-active-p)
10617 (buffer-substring (region-beginning) (region-end)))
10618 (t (buffer-substring (point-at-bol) (point-at-eol)))))
10619 (when (or (null txt) (string-match "\\S-" txt))
10620 (setq cpltxt
10621 (concat cpltxt "::"
10622 (if org-file-link-context-use-camel-case
10623 (org-make-org-heading-camel txt)
10624 (org-make-org-heading-search-string txt)))
10625 desc "NONE"))))
10626 (if (string-match "::\\'" cpltxt)
10627 (setq cpltxt (substring cpltxt 0 -2)))
10628 (setq link (org-make-link cpltxt)))
10630 (buffer-file-name
10631 ;; Just link to this file here.
10632 (setq cpltxt (concat "file:"
10633 (abbreviate-file-name buffer-file-name)))
10634 ;; Add a context string
10635 (when (org-xor org-context-in-file-links arg)
10636 (setq txt (if (org-region-active-p)
10637 (buffer-substring (region-beginning) (region-end))
10638 (buffer-substring (point-at-bol) (point-at-eol))))
10639 ;; Only use search option if there is some text.
10640 (when (string-match "\\S-" txt)
10641 (setq cpltxt
10642 (concat cpltxt "::"
10643 (if org-file-link-context-use-camel-case
10644 (org-make-org-heading-camel txt)
10645 (org-make-org-heading-search-string txt)))
10646 desc "NONE")))
10647 (setq link (org-make-link cpltxt)))
10649 ((interactive-p)
10650 (error "Cannot link to a buffer which is not visiting a file"))
10652 (t (setq link nil)))
10654 (if (consp link) (setq cpltxt (car link) link (cdr link)))
10655 (setq link (or link cpltxt)
10656 desc (or desc cpltxt))
10657 (if (equal desc "NONE") (setq desc nil))
10659 (if (and (interactive-p) link)
10660 (progn
10661 (setq org-stored-links
10662 (cons (list cpltxt link desc) org-stored-links))
10663 (message "Stored: %s" (or cpltxt link)))
10664 (org-make-link-string link desc))))
10666 (defun org-make-org-heading-search-string (&optional string heading)
10667 "Make search string for STRING or current headline."
10668 (interactive)
10669 (let ((s (or string (org-get-heading))))
10670 (unless (and string (not heading))
10671 ;; We are using a headline, clean up garbage in there.
10672 (if (string-match org-todo-regexp s)
10673 (setq s (replace-match "" t t s)))
10674 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
10675 (setq s (replace-match "" t t s)))
10676 (setq s (org-trim s))
10677 (if (string-match (concat "^\\(" org-quote-string "\\|"
10678 org-comment-string "\\)") s)
10679 (setq s (replace-match "" t t s)))
10680 (while (string-match org-ts-regexp s)
10681 (setq s (replace-match "" t t s))))
10682 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
10683 (setq s (replace-match " " t t s)))
10684 (or string (setq s (concat "*" s))) ; Add * for headlines
10685 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10687 (defun org-make-org-heading-camel (&optional string heading)
10688 "Make a CamelCase string for STRING or the current headline."
10689 (interactive)
10690 (let ((s (or string (org-get-heading))))
10691 (unless (and string (not heading))
10692 ;; We are using a headline, clean up garbage in there.
10693 (if (string-match org-todo-regexp s)
10694 (setq s (replace-match "" t t s)))
10695 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
10696 (setq s (replace-match "" t t s)))
10697 (setq s (org-trim s))
10698 (if (string-match (concat "^\\(" org-quote-string "\\|"
10699 org-comment-string "\\)") s)
10700 (setq s (replace-match "" t t s)))
10701 (while (string-match org-ts-regexp s)
10702 (setq s (replace-match "" t t s))))
10703 (while (string-match "[^a-zA-Z_ \t]+" s)
10704 (setq s (replace-match " " t t s)))
10705 (or string (setq s (concat "*" s))) ; Add * for headlines
10706 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
10708 (defun org-make-link (&rest strings)
10709 "Concatenate STRINGS, format resulting string with `org-link-format'."
10710 (format org-link-format (apply 'concat strings)))
10712 (defun org-make-link-string (link &optional description)
10713 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10714 (if (eq org-link-style 'plain)
10715 (if (equal description link)
10716 link
10717 (concat description "\n" link))
10718 (when (stringp description)
10719 ;; Remove brackets from the description, they are fatal.
10720 (while (string-match "\\[\\|\\]" description)
10721 (setq description (replace-match "" t t description))))
10722 (when (equal (org-link-escape link) description)
10723 ;; No description needed, it is identical
10724 (setq description nil))
10725 (when (and (not description)
10726 (not (equal link (org-link-escape link))))
10727 (setq description link))
10728 (concat "[[" (org-link-escape link) "]"
10729 (if description (concat "[" description "]") "")
10730 "]")))
10732 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
10733 "Association list of escapes for some characters problematic in links.")
10735 (defun org-link-escape (text)
10736 "Escape charaters in TEXT that are problematic for links."
10737 (when text
10738 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
10739 org-link-escape-chars "\\|")))
10740 (while (string-match re text)
10741 (setq text
10742 (replace-match
10743 (cdr (assoc (match-string 0 text) org-link-escape-chars))
10744 t t text)))
10745 text)))
10747 (defun org-link-unescape (text)
10748 "Reverse the action of `org-link-escape'."
10749 (when text
10750 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
10751 org-link-escape-chars "\\|")))
10752 (while (string-match re text)
10753 (setq text
10754 (replace-match
10755 (car (rassoc (match-string 0 text) org-link-escape-chars))
10756 t t text)))
10757 text)))
10759 (defun org-xor (a b)
10760 "Exclusive or."
10761 (if a (not b) b))
10763 (defun org-get-header (header)
10764 "Find a header field in the current buffer."
10765 (save-excursion
10766 (goto-char (point-min))
10767 (let ((case-fold-search t) s)
10768 (cond
10769 ((eq header 'from)
10770 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
10771 (setq s (match-string 1)))
10772 (while (string-match "\"" s)
10773 (setq s (replace-match "" t t s)))
10774 (if (string-match "[<(].*" s)
10775 (setq s (replace-match "" t t s))))
10776 ((eq header 'message-id)
10777 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
10778 (setq s (match-string 1))))
10779 ((eq header 'subject)
10780 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
10781 (setq s (match-string 1)))))
10782 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
10783 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
10784 s)))
10787 (defun org-fixup-message-id-for-http (s)
10788 "Replace special characters in a message id, so it can be used in an http query."
10789 (while (string-match "<" s)
10790 (setq s (replace-match "%3C" t t s)))
10791 (while (string-match ">" s)
10792 (setq s (replace-match "%3E" t t s)))
10793 (while (string-match "@" s)
10794 (setq s (replace-match "%40" t t s)))
10797 (defun org-insert-link (&optional complete-file)
10798 "Insert a link. At the prompt, enter the link.
10800 Completion can be used to select a link previously stored with
10801 `org-store-link'. When the empty string is entered (i.e. if you just
10802 press RET at the prompt), the link defaults to the most recently
10803 stored link. As SPC triggers completion in the minibuffer, you need to
10804 use M-SPC or C-q SPC to force the insertion of a space character.
10806 You will also be prompted for a description, and if one is given, it will
10807 be displayed in the buffer instead of the link.
10809 If there is already a link at point, this command will allow you to edit link
10810 and description parts.
10812 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
10813 selected using completion. The path to the file will be relative to
10814 the current directory if the file is in the current directory or a
10815 subdirectory. Otherwise, the link will be the absolute path as
10816 completed in the minibuffer (i.e. normally ~/path/to/file).
10818 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
10819 is in the current directory or below.
10820 With three \\[universal-argument] prefixes, negate the meaning of
10821 `org-keep-stored-link-after-insertion'."
10822 (interactive "P")
10823 (let (link desc entry remove file (pos (point)))
10824 (cond
10825 ((save-excursion
10826 (skip-chars-forward "^]\n\r")
10827 (and (re-search-backward "\\[\\[" nil t)
10828 (looking-at org-bracket-link-regexp)
10829 (<= (match-beginning 0) pos)
10830 (>= (match-end 0) pos)))
10831 ;; We do have a link at point, and we are going to edit it.
10832 (setq remove (list (match-beginning 0) (match-end 0)))
10833 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10834 (setq link (read-string "Link: "
10835 (org-link-unescape
10836 (org-match-string-no-properties 1)))))
10837 ((equal complete-file '(4))
10838 ;; Completing read for file names.
10839 (setq file (read-file-name "File: "))
10840 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10841 (pwd1 (file-name-as-directory (abbreviate-file-name
10842 (expand-file-name ".")))))
10843 (cond
10844 ((equal complete-file '(16))
10845 (setq link (org-make-link
10846 "file:"
10847 (abbreviate-file-name (expand-file-name file)))))
10848 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10849 (setq link (org-make-link "file:" (match-string 1 file))))
10850 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10851 (expand-file-name file))
10852 (setq link (org-make-link
10853 "file:" (match-string 1 (expand-file-name file)))))
10854 (t (setq link (org-make-link "file:" file))))))
10856 ;; Read link, with completion for stored links.
10857 (setq link (org-completing-read
10858 "Link: " org-stored-links nil nil nil
10859 org-insert-link-history
10860 (or (car (car org-stored-links)))))
10861 (setq entry (assoc link org-stored-links))
10862 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10863 (not org-keep-stored-link-after-insertion))
10864 (setq org-stored-links (delq (assoc link org-stored-links)
10865 org-stored-links)))
10866 (setq link (if entry (nth 1 entry) link)
10867 desc (or desc (nth 2 entry)))))
10869 (if (string-match org-plain-link-re link)
10870 ;; URL-like link, normalize the use of angular brackets.
10871 (setq link (org-make-link (org-remove-angle-brackets link))))
10873 ;; Check if we are linking to the current file with a search option
10874 ;; If yes, simplify the link by using only the search option.
10875 (when (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link)
10876 (let* ((path (match-string 1 link))
10877 (case-fold-search nil)
10878 (search (match-string 2 link)))
10879 (save-match-data
10880 (if (equal (file-truename buffer-file-name) (file-truename path))
10881 ;; We are linking to this same file, with a search option
10882 (setq link search)))))
10884 ;; Check if we can/should use a relative path. If yes, simplify the link
10885 (when (string-match "\\<file:\\(.*\\)" link)
10886 (let* ((path (match-string 1 link))
10887 (case-fold-search nil))
10888 (cond
10889 ((eq org-link-file-path-type 'absolute)
10890 (setq path (abbreviate-file-name (expand-file-name path))))
10891 ((eq org-link-file-path-type 'noabbrev)
10892 (setq path (expand-file-name path)))
10893 ((eq org-link-file-path-type 'relative)
10894 (setq path (file-relative-name path)))
10896 (save-match-data
10897 (if (string-match (concat "^" (regexp-quote
10898 (file-name-as-directory
10899 (expand-file-name "."))))
10900 (expand-file-name path))
10901 ;; We are linking a file with relative path name.
10902 (setq path (substring (expand-file-name path)
10903 (match-end 0)))))))
10904 (setq link (concat "file:" path))))
10906 (setq desc (read-string "Description: " desc))
10907 (unless (string-match "\\S-" desc) (setq desc nil))
10908 (if remove (apply 'delete-region remove))
10909 (insert (org-make-link-string link desc))))
10911 (defun org-completing-read (&rest args)
10912 (let ((minibuffer-local-completion-map
10913 (copy-keymap minibuffer-local-completion-map)))
10914 (define-key minibuffer-local-completion-map " " 'self-insert-command)
10915 (apply 'completing-read args)))
10917 ;;; Hooks for remember.el
10919 (defvar org-finish-function nil)
10921 ;;;###autoload
10922 (defun org-remember-annotation ()
10923 "Return a link to the current location as an annotation for remember.el.
10924 If you are using Org-mode files as target for data storage with
10925 remember.el, then the annotations should include a link compatible with the
10926 conventions in Org-mode. This function returns such a link."
10927 (org-store-link nil))
10929 (defconst org-remember-help
10930 "Select a destination location for the note.
10931 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
10932 RET at beg-of-buf -> Append to file as level 2 headline
10933 RET on headline -> Store as sublevel entry to current headline
10934 <left>/<right> -> before/after current headline, same headings level")
10936 ;;;###autoload
10937 (defun org-remember-apply-template ()
10938 "Initialize *remember* buffer with template, invoke `org-mode'.
10939 This function should be placed into `remember-mode-hook' and in fact requires
10940 to be run from that hook to fucntion properly."
10941 (if org-remember-templates
10943 (let* ((entry (if (= (length org-remember-templates) 1)
10944 (cdar org-remember-templates)
10945 (message "Select template: %s"
10946 (mapconcat
10947 (lambda (x) (char-to-string (car x)))
10948 org-remember-templates " "))
10949 (cdr (assoc (read-char-exclusive) org-remember-templates))))
10950 (tpl (car entry))
10951 (file (if (consp (cdr entry)) (nth 1 entry)))
10952 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
10953 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
10954 (v-u (concat "[" (substring v-t 1 -1) "]"))
10955 (v-U (concat "[" (substring v-T 1 -1) "]"))
10956 (v-a annotation) ; defined in `remember-mode'
10957 (v-i initial) ; defined in `remember-mode'
10958 (v-n user-full-name)
10960 (unless tpl (setq tpl "") (message "No template") (ding))
10961 (insert tpl) (goto-char (point-min))
10962 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
10963 (when (and initial (equal (match-string 0) "%i"))
10964 (save-match-data
10965 (let* ((lead (buffer-substring
10966 (point-at-bol) (match-beginning 0))))
10967 (setq v-i (mapconcat 'identity
10968 (org-split-string initial "\n")
10969 (concat "\n" lead))))))
10970 (replace-match
10971 (or (eval (intern (concat "v-" (match-string 1)))) "")
10972 t t))
10973 (let ((org-startup-folded nil)
10974 (org-startup-with-deadline-check nil))
10975 (org-mode))
10976 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
10977 (org-set-local 'org-default-notes-file file))
10978 (goto-char (point-min))
10979 (if (re-search-forward "%\\?" nil t) (replace-match "")))
10980 (let ((org-startup-folded nil)
10981 (org-startup-with-deadline-check nil))
10982 (org-mode)))
10983 (org-set-local 'org-finish-function 'remember-buffer))
10985 ;;;###autoload
10986 (defun org-remember-handler ()
10987 "Store stuff from remember.el into an org file.
10988 First prompts for an org file. If the user just presses return, the value
10989 of `org-default-notes-file' is used.
10990 Then the command offers the headings tree of the selected file in order to
10991 file the text at a specific location.
10992 You can either immediately press RET to get the note appended to the
10993 file, or you can use vertical cursor motion and visibility cycling (TAB) to
10994 find a better place. Then press RET or <left> or <right> in insert the note.
10996 Key Cursor position Note gets inserted
10997 -----------------------------------------------------------------------------
10998 RET buffer-start as level 2 heading at end of file
10999 RET on headline as sublevel of the heading at cursor
11000 RET no heading at cursor position, level taken from context.
11001 Or use prefix arg to specify level manually.
11002 <left> on headline as same level, before current heading
11003 <right> on headline as same level, after current heading
11005 So the fastest way to store the note is to press RET RET to append it to
11006 the default file. This way your current train of thought is not
11007 interrupted, in accordance with the principles of remember.el. But with
11008 little extra effort, you can push it directly to the correct location.
11010 Before being stored away, the function ensures that the text has a
11011 headline, i.e. a first line that starts with a \"*\". If not, a headline
11012 is constructed from the current date and some additional data.
11014 If the variable `org-adapt-indentation' is non-nil, the entire text is
11015 also indented so that it starts in the same column as the headline
11016 \(i.e. after the stars).
11018 See also the variable `org-reverse-note-order'."
11019 (catch 'quit
11020 (let* ((txt (buffer-substring (point-min) (point-max)))
11021 (fastp current-prefix-arg)
11022 (file (if fastp org-default-notes-file (org-get-org-file)))
11023 (visiting (find-buffer-visiting file))
11024 (org-startup-with-deadline-check nil)
11025 (org-startup-folded nil)
11026 (org-startup-align-all-tables nil)
11027 spos level indent reversed)
11028 ;; Modify text so that it becomes a nice subtree which can be inserted
11029 ;; into an org tree.
11030 (let* ((lines (split-string txt "\n"))
11031 first)
11032 ;; remove empty lines at the beginning
11033 (while (and lines (string-match "^[ \t]*\n" (car lines)))
11034 (setq lines (cdr lines)))
11035 (setq first (car lines) lines (cdr lines))
11036 (if (string-match "^\\*+" first)
11037 ;; Is already a headline
11038 (setq indent nil)
11039 ;; We need to add a headline: Use time and first buffer line
11040 (setq lines (cons first lines)
11041 first (concat "* " (current-time-string)
11042 " (" (remember-buffer-desc) ")")
11043 indent " "))
11044 (if (and org-adapt-indentation indent)
11045 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
11046 (setq txt (concat first "\n"
11047 (mapconcat 'identity lines "\n"))))
11048 ;; Find the file
11049 (if (not visiting)
11050 (find-file-noselect file))
11051 (with-current-buffer (get-file-buffer file)
11052 (save-excursion (and (goto-char (point-min))
11053 (not (re-search-forward "^\\* " nil t))
11054 (insert "\n* Notes\n")))
11055 (setq reversed (org-notes-order-reversed-p))
11056 (save-excursion
11057 (save-restriction
11058 (widen)
11059 ;; Ask the User for a location
11060 (setq spos (if fastp 1 (org-get-location
11061 (current-buffer)
11062 org-remember-help)))
11063 (if (not spos) (throw 'quit nil)) ; return nil to show we did
11064 ; not handle this note
11065 (goto-char spos)
11066 (cond ((bobp)
11067 ;; Put it at the start or end, as level 2
11068 (save-restriction
11069 (widen)
11070 (goto-char (if reversed (point-min) (point-max)))
11071 (if (not (bolp)) (newline))
11072 (org-paste-subtree 2 txt)))
11073 ((and (org-on-heading-p nil) (not current-prefix-arg))
11074 ;; Put it below this entry, at the beg/end of the subtree
11075 (org-back-to-heading)
11076 (setq level (funcall outline-level))
11077 (if reversed
11078 (outline-end-of-heading)
11079 (outline-end-of-subtree))
11080 (if (not (bolp)) (newline))
11081 (beginning-of-line 1)
11082 (org-paste-subtree (1+ level) txt))
11084 ;; Put it right there, with automatic level determined by
11085 ;; org-paste-subtree or from prefix arg
11086 (org-paste-subtree current-prefix-arg txt)))
11087 (when remember-save-after-remembering
11088 (save-buffer)
11089 (if (not visiting) (kill-buffer (current-buffer)))))))))
11090 t) ;; return t to indicate that we took care of this note.
11092 (defun org-get-org-file ()
11093 "Read a filename, with default directory `org-directory'."
11094 (let ((default (or org-default-notes-file remember-data-file)))
11095 (read-file-name (format "File name [%s]: " default)
11096 (file-name-as-directory org-directory)
11097 default)))
11099 (defun org-notes-order-reversed-p ()
11100 "Check if the current file should receive notes in reversed order."
11101 (cond
11102 ((not org-reverse-note-order) nil)
11103 ((eq t org-reverse-note-order) t)
11104 ((not (listp org-reverse-note-order)) nil)
11105 (t (catch 'exit
11106 (let ((all org-reverse-note-order)
11107 entry)
11108 (while (setq entry (pop all))
11109 (if (string-match (car entry) buffer-file-name)
11110 (throw 'exit (cdr entry))))
11111 nil)))))
11113 ;;; Tables
11115 ;; Watch out: Here we are talking about two different kind of tables.
11116 ;; Most of the code is for the tables created with the Org-mode table editor.
11117 ;; Sometimes, we talk about tables created and edited with the table.el
11118 ;; Emacs package. We call the former org-type tables, and the latter
11119 ;; table.el-type tables.
11122 (defun org-before-change-function (beg end)
11123 "Every change indicates that a table might need an update."
11124 (setq org-table-may-need-update t))
11126 (defconst org-table-line-regexp "^[ \t]*|"
11127 "Detects an org-type table line.")
11128 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
11129 "Detects an org-type table line.")
11130 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
11131 "Detects a table line marked for automatic recalculation.")
11132 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
11133 "Detects a table line marked for automatic recalculation.")
11134 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
11135 "Detects a table line marked for automatic recalculation.")
11136 (defconst org-table-hline-regexp "^[ \t]*|-"
11137 "Detects an org-type table hline.")
11138 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
11139 "Detects a table-type table hline.")
11140 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
11141 "Detects an org-type or table-type table.")
11142 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
11143 "Searching from within a table (any type) this finds the first line
11144 outside the table.")
11145 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
11146 "Searching from within a table (any type) this finds the first line
11147 outside the table.")
11149 (defun org-table-create-with-table.el ()
11150 "Use the table.el package to insert a new table.
11151 If there is already a table at point, convert between Org-mode tables
11152 and table.el tables."
11153 (interactive)
11154 (require 'table)
11155 (cond
11156 ((org-at-table.el-p)
11157 (if (y-or-n-p "Convert table to Org-mode table? ")
11158 (org-table-convert)))
11159 ((org-at-table-p)
11160 (if (y-or-n-p "Convert table to table.el table? ")
11161 (org-table-convert)))
11162 (t (call-interactively 'table-insert))))
11164 (defun org-table-create-or-convert-from-region (arg)
11165 "Convert region to table, or create an empty table.
11166 If there is an active region, convert it to a table. If there is no such
11167 region, create an empty table."
11168 (interactive "P")
11169 (if (org-region-active-p)
11170 (org-table-convert-region (region-beginning) (region-end) arg)
11171 (org-table-create arg)))
11173 (defun org-table-create (&optional size)
11174 "Query for a size and insert a table skeleton.
11175 SIZE is a string Columns x Rows like for example \"3x2\"."
11176 (interactive "P")
11177 (unless size
11178 (setq size (read-string
11179 (concat "Table size Columns x Rows [e.g. "
11180 org-table-default-size "]: ")
11181 "" nil org-table-default-size)))
11183 (let* ((pos (point))
11184 (indent (make-string (current-column) ?\ ))
11185 (split (org-split-string size " *x *"))
11186 (rows (string-to-number (nth 1 split)))
11187 (columns (string-to-number (car split)))
11188 (line (concat (apply 'concat indent "|" (make-list columns " |"))
11189 "\n")))
11190 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
11191 (point-at-bol) (point)))
11192 (beginning-of-line 1)
11193 (newline))
11194 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
11195 (dotimes (i rows) (insert line))
11196 (goto-char pos)
11197 (if (> rows 1)
11198 ;; Insert a hline after the first row.
11199 (progn
11200 (end-of-line 1)
11201 (insert "\n|-")
11202 (goto-char pos)))
11203 (org-table-align)))
11205 (defun org-table-convert-region (beg0 end0 &optional nspace)
11206 "Convert region to a table.
11207 The region goes from BEG0 to END0, but these borders will be moved
11208 slightly, to make sure a beginning of line in the first line is included.
11209 When NSPACE is non-nil, it indicates the minimum number of spaces that
11210 separate columns (default: just one space)."
11211 (interactive "rP")
11212 (let* ((beg (min beg0 end0))
11213 (end (max beg0 end0))
11214 (tabsep t)
11216 (goto-char beg)
11217 (beginning-of-line 1)
11218 (setq beg (move-marker (make-marker) (point)))
11219 (goto-char end)
11220 (if (bolp) (backward-char 1) (end-of-line 1))
11221 (setq end (move-marker (make-marker) (point)))
11222 ;; Lets see if this is tab-separated material. If every nonempty line
11223 ;; contains a tab, we will assume that it is tab-separated material
11224 (if nspace
11225 (setq tabsep nil)
11226 (goto-char beg)
11227 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
11228 (if nspace (setq tabsep nil))
11229 (if tabsep
11230 (setq re "^\\|\t")
11231 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
11232 (max 1 (prefix-numeric-value nspace)))))
11233 (goto-char beg)
11234 (while (re-search-forward re end t)
11235 (replace-match "|" t t))
11236 (goto-char beg)
11237 (insert " ")
11238 (org-table-align)))
11240 (defun org-table-import (file arg)
11241 "Import FILE as a table.
11242 The file is assumed to be tab-separated. Such files can be produced by most
11243 spreadsheet and database applications. If no tabs (at least one per line)
11244 are found, lines will be split on whitespace into fields."
11245 (interactive "f\nP")
11246 (or (bolp) (newline))
11247 (let ((beg (point))
11248 (pm (point-max)))
11249 (insert-file-contents file)
11250 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
11252 (defun org-table-export ()
11253 "Export table as a tab-separated file.
11254 Such a file can be imported into a spreadsheet program like Excel."
11255 (interactive)
11256 (let* ((beg (org-table-begin))
11257 (end (org-table-end))
11258 (table (buffer-substring beg end))
11259 (file (read-file-name "Export table to: "))
11260 buf)
11261 (unless (or (not (file-exists-p file))
11262 (y-or-n-p (format "Overwrite file %s? " file)))
11263 (error "Abort"))
11264 (with-current-buffer (find-file-noselect file)
11265 (setq buf (current-buffer))
11266 (erase-buffer)
11267 (fundamental-mode)
11268 (insert table)
11269 (goto-char (point-min))
11270 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
11271 (replace-match "" t t)
11272 (end-of-line 1))
11273 (goto-char (point-min))
11274 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
11275 (replace-match "" t t)
11276 (goto-char (min (1+ (point)) (point-max))))
11277 (goto-char (point-min))
11278 (while (re-search-forward "^-[-+]*$" nil t)
11279 (replace-match "")
11280 (if (looking-at "\n")
11281 (delete-char 1)))
11282 (goto-char (point-min))
11283 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
11284 (replace-match "\t" t t))
11285 (save-buffer))
11286 (kill-buffer buf)))
11288 (defvar org-table-aligned-begin-marker (make-marker)
11289 "Marker at the beginning of the table last aligned.
11290 Used to check if cursor still is in that table, to minimize realignment.")
11291 (defvar org-table-aligned-end-marker (make-marker)
11292 "Marker at the end of the table last aligned.
11293 Used to check if cursor still is in that table, to minimize realignment.")
11294 (defvar org-table-last-alignment nil
11295 "List of flags for flushright alignment, from the last re-alignment.
11296 This is being used to correctly align a single field after TAB or RET.")
11297 (defvar org-table-last-column-widths nil
11298 "List of max width of fields in each column.
11299 This is being used to correctly align a single field after TAB or RET.")
11301 (defvar org-last-recalc-line nil)
11302 (defconst org-narrow-column-arrow "=>"
11303 "Used as display property in narrowed table columns.")
11305 (defun org-table-align ()
11306 "Align the table at point by aligning all vertical bars."
11307 (interactive)
11308 (let* (
11309 ;; Limits of table
11310 (beg (org-table-begin))
11311 (end (org-table-end))
11312 ;; Current cursor position
11313 (linepos (org-current-line))
11314 (colpos (org-table-current-column))
11315 (winstart (window-start))
11316 (winstartline (org-current-line (min winstart (1- (point-max)))))
11317 lines (new "") lengths l typenums ty fields maxfields i
11318 column
11319 (indent "") cnt frac
11320 rfmt hfmt
11321 (spaces '(1 . 1))
11322 (sp1 (car spaces))
11323 (sp2 (cdr spaces))
11324 (rfmt1 (concat
11325 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
11326 (hfmt1 (concat
11327 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
11328 emptystrings links narrow fmax f1 len c e)
11329 (untabify beg end)
11330 (remove-text-properties beg end '(org-cwidth t display t))
11331 ;; Check if we have links
11332 (goto-char beg)
11333 (setq links (re-search-forward org-bracket-link-regexp end t))
11334 ;; Make sure the link properties are right
11335 (when links (goto-char beg) (while (org-activate-bracket-links end)))
11336 ;; Check if we are narrowing any columns
11337 (goto-char beg)
11338 (setq narrow (and org-format-transports-properties-p
11339 (re-search-forward "<[0-9]+>" end t)))
11340 ;; Get the rows
11341 (setq lines (org-split-string
11342 (buffer-substring beg end) "\n"))
11343 ;; Store the indentation of the first line
11344 (if (string-match "^ *" (car lines))
11345 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
11346 ;; Mark the hlines by setting the corresponding element to nil
11347 ;; At the same time, we remove trailing space.
11348 (setq lines (mapcar (lambda (l)
11349 (if (string-match "^ *|-" l)
11351 (if (string-match "[ \t]+$" l)
11352 (substring l 0 (match-beginning 0))
11353 l)))
11354 lines))
11355 ;; Get the data fields by splitting the lines.
11356 (setq fields (mapcar
11357 (lambda (l)
11358 (org-split-string l " *| *"))
11359 (delq nil (copy-sequence lines))))
11360 ;; How many fields in the longest line?
11361 (condition-case nil
11362 (setq maxfields (apply 'max (mapcar 'length fields)))
11363 (error
11364 (kill-region beg end)
11365 (org-table-create org-table-default-size)
11366 (error "Empty table - created default table")))
11367 ;; A list of empty strings to fill any short rows on output
11368 (setq emptystrings (make-list maxfields ""))
11369 ;; Check for special formatting.
11370 (setq i -1)
11371 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
11372 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
11373 ;; Check if there is an explicit width specified
11374 (when (and org-table-limit-column-width narrow)
11375 (setq c column fmax nil)
11376 (while c
11377 (setq e (pop c))
11378 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
11379 (setq fmax (string-to-number (match-string 1 e)) c nil)))
11380 ;; Find fields that are wider than fmax, and shorten them
11381 (when fmax
11382 (loop for xx in column do
11383 (when (and (stringp xx)
11384 (> (org-string-width xx) fmax))
11385 (org-add-props xx nil
11386 'help-echo
11387 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
11388 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
11389 (unless (> f1 1)
11390 (error "Cannot narrow field starting with wide link \"%s\""
11391 (match-string 0 xx)))
11392 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
11393 (add-text-properties (- f1 2) f1
11394 (list 'display org-narrow-column-arrow)
11395 xx)))))
11396 ;; Get the maximum width for each column
11397 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
11398 ;; Get the fraction of numbers, to decide about alignment of the column
11399 (setq cnt 0 frac 0.0)
11400 (loop for x in column do
11401 (if (equal x "")
11403 (setq frac ( / (+ (* frac cnt)
11404 (if (string-match org-table-number-regexp x) 1 0))
11405 (setq cnt (1+ cnt))))))
11406 (push (>= frac org-table-number-fraction) typenums))
11407 (setq lengths (nreverse lengths) typenums (nreverse typenums))
11409 ;; Store the alignment of this table, for later editing of single fields
11410 (setq org-table-last-alignment typenums
11411 org-table-last-column-widths lengths)
11413 ;; With invisible characters, `format' does not get the field width right
11414 ;; So we need to make these fields wide by hand.
11415 (when links
11416 (loop for i from 0 upto (1- maxfields) do
11417 (setq len (nth i lengths))
11418 (loop for j from 0 upto (1- (length fields)) do
11419 (setq c (nthcdr i (car (nthcdr j fields))))
11420 (if (and (stringp (car c))
11421 (string-match org-bracket-link-regexp (car c))
11422 (< (org-string-width (car c)) len))
11423 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
11425 ;; Compute the formats needed for output of the table
11426 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
11427 (while (setq l (pop lengths))
11428 (setq ty (if (pop typenums) "" "-")) ; number types flushright
11429 (setq rfmt (concat rfmt (format rfmt1 ty l))
11430 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
11431 (setq rfmt (concat rfmt "\n")
11432 hfmt (concat (substring hfmt 0 -1) "|\n"))
11434 (setq new (mapconcat
11435 (lambda (l)
11436 (if l (apply 'format rfmt
11437 (append (pop fields) emptystrings))
11438 hfmt))
11439 lines ""))
11440 ;; Replace the old one
11441 (delete-region beg end)
11442 (move-marker end nil)
11443 (move-marker org-table-aligned-begin-marker (point))
11444 (insert new)
11445 (move-marker org-table-aligned-end-marker (point))
11446 (when (and orgtbl-mode (not (org-mode-p)))
11447 (goto-char org-table-aligned-begin-marker)
11448 (while (org-hide-wide-columns org-table-aligned-end-marker)))
11449 ;; Try to move to the old location
11450 (goto-line winstartline)
11451 (setq winstart (point-at-bol))
11452 (goto-line linepos)
11453 (set-window-start (selected-window) winstart 'noforce)
11454 (org-table-goto-column colpos)
11455 (setq org-table-may-need-update nil)
11458 (defun org-string-width (s)
11459 "Compute width of string, ignoring invisible characters.
11460 This ignores character with invisibility property `org-link', and also
11461 characters with property `org-cwidth', because these will become invisible
11462 upon the next fontification round."
11463 (let (b)
11464 (when (or (eq t buffer-invisibility-spec)
11465 (assq 'org-link buffer-invisibility-spec))
11466 (while (setq b (text-property-any 0 (length s)
11467 'invisible 'org-link s))
11468 (setq s (concat (substring s 0 b)
11469 (substring s (or (next-single-property-change
11470 b 'invisible s) (length s)))))))
11471 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
11472 (setq s (concat (substring s 0 b)
11473 (substring s (or (next-single-property-change
11474 b 'org-cwidth s) (length s))))))
11475 (string-width s)))
11477 (defun org-table-begin (&optional table-type)
11478 "Find the beginning of the table and return its position.
11479 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
11480 (save-excursion
11481 (if (not (re-search-backward
11482 (if table-type org-table-any-border-regexp
11483 org-table-border-regexp)
11484 nil t))
11485 (progn (goto-char (point-min)) (point))
11486 (goto-char (match-beginning 0))
11487 (beginning-of-line 2)
11488 (point))))
11490 (defun org-table-end (&optional table-type)
11491 "Find the end of the table and return its position.
11492 With argument TABLE-TYPE, go to the end of a table.el-type table."
11493 (save-excursion
11494 (if (not (re-search-forward
11495 (if table-type org-table-any-border-regexp
11496 org-table-border-regexp)
11497 nil t))
11498 (goto-char (point-max))
11499 (goto-char (match-beginning 0)))
11500 (point-marker)))
11502 (defun org-table-justify-field-maybe (&optional new)
11503 "Justify the current field, text to left, number to right.
11504 Optional argument NEW may specify text to replace the current field content."
11505 (cond
11506 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
11507 ((org-at-table-hline-p))
11508 ((and (not new)
11509 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
11510 (current-buffer)))
11511 (< (point) org-table-aligned-begin-marker)
11512 (>= (point) org-table-aligned-end-marker)))
11513 ;; This is not the same table, force a full re-align
11514 (setq org-table-may-need-update t))
11515 (t ;; realign the current field, based on previous full realign
11516 (let* ((pos (point)) s
11517 (col (org-table-current-column))
11518 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
11519 l f n o e)
11520 (when (> col 0)
11521 (skip-chars-backward "^|\n")
11522 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
11523 (progn
11524 (setq s (match-string 1)
11525 o (match-string 0)
11526 l (max 1 (- (match-end 0) (match-beginning 0) 3))
11527 e (not (= (match-beginning 2) (match-end 2))))
11528 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
11529 l (if e "|" (setq org-table-may-need-update t) ""))
11530 n (format f s))
11531 (if new
11532 (if (<= (length new) l) ;; FIXME: length -> str-width?
11533 (setq n (format f new))
11534 (setq n (concat new "|") org-table-may-need-update t)))
11535 (or (equal n o)
11536 (let (org-table-may-need-update)
11537 (replace-match n))))
11538 (setq org-table-may-need-update t))
11539 (goto-char pos))))))
11541 (defun org-table-next-field ()
11542 "Go to the next field in the current table, creating new lines as needed.
11543 Before doing so, re-align the table if necessary."
11544 (interactive)
11545 (org-table-maybe-eval-formula)
11546 (org-table-maybe-recalculate-line)
11547 (if (and org-table-automatic-realign
11548 org-table-may-need-update)
11549 (org-table-align))
11550 (let ((end (org-table-end)))
11551 (if (org-at-table-hline-p)
11552 (end-of-line 1))
11553 (condition-case nil
11554 (progn
11555 (re-search-forward "|" end)
11556 (if (looking-at "[ \t]*$")
11557 (re-search-forward "|" end))
11558 (if (and (looking-at "-")
11559 org-table-tab-jumps-over-hlines
11560 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
11561 (goto-char (match-beginning 1)))
11562 (if (looking-at "-")
11563 (progn
11564 (beginning-of-line 0)
11565 (org-table-insert-row 'below))
11566 (if (looking-at " ") (forward-char 1))))
11567 (error
11568 (org-table-insert-row 'below)))))
11570 (defun org-table-previous-field ()
11571 "Go to the previous field in the table.
11572 Before doing so, re-align the table if necessary."
11573 (interactive)
11574 (org-table-justify-field-maybe)
11575 (org-table-maybe-recalculate-line)
11576 (if (and org-table-automatic-realign
11577 org-table-may-need-update)
11578 (org-table-align))
11579 (if (org-at-table-hline-p)
11580 (end-of-line 1))
11581 (re-search-backward "|" (org-table-begin))
11582 (re-search-backward "|" (org-table-begin))
11583 (while (looking-at "|\\(-\\|[ \t]*$\\)")
11584 (re-search-backward "|" (org-table-begin)))
11585 (if (looking-at "| ?")
11586 (goto-char (match-end 0))))
11588 (defun org-table-next-row ()
11589 "Go to the next row (same column) in the current table.
11590 Before doing so, re-align the table if necessary."
11591 (interactive)
11592 (org-table-maybe-eval-formula)
11593 (org-table-maybe-recalculate-line)
11594 (if (or (looking-at "[ \t]*$")
11595 (save-excursion (skip-chars-backward " \t") (bolp)))
11596 (newline)
11597 (if (and org-table-automatic-realign
11598 org-table-may-need-update)
11599 (org-table-align))
11600 (let ((col (org-table-current-column)))
11601 (beginning-of-line 2)
11602 (if (or (not (org-at-table-p))
11603 (org-at-table-hline-p))
11604 (progn
11605 (beginning-of-line 0)
11606 (org-table-insert-row 'below)))
11607 (org-table-goto-column col)
11608 (skip-chars-backward "^|\n\r")
11609 (if (looking-at " ") (forward-char 1)))))
11611 (defun org-table-copy-down (n)
11612 "Copy a field down in the current column.
11613 If the field at the cursor is empty, copy into it the content of the nearest
11614 non-empty field above. With argument N, use the Nth non-empty field.
11615 If the current field is not empty, it is copied down to the next row, and
11616 the cursor is moved with it. Therefore, repeating this command causes the
11617 column to be filled row-by-row.
11618 If the variable `org-table-copy-increment' is non-nil and the field is an
11619 integer, it will be incremented while copying."
11620 (interactive "p")
11621 (let* ((colpos (org-table-current-column))
11622 (field (org-table-get-field))
11623 (non-empty (string-match "[^ \t]" field))
11624 (beg (org-table-begin))
11625 txt)
11626 (org-table-check-inside-data-field)
11627 (if non-empty
11628 (progn
11629 (setq txt (org-trim field))
11630 (org-table-next-row)
11631 (org-table-blank-field))
11632 (save-excursion
11633 (setq txt
11634 (catch 'exit
11635 (while (progn (beginning-of-line 1)
11636 (re-search-backward org-table-dataline-regexp
11637 beg t))
11638 (org-table-goto-column colpos t)
11639 (if (and (looking-at
11640 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
11641 (= (setq n (1- n)) 0))
11642 (throw 'exit (match-string 1))))))))
11643 (if txt
11644 (progn
11645 (if (and org-table-copy-increment
11646 (string-match "^[0-9]+$" txt))
11647 (setq txt (format "%d" (+ (string-to-number txt) 1))))
11648 (insert txt)
11649 (org-table-maybe-recalculate-line)
11650 (org-table-align))
11651 (error "No non-empty field found"))))
11653 (defun org-table-check-inside-data-field ()
11654 "Is point inside a table data field?
11655 I.e. not on a hline or before the first or after the last column?
11656 This actually throws an error, so it aborts the current command."
11657 (if (or (not (org-at-table-p))
11658 (= (org-table-current-column) 0)
11659 (org-at-table-hline-p)
11660 (looking-at "[ \t]*$"))
11661 (error "Not in table data field")))
11663 (defvar org-table-clip nil
11664 "Clipboard for table regions.")
11666 (defun org-table-blank-field ()
11667 "Blank the current table field or active region."
11668 (interactive)
11669 (org-table-check-inside-data-field)
11670 (if (and (interactive-p) (org-region-active-p))
11671 (let (org-table-clip)
11672 (org-table-cut-region (region-beginning) (region-end)))
11673 (skip-chars-backward "^|")
11674 (backward-char 1)
11675 (if (looking-at "|[^|\n]+")
11676 (let* ((pos (match-beginning 0))
11677 (match (match-string 0))
11678 (len (org-string-width match)))
11679 (replace-match (concat "|" (make-string (1- len) ?\ )))
11680 (goto-char (+ 2 pos))
11681 (substring match 1)))))
11683 (defun org-table-get-field (&optional n replace)
11684 "Return the value of the field in column N of current row.
11685 N defaults to current field.
11686 If REPLACE is a string, replace field with this value. The return value
11687 is always the old value."
11688 (and n (org-table-goto-column n))
11689 (skip-chars-backward "^|\n")
11690 (backward-char 1)
11691 (if (looking-at "|[^|\r\n]*")
11692 (let* ((pos (match-beginning 0))
11693 (val (buffer-substring (1+ pos) (match-end 0))))
11694 (if replace
11695 (replace-match (concat "|" replace)))
11696 (goto-char (min (point-at-eol) (+ 2 pos)))
11697 val)
11698 (forward-char 1) ""))
11700 (defun org-table-current-column ()
11701 "Find out which column we are in.
11702 When called interactively, column is also displayed in echo area."
11703 (interactive)
11704 (if (interactive-p) (org-table-check-inside-data-field))
11705 (save-excursion
11706 (let ((cnt 0) (pos (point)))
11707 (beginning-of-line 1)
11708 (while (search-forward "|" pos t)
11709 (setq cnt (1+ cnt)))
11710 (if (interactive-p) (message "This is table column %d" cnt))
11711 cnt)))
11713 (defun org-table-goto-column (n &optional on-delim force)
11714 "Move the cursor to the Nth column in the current table line.
11715 With optional argument ON-DELIM, stop with point before the left delimiter
11716 of the field.
11717 If there are less than N fields, just go to after the last delimiter.
11718 However, when FORCE is non-nil, create new columns if necessary."
11719 (interactive "p")
11720 (let ((pos (point-at-eol)))
11721 (beginning-of-line 1)
11722 (when (> n 0)
11723 (while (and (> (setq n (1- n)) -1)
11724 (or (search-forward "|" pos t)
11725 (and force
11726 (progn (end-of-line 1)
11727 (skip-chars-backward "^|")
11728 (insert " | "))))))
11729 ; (backward-char 2) t)))))
11730 (when (and force (not (looking-at ".*|")))
11731 (save-excursion (end-of-line 1) (insert " | ")))
11732 (if on-delim
11733 (backward-char 1)
11734 (if (looking-at " ") (forward-char 1))))))
11736 (defun org-at-table-p (&optional table-type)
11737 "Return t if the cursor is inside an org-type table.
11738 If TABLE-TYPE is non-nil, also check for table.el-type tables."
11739 (if org-enable-table-editor
11740 (save-excursion
11741 (beginning-of-line 1)
11742 (looking-at (if table-type org-table-any-line-regexp
11743 org-table-line-regexp)))
11744 nil))
11746 (defun org-at-table.el-p ()
11747 "Return t if and only if we are at a table.el table."
11748 (and (org-at-table-p 'any)
11749 (save-excursion
11750 (goto-char (org-table-begin 'any))
11751 (looking-at org-table1-hline-regexp))))
11753 (defun org-table-recognize-table.el ()
11754 "If there is a table.el table nearby, recognize it and move into it."
11755 (if org-table-tab-recognizes-table.el
11756 (if (org-at-table.el-p)
11757 (progn
11758 (beginning-of-line 1)
11759 (if (looking-at org-table-dataline-regexp)
11761 (if (looking-at org-table1-hline-regexp)
11762 (progn
11763 (beginning-of-line 2)
11764 (if (looking-at org-table-any-border-regexp)
11765 (beginning-of-line -1)))))
11766 (if (re-search-forward "|" (org-table-end t) t)
11767 (progn
11768 (require 'table)
11769 (if (table--at-cell-p (point))
11771 (message "recognizing table.el table...")
11772 (table-recognize-table)
11773 (message "recognizing table.el table...done")))
11774 (error "This should not happen..."))
11776 nil)
11777 nil))
11779 (defun org-at-table-hline-p ()
11780 "Return t if the cursor is inside a hline in a table."
11781 (if org-enable-table-editor
11782 (save-excursion
11783 (beginning-of-line 1)
11784 (looking-at org-table-hline-regexp))
11785 nil))
11787 (defun org-table-insert-column ()
11788 "Insert a new column into the table."
11789 (interactive)
11790 (if (not (org-at-table-p))
11791 (error "Not at a table"))
11792 (org-table-find-dataline)
11793 (let* ((col (max 1 (org-table-current-column)))
11794 (beg (org-table-begin))
11795 (end (org-table-end))
11796 ;; Current cursor position
11797 (linepos (org-current-line))
11798 (colpos col))
11799 (goto-char beg)
11800 (while (< (point) end)
11801 (if (org-at-table-hline-p)
11803 (org-table-goto-column col t)
11804 (insert "| "))
11805 (beginning-of-line 2))
11806 (move-marker end nil)
11807 (goto-line linepos)
11808 (org-table-goto-column colpos)
11809 (org-table-align)
11810 (org-table-modify-formulas 'insert col)))
11812 (defun org-table-find-dataline ()
11813 "Find a dataline in the current table, which is needed for column commands."
11814 (if (and (org-at-table-p)
11815 (not (org-at-table-hline-p)))
11817 (let ((col (current-column))
11818 (end (org-table-end)))
11819 (move-to-column col)
11820 (while (and (< (point) end)
11821 (or (not (= (current-column) col))
11822 (org-at-table-hline-p)))
11823 (beginning-of-line 2)
11824 (move-to-column col))
11825 (if (and (org-at-table-p)
11826 (not (org-at-table-hline-p)))
11828 (error
11829 "Please position cursor in a data line for column operations")))))
11831 (defun org-table-delete-column ()
11832 "Delete a column from the table."
11833 (interactive)
11834 (if (not (org-at-table-p))
11835 (error "Not at a table"))
11836 (org-table-find-dataline)
11837 (org-table-check-inside-data-field)
11838 (let* ((col (org-table-current-column))
11839 (beg (org-table-begin))
11840 (end (org-table-end))
11841 ;; Current cursor position
11842 (linepos (org-current-line))
11843 (colpos col))
11844 (goto-char beg)
11845 (while (< (point) end)
11846 (if (org-at-table-hline-p)
11848 (org-table-goto-column col t)
11849 (and (looking-at "|[^|\n]+|")
11850 (replace-match "|")))
11851 (beginning-of-line 2))
11852 (move-marker end nil)
11853 (goto-line linepos)
11854 (org-table-goto-column colpos)
11855 (org-table-align)
11856 (org-table-modify-formulas 'remove col)))
11858 (defun org-table-move-column-right ()
11859 "Move column to the right."
11860 (interactive)
11861 (org-table-move-column nil))
11862 (defun org-table-move-column-left ()
11863 "Move column to the left."
11864 (interactive)
11865 (org-table-move-column 'left))
11867 (defun org-table-move-column (&optional left)
11868 "Move the current column to the right. With arg LEFT, move to the left."
11869 (interactive "P")
11870 (if (not (org-at-table-p))
11871 (error "Not at a table"))
11872 (org-table-find-dataline)
11873 (org-table-check-inside-data-field)
11874 (let* ((col (org-table-current-column))
11875 (col1 (if left (1- col) col))
11876 (beg (org-table-begin))
11877 (end (org-table-end))
11878 ;; Current cursor position
11879 (linepos (org-current-line))
11880 (colpos (if left (1- col) (1+ col))))
11881 (if (and left (= col 1))
11882 (error "Cannot move column further left"))
11883 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
11884 (error "Cannot move column further right"))
11885 (goto-char beg)
11886 (while (< (point) end)
11887 (if (org-at-table-hline-p)
11889 (org-table-goto-column col1 t)
11890 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
11891 (replace-match "|\\2|\\1|")))
11892 (beginning-of-line 2))
11893 (move-marker end nil)
11894 (goto-line linepos)
11895 (org-table-goto-column colpos)
11896 (org-table-align)
11897 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
11899 (defun org-table-move-row-down ()
11900 "Move table row down."
11901 (interactive)
11902 (org-table-move-row nil))
11903 (defun org-table-move-row-up ()
11904 "Move table row up."
11905 (interactive)
11906 (org-table-move-row 'up))
11908 (defun org-table-move-row (&optional up)
11909 "Move the current table line down. With arg UP, move it up."
11910 (interactive "P")
11911 (let ((col (current-column))
11912 (pos (point))
11913 (tonew (if up 0 2))
11914 txt)
11915 (beginning-of-line tonew)
11916 (if (not (org-at-table-p))
11917 (progn
11918 (goto-char pos)
11919 (error "Cannot move row further")))
11920 (goto-char pos)
11921 (beginning-of-line 1)
11922 (setq pos (point))
11923 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
11924 (delete-region (point) (1+ (point-at-eol)))
11925 (beginning-of-line tonew)
11926 (insert txt)
11927 (beginning-of-line 0)
11928 (move-to-column col)))
11930 (defun org-table-insert-row (&optional arg)
11931 "Insert a new row above the current line into the table.
11932 With prefix ARG, insert below the current line."
11933 (interactive "P")
11934 (if (not (org-at-table-p))
11935 (error "Not at a table"))
11936 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
11937 (new (org-table-clean-line line)))
11938 ;; Fix the first field if necessary
11939 (if (string-match "^[ \t]*| *[#$] *|" line)
11940 (setq new (replace-match (match-string 0 line) t t new)))
11941 (beginning-of-line (if arg 2 1))
11942 (let (org-table-may-need-update) (insert-before-markers new "\n"))
11943 (beginning-of-line 0)
11944 (re-search-forward "| ?" (point-at-eol) t)
11945 (and org-table-may-need-update (org-table-align))))
11947 (defun org-table-insert-hline (&optional arg)
11948 "Insert a horizontal-line below the current line into the table.
11949 With prefix ARG, insert above the current line."
11950 (interactive "P")
11951 (if (not (org-at-table-p))
11952 (error "Not at a table"))
11953 (let ((line (org-table-clean-line
11954 (buffer-substring (point-at-bol) (point-at-eol))))
11955 (col (current-column)))
11956 (while (string-match "|\\( +\\)|" line)
11957 (setq line (replace-match
11958 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
11959 ?-) "|") t t line)))
11960 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
11961 (beginning-of-line (if arg 1 2))
11962 (insert line "\n")
11963 (beginning-of-line (if arg 1 -1))
11964 (move-to-column col)))
11966 (defun org-table-clean-line (s)
11967 "Convert a table line S into a string with only \"|\" and space.
11968 In particular, this does handle wide and invisible characters."
11969 (if (string-match "^[ \t]*|-" s)
11970 ;; It's a hline, just map the characters
11971 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
11972 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
11973 (setq s (replace-match
11974 (concat "|" (make-string (org-string-width (match-string 1 s))
11975 ?\ ) "|")
11976 t t s)))
11979 (defun org-table-kill-row ()
11980 "Delete the current row or horizontal line from the table."
11981 (interactive)
11982 (if (not (org-at-table-p))
11983 (error "Not at a table"))
11984 (let ((col (current-column)))
11985 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
11986 (if (not (org-at-table-p)) (beginning-of-line 0))
11987 (move-to-column col)))
11989 (defun org-table-sort-lines (beg end numericp)
11990 "Sort table lines in region.
11991 Point and mark define the first and last line to include. Both point and
11992 mark should be in the column that is used for sorting. For example, to
11993 sort according to column 3, put the mark in the first line to sort, in
11994 table column 3. Put point into the last line to be included in the sorting,
11995 also in table column 3. The command will prompt for the sorting method
11996 \(n for numerical, a for alphanumeric)."
11997 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
11998 (setq numericp (string-match "[nN]" numericp))
11999 (org-table-align) ;; Just to be safe
12000 (let* (bcol ecol cmp column lns)
12001 (goto-char beg)
12002 (org-table-check-inside-data-field)
12003 (setq column (org-table-current-column)
12004 beg (move-marker (make-marker) (point-at-bol)))
12005 (goto-char end)
12006 (org-table-check-inside-data-field)
12007 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
12008 (untabify beg end)
12009 (goto-char beg)
12010 (org-table-goto-column column)
12011 (skip-chars-backward "^|")
12012 (setq bcol (current-column))
12013 (org-table-goto-column (1+ column))
12014 (skip-chars-backward "^|")
12015 (setq ecol (1- (current-column)))
12016 (setq cmp (if numericp
12017 (lambda (a b) (< (car a) (car b)))
12018 (lambda (a b) (string< (car a) (car b)))))
12019 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
12020 (org-split-string (buffer-substring beg end) "\n")))
12021 (if numericp
12022 (setq lns (mapcar (lambda(x)
12023 (cons (string-to-number (car x)) (cdr x)))
12024 lns)))
12025 (delete-region beg end)
12026 (move-marker beg nil)
12027 (move-marker end nil)
12028 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
12029 (message "%d lines sorted %s based on column %d"
12030 (length lns)
12031 (if numericp "numerically" "alphabetically") column)))
12033 (defun org-table-cut-region (beg end)
12034 "Copy region in table to the clipboard and blank all relevant fields."
12035 (interactive "r")
12036 (org-table-copy-region beg end 'cut))
12038 (defun org-table-copy-region (beg end &optional cut)
12039 "Copy rectangular region in table to clipboard.
12040 A special clipboard is used which can only be accessed
12041 with `org-table-paste-rectangle'."
12042 (interactive "rP")
12043 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
12044 region cols
12045 (rpl (if cut " " nil)))
12046 (goto-char beg)
12047 (org-table-check-inside-data-field)
12048 (setq l01 (count-lines (point-min) (point))
12049 c01 (org-table-current-column))
12050 (goto-char end)
12051 (org-table-check-inside-data-field)
12052 (setq l02 (count-lines (point-min) (point))
12053 c02 (org-table-current-column))
12054 (setq l1 (min l01 l02) l2 (max l01 l02)
12055 c1 (min c01 c02) c2 (max c01 c02))
12056 (catch 'exit
12057 (while t
12058 (catch 'nextline
12059 (if (> l1 l2) (throw 'exit t))
12060 (goto-line l1)
12061 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
12062 (setq cols nil ic1 c1 ic2 c2)
12063 (while (< ic1 (1+ ic2))
12064 (push (org-table-get-field ic1 rpl) cols)
12065 (setq ic1 (1+ ic1)))
12066 (push (nreverse cols) region)
12067 (setq l1 (1+ l1)))))
12068 (setq org-table-clip (nreverse region))
12069 (if cut (org-table-align))
12070 org-table-clip))
12072 (defun org-table-paste-rectangle ()
12073 "Paste a rectangular region into a table.
12074 The upper right corner ends up in the current field. All involved fields
12075 will be overwritten. If the rectangle does not fit into the present table,
12076 the table is enlarged as needed. The process ignores horizontal separator
12077 lines."
12078 (interactive)
12079 (unless (and org-table-clip (listp org-table-clip))
12080 (error "First cut/copy a region to paste!"))
12081 (org-table-check-inside-data-field)
12082 (let* ((clip org-table-clip)
12083 (line (count-lines (point-min) (point)))
12084 (col (org-table-current-column))
12085 (org-enable-table-editor t)
12086 (org-table-automatic-realign nil)
12087 c cols field)
12088 (while (setq cols (pop clip))
12089 (while (org-at-table-hline-p) (beginning-of-line 2))
12090 (if (not (org-at-table-p))
12091 (progn (end-of-line 0) (org-table-next-field)))
12092 (setq c col)
12093 (while (setq field (pop cols))
12094 (org-table-goto-column c nil 'force)
12095 (org-table-get-field nil field)
12096 (setq c (1+ c)))
12097 (beginning-of-line 2))
12098 (goto-line line)
12099 (org-table-goto-column col)
12100 (org-table-align)))
12102 (defun org-table-convert ()
12103 "Convert from `org-mode' table to table.el and back.
12104 Obviously, this only works within limits. When an Org-mode table is
12105 converted to table.el, all horizontal separator lines get lost, because
12106 table.el uses these as cell boundaries and has no notion of horizontal lines.
12107 A table.el table can be converted to an Org-mode table only if it does not
12108 do row or column spanning. Multiline cells will become multiple cells.
12109 Beware, Org-mode does not test if the table can be successfully converted - it
12110 blindly applies a recipe that works for simple tables."
12111 (interactive)
12112 (require 'table)
12113 (if (org-at-table.el-p)
12114 ;; convert to Org-mode table
12115 (let ((beg (move-marker (make-marker) (org-table-begin t)))
12116 (end (move-marker (make-marker) (org-table-end t))))
12117 (table-unrecognize-region beg end)
12118 (goto-char beg)
12119 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
12120 (replace-match ""))
12121 (goto-char beg))
12122 (if (org-at-table-p)
12123 ;; convert to table.el table
12124 (let ((beg (move-marker (make-marker) (org-table-begin)))
12125 (end (move-marker (make-marker) (org-table-end))))
12126 ;; first, get rid of all horizontal lines
12127 (goto-char beg)
12128 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
12129 (replace-match ""))
12130 ;; insert a hline before first
12131 (goto-char beg)
12132 (org-table-insert-hline 'above)
12133 (beginning-of-line -1)
12134 ;; insert a hline after each line
12135 (while (progn (beginning-of-line 3) (< (point) end))
12136 (org-table-insert-hline))
12137 (goto-char beg)
12138 (setq end (move-marker end (org-table-end)))
12139 ;; replace "+" at beginning and ending of hlines
12140 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
12141 (replace-match "\\1+-"))
12142 (goto-char beg)
12143 (while (re-search-forward "-|[ \t]*$" end t)
12144 (replace-match "-+"))
12145 (goto-char beg)))))
12147 (defun org-table-wrap-region (arg)
12148 "Wrap several fields in a column like a paragraph.
12149 This is useful if you'd like to spread the contents of a field over several
12150 lines, in order to keep the table compact.
12152 If there is an active region, and both point and mark are in the same column,
12153 the text in the column is wrapped to minimum width for the given number of
12154 lines. Generally, this makes the table more compact. A prefix ARG may be
12155 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
12156 formats the selected text to two lines. If the region was longer than two
12157 lines, the remaining lines remain empty. A negative prefix argument reduces
12158 the current number of lines by that amount. The wrapped text is pasted back
12159 into the table. If you formatted it to more lines than it was before, fields
12160 further down in the table get overwritten - so you might need to make space in
12161 the table first.
12163 If there is no region, the current field is split at the cursor position and
12164 the text fragment to the right of the cursor is prepended to the field one
12165 line down.
12167 If there is no region, but you specify a prefix ARG, the current field gets
12168 blank, and the content is appended to the field above."
12169 (interactive "P")
12170 (org-table-check-inside-data-field)
12171 (if (org-region-active-p)
12172 ;; There is a region: fill as a paragraph
12173 (let ((beg (region-beginning))
12174 nlines)
12175 (org-table-cut-region (region-beginning) (region-end))
12176 (if (> (length (car org-table-clip)) 1)
12177 (error "Region must be limited to single column"))
12178 (setq nlines (if arg
12179 (if (< arg 1)
12180 (+ (length org-table-clip) arg)
12181 arg)
12182 (length org-table-clip)))
12183 (setq org-table-clip
12184 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
12185 nil nlines)))
12186 (goto-char beg)
12187 (org-table-paste-rectangle))
12188 ;; No region, split the current field at point
12189 (if arg
12190 ;; combine with field above
12191 (let ((s (org-table-blank-field))
12192 (col (org-table-current-column)))
12193 (beginning-of-line 0)
12194 (while (org-at-table-hline-p) (beginning-of-line 0))
12195 (org-table-goto-column col)
12196 (skip-chars-forward "^|")
12197 (skip-chars-backward " ")
12198 (insert " " (org-trim s))
12199 (org-table-align))
12200 ;; split field
12201 (when (looking-at "\\([^|]+\\)+|")
12202 (let ((s (match-string 1)))
12203 (replace-match " |")
12204 (goto-char (match-beginning 0))
12205 (org-table-next-row)
12206 (insert (org-trim s) " ")
12207 (org-table-align))))))
12209 (defvar org-field-marker nil)
12211 (defun org-table-edit-field (arg)
12212 "Edit table field in a different window.
12213 This is mainly useful for fields that contain hidden parts.
12214 When called with a \\[universal-argument] prefix, just make the full field visible so that
12215 it can be edited in place."
12216 (interactive "P")
12217 (if arg
12218 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
12219 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
12220 (remove-text-properties b e '(org-cwidth t invisible t
12221 display t intangible t))
12222 (if (and (boundp 'font-lock-mode) font-lock-mode)
12223 (font-lock-fontify-block)))
12224 (let ((pos (move-marker (make-marker) (point)))
12225 (field (org-table-get-field))
12226 (cw (current-window-configuration))
12228 (switch-to-buffer-other-window "*Org tmp*")
12229 (erase-buffer)
12230 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
12231 (org-mode)
12232 (goto-char (setq p (point-max)))
12233 (insert (org-trim field))
12234 (remove-text-properties p (point-max)
12235 '(invisible t org-cwidth t display t
12236 intangible t))
12237 (goto-char p)
12238 (org-set-local 'org-finish-function
12239 'org-table-finish-edit-field)
12240 (org-set-local 'org-window-configuration cw)
12241 (org-set-local 'org-field-marker pos)
12242 (message "Edit and finish with C-c C-c"))))
12244 (defun org-table-finish-edit-field ()
12245 "Finish editing a table data field.
12246 Remove all newline characters, insert the result into the table, realign
12247 the table and kill the editing buffer."
12248 (let ((pos org-field-marker)
12249 (cw org-window-configuration)
12250 (cb (current-buffer))
12251 text)
12252 (goto-char (point-min))
12253 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
12254 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
12255 (replace-match " "))
12256 (setq text (org-trim (buffer-string)))
12257 (set-window-configuration cw)
12258 (kill-buffer cb)
12259 (select-window (get-buffer-window (marker-buffer pos)))
12260 (goto-char pos)
12261 (move-marker pos nil)
12262 (org-table-check-inside-data-field)
12263 (org-table-get-field nil text)
12264 (org-table-align)
12265 (message "New field value inserted")))
12267 (defun org-trim (s)
12268 "Remove whitespace at beginning and end of string."
12269 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
12270 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
12273 (defun org-wrap (string &optional width lines)
12274 "Wrap string to either a number of lines, or a width in characters.
12275 If WIDTH is non-nil, the string is wrapped to that width, however many lines
12276 that costs. If there is a word longer than WIDTH, the text is actually
12277 wrapped to the length of that word.
12278 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
12279 many lines, whatever width that takes.
12280 The return value is a list of lines, without newlines at the end."
12281 (let* ((words (org-split-string string "[ \t\n]+"))
12282 (maxword (apply 'max (mapcar 'org-string-width words)))
12283 w ll)
12284 (cond (width
12285 (org-do-wrap words (max maxword width)))
12286 (lines
12287 (setq w maxword)
12288 (setq ll (org-do-wrap words maxword))
12289 (if (<= (length ll) lines)
12291 (setq ll words)
12292 (while (> (length ll) lines)
12293 (setq w (1+ w))
12294 (setq ll (org-do-wrap words w)))
12295 ll))
12296 (t (error "Cannot wrap this")))))
12299 (defun org-do-wrap (words width)
12300 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
12301 (let (lines line)
12302 (while words
12303 (setq line (pop words))
12304 (while (and words (< (+ (length line) (length (car words))) width))
12305 (setq line (concat line " " (pop words))))
12306 (setq lines (push line lines)))
12307 (nreverse lines)))
12309 (defun org-split-string (string &optional separators)
12310 "Splits STRING into substrings at SEPARATORS.
12311 No empty strings are returned if there are matches at the beginning
12312 and end of string."
12313 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
12314 (start 0)
12315 notfirst
12316 (list nil))
12317 (while (and (string-match rexp string
12318 (if (and notfirst
12319 (= start (match-beginning 0))
12320 (< start (length string)))
12321 (1+ start) start))
12322 (< (match-beginning 0) (length string)))
12323 (setq notfirst t)
12324 (or (eq (match-beginning 0) 0)
12325 (and (eq (match-beginning 0) (match-end 0))
12326 (eq (match-beginning 0) start))
12327 (setq list
12328 (cons (substring string start (match-beginning 0))
12329 list)))
12330 (setq start (match-end 0)))
12331 (or (eq start (length string))
12332 (setq list
12333 (cons (substring string start)
12334 list)))
12335 (nreverse list)))
12337 (defun org-table-map-tables (function)
12338 "Apply FUNCTION to the start of all tables in the buffer."
12339 (save-excursion
12340 (save-restriction
12341 (widen)
12342 (goto-char (point-min))
12343 (while (re-search-forward org-table-any-line-regexp nil t)
12344 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
12345 (beginning-of-line 1)
12346 (if (looking-at org-table-line-regexp)
12347 (save-excursion (funcall function)))
12348 (re-search-forward org-table-any-border-regexp nil 1))))
12349 (message "Mapping tables: done"))
12351 (defun org-table-sum (&optional beg end nlast)
12352 "Sum numbers in region of current table column.
12353 The result will be displayed in the echo area, and will be available
12354 as kill to be inserted with \\[yank].
12356 If there is an active region, it is interpreted as a rectangle and all
12357 numbers in that rectangle will be summed. If there is no active
12358 region and point is located in a table column, sum all numbers in that
12359 column.
12361 If at least one number looks like a time HH:MM or HH:MM:SS, all other
12362 numbers are assumed to be times as well (in decimal hours) and the
12363 numbers are added as such.
12365 If NLAST is a number, only the NLAST fields will actually be summed."
12366 (interactive)
12367 (save-excursion
12368 (let (col (timecnt 0) diff h m s org-table-clip)
12369 (cond
12370 ((and beg end)) ; beg and end given explicitly
12371 ((org-region-active-p)
12372 (setq beg (region-beginning) end (region-end)))
12374 (setq col (org-table-current-column))
12375 (goto-char (org-table-begin))
12376 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
12377 (error "No table data"))
12378 (org-table-goto-column col)
12379 ;not needed? (skip-chars-backward "^|")
12380 (setq beg (point))
12381 (goto-char (org-table-end))
12382 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
12383 (error "No table data"))
12384 (org-table-goto-column col)
12385 ;not needed? (skip-chars-forward "^|")
12386 (setq end (point))))
12387 (let* ((items (apply 'append (org-table-copy-region beg end)))
12388 (items1 (cond ((not nlast) items)
12389 ((>= nlast (length items)) items)
12390 (t (setq items (reverse items))
12391 (setcdr (nthcdr (1- nlast) items) nil)
12392 (nreverse items))))
12393 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
12394 items1)))
12395 (res (apply '+ numbers))
12396 (sres (if (= timecnt 0)
12397 (format "%g" res)
12398 (setq diff (* 3600 res)
12399 h (floor (/ diff 3600)) diff (mod diff 3600)
12400 m (floor (/ diff 60)) diff (mod diff 60)
12401 s diff)
12402 (format "%d:%02d:%02d" h m s))))
12403 (kill-new sres)
12404 (if (interactive-p)
12405 (message "%s"
12406 (substitute-command-keys
12407 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
12408 (length numbers) sres))))
12409 sres))))
12411 (defun org-table-get-number-for-summing (s)
12412 (let (n)
12413 (if (string-match "^ *|? *" s)
12414 (setq s (replace-match "" nil nil s)))
12415 (if (string-match " *|? *$" s)
12416 (setq s (replace-match "" nil nil s)))
12417 (setq n (string-to-number s))
12418 (cond
12419 ((and (string-match "0" s)
12420 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
12421 ((string-match "\\`[ \t]+\\'" s) nil)
12422 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
12423 (let ((h (string-to-number (or (match-string 1 s) "0")))
12424 (m (string-to-number (or (match-string 2 s) "0")))
12425 (s (string-to-number (or (match-string 4 s) "0"))))
12426 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
12427 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
12428 ((equal n 0) nil)
12429 (t n))))
12431 (defun org-table-get-vertical-vector (desc &optional tbeg col)
12432 "Get a calc vector from a column, accorting to descriptor DESC.
12433 Optional arguments TBEG and COL can give the beginning of the table and
12434 the current column, to avoid unnecessary parsing."
12435 (save-excursion
12436 (or tbeg (setq tbeg (org-table-begin)))
12437 (or col (setq col (org-table-current-column)))
12438 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
12439 (cond
12440 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
12441 (setq n1 (- (match-end 1) (match-beginning 1)))
12442 (if (match-beginning 3)
12443 (setq n2 (- (match-end 2) (match-beginning 3))))
12444 (setq n (if n2 (max n1 n2) n1))
12445 (setq n1 (if n2 (min n1 n2)))
12446 (setq nn n)
12447 (while (and (> nn 0)
12448 (re-search-backward org-table-hline-regexp tbeg t))
12449 (push (org-current-line) hline-list)
12450 (setq nn (1- nn)))
12451 (setq hline-list (nreverse hline-list))
12452 (goto-line (nth (1- n) hline-list))
12453 (when (re-search-forward org-table-dataline-regexp)
12454 (org-table-goto-column col)
12455 (setq beg (point)))
12456 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
12457 (when (re-search-backward org-table-dataline-regexp)
12458 (org-table-goto-column col)
12459 (setq end (point)))
12460 (setq l (apply 'append (org-table-copy-region beg end)))
12461 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
12462 (if (equal x "") "0" x))
12463 l ",") "]"))
12464 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
12465 (setq n1 (string-to-number (match-string 1 desc))
12466 n2 (string-to-number (match-string 2 desc)))
12467 (beginning-of-line 1)
12468 (save-excursion
12469 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
12470 (org-table-goto-column col)
12471 (setq beg (point))))
12472 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
12473 (org-table-goto-column col)
12474 (setq end (point)))
12475 (setq l (apply 'append (org-table-copy-region beg end)))
12476 (concat "[" (mapconcat
12477 (lambda (x) (setq x (org-trim x))
12478 (if (equal x "") "0" x))
12479 l ",") "]"))
12480 ((string-match "\\([0-9]+\\)" desc)
12481 (beginning-of-line 1)
12482 (when (re-search-backward org-table-dataline-regexp tbeg t
12483 (string-to-number (match-string 0 desc)))
12484 (org-table-goto-column col)
12485 (org-trim (org-table-get-field))))))))
12487 (defvar org-table-formula-history nil)
12489 (defvar org-table-column-names nil
12490 "Alist with column names, derived from the `!' line.")
12491 (defvar org-table-column-name-regexp nil
12492 "Regular expression matching the current column names.")
12493 (defvar org-table-local-parameters nil
12494 "Alist with parameter names, derived from the `$' line.")
12495 (defvar org-table-named-field-locations nil
12496 "Alist with locations of named fields.")
12498 (defun org-table-get-formula (&optional equation named)
12499 "Read a formula from the minibuffer, offer stored formula as default."
12500 (let* ((name (car (rassoc (list (org-current-line)
12501 (org-table-current-column))
12502 org-table-named-field-locations)))
12503 (scol (if named
12504 (if name name
12505 (error "Not in a named field"))
12506 (int-to-string (org-table-current-column))))
12507 (dummy (and name (not named)
12508 (not (y-or-n-p "Replace named-field formula with column equation? " ))
12509 (error "Abort")))
12510 (org-table-may-need-update nil)
12511 (stored-list (org-table-get-stored-formulas))
12512 (stored (cdr (assoc scol stored-list)))
12513 (eq (cond
12514 ((and stored equation (string-match "^ *=? *$" equation))
12515 stored)
12516 ((stringp equation)
12517 equation)
12518 (t (read-string
12519 (format "%s formula $%s=" (if named "Field" "Column") scol)
12520 (or stored "") 'org-table-formula-history
12521 ;stored
12522 ))))
12523 mustsave)
12524 (when (not (string-match "\\S-" eq))
12525 ;; remove formula
12526 (setq stored-list (delq (assoc scol stored-list) stored-list))
12527 (org-table-store-formulas stored-list)
12528 (error "Formula removed"))
12529 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
12530 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
12531 (if (and name (not named))
12532 ;; We set the column equation, delete the named one.
12533 (setq stored-list (delq (assoc name stored-list) stored-list)
12534 mustsave t))
12535 (if stored
12536 (setcdr (assoc scol stored-list) eq)
12537 (setq stored-list (cons (cons scol eq) stored-list)))
12538 (if (or mustsave (not (equal stored eq)))
12539 (org-table-store-formulas stored-list))
12540 eq))
12542 (defun org-table-store-formulas (alist)
12543 "Store the list of formulas below the current table."
12544 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
12545 (save-excursion
12546 (goto-char (org-table-end))
12547 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
12548 (delete-region (point) (match-end 0)))
12549 (insert "#+TBLFM: "
12550 (mapconcat (lambda (x)
12551 (concat "$" (car x) "=" (cdr x)))
12552 alist "::")
12553 "\n")))
12555 (defun org-table-get-stored-formulas ()
12556 "Return an alist with the stored formulas directly after current table."
12557 (interactive)
12558 (let (scol eq eq-alist strings string seen)
12559 (save-excursion
12560 (goto-char (org-table-end))
12561 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
12562 (setq strings (org-split-string (match-string 2) " *:: *"))
12563 (while (setq string (pop strings))
12564 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
12565 (setq scol (match-string 1 string)
12566 eq (match-string 2 string)
12567 eq-alist (cons (cons scol eq) eq-alist))
12568 (if (member scol seen)
12569 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
12570 (push scol seen))))))
12571 (nreverse eq-alist)))
12573 (defun org-table-modify-formulas (action &rest columns)
12574 "Modify the formulas stored below the current table.
12575 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
12576 expected, for the other actions only a single column number is needed."
12577 (let ((list (org-table-get-stored-formulas))
12578 (nmax (length (org-split-string
12579 (buffer-substring (point-at-bol) (point-at-eol))
12580 "|")))
12581 col col1 col2 scol si sc1 sc2)
12582 (cond
12583 ((null list)) ; No action needed if there are no stored formulas
12584 ((eq action 'remove)
12585 (setq col (car columns)
12586 scol (int-to-string col))
12587 (org-table-replace-in-formulas list scol "INVALID")
12588 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
12589 (loop for i from (1+ col) upto nmax by 1 do
12590 (setq si (int-to-string i))
12591 (org-table-replace-in-formulas list si (int-to-string (1- i)))
12592 (if (assoc si list) (setcar (assoc si list)
12593 (int-to-string (1- i))))))
12594 ((eq action 'insert)
12595 (setq col (car columns))
12596 (loop for i from nmax downto col by 1 do
12597 (setq si (int-to-string i))
12598 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
12599 (if (assoc si list) (setcar (assoc si list)
12600 (int-to-string (1+ i))))))
12601 ((eq action 'swap)
12602 (setq col1 (car columns) col2 (nth 1 columns)
12603 sc1 (int-to-string col1) sc2 (int-to-string col2))
12604 ;; Hopefully, ZqZtZ will never be a name in a table
12605 (org-table-replace-in-formulas list sc1 "ZqZtZ")
12606 (org-table-replace-in-formulas list sc2 sc1)
12607 (org-table-replace-in-formulas list "ZqZtZ" sc2)
12608 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
12609 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
12610 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
12611 (t (error "Invalid action in `org-table-modify-formulas'")))
12612 (if list (org-table-store-formulas list))))
12614 (defun org-table-replace-in-formulas (list s1 s2)
12615 (let (elt re s)
12616 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
12617 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
12618 re (concat (regexp-quote s1) "\\>"))
12619 (while (setq elt (pop list))
12620 (setq s (cdr elt))
12621 (while (string-match re s)
12622 (setq s (replace-match s2 t t s)))
12623 (setcdr elt s))))
12625 (defun org-table-get-specials ()
12626 "Get the column names and local parameters for this table."
12627 (save-excursion
12628 (let ((beg (org-table-begin)) (end (org-table-end))
12629 names name fields fields1 field cnt c v line col)
12630 (setq org-table-column-names nil
12631 org-table-local-parameters nil
12632 org-table-named-field-locations nil)
12633 (goto-char beg)
12634 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
12635 (setq names (org-split-string (match-string 1) " *| *")
12636 cnt 1)
12637 (while (setq name (pop names))
12638 (setq cnt (1+ cnt))
12639 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
12640 (push (cons name (int-to-string cnt)) org-table-column-names))))
12641 (setq org-table-column-names (nreverse org-table-column-names))
12642 (setq org-table-column-name-regexp
12643 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
12644 (goto-char beg)
12645 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
12646 (setq fields (org-split-string (match-string 1) " *| *"))
12647 (while (setq field (pop fields))
12648 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
12649 (push (cons (match-string 1 field) (match-string 2 field))
12650 org-table-local-parameters))))
12651 (goto-char beg)
12652 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
12653 (setq c (match-string 1)
12654 fields (org-split-string (match-string 2) " *| *"))
12655 (save-excursion
12656 (beginning-of-line (if (equal c "_") 2 0))
12657 (setq line (org-current-line) col 1)
12658 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
12659 (setq fields1 (org-split-string (match-string 1) " *| *"))))
12660 (while (and fields1 (setq field (pop fields)))
12661 (setq v (pop fields1) col (1+ col))
12662 (when (and (stringp field) (stringp v)
12663 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
12664 (push (cons field v) org-table-local-parameters)
12665 (push (list field line col) org-table-named-field-locations)))))))
12667 (defun org-this-word ()
12668 ;; Get the current word
12669 (save-excursion
12670 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
12671 (end (progn (skip-chars-forward "^ \t\n") (point))))
12672 (buffer-substring-no-properties beg end))))
12674 (defun org-table-maybe-eval-formula ()
12675 "Check if the current field starts with \"=\" or \":=\".
12676 If yes, store the formula and apply it."
12677 ;; We already know we are in a table. Get field will only return a formula
12678 ;; when appropriate. It might return a separator line, but no problem.
12679 (when org-table-formula-evaluate-inline
12680 (let* ((field (org-trim (or (org-table-get-field) "")))
12681 named eq)
12682 (when (string-match "^:?=\\(.*\\)" field)
12683 (setq named (equal (string-to-char field) ?:)
12684 eq (match-string 1 field))
12685 (if (fboundp 'calc-eval)
12686 (org-table-eval-formula (if named '(4) nil) eq))))))
12688 (defvar org-recalc-commands nil
12689 "List of commands triggering the recalculation of a line.
12690 Will be filled automatically during use.")
12692 (defvar org-recalc-marks
12693 '((" " . "Unmarked: no special line, no automatic recalculation")
12694 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
12695 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
12696 ("!" . "Column name definition line. Reference in formula as $name.")
12697 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
12698 ("_" . "Names for values in row below this one.")
12699 ("^" . "Names for values in row above this one.")))
12701 (defun org-table-rotate-recalc-marks (&optional newchar)
12702 "Rotate the recalculation mark in the first column.
12703 If in any row, the first field is not consistent with a mark,
12704 insert a new column for the markers.
12705 When there is an active region, change all the lines in the region,
12706 after prompting for the marking character.
12707 After each change, a message will be displayed indicating the meaning
12708 of the new mark."
12709 (interactive)
12710 (unless (org-at-table-p) (error "Not at a table"))
12711 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
12712 (beg (org-table-begin))
12713 (end (org-table-end))
12714 (l (org-current-line))
12715 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
12716 (l2 (if (org-region-active-p) (org-current-line (region-end))))
12717 (have-col
12718 (save-excursion
12719 (goto-char beg)
12720 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
12721 (col (org-table-current-column))
12722 (forcenew (car (assoc newchar org-recalc-marks)))
12723 epos new)
12724 (when l1
12725 (message "Change region to what mark? Type # * ! $ or SPC: ")
12726 (setq newchar (char-to-string (read-char-exclusive))
12727 forcenew (car (assoc newchar org-recalc-marks))))
12728 (if (and newchar (not forcenew))
12729 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
12730 newchar))
12731 (if l1 (goto-line l1))
12732 (save-excursion
12733 (beginning-of-line 1)
12734 (unless (looking-at org-table-dataline-regexp)
12735 (error "Not at a table data line")))
12736 (unless have-col
12737 (org-table-goto-column 1)
12738 (org-table-insert-column)
12739 (org-table-goto-column (1+ col)))
12740 (setq epos (point-at-eol))
12741 (save-excursion
12742 (beginning-of-line 1)
12743 (org-table-get-field
12744 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
12745 (concat " "
12746 (setq new (or forcenew
12747 (cadr (member (match-string 1) marks))))
12748 " ")
12749 " # ")))
12750 (if (and l1 l2)
12751 (progn
12752 (goto-line l1)
12753 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
12754 (and (looking-at org-table-dataline-regexp)
12755 (org-table-get-field 1 (concat " " new " "))))
12756 (goto-line l1)))
12757 (if (not (= epos (point-at-eol))) (org-table-align))
12758 (goto-line l)
12759 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
12761 (defun org-table-maybe-recalculate-line ()
12762 "Recompute the current line if marked for it, and if we haven't just done it."
12763 (interactive)
12764 (and org-table-allow-automatic-line-recalculation
12765 (not (and (memq last-command org-recalc-commands)
12766 (equal org-last-recalc-line (org-current-line))))
12767 (save-excursion (beginning-of-line 1)
12768 (looking-at org-table-auto-recalculate-regexp))
12769 (fboundp 'calc-eval)
12770 (org-table-recalculate) t))
12772 (defvar org-table-formula-debug nil
12773 "Non-nil means, debug table formulas.
12774 When nil, simply write \"#ERROR\" in corrupted fields.")
12776 (defvar modes)
12777 (defsubst org-set-calc-mode (var &optional value)
12778 (if (stringp var)
12779 (setq var (assoc var '(("D" calc-angle-mode deg)
12780 ("R" calc-angle-mode rad)
12781 ("F" calc-prefer-frac t)
12782 ("S" calc-symbolic-mode t)))
12783 value (nth 2 var) var (nth 1 var)))
12784 (if (memq var modes)
12785 (setcar (cdr (memq var modes)) value)
12786 (cons var (cons value modes)))
12787 modes)
12789 (defun org-table-eval-formula (&optional arg equation
12790 suppress-align suppress-const
12791 suppress-store)
12792 "Replace the table field value at the cursor by the result of a calculation.
12794 This function makes use of Dave Gillespie's Calc package, in my view the
12795 most exciting program ever written for GNU Emacs. So you need to have Calc
12796 installed in order to use this function.
12798 In a table, this command replaces the value in the current field with the
12799 result of a formula. It also installs the formula as the \"current\" column
12800 formula, by storing it in a special line below the table. When called
12801 with a `C-u' prefix, the current field must ba a named field, and the
12802 formula is installed as valid in only this specific field.
12804 When called, the command first prompts for a formula, which is read in
12805 the minibuffer. Previously entered formulas are available through the
12806 history list, and the last used formula is offered as a default.
12807 These stored formulas are adapted correctly when moving, inserting, or
12808 deleting columns with the corresponding commands.
12810 The formula can be any algebraic expression understood by the Calc package.
12811 For details, see the Org-mode manual.
12813 This function can also be called from Lisp programs and offers
12814 additional arguments: EQUATION can be the formula to apply. If this
12815 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
12816 used to speed-up recursive calls by by-passing unnecessary aligns.
12817 SUPPRESS-CONST suppresses the interpretation of constants in the
12818 formula, assuming that this has been done already outside the function.
12819 SUPPRESS-STORE means the formula should not be stored, either because
12820 it is already stored, or because it is a modified equation that should
12821 not overwrite the stored one."
12822 (interactive "P")
12823 (require 'calc)
12824 (org-table-check-inside-data-field)
12825 (org-table-get-specials)
12826 (let* (fields
12827 (ndown (if (integerp arg) arg 1))
12828 (org-table-automatic-realign nil)
12829 (case-fold-search nil)
12830 (down (> ndown 1))
12831 (formula (if (and equation suppress-store)
12832 equation
12833 (org-table-get-formula equation (equal arg '(4)))))
12834 (n0 (org-table-current-column))
12835 (modes (copy-sequence org-calc-default-modes))
12836 n form fmt x ev orig c lispp)
12837 ;; Parse the format string. Since we have a lot of modes, this is
12838 ;; a lot of work. However, I think calc still uses most of the time.
12839 (if (string-match ";" formula)
12840 (let ((tmp (org-split-string formula ";")))
12841 (setq formula (car tmp)
12842 fmt (concat (cdr (assoc "%" org-table-local-parameters))
12843 (nth 1 tmp)))
12844 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
12845 (setq c (string-to-char (match-string 1 fmt))
12846 n (string-to-number (match-string 2 fmt)))
12847 (if (= c ?p)
12848 (setq modes (org-set-calc-mode 'calc-internal-prec n))
12849 (setq modes (org-set-calc-mode
12850 'calc-float-format
12851 (list (cdr (assoc c '((?n . float) (?f . fix)
12852 (?s . sci) (?e . eng))))
12853 n))))
12854 (setq fmt (replace-match "" t t fmt)))
12855 (while (string-match "[DRFS]" fmt)
12856 (setq modes (org-set-calc-mode (match-string 0 fmt)))
12857 (setq fmt (replace-match "" t t fmt)))
12858 (unless (string-match "\\S-" fmt)
12859 (setq fmt nil))))
12860 (if (and (not suppress-const) org-table-formula-use-constants)
12861 (setq formula (org-table-formula-substitute-names formula)))
12862 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
12863 (while (> ndown 0)
12864 (setq fields (org-split-string
12865 (buffer-substring
12866 (point-at-bol) (point-at-eol)) " *| *"))
12867 (if org-table-formula-numbers-only
12868 (setq fields (mapcar
12869 (lambda (x) (number-to-string (string-to-number x)))
12870 fields)))
12871 (setq ndown (1- ndown))
12872 (setq form (copy-sequence formula)
12873 lispp (equal (substring form 0 2) "'("))
12874 ;; Insert the references to fields in same row
12875 (while (string-match "\\$\\([0-9]+\\)?" form)
12876 (setq n (if (match-beginning 1)
12877 (string-to-number (match-string 1 form))
12879 x (nth (1- n) fields))
12880 (unless x (error "Invalid field specifier \"%s\""
12881 (match-string 0 form)))
12882 (if (equal x "") (setq x "0"))
12883 (setq form (replace-match
12884 (if lispp x (concat "(" x ")"))
12885 t t form)))
12886 ;; Insert ranges in current column
12887 (while (string-match "\\&[-I0-9]+" form)
12888 (setq form (replace-match
12889 (save-match-data
12890 (org-table-get-vertical-vector (match-string 0 form)
12891 nil n0))
12892 t t form)))
12893 (if lispp
12894 (setq ev (eval (eval (read form)))
12895 ev (if (numberp ev) (number-to-string ev) ev))
12896 (setq ev (calc-eval (cons form modes)
12897 (if org-table-formula-numbers-only 'num))))
12899 (when org-table-formula-debug
12900 (with-output-to-temp-buffer "*Help*"
12901 (princ (format "Substitution history of formula
12902 Orig: %s
12903 $xyz-> %s
12904 $1-> %s\n" orig formula form))
12905 (if (listp ev)
12906 (princ (format " %s^\nError: %s"
12907 (make-string (car ev) ?\-) (nth 1 ev)))
12908 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
12909 ev (or fmt "NONE")
12910 (if fmt (format fmt (string-to-number ev)) ev)))))
12911 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
12912 (unless (and (interactive-p) (not ndown))
12913 (unless (let (inhibit-redisplay)
12914 (y-or-n-p "Debugging Formula. Continue to next? "))
12915 (org-table-align)
12916 (error "Abort"))
12917 (delete-window (get-buffer-window "*Help*"))
12918 (message "")))
12919 (if (listp ev) (setq fmt nil ev "#ERROR"))
12920 (org-table-justify-field-maybe
12921 (if fmt (format fmt (string-to-number ev)) ev))
12922 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
12923 (call-interactively 'org-return)
12924 (setq ndown 0)))
12925 (and down (org-table-maybe-recalculate-line))
12926 (or suppress-align (and org-table-may-need-update
12927 (org-table-align)))))
12929 (defun org-table-recalculate (&optional all noalign)
12930 "Recalculate the current table line by applying all stored formulas.
12931 With prefix arg ALL, do this for all lines in the table."
12932 (interactive "P")
12933 (or (memq this-command org-recalc-commands)
12934 (setq org-recalc-commands (cons this-command org-recalc-commands)))
12935 (unless (org-at-table-p) (error "Not at a table"))
12936 (org-table-get-specials)
12937 (let* ((eqlist (sort (org-table-get-stored-formulas)
12938 (lambda (a b) (string< (car a) (car b)))))
12939 (inhibit-redisplay t)
12940 (line-re org-table-dataline-regexp)
12941 (thisline (org-current-line))
12942 (thiscol (org-table-current-column))
12943 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
12944 ;; Insert constants in all formulas
12945 (setq eqlist
12946 (mapcar (lambda (x)
12947 (setcdr x (org-table-formula-substitute-names (cdr x)))
12949 eqlist))
12950 ;; Split the equation list
12951 (while (setq eq (pop eqlist))
12952 (if (<= (string-to-char (car eq)) ?9)
12953 (push eq eqlnum)
12954 (push eq eqlname)))
12955 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
12956 (if all
12957 (progn
12958 (setq end (move-marker (make-marker) (1+ (org-table-end))))
12959 (goto-char (setq beg (org-table-begin)))
12960 (if (re-search-forward org-table-calculate-mark-regexp end t)
12961 ;; This is a table with marked lines, only compute selected lines
12962 (setq line-re org-table-recalculate-regexp)
12963 ;; Move forward to the first non-header line
12964 (if (and (re-search-forward org-table-dataline-regexp end t)
12965 (re-search-forward org-table-hline-regexp end t)
12966 (re-search-forward org-table-dataline-regexp end t))
12967 (setq beg (match-beginning 0))
12968 nil))) ;; just leave beg where it is
12969 (setq beg (point-at-bol)
12970 end (move-marker (make-marker) (1+ (point-at-eol)))))
12971 (goto-char beg)
12972 (and all (message "Re-applying formulas to full table..."))
12973 (while (re-search-forward line-re end t)
12974 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
12975 ;; Unprotected line, recalculate
12976 (and all (message "Re-applying formulas to full table...(line %d)"
12977 (setq cnt (1+ cnt))))
12978 (setq org-last-recalc-line (org-current-line))
12979 (setq eql eqlnum)
12980 (while (setq entry (pop eql))
12981 (goto-line org-last-recalc-line)
12982 (org-table-goto-column (string-to-number (car entry)) nil 'force)
12983 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
12984 (goto-line thisline)
12985 (org-table-goto-column thiscol)
12986 (or noalign (and org-table-may-need-update (org-table-align))
12987 (and all (message "Re-applying formulas to %d lines...done" cnt)))
12988 ;; Now do the names fields
12989 (while (setq eq (pop eqlname))
12990 (setq name (car eq)
12991 a (assoc name org-table-named-field-locations))
12992 (when a
12993 (message "Re-applying formula to named field: %s" name)
12994 (goto-line (nth 1 a))
12995 (org-table-goto-column (nth 2 a))
12996 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
12997 ;; back to initial position
12998 (goto-line thisline)
12999 (org-table-goto-column thiscol)
13000 (or noalign (and org-table-may-need-update (org-table-align))
13001 (and all (message "Re-applying formulas...done")))))
13003 (defun org-table-formula-substitute-names (f)
13004 "Replace $const with values in string F."
13005 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
13006 ;; First, check for column names
13007 (while (setq start (string-match org-table-column-name-regexp f start))
13008 (setq start (1+ start))
13009 (setq a (assoc (match-string 1 f) org-table-column-names))
13010 (setq f (replace-match (concat "$" (cdr a)) t t f)))
13011 ;; Expand ranges to vectors
13012 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
13013 (setq n1 (string-to-number (match-string 1 f))
13014 n2 (string-to-number (match-string 2 f))
13015 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
13016 s (concat "[($" (number-to-string (1- nn1)) ")"))
13017 (loop for i from nn1 upto nn2 do
13018 (setq s (concat s ",($" (int-to-string i) ")")))
13019 (setq s (concat s "]"))
13020 (if (< n2 n1) (setq s (concat "rev(" s ")")))
13021 (setq f (replace-match s t t f)))
13022 ;; Parameters and constants
13023 (setq start 0)
13024 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
13025 (setq start (1+ start))
13026 (if (setq a (save-match-data
13027 (org-table-get-constant (match-string 1 f))))
13028 (setq f (replace-match (concat "(" a ")") t t f))))
13029 (if org-table-formula-debug
13030 (put-text-property 0 (length f) :orig-formula f1 f))
13033 (defun org-table-get-constant (const)
13034 "Find the value for a parameter or constant in a formula.
13035 Parameters get priority."
13036 (or (cdr (assoc const org-table-local-parameters))
13037 (cdr (assoc const org-table-formula-constants))
13038 (and (fboundp 'constants-get) (constants-get const))
13039 "#UNDEFINED_NAME"))
13041 (defvar org-edit-formulas-map (make-sparse-keymap))
13042 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
13043 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
13044 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
13046 (defvar org-pos)
13048 (defun org-table-edit-formulas ()
13049 "Edit the formulas of the current table in a separate buffer."
13050 (interactive)
13051 (unless (org-at-table-p)
13052 (error "Not at a table"))
13053 (org-table-get-specials)
13054 (let ((eql (org-table-get-stored-formulas))
13055 (pos (move-marker (make-marker) (point)))
13056 (wc (current-window-configuration))
13057 entry loc s)
13058 (switch-to-buffer-other-window "*Edit Formulas*")
13059 (erase-buffer)
13060 (fundamental-mode)
13061 (org-set-local 'org-pos pos)
13062 (org-set-local 'org-window-configuration wc)
13063 (use-local-map org-edit-formulas-map)
13064 (setq s "# Edit formulas and finish with `C-c C-c'.
13065 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
13066 # Use `C-c ?' to get information about $name at point.
13067 # To cancel editing, press `C-c C-q'.\n")
13068 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
13069 (insert s)
13070 (while (setq entry (pop eql))
13071 (when (setq loc (assoc (car entry) org-table-named-field-locations))
13072 (setq s (format "# Named formula, referring to column %d in line %d\n"
13073 (nth 2 loc) (nth 1 loc)))
13074 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
13075 (insert s))
13076 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
13077 (remove-text-properties 0 (length s) '(face nil) s)
13078 (insert s))
13079 (goto-char (point-min))
13080 (message "Edit formulas and finish with `C-c C-c'.")))
13082 (defun org-show-variable ()
13083 "Show the location/value of the $ expression at point."
13084 (interactive)
13085 (let (var (pos org-pos) (win (selected-window)) e)
13086 (save-excursion
13087 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
13088 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
13089 (setq var (match-string 1))
13090 (error "No variable at point")))
13091 (cond
13092 ((setq e (assoc var org-table-named-field-locations))
13093 (switch-to-buffer-other-window (marker-buffer pos))
13094 (goto-line (nth 1 e))
13095 (org-table-goto-column (nth 2 e))
13096 (select-window win)
13097 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
13098 ((setq e (assoc var org-table-column-names))
13099 (switch-to-buffer-other-window (marker-buffer pos))
13100 (goto-char pos)
13101 (goto-char (org-table-begin))
13102 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
13103 (org-table-end) t)
13104 (progn
13105 (goto-char (match-beginning 1))
13106 (message "Named column (column %s)" (cdr e)))
13107 (error "Column name not found"))
13108 (select-window win))
13109 ((string-match "^[0-9]$" var)
13110 ;; column number
13111 (switch-to-buffer-other-window (marker-buffer pos))
13112 (goto-char pos)
13113 (goto-char (org-table-begin))
13114 (recenter 1)
13115 (if (re-search-forward org-table-dataline-regexp
13116 (org-table-end) t)
13117 (progn
13118 (goto-char (match-beginning 0))
13119 (org-table-goto-column (string-to-number var))
13120 (message "Column %s" var))
13121 (error "Column name not found"))
13122 (select-window win))
13123 ((setq e (assoc var org-table-local-parameters))
13124 (switch-to-buffer-other-window (marker-buffer pos))
13125 (goto-char pos)
13126 (goto-char (org-table-begin))
13127 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
13128 (progn
13129 (goto-char (match-beginning 1))
13130 (message "Local parameter."))
13131 (error "Parameter not found"))
13132 (select-window win))
13134 (cond
13135 ((setq e (assoc var org-table-formula-constants))
13136 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
13137 ((setq e (and (fboundp 'constants-get) (constants-get var)))
13138 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
13139 (t (error "Undefined name $%s" var)))))))
13141 (defun org-finish-edit-formulas (&optional arg)
13142 "Parse the buffer for formula definitions and install them.
13143 With prefix ARG, apply the new formulas to the table."
13144 (interactive "P")
13145 (let ((pos org-pos) eql)
13146 (goto-char (point-min))
13147 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
13148 (push (cons (match-string 1) (match-string 2)) eql))
13149 (set-window-configuration org-window-configuration)
13150 (select-window (get-buffer-window (marker-buffer pos)))
13151 (goto-char pos)
13152 (unless (org-at-table-p)
13153 (error "Lost table position - cannot install formulae"))
13154 (org-table-store-formulas eql)
13155 (move-marker pos nil)
13156 (kill-buffer "*Edit Formulas*")
13157 (if arg
13158 (org-table-recalculate 'all)
13159 (message "New formulas installed - press C-u C-c C-c to apply."))))
13161 (defun org-abort-edit-formulas ()
13162 "Abort editing formulas, without installing the changes."
13163 (interactive)
13164 (let ((pos org-pos))
13165 (set-window-configuration org-window-configuration)
13166 (select-window (get-buffer-window (marker-buffer pos)))
13167 (goto-char pos)
13168 (message "Formula editing aborted without installing changes")))
13170 ;;; The orgtbl minor mode
13172 ;; Define a minor mode which can be used in other modes in order to
13173 ;; integrate the org-mode table editor.
13175 ;; This is really a hack, because the org-mode table editor uses several
13176 ;; keys which normally belong to the major mode, for example the TAB and
13177 ;; RET keys. Here is how it works: The minor mode defines all the keys
13178 ;; necessary to operate the table editor, but wraps the commands into a
13179 ;; function which tests if the cursor is currently inside a table. If that
13180 ;; is the case, the table editor command is executed. However, when any of
13181 ;; those keys is used outside a table, the function uses `key-binding' to
13182 ;; look up if the key has an associated command in another currently active
13183 ;; keymap (minor modes, major mode, global), and executes that command.
13184 ;; There might be problems if any of the keys used by the table editor is
13185 ;; otherwise used as a prefix key.
13187 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
13188 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
13189 ;; addresses this by checking explicitly for both bindings.
13191 ;; The optimized version (see variable `orgtbl-optimized') takes over
13192 ;; all keys which are bound to `self-insert-command' in the *global map*.
13193 ;; Some modes bind other commands to simple characters, for example
13194 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
13195 ;; active, this binding is ignored inside tables and replaced with a
13196 ;; modified self-insert.
13198 (defvar orgtbl-mode nil
13199 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
13200 table editor in arbitrary modes.")
13201 (make-variable-buffer-local 'orgtbl-mode)
13203 (defvar orgtbl-mode-map (make-keymap)
13204 "Keymap for `orgtbl-mode'.")
13206 ;;;###autoload
13207 (defun turn-on-orgtbl ()
13208 "Unconditionally turn on `orgtbl-mode'."
13209 (orgtbl-mode 1))
13211 ;;;###autoload
13212 (defun orgtbl-mode (&optional arg)
13213 "The `org-mode' table editor as a minor mode for use in other modes."
13214 (interactive)
13215 (if (org-mode-p)
13216 ;; Exit without error, in case some hook functions calls this
13217 ;; by accident in org-mode.
13218 (message "Orgtbl-mode is not useful in org-mode, command ignored")
13219 (setq orgtbl-mode
13220 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
13221 (if orgtbl-mode
13222 (progn
13223 (and (orgtbl-setup) (defun orgtbl-setup () nil))
13224 ;; Make sure we are first in minor-mode-map-alist
13225 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
13226 (and c (setq minor-mode-map-alist
13227 (cons c (delq c minor-mode-map-alist)))))
13228 (org-set-local (quote org-table-may-need-update) t)
13229 (org-add-hook 'before-change-functions 'org-before-change-function
13230 nil 'local)
13231 (org-set-local 'org-old-auto-fill-inhibit-regexp
13232 auto-fill-inhibit-regexp)
13233 (org-set-local 'auto-fill-inhibit-regexp
13234 (if auto-fill-inhibit-regexp
13235 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
13236 "[ \t]*|"))
13237 (org-add-to-invisibility-spec '(org-cwidth))
13238 (easy-menu-add orgtbl-mode-menu)
13239 (run-hooks 'orgtbl-mode-hook))
13240 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
13241 (org-cleanup-narrow-column-properties)
13242 (org-remove-from-invisibility-spec '(org-cwidth))
13243 (remove-hook 'before-change-functions 'org-before-change-function t)
13244 (easy-menu-remove orgtbl-mode-menu)
13245 (force-mode-line-update 'all))))
13247 (defun org-cleanup-narrow-column-properties ()
13248 "Remove all properties related to narrow-column invisibility."
13249 (let ((s 1))
13250 (while (setq s (text-property-any s (point-max)
13251 'display org-narrow-column-arrow))
13252 (remove-text-properties s (1+ s) '(display t)))
13253 (setq s 1)
13254 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
13255 (remove-text-properties s (1+ s) '(org-cwidth t)))
13256 (setq s 1)
13257 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
13258 (remove-text-properties s (1+ s) '(invisible t)))))
13260 ;; Install it as a minor mode.
13261 (put 'orgtbl-mode :included t)
13262 (put 'orgtbl-mode :menu-tag "Org Table Mode")
13263 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
13265 (defun orgtbl-make-binding (fun n &rest keys)
13266 "Create a function for binding in the table minor mode.
13267 FUN is the command to call inside a table. N is used to create a unique
13268 command name. KEYS are keys that should be checked in for a command
13269 to execute outside of tables."
13270 (eval
13271 (list 'defun
13272 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
13273 '(arg)
13274 (concat "In tables, run `" (symbol-name fun) "'.\n"
13275 "Outside of tables, run the binding of `"
13276 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
13277 "'.")
13278 '(interactive "p")
13279 (list 'if
13280 '(org-at-table-p)
13281 (list 'call-interactively (list 'quote fun))
13282 (list 'let '(orgtbl-mode)
13283 (list 'call-interactively
13284 (append '(or)
13285 (mapcar (lambda (k)
13286 (list 'key-binding k))
13287 keys)
13288 '('orgtbl-error))))))))
13290 (defun orgtbl-error ()
13291 "Error when there is no default binding for a table key."
13292 (interactive)
13293 (error "This key is has no function outside tables"))
13295 (defun orgtbl-setup ()
13296 "Setup orgtbl keymaps."
13297 (let ((nfunc 0)
13298 (bindings
13299 (list
13300 '([(meta shift left)] org-table-delete-column)
13301 '([(meta left)] org-table-move-column-left)
13302 '([(meta right)] org-table-move-column-right)
13303 '([(meta shift right)] org-table-insert-column)
13304 '([(meta shift up)] org-table-kill-row)
13305 '([(meta shift down)] org-table-insert-row)
13306 '([(meta up)] org-table-move-row-up)
13307 '([(meta down)] org-table-move-row-down)
13308 '("\C-c\C-w" org-table-cut-region)
13309 '("\C-c\M-w" org-table-copy-region)
13310 '("\C-c\C-y" org-table-paste-rectangle)
13311 '("\C-c-" org-table-insert-hline)
13312 ; '([(shift tab)] org-table-previous-field)
13313 '("\C-m" org-table-next-row)
13314 (list (org-key 'S-return) 'org-table-copy-down)
13315 '([(meta return)] org-table-wrap-region)
13316 '("\C-c\C-q" org-table-wrap-region)
13317 '("\C-c?" org-table-current-column)
13318 '("\C-c " org-table-blank-field)
13319 '("\C-c+" org-table-sum)
13320 '("\C-c=" org-table-eval-formula)
13321 '("\C-c'" org-table-edit-formulas)
13322 '("\C-c`" org-table-edit-field)
13323 '("\C-c*" org-table-recalculate)
13324 '("\C-c|" org-table-create-or-convert-from-region)
13325 '("\C-c^" org-table-sort-lines)
13326 '([(control ?#)] org-table-rotate-recalc-marks)))
13327 elt key fun cmd)
13328 (while (setq elt (pop bindings))
13329 (setq nfunc (1+ nfunc))
13330 (setq key (car elt)
13331 fun (nth 1 elt)
13332 cmd (orgtbl-make-binding fun nfunc key))
13333 (define-key orgtbl-mode-map key cmd))
13334 ;; Special treatment needed for TAB and RET
13335 (define-key orgtbl-mode-map [(return)]
13336 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
13337 (define-key orgtbl-mode-map "\C-m"
13338 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
13339 (define-key orgtbl-mode-map [(tab)]
13340 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
13341 (define-key orgtbl-mode-map "\C-i"
13342 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
13343 (define-key orgtbl-mode-map "\C-i"
13344 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
13345 (define-key orgtbl-mode-map "\C-c\C-c"
13346 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
13347 (when orgtbl-optimized
13348 ;; If the user wants maximum table support, we need to hijack
13349 ;; some standard editing functions
13350 (org-remap orgtbl-mode-map
13351 'self-insert-command 'orgtbl-self-insert-command
13352 'delete-char 'org-delete-char
13353 'delete-backward-char 'org-delete-backward-char)
13354 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
13355 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
13356 '("OrgTbl"
13357 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
13358 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
13359 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
13360 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
13361 "--"
13362 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
13363 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
13364 ["Copy Field from Above"
13365 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
13366 "--"
13367 ("Column"
13368 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
13369 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
13370 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
13371 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
13372 "--"
13373 ["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])
13374 ("Row"
13375 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
13376 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
13377 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
13378 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
13379 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
13380 "--"
13381 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
13382 ("Rectangle"
13383 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
13384 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
13385 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
13386 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
13387 "--"
13388 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
13389 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13390 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
13391 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
13392 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
13393 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
13394 ["Sum Column/Rectangle" org-table-sum
13395 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
13396 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
13397 ["Debug Formulas"
13398 (setq org-table-formula-debug (not org-table-formula-debug))
13399 :style toggle :selected org-table-formula-debug]
13403 (defun orgtbl-tab (arg)
13404 "Justification and field motion for `orgtbl-mode'."
13405 (interactive "P")
13406 (if arg (org-table-edit-field t)
13407 (org-table-justify-field-maybe)
13408 (org-table-next-field)))
13410 (defun orgtbl-ret ()
13411 "Justification and field motion for `orgtbl-mode'."
13412 (interactive)
13413 (org-table-justify-field-maybe)
13414 (org-table-next-row))
13416 (defun orgtbl-self-insert-command (N)
13417 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13418 If the cursor is in a table looking at whitespace, the whitespace is
13419 overwritten, and the table is not marked as requiring realignment."
13420 (interactive "p")
13421 (if (and (org-at-table-p)
13423 (and org-table-auto-blank-field
13424 (member last-command
13425 '(orgtbl-hijacker-command-100
13426 orgtbl-hijacker-command-101
13427 orgtbl-hijacker-command-102
13428 orgtbl-hijacker-command-103
13429 orgtbl-hijacker-command-104
13430 orgtbl-hijacker-command-105))
13431 (org-table-blank-field))
13433 (eq N 1)
13434 (looking-at "[^|\n]* +|"))
13435 (let (org-table-may-need-update)
13436 (goto-char (1- (match-end 0)))
13437 (delete-backward-char 1)
13438 (goto-char (match-beginning 0))
13439 (self-insert-command N))
13440 (setq org-table-may-need-update t)
13441 (let (orgtbl-mode)
13442 (call-interactively (key-binding (vector last-input-event))))))
13444 (defun org-force-self-insert (N)
13445 "Needed to enforce self-insert under remapping."
13446 (interactive "p")
13447 (self-insert-command N))
13449 ;;; Exporting
13451 (defconst org-level-max 20)
13453 (defvar org-export-html-preamble nil
13454 "Preamble, to be inserted just after <body>. Set by publishing functions.")
13455 (defvar org-export-html-postamble nil
13456 "Preamble, to be inserted just before </body>. Set by publishing functions.")
13457 (defvar org-export-html-auto-preamble t
13458 "Should default preamble be inserted? Set by publishing functions.")
13459 (defvar org-export-html-auto-postamble t
13460 "Should default postamble be inserted? Set by publishing functions.")
13462 (defconst org-export-plist-vars
13463 '((:language . org-export-default-language)
13464 (:headline-levels . org-export-headline-levels)
13465 (:section-numbers . org-export-with-section-numbers)
13466 (:table-of-contents . org-export-with-toc)
13467 (:archived-trees . org-export-with-archived-trees)
13468 (:emphasize . org-export-with-emphasize)
13469 (:sub-superscript . org-export-with-sub-superscripts)
13470 (:TeX-macros . org-export-with-TeX-macros)
13471 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
13472 (:fixed-width . org-export-with-fixed-width)
13473 (:timestamps . org-export-with-timestamps)
13474 (:tables . org-export-with-tables)
13475 (:table-auto-headline . org-export-highlight-first-table-line)
13476 (:style . org-export-html-style)
13477 (:convert-org-links . org-export-html-link-org-files-as-html)
13478 (:inline-images . org-export-html-inline-images)
13479 (:expand-quoted-html . org-export-html-expand)
13480 (:timestamp . org-export-html-with-timestamp)
13481 (:publishing-directory . org-export-publishing-directory)
13482 (:preamble . org-export-html-preamble)
13483 (:postamble . org-export-html-postamble)
13484 (:auto-preamble . org-export-html-auto-preamble)
13485 (:auto-postamble . org-export-html-auto-postamble)
13486 (:author . user-full-name)
13487 (:email . user-mail-address)))
13489 (defun org-default-export-plist ()
13490 "Return the property list with default settings for the export variables."
13491 (let ((l org-export-plist-vars) rtn e)
13492 (while (setq e (pop l))
13493 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
13494 rtn))
13496 (defun org-infile-export-plist ()
13497 "Return the property list with file-local settings for export."
13498 (save-excursion
13499 (goto-char 0)
13500 (let ((re (org-make-options-regexp
13501 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
13502 p key val text options)
13503 (while (re-search-forward re nil t)
13504 (setq key (org-match-string-no-properties 1)
13505 val (org-match-string-no-properties 2))
13506 (cond
13507 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
13508 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
13509 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
13510 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
13511 ((string-equal key "TEXT")
13512 (setq text (if text (concat text "\n" val) val)))
13513 ((string-equal key "OPTIONS") (setq options val))))
13514 (setq p (plist-put p :text text))
13515 (when options
13516 (let ((op '(("H" . :headline-levels)
13517 ("num" . :section-numbers)
13518 ("toc" . :table-of-contents)
13519 ("\\n" . :preserve-breaks)
13520 ("@" . :expand-quoted-html)
13521 (":" . :fixed-width)
13522 ("|" . :tables)
13523 ("^" . :sub-superscript)
13524 ("*" . :emphasize)
13525 ("TeX" . :TeX-macros)
13526 ("LaTeX" . :LaTeX-fragments)))
13528 (while (setq o (pop op))
13529 (if (string-match (concat (regexp-quote (car o))
13530 ":\\([^ \t\n\r;,.]*\\)")
13531 options)
13532 (setq p (plist-put p (cdr o)
13533 (car (read-from-string
13534 (match-string 1 options)))))))))
13535 p)))
13537 (defun org-combine-plists (&rest plists)
13538 "Create a single property list from all plists in PLISTS.
13539 The process starts by copying the last list, and then setting properties
13540 from the other lists. Settings in the first list are the most significant
13541 ones and overrule settings in the other lists."
13542 (let ((rtn (copy-sequence (pop plists)))
13543 p v ls)
13544 (while plists
13545 (setq ls (pop plists))
13546 (while ls
13547 (setq p (pop ls) v (pop ls))
13548 (setq rtn (plist-put rtn p v))))
13549 rtn))
13551 (defun org-export-directory (type plist)
13552 (let* ((val (plist-get plist :publishing-directory))
13553 (dir (if (listp val)
13554 (or (cdr (assoc type val)) ".")
13555 val)))
13556 dir))
13558 (defun org-export-find-first-heading-line (list)
13559 "Remove all lines from LIST which are before the first headline."
13560 (let ((orig-list list)
13561 (re (concat "^" outline-regexp)))
13562 (while (and list
13563 (not (string-match re (car list))))
13564 (pop list))
13565 (or list orig-list)))
13567 (defun org-skip-comments (lines)
13568 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
13569 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
13570 (re2 "^\\(\\*+\\)[ \t\n\r]")
13571 rtn line level)
13572 (while (setq line (pop lines))
13573 (cond
13574 ((and (string-match re1 line)
13575 (setq level (- (match-end 1) (match-beginning 1))))
13576 ;; Beginning of a COMMENT subtree. Skip it.
13577 (while (and (setq line (pop lines))
13578 (or (not (string-match re2 line))
13579 (> (- (match-end 1) (match-beginning 1)) level))))
13580 (setq lines (cons line lines)))
13581 ((string-match "^#" line)
13582 ;; an ordinary comment line
13584 ((and org-export-table-remove-special-lines
13585 (string-match "^[ \t]*|" line)
13586 (or (string-match "^[ \t]*| *[!_^] *|" line)
13587 (and (string-match "| *<[0-9]+> *|" line)
13588 (not (string-match "| *[^ <|]" line)))))
13589 ;; a special table line that should be removed
13591 (t (setq rtn (cons line rtn)))))
13592 (nreverse rtn)))
13594 (defun org-export (&optional arg)
13595 (interactive)
13596 (let ((help "[t] insert the export option template
13597 \[v] limit export to visible part of outline tree
13599 \[a] export as ASCII
13600 \[h] export as HTML
13601 \[b] export as HTML and browse immediately
13602 \[x] export as XOXO
13604 \[i] export current file as iCalendar file
13605 \[I] export all agenda files as iCalendar files
13606 \[c] export agenda files into combined iCalendar file
13608 \[F] publish current file
13609 \[P] publish current project
13610 \[X] publish... (project will be prompted for)
13611 \[A] publish all projects")
13612 (cmds
13613 '((?t . org-insert-export-options-template)
13614 (?v . org-export-visible)
13615 (?a . org-export-as-ascii)
13616 (?h . org-export-as-html)
13617 (?b . org-export-as-html-and-open)
13618 (?x . org-export-as-xoxo)
13619 (?i . org-export-icalendar-this-file)
13620 (?I . org-export-icalendar-all-agenda-files)
13621 (?c . org-export-icalendar-combine-agenda-files)
13622 (?F . org-publish-current-file)
13623 (?P . org-publish-current-project)
13624 (?X . org-publish)
13625 (?A . org-publish-all)))
13626 r1 r2 ass)
13627 (save-window-excursion
13628 (delete-other-windows)
13629 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
13630 (princ help))
13631 (message "Select command: ")
13632 (setq r1 (read-char-exclusive)))
13633 (setq r2 (if (< r1 27) (+ r1 96) r1))
13634 (if (setq ass (assq r2 cmds))
13635 (call-interactively (cdr ass))
13636 (error "No command associated with key %c" r1))))
13638 ;; ASCII
13640 (defconst org-html-entities
13641 '(("nbsp")
13642 ("iexcl")
13643 ("cent")
13644 ("pound")
13645 ("curren")
13646 ("yen")
13647 ("brvbar")
13648 ("sect")
13649 ("uml")
13650 ("copy")
13651 ("ordf")
13652 ("laquo")
13653 ("not")
13654 ("shy")
13655 ("reg")
13656 ("macr")
13657 ("deg")
13658 ("plusmn")
13659 ("sup2")
13660 ("sup3")
13661 ("acute")
13662 ("micro")
13663 ("para")
13664 ("middot")
13665 ("odot"."o")
13666 ("star"."*")
13667 ("cedil")
13668 ("sup1")
13669 ("ordm")
13670 ("raquo")
13671 ("frac14")
13672 ("frac12")
13673 ("frac34")
13674 ("iquest")
13675 ("Agrave")
13676 ("Aacute")
13677 ("Acirc")
13678 ("Atilde")
13679 ("Auml")
13680 ("Aring") ("AA"."&Aring;")
13681 ("AElig")
13682 ("Ccedil")
13683 ("Egrave")
13684 ("Eacute")
13685 ("Ecirc")
13686 ("Euml")
13687 ("Igrave")
13688 ("Iacute")
13689 ("Icirc")
13690 ("Iuml")
13691 ("ETH")
13692 ("Ntilde")
13693 ("Ograve")
13694 ("Oacute")
13695 ("Ocirc")
13696 ("Otilde")
13697 ("Ouml")
13698 ("times")
13699 ("Oslash")
13700 ("Ugrave")
13701 ("Uacute")
13702 ("Ucirc")
13703 ("Uuml")
13704 ("Yacute")
13705 ("THORN")
13706 ("szlig")
13707 ("agrave")
13708 ("aacute")
13709 ("acirc")
13710 ("atilde")
13711 ("auml")
13712 ("aring")
13713 ("aelig")
13714 ("ccedil")
13715 ("egrave")
13716 ("eacute")
13717 ("ecirc")
13718 ("euml")
13719 ("igrave")
13720 ("iacute")
13721 ("icirc")
13722 ("iuml")
13723 ("eth")
13724 ("ntilde")
13725 ("ograve")
13726 ("oacute")
13727 ("ocirc")
13728 ("otilde")
13729 ("ouml")
13730 ("divide")
13731 ("oslash")
13732 ("ugrave")
13733 ("uacute")
13734 ("ucirc")
13735 ("uuml")
13736 ("yacute")
13737 ("thorn")
13738 ("yuml")
13739 ("fnof")
13740 ("Alpha")
13741 ("Beta")
13742 ("Gamma")
13743 ("Delta")
13744 ("Epsilon")
13745 ("Zeta")
13746 ("Eta")
13747 ("Theta")
13748 ("Iota")
13749 ("Kappa")
13750 ("Lambda")
13751 ("Mu")
13752 ("Nu")
13753 ("Xi")
13754 ("Omicron")
13755 ("Pi")
13756 ("Rho")
13757 ("Sigma")
13758 ("Tau")
13759 ("Upsilon")
13760 ("Phi")
13761 ("Chi")
13762 ("Psi")
13763 ("Omega")
13764 ("alpha")
13765 ("beta")
13766 ("gamma")
13767 ("delta")
13768 ("epsilon")
13769 ("varepsilon"."&epsilon;")
13770 ("zeta")
13771 ("eta")
13772 ("theta")
13773 ("iota")
13774 ("kappa")
13775 ("lambda")
13776 ("mu")
13777 ("nu")
13778 ("xi")
13779 ("omicron")
13780 ("pi")
13781 ("rho")
13782 ("sigmaf") ("varsigma"."&sigmaf;")
13783 ("sigma")
13784 ("tau")
13785 ("upsilon")
13786 ("phi")
13787 ("chi")
13788 ("psi")
13789 ("omega")
13790 ("thetasym") ("vartheta"."&thetasym;")
13791 ("upsih")
13792 ("piv")
13793 ("bull") ("bullet"."&bull;")
13794 ("hellip") ("dots"."&hellip;")
13795 ("prime")
13796 ("Prime")
13797 ("oline")
13798 ("frasl")
13799 ("weierp")
13800 ("image")
13801 ("real")
13802 ("trade")
13803 ("alefsym")
13804 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
13805 ("uarr") ("uparrow"."&uarr;")
13806 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
13807 ("darr")("downarrow"."&darr;")
13808 ("harr") ("leftrightarrow"."&harr;")
13809 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
13810 ("lArr") ("Leftarrow"."&lArr;")
13811 ("uArr") ("Uparrow"."&uArr;")
13812 ("rArr") ("Rightarrow"."&rArr;")
13813 ("dArr") ("Downarrow"."&dArr;")
13814 ("hArr") ("Leftrightarrow"."&hArr;")
13815 ("forall")
13816 ("part") ("partial"."&part;")
13817 ("exist") ("exists"."&exist;")
13818 ("empty") ("emptyset"."&empty;")
13819 ("nabla")
13820 ("isin") ("in"."&isin;")
13821 ("notin")
13822 ("ni")
13823 ("prod")
13824 ("sum")
13825 ("minus")
13826 ("lowast") ("ast"."&lowast;")
13827 ("radic")
13828 ("prop") ("proptp"."&prop;")
13829 ("infin") ("infty"."&infin;")
13830 ("ang") ("angle"."&ang;")
13831 ("and") ("vee"."&and;")
13832 ("or") ("wedge"."&or;")
13833 ("cap")
13834 ("cup")
13835 ("int")
13836 ("there4")
13837 ("sim")
13838 ("cong") ("simeq"."&cong;")
13839 ("asymp")("approx"."&asymp;")
13840 ("ne") ("neq"."&ne;")
13841 ("equiv")
13842 ("le")
13843 ("ge")
13844 ("sub") ("subset"."&sub;")
13845 ("sup") ("supset"."&sup;")
13846 ("nsub")
13847 ("sube")
13848 ("supe")
13849 ("oplus")
13850 ("otimes")
13851 ("perp")
13852 ("sdot") ("cdot"."&sdot;")
13853 ("lceil")
13854 ("rceil")
13855 ("lfloor")
13856 ("rfloor")
13857 ("lang")
13858 ("rang")
13859 ("loz") ("Diamond"."&loz;")
13860 ("spades") ("spadesuit"."&spades;")
13861 ("clubs") ("clubsuit"."&clubs;")
13862 ("hearts") ("diamondsuit"."&hearts;")
13863 ("diams") ("diamondsuit"."&diams;")
13864 ("quot")
13865 ("amp")
13866 ("lt")
13867 ("gt")
13868 ("OElig")
13869 ("oelig")
13870 ("Scaron")
13871 ("scaron")
13872 ("Yuml")
13873 ("circ")
13874 ("tilde")
13875 ("ensp")
13876 ("emsp")
13877 ("thinsp")
13878 ("zwnj")
13879 ("zwj")
13880 ("lrm")
13881 ("rlm")
13882 ("ndash")
13883 ("mdash")
13884 ("lsquo")
13885 ("rsquo")
13886 ("sbquo")
13887 ("ldquo")
13888 ("rdquo")
13889 ("bdquo")
13890 ("dagger")
13891 ("Dagger")
13892 ("permil")
13893 ("lsaquo")
13894 ("rsaquo")
13895 ("euro")
13897 ("arccos"."arccos")
13898 ("arcsin"."arcsin")
13899 ("arctan"."arctan")
13900 ("arg"."arg")
13901 ("cos"."cos")
13902 ("cosh"."cosh")
13903 ("cot"."cot")
13904 ("coth"."coth")
13905 ("csc"."csc")
13906 ("deg"."deg")
13907 ("det"."det")
13908 ("dim"."dim")
13909 ("exp"."exp")
13910 ("gcd"."gcd")
13911 ("hom"."hom")
13912 ("inf"."inf")
13913 ("ker"."ker")
13914 ("lg"."lg")
13915 ("lim"."lim")
13916 ("liminf"."liminf")
13917 ("limsup"."limsup")
13918 ("ln"."ln")
13919 ("log"."log")
13920 ("max"."max")
13921 ("min"."min")
13922 ("Pr"."Pr")
13923 ("sec"."sec")
13924 ("sin"."sin")
13925 ("sinh"."sinh")
13926 ("sup"."sup")
13927 ("tan"."tan")
13928 ("tanh"."tanh")
13930 "Entities for TeX->HTML translation.
13931 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
13932 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
13933 In that case, \"\\ent\" will be translated to \"&other;\".
13934 The list contains HTML entities for Latin-1, Greek and other symbols.
13935 It is supplemented by a number of commonly used TeX macros with appropriate
13936 translations. There is currently no way for users to extend this.")
13938 (defun org-cleaned-string-for-export (string &rest parameters)
13939 "Cleanup a buffer substring so that links can be created safely."
13940 (interactive)
13941 (let* ((re-radio (and org-target-link-regexp
13942 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
13943 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
13944 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
13945 (re-archive (concat ":" org-archive-tag ":"))
13946 rtn)
13947 (save-excursion
13948 (set-buffer (get-buffer-create " org-mode-tmp"))
13949 (erase-buffer)
13950 (insert string)
13951 (let ((org-inhibit-startup t)) (org-mode))
13953 ;; Get rid of archived trees
13954 (when (not (eq org-export-with-archived-trees t))
13955 (goto-char (point-min))
13956 (while (re-search-forward re-archive nil t)
13957 (if (not (org-on-heading-p))
13958 (org-end-of-subtree t)
13959 (beginning-of-line 1)
13960 (delete-region
13961 (if org-export-with-archived-trees (1+ (point-at-eol)) (point))
13962 (org-end-of-subtree t)))))
13964 ;; Find targets in comments and move them out of comments,
13965 ;; but mark them as targets that should be invisible
13966 (goto-char (point-min))
13967 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
13968 (replace-match "\\1(INVISIBLE)"))
13970 ;; Find matches for radio targets and turn them into internal links
13971 (goto-char (point-min))
13972 (when re-radio
13973 (while (re-search-forward re-radio nil t)
13974 (replace-match "\\1[[\\2]]")))
13976 ;; Find all links that contain a newline and put them into a single line
13977 (goto-char (point-min))
13978 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
13979 (replace-match "\\1 \\3")
13980 (goto-char (match-beginning 0)))
13982 ;; Convert LaTeX fragments to images
13983 (when (memq :LaTeX-fragments parameters)
13984 (org-format-latex
13985 (concat "ltxpng/" (file-name-sans-extension
13986 (file-name-nondirectory
13987 org-current-export-file)))
13988 org-current-export-dir nil "Creating LaTeX image %s"))
13989 (message "Exporting...")
13991 ;; Normalize links: Convert angle and plain links into bracket links
13992 ;; Expand link abbreviations
13993 (goto-char (point-min))
13994 (while (re-search-forward re-plain-link nil t)
13995 (replace-match
13996 (concat
13997 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
13998 t t))
13999 (goto-char (point-min))
14000 (while (re-search-forward re-angle-link nil t)
14001 (replace-match
14002 (concat
14003 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
14004 t t))
14005 (goto-char (point-min))
14006 (while (re-search-forward "\\[\\[\\([^]]+\\)\\]" nil t)
14007 (replace-match (concat "[[" (save-match-data
14008 (org-link-expand-abbrev (match-string 1)))
14009 "]")))
14011 ;; Find multiline emphasis and put them into single line
14012 (when (memq :emph-multiline parameters)
14013 (goto-char (point-min))
14014 (while (re-search-forward org-emph-re nil t)
14015 (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\ t)
14016 (goto-char (1- (match-end 0)))))
14018 ;; Remove comments
14019 (goto-char (point-min))
14020 (while (re-search-forward "^#.*\n?" nil t)
14021 (replace-match ""))
14022 (setq rtn (buffer-string)))
14023 (kill-buffer " org-mode-tmp")
14024 rtn))
14026 (defun org-solidify-link-text (s &optional alist)
14027 "Take link text and make a safe target out of it."
14028 (save-match-data
14029 (let* ((rtn
14030 (mapconcat
14031 'identity
14032 (org-split-string s "[ \t\r\n]+") "--"))
14033 (a (assoc rtn alist)))
14034 (or (cdr a) rtn))))
14036 (defun org-convert-to-odd-levels ()
14037 "Convert an org-mode file with all levels allowed to one with odd levels.
14038 This will leave level 1 alone, convert level 2 to level 3, level 3 to
14039 level 5 etc."
14040 (interactive)
14041 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
14042 (let ((org-odd-levels-only nil) n)
14043 (save-excursion
14044 (goto-char (point-min))
14045 (while (re-search-forward "^\\*\\*+" nil t)
14046 (setq n (1- (length (match-string 0))))
14047 (while (>= (setq n (1- n)) 0)
14048 (org-demote))
14049 (end-of-line 1))))))
14052 (defun org-convert-to-oddeven-levels ()
14053 "Convert an org-mode file with only odd levels to one with odd and even levels.
14054 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
14055 section with an even level, conversion would destroy the structure of the file. An error
14056 is signaled in this case."
14057 (interactive)
14058 (goto-char (point-min))
14059 ;; First check if there are no even levels
14060 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
14061 (org-show-hierarchy-above t)
14062 (error "Not all levels are odd in this file. Conversion not possible."))
14063 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
14064 (let ((org-odd-levels-only nil) n)
14065 (save-excursion
14066 (goto-char (point-min))
14067 (while (re-search-forward "^\\*\\*+" nil t)
14068 (setq n (/ (length (match-string 0)) 2))
14069 (while (>= (setq n (1- n)) 0)
14070 (org-promote))
14071 (end-of-line 1))))))
14073 (defun org-tr-level (n)
14074 "Make N odd if required."
14075 (if org-odd-levels-only (1+ (/ n 2)) n))
14077 (defvar org-last-level nil) ; dynamically scoped variable
14078 (defvar org-ascii-current-indentation nil) ; For communication
14080 (defun org-export-as-ascii (arg)
14081 "Export the outline as a pretty ASCII file.
14082 If there is an active region, export only the region.
14083 The prefix ARG specifies how many levels of the outline should become
14084 underlined headlines. The default is 3."
14085 (interactive "P")
14086 (setq-default org-todo-line-regexp org-todo-line-regexp)
14087 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
14088 (org-infile-export-plist)))
14089 (region
14090 (buffer-substring
14091 (if (org-region-active-p) (region-beginning) (point-min))
14092 (if (org-region-active-p) (region-end) (point-max))))
14093 (lines (org-export-find-first-heading-line
14094 (org-skip-comments
14095 (org-split-string
14096 (org-cleaned-string-for-export region)
14097 "[\r\n]"))))
14098 (org-ascii-current-indentation '(0 . 0))
14099 (org-startup-with-deadline-check nil)
14100 (level 0) line txt
14101 (umax nil)
14102 (case-fold-search nil)
14103 (filename (concat (file-name-as-directory
14104 (org-export-directory :ascii opt-plist))
14105 (file-name-sans-extension
14106 (file-name-nondirectory buffer-file-name))
14107 ".txt"))
14108 (buffer (find-file-noselect filename))
14109 (levels-open (make-vector org-level-max nil))
14110 (odd org-odd-levels-only)
14111 (date (format-time-string "%Y/%m/%d" (current-time)))
14112 (time (format-time-string "%X" (org-current-time)))
14113 (author (plist-get opt-plist :author))
14114 (title (or (plist-get opt-plist :title)
14115 (file-name-sans-extension
14116 (file-name-nondirectory buffer-file-name))))
14117 (email (plist-get opt-plist :email))
14118 (language (plist-get opt-plist :language))
14119 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
14120 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
14121 (text nil)
14122 (todo nil)
14123 (lang-words nil))
14125 (setq org-last-level 1)
14126 (org-init-section-numbers)
14128 (find-file-noselect filename)
14130 (setq lang-words (or (assoc language org-export-language-setup)
14131 (assoc "en" org-export-language-setup)))
14132 (if org-export-ascii-show-new-buffer
14133 (switch-to-buffer-other-window buffer)
14134 (set-buffer buffer))
14135 (erase-buffer)
14136 (fundamental-mode)
14137 ;; create local variables for all options, to make sure all called
14138 ;; functions get the correct information
14139 (mapcar (lambda (x)
14140 (set (make-local-variable (cdr x))
14141 (plist-get opt-plist (car x))))
14142 org-export-plist-vars)
14143 (org-set-local 'org-odd-levels-only odd)
14144 (setq umax (if arg (prefix-numeric-value arg)
14145 org-export-headline-levels))
14147 ;; File header
14148 (if title (org-insert-centered title ?=))
14149 (insert "\n")
14150 (if (or author email)
14151 (insert (concat (nth 1 lang-words) ": " (or author "")
14152 (if email (concat " <" email ">") "")
14153 "\n")))
14154 (if (and date time)
14155 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
14156 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
14158 (insert "\n\n")
14160 (if org-export-with-toc
14161 (progn
14162 (insert (nth 3 lang-words) "\n"
14163 (make-string (length (nth 3 lang-words)) ?=) "\n")
14164 (mapcar '(lambda (line)
14165 (if (string-match org-todo-line-regexp
14166 line)
14167 ;; This is a headline
14168 (progn
14169 (setq level (- (match-end 1) (match-beginning 1))
14170 level (org-tr-level level)
14171 txt (match-string 3 line)
14172 todo
14173 (or (and org-export-mark-todo-in-toc
14174 (match-beginning 2)
14175 (not (equal (match-string 2 line)
14176 org-done-string)))
14177 ; TODO, not DONE
14178 (and org-export-mark-todo-in-toc
14179 (= level umax)
14180 (org-search-todo-below
14181 line lines level))))
14182 (setq txt (org-html-expand-for-ascii txt))
14184 (if (and (memq org-export-with-tags '(not-in-toc nil))
14185 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
14186 (setq txt (replace-match "" t t txt)))
14187 (if (string-match quote-re0 txt)
14188 (setq txt (replace-match "" t t txt)))
14190 (if org-export-with-section-numbers
14191 (setq txt (concat (org-section-number level)
14192 " " txt)))
14193 (if (<= level umax)
14194 (progn
14195 (insert
14196 (make-string (* (1- level) 4) ?\ )
14197 (format (if todo "%s (*)\n" "%s\n") txt))
14198 (setq org-last-level level))
14199 ))))
14200 lines)))
14202 (org-init-section-numbers)
14203 (while (setq line (pop lines))
14204 ;; Remove the quoted HTML tags.
14205 (setq line (org-html-expand-for-ascii line))
14206 ;; Remove targets
14207 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
14208 (setq line (replace-match "" t t line)))
14209 ;; Replace internal links
14210 (while (string-match org-bracket-link-regexp line)
14211 (setq line (replace-match
14212 (if (match-end 3) "[\\3]" "[\\1]")
14213 t nil line)))
14214 (cond
14215 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
14216 ;; a Headline
14217 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
14218 txt (match-string 2 line))
14219 (org-ascii-level-start level txt umax lines))
14221 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
14222 (normal-mode)
14223 (save-buffer)
14224 ;; remove display and invisible chars
14225 (let (beg end)
14226 (goto-char (point-min))
14227 (while (setq beg (next-single-property-change (point) 'display))
14228 (setq end (next-single-property-change beg 'display))
14229 (delete-region beg end)
14230 (goto-char beg)
14231 (insert "=>"))
14232 (goto-char (point-min))
14233 (while (setq beg (next-single-property-change (point) 'org-cwidth))
14234 (setq end (next-single-property-change beg 'org-cwidth))
14235 (delete-region beg end)
14236 (goto-char beg)))
14237 (goto-char (point-min))))
14239 (defun org-search-todo-below (line lines level)
14240 "Search the subtree below LINE for any TODO entries."
14241 (let ((rest (cdr (memq line lines)))
14242 (re org-todo-line-regexp)
14243 line lv todo)
14244 (catch 'exit
14245 (while (setq line (pop rest))
14246 (if (string-match re line)
14247 (progn
14248 (setq lv (- (match-end 1) (match-beginning 1))
14249 todo (and (match-beginning 2)
14250 (not (equal (match-string 2 line)
14251 org-done-string))))
14252 ; TODO, not DONE
14253 (if (<= lv level) (throw 'exit nil))
14254 (if todo (throw 'exit t))))))))
14256 (defun org-html-expand-for-ascii (line)
14257 "Handle quoted HTML for ASCII export."
14258 (if org-export-html-expand
14259 (while (string-match "@<[^<>\n]*>" line)
14260 ;; We just remove the tags for now.
14261 (setq line (replace-match "" nil nil line))))
14262 line)
14264 (defun org-insert-centered (s &optional underline)
14265 "Insert the string S centered and underline it with character UNDERLINE."
14266 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
14267 (insert (make-string ind ?\ ) s "\n")
14268 (if underline
14269 (insert (make-string ind ?\ )
14270 (make-string (string-width s) underline)
14271 "\n"))))
14273 (defun org-ascii-level-start (level title umax &optional lines)
14274 "Insert a new level in ASCII export."
14275 (let (char (n (- level umax 1)) (ind 0))
14276 (if (> level umax)
14277 (progn
14278 (insert (make-string (* 2 n) ?\ )
14279 (char-to-string (nth (% n (length org-export-ascii-bullets))
14280 org-export-ascii-bullets))
14281 " " title "\n")
14282 ;; find the indentation of the next non-empty line
14283 (catch 'stop
14284 (while lines
14285 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
14286 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
14287 (throw 'stop (setq ind (org-get-indentation (car lines)))))
14288 (pop lines)))
14289 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
14290 (if (or (not (equal (char-before) ?\n))
14291 (not (equal (char-before (1- (point))) ?\n)))
14292 (insert "\n"))
14293 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
14294 (unless org-export-with-tags
14295 (if (string-match "[ \t]+\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
14296 (setq title (replace-match "" t t title))))
14297 (if org-export-with-section-numbers
14298 (setq title (concat (org-section-number level) " " title)))
14299 (insert title "\n" (make-string (string-width title) char) "\n")
14300 (setq org-ascii-current-indentation '(0 . 0)))))
14302 (defun org-export-visible (type arg)
14303 "Create a copy of the visible part of the current buffer, and export it.
14304 The copy is created in a temporary buffer and removed after use.
14305 TYPE is the final key (as a string) that also select the export command in
14306 the `C-c C-e' export dispatcher.
14307 As a special case, if the you type SPC at the prompt, the temporary
14308 org-mode file will not be removed but presented to you so that you can
14309 continue to use it. The prefix arg ARG is passed through to the exporting
14310 command."
14311 (interactive
14312 (list (progn
14313 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
14314 (read-char-exclusive))
14315 current-prefix-arg))
14316 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
14317 (error "Invalid export key"))
14318 (let* ((binding (cdr (assoc type
14319 '((?a . org-export-as-ascii)
14320 (?\C-a . org-export-as-ascii)
14321 (?b . org-export-as-html-and-open)
14322 (?\C-b . org-export-as-html-and-open)
14323 (?h . org-export-as-html)
14324 (?x . org-export-as-xoxo)))))
14325 (keepp (equal type ?\ ))
14326 (file buffer-file-name)
14327 (buffer (get-buffer-create "*Org Export Visible*"))
14328 s e)
14329 (with-current-buffer buffer (erase-buffer))
14330 (save-excursion
14331 (setq s (goto-char (point-min)))
14332 (while (not (= (point) (point-max)))
14333 (goto-char (org-find-invisible))
14334 (append-to-buffer buffer s (point))
14335 (setq s (goto-char (org-find-visible))))
14336 (goto-char (point-min))
14337 (unless keepp
14338 ;; Copy all comment lines to the end, to make sure #+ settings are
14339 ;; still available for the second export step. Kind of a hack, but
14340 ;; does do the trick.
14341 (if (looking-at "#[^\r\n]*")
14342 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
14343 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
14344 (append-to-buffer buffer (1+ (match-beginning 0))
14345 (min (point-max) (1+ (match-end 0))))))
14346 (set-buffer buffer)
14347 (let ((buffer-file-name file)
14348 (org-inhibit-startup t))
14349 (org-mode)
14350 (show-all)
14351 (unless keepp (funcall binding arg))))
14352 (if (not keepp)
14353 (kill-buffer buffer)
14354 (switch-to-buffer-other-window buffer)
14355 (goto-char (point-min)))))
14357 (defun org-find-visible ()
14358 (let ((s (point)))
14359 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
14360 (get-char-property s 'invisible)))
14362 (defun org-find-invisible ()
14363 (let ((s (point)))
14364 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
14365 (not (get-char-property s 'invisible))))
14368 ;; HTML
14370 (defun org-get-current-options ()
14371 "Return a string with current options as keyword options.
14372 Does include HTML export options as well as TODO and CATEGORY stuff."
14373 (format
14374 "#+TITLE: %s
14375 #+AUTHOR: %s
14376 #+EMAIL: %s
14377 #+LANGUAGE: %s
14378 #+TEXT: Some descriptive text to be emitted. Several lines OK.
14379 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s
14380 #+CATEGORY: %s
14381 #+SEQ_TODO: %s
14382 #+TYP_TODO: %s
14383 #+STARTUP: %s %s %s %s %s %s
14384 #+TAGS: %s
14385 #+ARCHIVE: %s
14387 (buffer-name) (user-full-name) user-mail-address org-export-default-language
14388 org-export-headline-levels
14389 org-export-with-section-numbers
14390 org-export-with-toc
14391 org-export-preserve-breaks
14392 org-export-html-expand
14393 org-export-with-fixed-width
14394 org-export-with-tables
14395 org-export-with-sub-superscripts
14396 org-export-with-emphasize
14397 org-export-with-TeX-macros
14398 org-export-with-LaTeX-fragments
14399 (file-name-nondirectory buffer-file-name)
14400 (if (equal org-todo-interpretation 'sequence)
14401 (mapconcat 'identity org-todo-keywords " ")
14402 "TODO FEEDBACK VERIFY DONE")
14403 (if (equal org-todo-interpretation 'type)
14404 (mapconcat 'identity org-todo-keywords " ")
14405 "Me Jason Marie DONE")
14406 (cdr (assoc org-startup-folded
14407 '((nil . "showall") (t . "overview") (content . "content"))))
14408 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
14409 (if org-odd-levels-only "odd" "oddeven")
14410 (if org-hide-leading-stars "hidestars" "showstars")
14411 (if org-startup-align-all-tables "align" "noalign")
14412 (if org-log-done "logging" "nologging")
14413 (or (mapconcat (lambda (x)
14414 (cond
14415 ((equal '(:startgroup) x) "{")
14416 ((equal '(:endgroup) x) "}")
14417 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
14418 (t (car x))))
14419 (or org-tag-alist (org-get-buffer-tags)) " ") "")
14420 org-archive-location
14423 (defun org-insert-export-options-template ()
14424 "Insert into the buffer a template with information for exporting."
14425 (interactive)
14426 (if (not (bolp)) (newline))
14427 (let ((s (org-get-current-options)))
14428 (and (string-match "#\\+CATEGORY" s)
14429 (setq s (substring s 0 (match-beginning 0))))
14430 (insert s)))
14432 (defun org-toggle-fixed-width-section (arg)
14433 "Toggle the fixed-width export.
14434 If there is no active region, the QUOTE keyword at the current headline is
14435 inserted or removed. When present, it causes the text between this headline
14436 and the next to be exported as fixed-width text, and unmodified.
14437 If there is an active region, this command adds or removes a colon as the
14438 first character of this line. If the first character of a line is a colon,
14439 this line is also exported in fixed-width font."
14440 (interactive "P")
14441 (let* ((cc 0)
14442 (regionp (org-region-active-p))
14443 (beg (if regionp (region-beginning) (point)))
14444 (end (if regionp (region-end)))
14445 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14446 (re "[ \t]*\\(:\\)")
14447 off)
14448 (if regionp
14449 (save-excursion
14450 (goto-char beg)
14451 (setq cc (current-column))
14452 (beginning-of-line 1)
14453 (setq off (looking-at re))
14454 (while (> nlines 0)
14455 (setq nlines (1- nlines))
14456 (beginning-of-line 1)
14457 (cond
14458 (arg
14459 (move-to-column cc t)
14460 (insert ":\n")
14461 (forward-line -1))
14462 ((and off (looking-at re))
14463 (replace-match "" t t nil 1))
14464 ((not off) (move-to-column cc t) (insert ":")))
14465 (forward-line 1)))
14466 (save-excursion
14467 (org-back-to-heading)
14468 (if (looking-at (concat outline-regexp
14469 "\\( +\\<" org-quote-string "\\>\\)"))
14470 (replace-match "" t t nil 1)
14471 (if (looking-at outline-regexp)
14472 (progn
14473 (goto-char (match-end 0))
14474 (insert " " org-quote-string))))))))
14476 (defun org-export-as-html-and-open (arg)
14477 "Export the outline as HTML and immediately open it with a browser.
14478 If there is an active region, export only the region.
14479 The prefix ARG specifies how many levels of the outline should become
14480 headlines. The default is 3. Lower levels will become bulleted lists."
14481 (interactive "P")
14482 (org-export-as-html arg 'hidden)
14483 (org-open-file buffer-file-name))
14485 (defun org-export-as-html-batch ()
14486 "Call `org-export-as-html', may be used in batch processing as
14487 emacs --batch
14488 --load=$HOME/lib/emacs/org.el
14489 --eval \"(setq org-export-headline-levels 2)\"
14490 --visit=MyFile --funcall org-export-as-html-batch"
14491 (org-export-as-html org-export-headline-levels 'hidden))
14493 (defun org-export-as-html (arg &optional hidden ext-plist)
14494 "Export the outline as a pretty HTML file.
14495 If there is an active region, export only the region.
14496 The prefix ARG specifies how many levels of the outline should become
14497 headlines. The default is 3. Lower levels will become bulleted lists.
14498 When HIDDEN is non-nil, don't display the HTML buffer.
14499 EXT-PLIST is a property list with external parameters overriding
14500 org-mode's default settings, but still inferior to file-local settings."
14501 (interactive "P")
14502 (message "Exporting...")
14503 (setq-default org-todo-line-regexp org-todo-line-regexp)
14504 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
14505 (setq-default org-done-string org-done-string)
14506 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
14507 ext-plist
14508 (org-infile-export-plist)))
14510 (style (plist-get opt-plist :style))
14511 (link-validate (plist-get opt-plist :link-validation-function))
14512 valid
14513 (odd org-odd-levels-only)
14514 (region-p (org-region-active-p))
14515 (region
14516 (buffer-substring
14517 (if region-p (region-beginning) (point-min))
14518 (if region-p (region-end) (point-max))))
14519 ;; The following two are dynamically scoped into other
14520 ;; routines below.
14521 (org-current-export-dir (org-export-directory :html opt-plist))
14522 (org-current-export-file buffer-file-name)
14523 (all_lines
14524 (org-skip-comments (org-split-string
14525 (org-cleaned-string-for-export
14526 region :emph-multiline
14527 (if (plist-get opt-plist :LaTeX-fragments)
14528 :LaTeX-fragments))
14529 "[\r\n]")))
14530 (lines (org-export-find-first-heading-line all_lines))
14531 (level 0) (line "") (origline "") txt todo
14532 (umax nil)
14533 (filename (concat (file-name-as-directory
14534 (org-export-directory :html opt-plist))
14535 (file-name-sans-extension
14536 (file-name-nondirectory buffer-file-name))
14537 ".html"))
14538 (current-dir (file-name-directory buffer-file-name))
14539 (buffer (find-file-noselect filename))
14540 (levels-open (make-vector org-level-max nil))
14541 (date (format-time-string "%Y/%m/%d" (current-time)))
14542 (time (format-time-string "%X" (org-current-time)))
14543 (author (plist-get opt-plist :author))
14544 (title (or (plist-get opt-plist :title)
14545 (file-name-sans-extension
14546 (file-name-nondirectory buffer-file-name))))
14547 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
14548 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
14549 (inquote nil)
14550 (infixed nil)
14551 (in-local-list nil)
14552 (local-list-num nil)
14553 (local-list-indent nil)
14554 (llt org-plain-list-ordered-item-terminator)
14555 (email (plist-get opt-plist :email))
14556 (language (plist-get opt-plist :language))
14557 (text (plist-get opt-plist :text))
14558 (lang-words nil)
14559 (target-alist nil) tg
14560 (head-count 0) cnt
14561 (start 0)
14562 (coding-system (and (boundp 'buffer-file-coding-system)
14563 buffer-file-coding-system))
14564 (coding-system-for-write coding-system)
14565 (save-buffer-coding-system coding-system)
14566 (charset (and coding-system
14567 (fboundp 'coding-system-get)
14568 (coding-system-get coding-system 'mime-charset)))
14569 table-open type
14570 table-buffer table-orig-buffer
14571 ind start-is-num starter
14572 rpl path desc descp desc1 desc2 link
14574 (message "Exporting...")
14576 (setq org-last-level 1)
14577 (org-init-section-numbers)
14579 ;; Get the language-dependent settings
14580 (setq lang-words (or (assoc language org-export-language-setup)
14581 (assoc "en" org-export-language-setup)))
14583 ;; Switch to the output buffer
14584 (if (or hidden (not org-export-html-show-new-buffer))
14585 (set-buffer buffer)
14586 (switch-to-buffer-other-window buffer))
14587 (erase-buffer)
14588 (fundamental-mode)
14589 (let ((case-fold-search nil)
14590 (org-odd-levels-only odd))
14591 ;; create local variables for all options, to make sure all called
14592 ;; functions get the correct information
14593 (mapcar (lambda (x)
14594 (set (make-local-variable (cdr x))
14595 (plist-get opt-plist (car x))))
14596 org-export-plist-vars)
14597 (setq umax (if arg (prefix-numeric-value arg)
14598 org-export-headline-levels))
14600 ;; File header
14601 (insert (format
14602 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
14603 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
14604 <html xmlns=\"http://www.w3.org/1999/xhtml\"
14605 lang=\"%s\" xml:lang=\"%s\">
14606 <head>
14607 <title>%s</title>
14608 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
14609 <meta name=\"generator\" content=\"Org-mode\"/>
14610 <meta name=\"generated\" content=\"%s %s\"/>
14611 <meta name=\"author\" content=\"%s\"/>
14613 </head><body>
14615 language language (org-html-expand title) (or charset "iso-8859-1")
14616 date time author style))
14619 (insert (or (plist-get opt-plist :preamble) ""))
14621 (when (plist-get opt-plist :auto-preamble)
14622 (if title (insert (format org-export-html-title-format
14623 (org-html-expand title))))
14624 (if text (insert "<p>\n" (org-html-expand text) "</p>")))
14626 (if org-export-with-toc
14627 (progn
14628 (insert (format "<h%d>%s</h%d>\n"
14629 org-export-html-toplevel-hlevel
14630 (nth 3 lang-words)
14631 org-export-html-toplevel-hlevel))
14632 (insert "<ul>\n<li>")
14633 (setq lines
14634 (mapcar '(lambda (line)
14635 (if (string-match org-todo-line-regexp line)
14636 ;; This is a headline
14637 (progn
14638 (setq level (- (match-end 1) (match-beginning 1))
14639 level (org-tr-level level)
14640 txt (save-match-data
14641 (org-html-expand
14642 (org-export-cleanup-toc-line
14643 (match-string 3 line))))
14644 todo
14645 (or (and org-export-mark-todo-in-toc
14646 (match-beginning 2)
14647 (not (equal (match-string 2 line)
14648 org-done-string)))
14649 ; TODO, not DONE
14650 (and org-export-mark-todo-in-toc
14651 (= level umax)
14652 (org-search-todo-below
14653 line lines level))))
14654 (if (and (memq org-export-with-tags '(not-in-toc nil))
14655 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
14656 (setq txt (replace-match "" t t txt)))
14657 (if (string-match quote-re0 txt)
14658 (setq txt (replace-match "" t t txt)))
14659 (if org-export-with-section-numbers
14660 (setq txt (concat (org-section-number level)
14661 " " txt)))
14662 (if (<= level umax)
14663 (progn
14664 (setq head-count (+ head-count 1))
14665 (if (> level org-last-level)
14666 (progn
14667 (setq cnt (- level org-last-level))
14668 (while (>= (setq cnt (1- cnt)) 0)
14669 (insert "\n<ul>\n<li>"))
14670 (insert "\n")))
14671 (if (< level org-last-level)
14672 (progn
14673 (setq cnt (- org-last-level level))
14674 (while (>= (setq cnt (1- cnt)) 0)
14675 (insert "</li>\n</ul>"))
14676 (insert "\n")))
14677 ;; Check for targets
14678 (while (string-match org-target-regexp line)
14679 (setq tg (match-string 1 line)
14680 line (replace-match
14681 (concat "@<span class=\"target\">" tg "@</span> ")
14682 t t line))
14683 (push (cons (org-solidify-link-text tg)
14684 (format "sec-%d" head-count))
14685 target-alist))
14686 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
14687 (setq txt (replace-match "" t t txt)))
14688 (insert
14689 (format
14690 (if todo
14691 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
14692 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
14693 head-count txt))
14695 (setq org-last-level level))
14697 line)
14698 lines))
14699 (while (> org-last-level 0)
14700 (setq org-last-level (1- org-last-level))
14701 (insert "</li>\n</ul>\n"))
14703 (setq head-count 0)
14704 (org-init-section-numbers)
14706 (while (setq line (pop lines) origline line)
14707 (catch 'nextline
14709 ;; end of quote section?
14710 (when (and inquote (string-match "^\\*+" line))
14711 (insert "</pre>\n")
14712 (setq inquote nil))
14713 ;; inside a quote section?
14714 (when inquote
14715 (insert (org-html-protect line) "\n")
14716 (throw 'nextline nil))
14718 ;; verbatim lines
14719 (when (and org-export-with-fixed-width
14720 (string-match "^[ \t]*:\\(.*\\)" line))
14721 (when (not infixed)
14722 (setq infixed t)
14723 (insert "<pre>\n"))
14724 (insert (org-html-protect (match-string 1 line)) "\n")
14725 (when (and lines
14726 (not (string-match "^[ \t]*\\(:.*\\)"
14727 (car lines))))
14728 (setq infixed nil)
14729 (insert "</pre>\n"))
14730 (throw 'nextline nil))
14733 ;; make targets to anchors
14734 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
14735 (cond
14736 ((match-end 2)
14737 (setq line (replace-match
14738 (concat "@<a name=\""
14739 (org-solidify-link-text (match-string 1 line))
14740 "\">\\nbsp@</a>")
14741 t t line)))
14742 ((and org-export-with-toc (equal (string-to-char line) ?*))
14743 (setq line (replace-match
14744 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
14745 ; (concat "@<i>" (match-string 1 line) "@</i> ")
14746 t t line)))
14748 (setq line (replace-match
14749 (concat "@<a name=\""
14750 (org-solidify-link-text (match-string 1 line))
14751 "\" class=\"target\">" (match-string 1 line) "@</a> ")
14752 t t line)))))
14754 (setq line (org-html-handle-time-stamps line))
14756 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
14757 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
14758 ;; Also handle sub_superscripts and checkboxes
14759 (setq line (org-html-expand line))
14761 ;; Format the links
14762 (setq start 0)
14763 (while (string-match org-bracket-link-analytic-regexp line start)
14764 (setq start (match-beginning 0))
14765 (setq type (if (match-end 2) (match-string 2 line) "internal"))
14766 (setq path (match-string 3 line))
14767 (setq desc1 (if (match-end 5) (match-string 5 line))
14768 desc2 (if (match-end 2) (concat type ":" path) path)
14769 descp (and desc1 (not (equal desc1 desc2)))
14770 desc (or desc1 desc2))
14771 ;; FIXME: do we need to unescape here somewhere?
14772 (cond
14773 ((equal type "internal")
14774 (setq rpl
14775 (concat
14776 "<a href=\"#"
14777 (org-solidify-link-text path target-alist)
14778 "\">" desc "</a>")))
14779 ((member type '("http" "https" "ftp" "mailto" "news"))
14780 ;; standard URL
14781 (setq link (concat type ":" path))
14782 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
14783 ((string= type "file")
14784 ;; FILE link
14785 (let* ((filename path)
14786 (abs-p (file-name-absolute-p filename))
14787 thefile file-is-image-p search)
14788 (save-match-data
14789 (if (string-match "::\\(.*\\)" filename)
14790 (setq search (match-string 1 filename)
14791 filename (replace-match "" t nil filename)))
14792 (setq valid
14793 (if (functionp link-validate)
14794 (funcall link-validate filename current-dir)
14795 t))
14796 (setq file-is-image-p
14797 (string-match (org-image-file-name-regexp) filename))
14798 (setq thefile (if abs-p (expand-file-name filename) filename))
14799 (when (and org-export-html-link-org-files-as-html
14800 (string-match "\\.org$" thefile))
14801 (setq thefile (concat (substring thefile 0
14802 (match-beginning 0))
14803 ".html"))
14804 (if (and search
14805 ;; make sure this is can be used as target search
14806 (not (string-match "^[0-9]*$" search))
14807 (not (string-match "^\\*" search))
14808 (not (string-match "^/.*/$" search)))
14809 (setq thefile (concat thefile "#"
14810 (org-solidify-link-text
14811 (org-link-unescape search)))))
14812 (when (string-match "^file:" desc)
14813 (setq desc (replace-match "" t t desc))
14814 (if (string-match "\\.org$" desc)
14815 (setq desc (replace-match "" t t desc))))))
14816 (setq rpl (if (and file-is-image-p
14817 (or (eq t org-export-html-inline-images)
14818 (and org-export-html-inline-images
14819 (not descp))))
14820 (concat "<img src=\"" thefile "\"/>")
14821 (concat "<a href=\"" thefile "\">" desc "</a>")))
14822 (if (not valid) (setq rpl desc))))
14823 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
14824 (setq rpl (concat "<i>&lt;" type ":"
14825 (save-match-data (org-link-unescape path))
14826 "&gt;</i>"))))
14827 (setq line (replace-match rpl t t line)
14828 start (+ start (length rpl))))
14829 ;; TODO items
14830 (if (and (string-match org-todo-line-regexp line)
14831 (match-beginning 2))
14832 (if (equal (match-string 2 line) org-done-string)
14833 (setq line (replace-match
14834 "<span class=\"done\">\\2</span>"
14835 t nil line 2))
14836 (setq line (replace-match "<span class=\"todo\">\\2</span>"
14837 t nil line 2))))
14839 (cond
14840 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
14841 ;; This is a headline
14842 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
14843 txt (match-string 2 line))
14844 (if (string-match quote-re0 txt)
14845 (setq txt (replace-match "" t t txt)))
14846 (if (<= level umax) (setq head-count (+ head-count 1)))
14847 (when in-local-list
14848 ;; Close any local lists before inserting a new header line
14849 (while local-list-num
14850 (org-close-li)
14851 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
14852 (pop local-list-num))
14853 (setq local-list-indent nil
14854 in-local-list nil))
14855 (org-html-level-start level txt umax
14856 (and org-export-with-toc (<= level umax))
14857 head-count)
14858 ;; QUOTES
14859 (when (string-match quote-re line)
14860 (insert "<pre>")
14861 (setq inquote t)))
14863 ((and org-export-with-tables
14864 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
14865 (if (not table-open)
14866 ;; New table starts
14867 (setq table-open t table-buffer nil table-orig-buffer nil))
14868 ;; Accumulate lines
14869 (setq table-buffer (cons line table-buffer)
14870 table-orig-buffer (cons origline table-orig-buffer))
14871 (when (or (not lines)
14872 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
14873 (car lines))))
14874 (setq table-open nil
14875 table-buffer (nreverse table-buffer)
14876 table-orig-buffer (nreverse table-orig-buffer))
14877 (org-close-par-maybe)
14878 (insert (org-format-table-html table-buffer table-orig-buffer))))
14880 ;; Normal lines
14881 (when (string-match
14882 (cond
14883 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14884 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14885 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14886 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
14887 line)
14888 (setq ind (org-get-string-indentation line)
14889 start-is-num (match-beginning 4)
14890 starter (if (match-beginning 2)
14891 (substring (match-string 2 line) 0 -1))
14892 line (substring line (match-beginning 5)))
14893 (unless (string-match "[^ \t]" line)
14894 ;; empty line. Pretend indentation is large.
14895 (setq ind (1+ (or (car local-list-indent) 1))))
14896 (while (and in-local-list
14897 (or (and (= ind (car local-list-indent))
14898 (not starter))
14899 (< ind (car local-list-indent))))
14900 (org-close-li)
14901 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
14902 (pop local-list-num) (pop local-list-indent)
14903 (setq in-local-list local-list-indent))
14904 (cond
14905 ((and starter
14906 (or (not in-local-list)
14907 (> ind (car local-list-indent))))
14908 ;; Start new (level of ) list
14909 (org-close-par-maybe)
14910 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
14911 (push start-is-num local-list-num)
14912 (push ind local-list-indent)
14913 (setq in-local-list t))
14914 (starter
14915 ;; continue current list
14916 (org-close-li)
14917 (insert "<li>\n")))
14918 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
14919 (setq line
14920 (replace-match
14921 (if (equal (match-string 1 line) "X")
14922 "<b>[X]</b>"
14923 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
14924 t t line))))
14926 ;; Empty lines start a new paragraph. If hand-formatted lists
14927 ;; are not fully interpreted, lines starting with "-", "+", "*"
14928 ;; also start a new paragraph.
14929 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
14931 ;; Check if the line break needs to be conserved
14932 (cond
14933 ((string-match "\\\\\\\\[ \t]*$" line)
14934 (setq line (replace-match "<br/>" t t line)))
14935 (org-export-preserve-breaks
14936 (setq line (concat line "<br/>"))))
14938 (insert line "\n")))))
14940 ;; Properly close all local lists and other lists
14941 (when inquote (insert "</pre>\n"))
14942 (when in-local-list
14943 ;; Close any local lists before inserting a new header line
14944 (while local-list-num
14945 (org-close-li)
14946 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
14947 (pop local-list-num))
14948 (setq local-list-indent nil
14949 in-local-list nil))
14950 (org-html-level-start 1 nil umax
14951 (and org-export-with-toc (<= level umax))
14952 head-count)
14954 (when (plist-get opt-plist :auto-postamble)
14955 (when author
14956 (insert "<p class=\"author\"> "
14957 (nth 1 lang-words) ": " author "\n")
14958 (when email
14959 (insert "<a href=\"mailto:" email "\">&lt;"
14960 email "&gt;</a>\n"))
14961 (insert "</p>\n"))
14962 (when (and date time)
14963 (insert "<p class=\"date\"> "
14964 (nth 2 lang-words) ": "
14965 date " " time "</p>\n")))
14967 (if org-export-html-with-timestamp
14968 (insert org-export-html-html-helper-timestamp))
14969 (insert (or (plist-get opt-plist :postamble) ""))
14970 (insert "</body>\n</html>\n")
14971 (normal-mode)
14972 ;; remove empty paragraphs and lists
14973 (goto-char (point-min))
14974 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
14975 (replace-match ""))
14976 (goto-char (point-min))
14977 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
14978 (replace-match ""))
14979 (save-buffer)
14980 (goto-char (point-min))
14981 (message "Exporting... done"))))
14984 (defun org-format-table-html (lines olines)
14985 "Find out which HTML converter to use and return the HTML code."
14986 (if (string-match "^[ \t]*|" (car lines))
14987 ;; A normal org table
14988 (org-format-org-table-html lines)
14989 ;; Table made by table.el - test for spanning
14990 (let* ((hlines (delq nil (mapcar
14991 (lambda (x)
14992 (if (string-match "^[ \t]*\\+-" x) x
14993 nil))
14994 lines)))
14995 (first (car hlines))
14996 (ll (and (string-match "\\S-+" first)
14997 (match-string 0 first)))
14998 (re (concat "^[ \t]*" (regexp-quote ll)))
14999 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
15000 hlines))))
15001 (if (and (not spanning)
15002 (not org-export-prefer-native-exporter-for-tables))
15003 ;; We can use my own converter with HTML conversions
15004 (org-format-table-table-html lines)
15005 ;; Need to use the code generator in table.el, with the original text.
15006 (org-format-table-table-html-using-table-generate-source olines)))))
15008 (defun org-format-org-table-html (lines)
15009 "Format a table into HTML."
15010 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
15011 (setq lines (nreverse lines))
15012 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
15013 (setq lines (nreverse lines))
15014 (when org-export-table-remove-special-lines
15015 ;; Check if the table has a marking column. If yes remove the
15016 ;; column and the special lines
15017 (let* ((special
15018 (not
15019 (memq nil
15020 (mapcar
15021 (lambda (x)
15022 (or (string-match "^[ \t]*|-" x)
15023 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
15024 lines)))))
15025 (if special
15026 (setq lines
15027 (delq nil
15028 (mapcar
15029 (lambda (x)
15030 (if (string-match "^[ \t]*| *[!_^] *|" x)
15031 nil ; ignore this line
15032 (and (or (string-match "^[ \t]*|-+\\+" x)
15033 (string-match "^[ \t]*|[^|]*|" x))
15034 (replace-match "|" t t x))))
15035 lines))))))
15037 (let ((head (and org-export-highlight-first-table-line
15038 (delq nil (mapcar
15039 (lambda (x) (string-match "^[ \t]*|-" x))
15040 (cdr lines)))))
15041 line fields html)
15042 (setq html (concat org-export-html-table-tag "\n"))
15043 (while (setq line (pop lines))
15044 (catch 'next-line
15045 (if (string-match "^[ \t]*|-" line)
15046 (progn
15047 (setq head nil) ;; head ends here, first time around
15048 ;; ignore this line
15049 (throw 'next-line t)))
15050 ;; Break the line into fields
15051 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
15052 (setq html (concat
15053 html
15054 "<tr>"
15055 (mapconcat (lambda (x)
15056 (if head
15057 (concat "<th>" x "</th>")
15058 (concat "<td>" x "</td>")))
15059 fields "")
15060 "</tr>\n"))))
15061 (setq html (concat html "</table>\n"))
15062 html))
15064 (defun org-fake-empty-table-line (line)
15065 "Replace everything except \"|\" with spaces."
15066 (let ((i (length line))
15067 (newstr (copy-sequence line)))
15068 (while (> i 0)
15069 (setq i (1- i))
15070 (if (not (eq (aref newstr i) ?|))
15071 (aset newstr i ?\ )))
15072 newstr))
15074 (defun org-format-table-table-html (lines)
15075 "Format a table generated by table.el into HTML.
15076 This conversion does *not* use `table-generate-source' from table.el.
15077 This has the advantage that Org-mode's HTML conversions can be used.
15078 But it has the disadvantage, that no cell- or row-spanning is allowed."
15079 (let (line field-buffer
15080 (head org-export-highlight-first-table-line)
15081 fields html empty)
15082 (setq html (concat org-export-html-table-tag "\n"))
15083 (while (setq line (pop lines))
15084 (setq empty "&nbsp;")
15085 (catch 'next-line
15086 (if (string-match "^[ \t]*\\+-" line)
15087 (progn
15088 (if field-buffer
15089 (progn
15090 (setq html (concat
15091 html
15092 "<tr>"
15093 (mapconcat
15094 (lambda (x)
15095 (if (equal x "") (setq x empty))
15096 (if head
15097 (concat "<th>" x "</th>\n")
15098 (concat "<td>" x "</td>\n")))
15099 field-buffer "\n")
15100 "</tr>\n"))
15101 (setq head nil)
15102 (setq field-buffer nil)))
15103 ;; Ignore this line
15104 (throw 'next-line t)))
15105 ;; Break the line into fields and store the fields
15106 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
15107 (if field-buffer
15108 (setq field-buffer (mapcar
15109 (lambda (x)
15110 (concat x "<br/>" (pop fields)))
15111 field-buffer))
15112 (setq field-buffer fields))))
15113 (setq html (concat html "</table>\n"))
15114 html))
15116 (defun org-format-table-table-html-using-table-generate-source (lines)
15117 "Format a table into html, using `table-generate-source' from table.el.
15118 This has the advantage that cell- or row-spanning is allowed.
15119 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
15120 (require 'table)
15121 (with-current-buffer (get-buffer-create " org-tmp1 ")
15122 (erase-buffer)
15123 (insert (mapconcat 'identity lines "\n"))
15124 (goto-char (point-min))
15125 (if (not (re-search-forward "|[^+]" nil t))
15126 (error "Error processing table"))
15127 (table-recognize-table)
15128 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
15129 (table-generate-source 'html " org-tmp2 ")
15130 (set-buffer " org-tmp2 ")
15131 (buffer-substring (point-min) (point-max))))
15133 (defun org-html-handle-time-stamps (s)
15134 "Format time stamps in string S, or remove them."
15135 (catch 'exit
15136 (let (r b)
15137 (while (string-match org-maybe-keyword-time-regexp s)
15138 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
15139 ;; never export CLOCK
15140 (throw 'exit ""))
15141 (or b (setq b (substring s 0 (match-beginning 0))))
15142 (if (not org-export-with-timestamps)
15143 (setq r (concat r (substring s 0 (match-beginning 0)))
15144 s (substring s (match-end 0)))
15145 (setq r (concat
15146 r (substring s 0 (match-beginning 0))
15147 (if (match-end 1)
15148 (format "@<span class=\"timestamp-kwd\">%s @</span>"
15149 (match-string 1 s)))
15150 (format " @<span class=\"timestamp\">%s@</span>"
15151 (substring (match-string 3 s) 1 -1)))
15152 s (substring s (match-end 0)))))
15153 ;; Line break if line started and ended with time stamp stuff
15154 (if (not r)
15156 (setq r (concat r s))
15157 (unless (string-match "\\S-" (concat b s))
15158 (setq r (concat r "@<br/>")))
15159 r))))
15161 (defun org-html-protect (s)
15162 ;; convert & to &amp;, < to &lt; and > to &gt;
15163 (let ((start 0))
15164 (while (string-match "&" s start)
15165 (setq s (replace-match "&amp;" t t s)
15166 start (1+ (match-beginning 0))))
15167 (while (string-match "<" s)
15168 (setq s (replace-match "&lt;" t t s)))
15169 (while (string-match ">" s)
15170 (setq s (replace-match "&gt;" t t s))))
15173 (defun org-export-cleanup-toc-line (s)
15174 "Remove tags and time staps from lines going into the toc."
15175 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
15176 (setq s (replace-match "" t t s)))
15177 (when org-export-remove-timestamps-from-toc
15178 (while (string-match org-maybe-keyword-time-regexp s)
15179 (setq s (replace-match "" t t s))))
15182 (defun org-html-expand (string)
15183 "Prepare STRING for HTML export. Applies all active conversions.
15184 If there are links in the string, don't modify these."
15185 (let* (m s l res)
15186 (while (setq m (string-match org-bracket-link-regexp string))
15187 (setq s (substring string 0 m)
15188 l (match-string 0 string)
15189 string (substring string (match-end 0)))
15190 (push (org-html-do-expand s) res)
15191 (push l res))
15192 (push (org-html-do-expand string) res)
15193 (apply 'concat (nreverse res))))
15195 (defun org-html-do-expand (s)
15196 "Apply all active conversions to translate special ASCII to HTML."
15197 (setq s (org-html-protect s))
15198 (if org-export-html-expand
15199 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
15200 (setq s (replace-match "<\\1>" t nil s))))
15201 (if org-export-with-emphasize
15202 (setq s (org-export-html-convert-emphasize s)))
15203 (if org-export-with-sub-superscripts
15204 (setq s (org-export-html-convert-sub-super s)))
15205 (if org-export-with-TeX-macros
15206 (let ((start 0) wd ass)
15207 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
15208 (setq wd (match-string 1 s))
15209 (if (setq ass (assoc wd org-html-entities))
15210 (setq s (replace-match (or (cdr ass)
15211 (concat "&" (car ass) ";"))
15212 t t s))
15213 (setq start (+ start (length wd)))))))
15216 (defun org-create-multibrace-regexp (left right n)
15217 "Create a regular expression which will match a balanced sexp.
15218 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
15219 as single character strings.
15220 The regexp returned will match the entire expression including the
15221 delimiters. It will also define a single group which contains the
15222 match except for the outermost delimiters. The maximum depth of
15223 stacked delimiters is N. Escaping delimiters is not possible."
15224 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
15225 (or "\\|")
15226 (re nothing)
15227 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
15228 (while (> n 1)
15229 (setq n (1- n)
15230 re (concat re or next)
15231 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
15232 (concat left "\\(" re "\\)" right)))
15234 (defvar org-match-substring-regexp
15235 (concat
15236 "\\([^\\]\\)\\([_^]\\)\\("
15237 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
15238 "\\|"
15239 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
15240 "\\|"
15241 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
15242 "The regular expression matching a sub- or superscript.")
15244 (defun org-export-html-convert-sub-super (string)
15245 "Convert sub- and superscripts in STRING to HTML."
15246 (let (key c)
15247 (while (string-match org-match-substring-regexp string)
15248 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
15249 (setq c (or (match-string 8 string)
15250 (match-string 6 string)
15251 (match-string 5 string)))
15252 (setq string (replace-match
15253 (concat (match-string 1 string)
15254 "<" key ">" c "</" key ">")
15255 t t string)))
15256 (while (string-match "\\\\\\([_^]\\)" string)
15257 (setq string (replace-match (match-string 1 string) t t string))))
15258 string)
15260 (defun org-export-html-convert-emphasize (string)
15261 "Apply emphasis."
15262 (while (string-match org-emph-re string)
15263 (setq string (replace-match (concat "\\1" (nth 2 (assoc (match-string 3 string) org-emphasis-alist)) "\\4" (nth 3 (assoc (match-string 3 string) org-emphasis-alist)) "\\5") t nil string)))
15264 string)
15266 (defvar org-par-open nil)
15267 (defun org-open-par ()
15268 "Insert <p>, but first close previous paragraph if any."
15269 (org-close-par-maybe)
15270 (insert "\n<p>")
15271 (setq org-par-open t))
15272 (defun org-close-par-maybe ()
15273 "Close paragraph if there is one open."
15274 (when org-par-open
15275 (insert "</p>")
15276 (setq org-par-open nil)))
15277 (defun org-close-li ()
15278 "Close <li> if necessary."
15279 (org-close-par-maybe)
15280 (insert "</li>\n"))
15281 ; (when (save-excursion
15282 ; (re-search-backward "</?\\(ul\\|ol\\|li\\|[hH][0-9]\\)>" nil t))
15283 ; (if (member (match-string 0) '("</ul>" "</ol>" "<li>"))
15284 ; (insert "</li>"))))
15286 (defun org-html-level-start (level title umax with-toc head-count)
15287 "Insert a new level in HTML export.
15288 When TITLE is nil, just close all open levels."
15289 (org-close-par-maybe)
15290 (let ((l (1+ (max level umax))))
15291 (while (<= l org-level-max)
15292 (if (aref levels-open (1- l))
15293 (progn
15294 (org-html-level-close l)
15295 (aset levels-open (1- l) nil)))
15296 (setq l (1+ l)))
15297 (when title
15298 ;; If title is nil, this means this function is called to close
15299 ;; all levels, so the rest is done only if title is given
15300 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
15301 (setq title (replace-match
15302 (if org-export-with-tags
15303 (save-match-data
15304 (concat
15305 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
15306 (mapconcat 'identity (org-split-string
15307 (match-string 1 title) ":")
15308 "&nbsp;")
15309 "</span>"))
15311 t t title)))
15312 (if (> level umax)
15313 (progn
15314 (if (aref levels-open (1- level))
15315 (progn
15316 (org-close-li)
15317 (insert "<li>" title "<br/>\n"))
15318 (aset levels-open (1- level) t)
15319 (org-close-par-maybe)
15320 (insert "<ul>\n<li>" title "<br/>\n")))
15321 (if org-export-with-section-numbers
15322 (setq title (concat (org-section-number level) " " title)))
15323 (setq level (+ level org-export-html-toplevel-hlevel -1))
15324 (if with-toc
15325 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
15326 level head-count title level))
15327 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
15328 (org-open-par)))))
15330 (defun org-html-level-close (&rest args)
15331 "Terminate one level in HTML export."
15332 (org-close-li)
15333 (insert "</ul>"))
15335 ;; Variable holding the vector with section numbers
15336 (defvar org-section-numbers (make-vector org-level-max 0))
15338 (defun org-init-section-numbers ()
15339 "Initialize the vector for the section numbers."
15340 (let* ((level -1)
15341 (numbers (nreverse (org-split-string "" "\\.")))
15342 (depth (1- (length org-section-numbers)))
15343 (i depth) number-string)
15344 (while (>= i 0)
15345 (if (> i level)
15346 (aset org-section-numbers i 0)
15347 (setq number-string (or (car numbers) "0"))
15348 (if (string-match "\\`[A-Z]\\'" number-string)
15349 (aset org-section-numbers i
15350 (- (string-to-char number-string) ?A -1))
15351 (aset org-section-numbers i (string-to-number number-string)))
15352 (pop numbers))
15353 (setq i (1- i)))))
15355 (defun org-section-number (&optional level)
15356 "Return a string with the current section number.
15357 When LEVEL is non-nil, increase section numbers on that level."
15358 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
15359 (when level
15360 (when (> level -1)
15361 (aset org-section-numbers
15362 level (1+ (aref org-section-numbers level))))
15363 (setq idx (1+ level))
15364 (while (<= idx depth)
15365 (if (not (= idx 1))
15366 (aset org-section-numbers idx 0))
15367 (setq idx (1+ idx))))
15368 (setq idx 0)
15369 (while (<= idx depth)
15370 (setq n (aref org-section-numbers idx))
15371 (setq string (concat string (if (not (string= string "")) "." "")
15372 (int-to-string n)))
15373 (setq idx (1+ idx)))
15374 (save-match-data
15375 (if (string-match "\\`\\([@0]\\.\\)+" string)
15376 (setq string (replace-match "" t nil string)))
15377 (if (string-match "\\(\\.0\\)+\\'" string)
15378 (setq string (replace-match "" t nil string))))
15379 string))
15382 ;;;###autoload
15383 (defun org-export-icalendar-this-file ()
15384 "Export current file as an iCalendar file.
15385 The iCalendar file will be located in the same directory as the Org-mode
15386 file, but with extension `.ics'."
15387 (interactive)
15388 (org-export-icalendar nil buffer-file-name))
15390 (defun org-export-as-xoxo-insert-into (buffer &rest output)
15391 (with-current-buffer buffer
15392 (apply 'insert output)))
15393 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
15395 (defun org-export-as-xoxo (&optional buffer)
15396 "Export the org buffer as XOXO.
15397 The XOXO buffer is named *xoxo-<source buffer name>*"
15398 (interactive (list (current-buffer)))
15399 ;; A quickie abstraction
15401 ;; Output everything as XOXO
15402 (with-current-buffer (get-buffer buffer)
15403 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
15404 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
15405 (org-infile-export-plist)))
15406 (filename (concat (file-name-as-directory
15407 (org-export-directory :xoxo opt-plist))
15408 (file-name-sans-extension
15409 (file-name-nondirectory buffer-file-name))
15410 ".html"))
15411 (out (find-file-noselect filename))
15412 (last-level 1)
15413 (hanging-li nil))
15414 ;; Check the output buffer is empty.
15415 (with-current-buffer out (erase-buffer))
15416 ;; Kick off the output
15417 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
15418 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
15419 (let* ((hd (match-string-no-properties 1))
15420 (level (length hd))
15421 (text (concat
15422 (match-string-no-properties 2)
15423 (save-excursion
15424 (goto-char (match-end 0))
15425 (let ((str ""))
15426 (catch 'loop
15427 (while 't
15428 (forward-line)
15429 (if (looking-at "^[ \t]\\(.*\\)")
15430 (setq str (concat str (match-string-no-properties 1)))
15431 (throw 'loop str)))))))))
15433 ;; Handle level rendering
15434 (cond
15435 ((> level last-level)
15436 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
15438 ((< level last-level)
15439 (dotimes (- (- last-level level) 1)
15440 (if hanging-li
15441 (org-export-as-xoxo-insert-into out "</li>\n"))
15442 (org-export-as-xoxo-insert-into out "</ol>\n"))
15443 (when hanging-li
15444 (org-export-as-xoxo-insert-into out "</li>\n")
15445 (setq hanging-li nil)))
15447 ((equal level last-level)
15448 (if hanging-li
15449 (org-export-as-xoxo-insert-into out "</li>\n")))
15452 (setq last-level level)
15454 ;; And output the new li
15455 (setq hanging-li 't)
15456 (if (equal ?+ (elt text 0))
15457 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
15458 (org-export-as-xoxo-insert-into out "<li>" text))))
15460 ;; Finally finish off the ol
15461 (dotimes (- last-level 1)
15462 (if hanging-li
15463 (org-export-as-xoxo-insert-into out "</li>\n"))
15464 (org-export-as-xoxo-insert-into out "</ol>\n"))
15466 ;; Finish the buffer off and clean it up.
15467 (switch-to-buffer-other-window out)
15468 (indent-region (point-min) (point-max) nil)
15469 (save-buffer)
15470 (goto-char (point-min))
15473 ;;;###autoload
15474 (defun org-export-icalendar-all-agenda-files ()
15475 "Export all files in `org-agenda-files' to iCalendar .ics files.
15476 Each iCalendar file will be located in the same directory as the Org-mode
15477 file, but with extension `.ics'."
15478 (interactive)
15479 (apply 'org-export-icalendar nil (org-agenda-files t)))
15481 ;;;###autoload
15482 (defun org-export-icalendar-combine-agenda-files ()
15483 "Export all files in `org-agenda-files' to a single combined iCalendar file.
15484 The file is stored under the name `org-combined-agenda-icalendar-file'."
15485 (interactive)
15486 (apply 'org-export-icalendar t (org-agenda-files t)))
15488 (defun org-export-icalendar (combine &rest files)
15489 "Create iCalendar files for all elements of FILES.
15490 If COMBINE is non-nil, combine all calendar entries into a single large
15491 file and store it under the name `org-combined-agenda-icalendar-file'."
15492 (save-excursion
15493 (let* ((dir (org-export-directory
15494 :ical (list :publishing-directory
15495 org-export-publishing-directory)))
15496 file ical-file ical-buffer category started org-agenda-new-buffers)
15498 (when combine
15499 (setq ical-file
15500 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
15501 org-combined-agenda-icalendar-file
15502 (expand-file-name org-combined-agenda-icalendar-file dir))
15503 ical-buffer (org-get-agenda-file-buffer ical-file))
15504 (set-buffer ical-buffer) (erase-buffer))
15505 (while (setq file (pop files))
15506 (catch 'nextfile
15507 (org-check-agenda-file file)
15508 (set-buffer (org-get-agenda-file-buffer file))
15509 (unless combine
15510 (setq ical-file (concat (file-name-as-directory dir)
15511 (file-name-sans-extension
15512 (file-name-nondirectory buffer-file-name))
15513 ".ics"))
15514 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
15515 (with-current-buffer ical-buffer (erase-buffer)))
15516 (setq category (or org-category
15517 (file-name-sans-extension
15518 (file-name-nondirectory buffer-file-name))))
15519 (if (symbolp category) (setq category (symbol-name category)))
15520 (let ((standard-output ical-buffer))
15521 (if combine
15522 (and (not started) (setq started t)
15523 (org-start-icalendar-file org-icalendar-combined-name))
15524 (org-start-icalendar-file category))
15525 (org-print-icalendar-entries combine category)
15526 (when (or (and combine (not files)) (not combine))
15527 (org-finish-icalendar-file)
15528 (set-buffer ical-buffer)
15529 (save-buffer)
15530 (run-hooks 'org-after-save-iCalendar-file-hook)))))
15531 (org-release-buffers org-agenda-new-buffers))))
15533 (defvar org-after-save-iCalendar-file-hook nil
15534 "Hook run after an iCalendar file has been saved.
15535 The iCalendar buffer is still current when this hook is run.
15536 A good way to use this is to tell a desktop calenndar application to re-read
15537 the iCalendar file.")
15539 (defun org-print-icalendar-entries (&optional combine category)
15540 "Print iCalendar entries for the current Org-mode file to `standard-output'.
15541 When COMBINE is non nil, add the category to each line."
15542 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
15543 (dts (org-ical-ts-to-string
15544 (format-time-string (cdr org-time-stamp-formats) (current-time))
15545 "DTSTART"))
15546 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
15547 (save-excursion
15548 (goto-char (point-min))
15549 (while (re-search-forward org-ts-regexp nil t)
15550 (setq pos (match-beginning 0)
15551 ts (match-string 0)
15552 inc t
15553 hd (org-get-heading))
15554 (if (looking-at re2)
15555 (progn
15556 (goto-char (match-end 0))
15557 (setq ts2 (match-string 1) inc nil))
15558 (setq ts2 ts
15559 tmp (buffer-substring (max (point-min)
15560 (- pos org-ds-keyword-length))
15561 pos)
15562 deadlinep (string-match org-deadline-regexp tmp)
15563 scheduledp (string-match org-scheduled-regexp tmp)
15564 ;; donep (org-entry-is-done-p)
15566 (if (or (string-match org-tr-regexp hd)
15567 (string-match org-ts-regexp hd))
15568 (setq hd (replace-match "" t t hd)))
15569 (if combine
15570 (setq hd (concat hd " (category " category ")")))
15571 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
15572 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
15573 (princ (format "BEGIN:VEVENT
15576 SUMMARY:%s
15577 END:VEVENT\n"
15578 (org-ical-ts-to-string ts "DTSTART")
15579 (org-ical-ts-to-string ts2 "DTEND" inc)
15580 hd)))
15581 (when org-icalendar-include-todo
15582 (goto-char (point-min))
15583 (while (re-search-forward org-todo-line-regexp nil t)
15584 (setq state (match-string 1))
15585 (unless (equal state org-done-string)
15586 (setq hd (match-string 3))
15587 (if (string-match org-priority-regexp hd)
15588 (setq pri (string-to-char (match-string 2 hd))
15589 hd (concat (substring hd 0 (match-beginning 1))
15590 (substring hd (- (match-end 1)))))
15591 (setq pri org-default-priority))
15592 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
15593 (- org-lowest-priority ?A))))))
15595 (princ (format "BEGIN:VTODO
15597 SUMMARY:%s
15598 SEQUENCE:1
15599 PRIORITY:%d
15600 END:VTODO\n"
15601 dts hd pri))))))))
15603 (defun org-start-icalendar-file (name)
15604 "Start an iCalendar file by inserting the header."
15605 (let ((user user-full-name)
15606 (name (or name "unknown"))
15607 (timezone (cadr (current-time-zone))))
15608 (princ
15609 (format "BEGIN:VCALENDAR
15610 VERSION:2.0
15611 X-WR-CALNAME:%s
15612 PRODID:-//%s//Emacs with Org-mode//EN
15613 X-WR-TIMEZONE:%s
15614 CALSCALE:GREGORIAN\n" name user timezone))))
15616 (defun org-finish-icalendar-file ()
15617 "Finish an iCalendar file by inserting the END statement."
15618 (princ "END:VCALENDAR\n"))
15620 (defun org-ical-ts-to-string (s keyword &optional inc)
15621 "Take a time string S and convert it to iCalendar format.
15622 KEYWORD is added in front, to make a complete line like DTSTART....
15623 When INC is non-nil, increase the hour by two (if time string contains
15624 a time), or the day by one (if it does not contain a time)."
15625 (let ((t1 (org-parse-time-string s 'nodefault))
15626 t2 fmt have-time time)
15627 (if (and (car t1) (nth 1 t1) (nth 2 t1))
15628 (setq t2 t1 have-time t)
15629 (setq t2 (org-parse-time-string s)))
15630 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
15631 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
15632 (when inc
15633 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
15634 (setq time (encode-time s mi h d m y)))
15635 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
15636 (concat keyword (format-time-string fmt time))))
15638 ;;; LaTeX stuff
15640 (defvar org-cdlatex-mode-map (make-sparse-keymap)
15641 "Keymap for the minor `org-cdlatex-mode'.")
15643 (define-key org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
15644 (define-key org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
15645 (define-key org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
15646 (define-key org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
15647 (define-key org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
15649 (defvar org-cdlatex-texmathp-advice-is-done nil
15650 "Flag remembering if we have applied the advice to texmathp already.")
15652 (define-minor-mode org-cdlatex-mode
15653 "Toggle the minor `org-cdlatex-mode'.
15654 This mode supports entering LaTeX environment and math in LaTeX fragments
15655 in Org-mode.
15656 \\{org-cdlatex-mode-map}"
15657 nil " OCDL" nil
15658 (when org-cdlatex-mode (require 'cdlatex))
15659 (unless org-cdlatex-texmathp-advice-is-done
15660 (setq org-cdlatex-texmathp-advice-is-done t)
15661 (defadvice texmathp (around org-math-always-on activate)
15662 "Always return t in org-mode buffers.
15663 This is because we want to insert math symbols without dollars even outside
15664 the LaTeX math segments. If Orgmode thinks that point is actually inside
15665 en embedded LaTeX fragement, let texmathp do its job.
15666 \\[org-cdlatex-mode-map]"
15667 (interactive)
15668 (let (p)
15669 (cond
15670 ((not (org-mode-p)) ad-do-it)
15671 ((eq this-command 'cdlatex-math-symbol)
15672 (setq ad-return-value t
15673 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
15675 (let ((p (org-inside-LaTeX-fragment-p)))
15676 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
15677 (setq ad-return-value t
15678 texmathp-why '("Org-mode embedded math" . 0))
15679 (if p ad-do-it)))))))))
15681 (defun turn-on-org-cdlatex ()
15682 "Unconditionally turn on `org-cdlatex-mode'."
15683 (org-cdlatex-mode 1))
15685 (defun org-inside-LaTeX-fragment-p ()
15686 "Test if point is inside a LaTeX fragment.
15687 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
15688 sequence appearing also before point.
15689 Even though the matchers for math are configurable, this function assumes
15690 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
15691 delimiters are skipped when they have been removed by customization.
15692 The return value is nil, or a cons cell with the delimiter and
15693 and the position of this delimiter.
15695 This function does a reasonably good job, but can locally be fooled by
15696 for example currency specifications. For example it will assume being in
15697 inline math after \"$22.34\". The LaTeX fragment formatter will only format
15698 fragments that are properly closed, but during editing, we have to live
15699 with the uncertainty caused by missing closing delimiters. This function
15700 looks only before point, not after."
15701 (catch 'exit
15702 (let ((pos (point))
15703 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
15704 (lim (progn
15705 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
15706 (point)))
15707 dd-on str (start 0) m re)
15708 (goto-char pos)
15709 (when dodollar
15710 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
15711 re (nth 1 (assoc "$" org-latex-regexps)))
15712 (while (string-match re str start)
15713 (cond
15714 ((= (match-end 0) (length str))
15715 (throw 'exit (cons "$" (+ lim (match-beginning 0)))))
15716 ((= (match-end 0) (- (length str) 5))
15717 (throw 'exit nil))
15718 (t (setq start (match-end 0))))))
15719 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
15720 (goto-char pos)
15721 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
15722 (and (match-beginning 2) (throw 'exit nil))
15723 ;; count $$
15724 (while (re-search-backward "\\$\\$" lim t)
15725 (setq dd-on (not dd-on)))
15726 (goto-char pos)
15727 (if dd-on (cons "$$" m))))))
15730 (defun org-try-cdlatex-tab ()
15731 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15732 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15733 - inside a LaTeX fragment, or
15734 - after the first word in a line, where an abbreviation expansion could
15735 insert a LaTeX environment."
15736 (when org-cdlatex-mode
15737 (cond
15738 ((save-excursion
15739 (skip-chars-backward "a-zA-Z0-9*")
15740 (skip-chars-backward " \t")
15741 (bolp))
15742 (cdlatex-tab) t)
15743 ((org-inside-LaTeX-fragment-p)
15744 (cdlatex-tab) t)
15745 (t nil))))
15747 (defun org-cdlatex-underscore-caret (&optional arg)
15748 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15749 Revert to the normal definition outside of these fragments."
15750 (interactive "P")
15751 (if (org-inside-LaTeX-fragment-p)
15752 (call-interactively 'cdlatex-sub-superscript)
15753 (let (org-cdlatex-mode)
15754 (call-interactively (key-binding (vector last-input-event))))))
15756 (defun org-cdlatex-math-modify (&optional arg)
15757 "Execute `cdlatex-math-modify' in LaTeX fragments.
15758 Revert to the normal definition outside of these fragments."
15759 (interactive "P")
15760 (if (org-inside-LaTeX-fragment-p)
15761 (call-interactively 'cdlatex-math-modify)
15762 (let (org-cdlatex-mode)
15763 (call-interactively (key-binding (vector last-input-event))))))
15765 (defvar org-latex-fragment-image-overlays nil
15766 "List of overlays carrying the images of latex fragments.")
15767 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15769 (defun org-remove-latex-fragment-image-overlays ()
15770 "Remove all overlays with LaTeX fragment images in current buffer."
15771 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
15772 (setq org-latex-fragment-image-overlays nil))
15774 (defun org-preview-latex-fragment (&optional subtree)
15775 "Preview the LaTeX fragment at point, or all locally or globally.
15776 If the cursor is in a LaTeX fragment, create the image and overlay
15777 it over the source code. If there is no fragment at point, display
15778 all fragments in the current text, from one headline to the next. With
15779 prefix SUBTREE, display all fragments in the current subtree. With a
15780 double prefix `C-u C-u', or when the cursor is before the first headline,
15781 display all fragments in the buffer.
15782 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15783 (interactive "P")
15784 (org-remove-latex-fragment-image-overlays)
15785 (save-excursion
15786 (save-restriction
15787 (let (beg end at msg)
15788 (cond
15789 ((or (equal subtree '(16))
15790 (not (save-excursion
15791 (re-search-backward (concat "^" outline-regexp) nil t))))
15792 (setq beg (point-min) end (point-max)
15793 msg "Creating images for buffer...%s"))
15794 ((equal subtree '(4))
15795 (org-back-to-heading)
15796 (setq beg (point) end (org-end-of-subtree t)
15797 msg "Creating images for subtree...%s"))
15799 (if (setq at (org-inside-LaTeX-fragment-p))
15800 (goto-char (max (point-min) (- (cdr at) 2)))
15801 (org-back-to-heading))
15802 (setq beg (point) end (progn (outline-next-heading) (point))
15803 msg (if at "Creating image...%s"
15804 "Creating images for entry...%s"))))
15805 (message msg "")
15806 (narrow-to-region beg end)
15807 (org-format-latex
15808 (concat "ltxpng/" (file-name-sans-extension
15809 (file-name-nondirectory
15810 buffer-file-name)))
15811 default-directory 'overlays msg at)
15812 (message msg "done. Use `C-c C-c' to remove images.")))))
15814 (defvar org-latex-regexps
15815 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15816 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15817 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15818 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
15819 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15820 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
15821 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
15822 "Regular expressions for matching embedded LaTeX.")
15824 (defun org-format-latex (prefix &optional dir overlays msg at)
15825 "Replace LaTeX fragments with links to an image, and produce images."
15826 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15827 (let* ((prefixnodir (file-name-nondirectory prefix))
15828 (absprefix (expand-file-name prefix dir))
15829 (todir (file-name-directory absprefix))
15830 (opt org-format-latex-options)
15831 (matchers (plist-get opt :matchers))
15832 (re-list org-latex-regexps)
15833 (cnt 0) txt link beg end re e oldfiles
15834 m n block linkfile movefile ov)
15835 ;; Make sure the directory exists
15836 (or (file-directory-p todir) (make-directory todir))
15837 ;; Check if there are old images files with this prefix, and remove them
15838 (setq oldfiles (directory-files
15839 todir 'full
15840 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$")))
15841 (while oldfiles (delete-file (pop oldfiles)))
15842 ;; Check the different regular expressions
15843 (while (setq e (pop re-list))
15844 (setq m (car e) re (nth 1 e) n (nth 2 e)
15845 block (if (nth 3 e) "\n\n" ""))
15846 (when (member m matchers)
15847 (goto-char (point-min))
15848 (while (re-search-forward re nil t)
15849 (when (or (not at) (equal (cdr at) (match-beginning n)))
15850 (setq txt (match-string n)
15851 beg (match-beginning n) end (match-end n)
15852 cnt (1+ cnt)
15853 linkfile (format "%s_%04d.png" prefix cnt)
15854 movefile (format "%s_%04d.png" absprefix cnt)
15855 link (concat block "[[file:" linkfile "]]" block))
15856 (if msg (message msg cnt))
15857 (goto-char beg)
15858 (org-create-formula-image
15859 txt movefile opt)
15860 (if overlays
15861 (progn
15862 (setq ov (org-make-overlay beg end))
15863 (if (featurep 'xemacs)
15864 (progn
15865 (org-overlay-put ov 'invisible t)
15866 (org-overlay-put
15867 ov 'end-glyph
15868 (make-glyph (vector 'png :file movefile))))
15869 (org-overlay-put
15870 ov 'display
15871 (list 'image :type 'png :file movefile :ascent 'center)))
15872 (push ov org-latex-fragment-image-overlays)
15873 (goto-char end))
15874 (delete-region beg end)
15875 (insert link))))))))
15877 ;; This function borrows from Ganesh Swami's latex2png.el
15878 (defun org-create-formula-image (string tofile options)
15879 (let* ((tmpdir (if (featurep 'xemacs)
15880 (temp-directory)
15881 temporary-file-directory))
15882 (texfilebase (make-temp-name
15883 (expand-file-name "orgtex" tmpdir)))
15885 ;(texfilebase (make-temp-file "orgtex"))
15886 ; (dummy (delete-file texfilebase))
15887 (texfile (concat texfilebase ".tex"))
15888 (dvifile (concat texfilebase ".dvi"))
15889 (pngfile (concat texfilebase ".png"))
15890 (scale (number-to-string (* 1000 (or (plist-get options :scale) 1.0))))
15891 (fg (or (plist-get options :foreground) "Black"))
15892 (bg (or (plist-get options :background) "Transparent")))
15893 (with-temp-file texfile
15894 (insert "\\documentclass{article}
15895 \\usepackage{fullpage}
15896 \\usepackage{amssymb}
15897 \\usepackage[usenames]{color}
15898 \\usepackage{amsmath}
15899 \\usepackage{latexsym}
15900 \\usepackage[mathscr]{eucal}
15901 \\pagestyle{empty}
15902 \\begin{document}\n" string "\n\\end{document}\n"))
15903 (let ((dir default-directory))
15904 (condition-case nil
15905 (progn
15906 (cd tmpdir)
15907 (call-process "latex" nil nil nil texfile))
15908 (error nil))
15909 (cd dir))
15910 (if (not (file-exists-p dvifile))
15911 (progn (message "Failed to create dvi file from %s" texfile) nil)
15912 (call-process "dvipng" nil nil nil
15913 "-E" "-fg" fg "-bg" bg
15914 "-x" scale "-y" scale "-T" "tight"
15915 "-o" pngfile
15916 dvifile)
15917 (if (not (file-exists-p pngfile))
15918 (progn (message "Failed to create png file from %s" texfile) nil)
15919 ;; Use the requested file name and clean up
15920 (copy-file pngfile tofile 'replace)
15921 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15922 (delete-file (concat texfilebase e)))
15923 pngfile))))
15925 ;;; Key bindings
15927 ;; - Bindings in Org-mode map are currently
15928 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
15929 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
15930 ;; e (?) useful from outline-mode
15931 ;; i k @ expendable from outline-mode
15932 ;; 0123456789 % & ()_{} " ` free
15934 ;; Make `C-c C-x' a prefix key
15935 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
15937 ;; TAB key with modifiers
15938 (define-key org-mode-map "\C-i" 'org-cycle)
15939 (define-key org-mode-map [(tab)] 'org-cycle)
15940 (define-key org-mode-map [(control tab)] 'org-force-cycle-archived)
15941 (define-key org-mode-map [(meta tab)] 'org-complete)
15942 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
15943 ;; The following line is necessary under Suse GNU/Linux
15944 (unless (featurep 'xemacs)
15945 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
15946 (define-key org-mode-map [(shift tab)] 'org-shifttab)
15948 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
15949 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
15950 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15951 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
15952 (define-key org-mode-map [(meta return)] 'org-meta-return)
15953 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
15954 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
15956 ;; Cursor keys with modifiers
15957 (define-key org-mode-map [(meta left)] 'org-metaleft)
15958 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
15959 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
15960 (define-key org-mode-map [(meta right)] 'org-metaright)
15961 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
15962 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
15963 (define-key org-mode-map [(meta up)] 'org-metaup)
15964 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
15965 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
15966 (define-key org-mode-map [(meta down)] 'org-metadown)
15967 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
15968 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
15970 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15971 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
15972 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
15973 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
15974 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
15975 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
15976 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
15977 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
15978 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
15979 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
15980 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
15981 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
15982 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
15983 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
15984 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
15985 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
15987 ;; All the other keys
15989 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15990 (define-key org-mode-map "\C-xns" 'org-narrow-to-subtree)
15991 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
15992 (define-key org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
15993 (define-key org-mode-map "\C-c\C-j" 'org-goto)
15994 (define-key org-mode-map "\C-c\C-t" 'org-todo)
15995 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
15996 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
15997 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
15998 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15999 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
16000 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
16001 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
16002 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
16003 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
16004 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
16005 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
16006 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
16007 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
16008 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
16009 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
16010 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
16011 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
16012 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
16013 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
16014 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
16015 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
16016 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
16017 (define-key org-mode-map "\C-c]" 'org-remove-file)
16018 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
16019 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
16020 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
16021 (define-key org-mode-map "\C-c#" 'org-update-checkbox-count)
16022 (define-key org-mode-map "\C-m" 'org-return)
16023 (define-key org-mode-map "\C-c?" 'org-table-current-column)
16024 (define-key org-mode-map "\C-c " 'org-table-blank-field)
16025 (define-key org-mode-map "\C-c+" 'org-table-sum)
16026 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
16027 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
16028 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
16029 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
16030 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
16031 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
16032 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
16033 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
16034 (define-key org-mode-map "\C-c\C-e" 'org-export)
16035 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
16037 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
16038 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
16039 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
16040 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
16042 (define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
16043 (define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
16044 (define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
16045 (define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
16046 (define-key org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
16047 (define-key org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
16048 (define-key org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
16049 (define-key org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
16051 (when (featurep 'xemacs)
16052 (define-key org-mode-map 'button3 'popup-mode-menu))
16054 (defsubst org-table-p () (org-at-table-p))
16056 (defun org-self-insert-command (N)
16057 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
16058 If the cursor is in a table looking at whitespace, the whitespace is
16059 overwritten, and the table is not marked as requiring realignment."
16060 (interactive "p")
16061 (if (and (org-table-p)
16062 (progn
16063 ;; check if we blank the field, and if that triggers align
16064 (and org-table-auto-blank-field
16065 (member last-command
16066 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
16067 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
16068 ;; got extra space, this field does not determine column width
16069 (let (org-table-may-need-update) (org-table-blank-field))
16070 ;; no extra space, this field may determine column width
16071 (org-table-blank-field)))
16073 (eq N 1)
16074 (looking-at "[^|\n]* |"))
16075 (let (org-table-may-need-update)
16076 (goto-char (1- (match-end 0)))
16077 (delete-backward-char 1)
16078 (goto-char (match-beginning 0))
16079 (self-insert-command N))
16080 (setq org-table-may-need-update t)
16081 (self-insert-command N)))
16083 (defun org-delete-backward-char (N)
16084 "Like `delete-backward-char', insert whitespace at field end in tables.
16085 When deleting backwards, in tables this function will insert whitespace in
16086 front of the next \"|\" separator, to keep the table aligned. The table will
16087 still be marked for re-alignment if the field did fill the entire column,
16088 because, in this case the deletion might narrow the column."
16089 (interactive "p")
16090 (if (and (org-table-p)
16091 (eq N 1)
16092 (string-match "|" (buffer-substring (point-at-bol) (point)))
16093 (looking-at ".*?|"))
16094 (let ((pos (point))
16095 (noalign (looking-at "[^|\n\r]* |"))
16096 (c org-table-may-need-update))
16097 (backward-delete-char N)
16098 (skip-chars-forward "^|")
16099 (insert " ")
16100 (goto-char (1- pos))
16101 ;; noalign: if there were two spaces at the end, this field
16102 ;; does not determine the width of the column.
16103 (if noalign (setq org-table-may-need-update c)))
16104 (backward-delete-char N)))
16106 (defun org-delete-char (N)
16107 "Like `delete-char', but insert whitespace at field end in tables.
16108 When deleting characters, in tables this function will insert whitespace in
16109 front of the next \"|\" separator, to keep the table aligned. The table will
16110 still be marked for re-alignment if the field did fill the entire column,
16111 because, in this case the deletion might narrow the column."
16112 (interactive "p")
16113 (if (and (org-table-p)
16114 (not (bolp))
16115 (not (= (char-after) ?|))
16116 (eq N 1))
16117 (if (looking-at ".*?|")
16118 (let ((pos (point))
16119 (noalign (looking-at "[^|\n\r]* |"))
16120 (c org-table-may-need-update))
16121 (replace-match (concat
16122 (substring (match-string 0) 1 -1)
16123 " |"))
16124 (goto-char pos)
16125 ;; noalign: if there were two spaces at the end, this field
16126 ;; does not determine the width of the column.
16127 (if noalign (setq org-table-may-need-update c)))
16128 (delete-char N))
16129 (delete-char N)))
16131 ;; How to do this: Measure non-white length of current string
16132 ;; If equal to column width, we should realign.
16134 (defun org-remap (map &rest commands)
16135 "In MAP, remap the functions given in COMMANDS.
16136 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
16137 (let (new old)
16138 (while commands
16139 (setq old (pop commands) new (pop commands))
16140 (if (fboundp 'command-remapping)
16141 (define-key map (vector 'remap old) new)
16142 (substitute-key-definition old new map global-map)))))
16144 (when (eq org-enable-table-editor 'optimized)
16145 ;; If the user wants maximum table support, we need to hijack
16146 ;; some standard editing functions
16147 (org-remap org-mode-map
16148 'self-insert-command 'org-self-insert-command
16149 'delete-char 'org-delete-char
16150 'delete-backward-char 'org-delete-backward-char)
16151 (define-key org-mode-map "|" 'org-force-self-insert))
16153 (defun org-shiftcursor-error ()
16154 "Throw an error because Shift-Cursor command was applied in wrong context."
16155 (error "This command is active in special context like tables, headlines or timestamps"))
16157 (defun org-shifttab (&optional arg)
16158 "Global visibility cycling or move to previous table field.
16159 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
16160 on context.
16161 See the individual commands for more information."
16162 (interactive "P")
16163 (cond
16164 ((org-at-table-p) (call-interactively 'org-table-previous-field))
16165 (t (call-interactively 'org-global-cycle))))
16167 (defun org-shiftmetaleft ()
16168 "Promote subtree or delete table column.
16169 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
16170 See the individual commands for more information."
16171 (interactive)
16172 (cond
16173 ((org-at-table-p) (call-interactively 'org-table-delete-column))
16174 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
16175 ((org-at-item-p) (call-interactively 'org-outdent-item))
16176 (t (org-shiftcursor-error))))
16178 (defun org-shiftmetaright ()
16179 "Demote subtree or insert table column.
16180 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
16181 See the individual commands for more information."
16182 (interactive)
16183 (cond
16184 ((org-at-table-p) (call-interactively 'org-table-insert-column))
16185 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
16186 ((org-at-item-p) (call-interactively 'org-indent-item))
16187 (t (org-shiftcursor-error))))
16189 (defun org-shiftmetaup (&optional arg)
16190 "Move subtree up or kill table row.
16191 Calls `org-move-subtree-up' or `org-table-kill-row' or
16192 `org-move-item-up' depending on context. See the individual commands
16193 for more information."
16194 (interactive "P")
16195 (cond
16196 ((org-at-table-p) (call-interactively 'org-table-kill-row))
16197 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16198 ((org-at-item-p) (call-interactively 'org-move-item-up))
16199 (t (org-shiftcursor-error))))
16200 (defun org-shiftmetadown (&optional arg)
16201 "Move subtree down or insert table row.
16202 Calls `org-move-subtree-down' or `org-table-insert-row' or
16203 `org-move-item-down', depending on context. See the individual
16204 commands for more information."
16205 (interactive "P")
16206 (cond
16207 ((org-at-table-p) (call-interactively 'org-table-insert-row))
16208 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16209 ((org-at-item-p) (call-interactively 'org-move-item-down))
16210 (t (org-shiftcursor-error))))
16212 (defun org-metaleft (&optional arg)
16213 "Promote heading or move table column to left.
16214 Calls `org-do-promote' or `org-table-move-column', depending on context.
16215 With no specific context, calls the Emacs default `backward-word'.
16216 See the individual commands for more information."
16217 (interactive "P")
16218 (cond
16219 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
16220 ((or (org-on-heading-p) (org-region-active-p))
16221 (call-interactively 'org-do-promote))
16222 (t (call-interactively 'backward-word))))
16224 (defun org-metaright (&optional arg)
16225 "Demote subtree or move table column to right.
16226 Calls `org-do-demote' or `org-table-move-column', depending on context.
16227 With no specific context, calls the Emacs default `forward-word'.
16228 See the individual commands for more information."
16229 (interactive "P")
16230 (cond
16231 ((org-at-table-p) (call-interactively 'org-table-move-column))
16232 ((or (org-on-heading-p) (org-region-active-p))
16233 (call-interactively 'org-do-demote))
16234 (t (call-interactively 'forward-word))))
16236 (defun org-metaup (&optional arg)
16237 "Move subtree up or move table row up.
16238 Calls `org-move-subtree-up' or `org-table-move-row' or
16239 `org-move-item-up', depending on context. See the individual commands
16240 for more information."
16241 (interactive "P")
16242 (cond
16243 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
16244 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16245 ((org-at-item-p) (call-interactively 'org-move-item-up))
16246 (t (org-shiftcursor-error))))
16248 (defun org-metadown (&optional arg)
16249 "Move subtree down or move table row down.
16250 Calls `org-move-subtree-down' or `org-table-move-row' or
16251 `org-move-item-down', depending on context. See the individual
16252 commands for more information."
16253 (interactive "P")
16254 (cond
16255 ((org-at-table-p) (call-interactively 'org-table-move-row))
16256 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16257 ((org-at-item-p) (call-interactively 'org-move-item-down))
16258 (t (org-shiftcursor-error))))
16260 (defun org-shiftup (&optional arg)
16261 "Increase item in timestamp or increase priority of current headline.
16262 Calls `org-timestamp-up' or `org-priority-up', depending on context.
16263 See the individual commands for more information."
16264 (interactive "P")
16265 (cond
16266 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
16267 ((org-on-heading-p) (call-interactively 'org-priority-up))
16268 ((org-at-item-p) (call-interactively 'org-previous-item))
16269 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
16271 (defun org-shiftdown (&optional arg)
16272 "Decrease item in timestamp or decrease priority of current headline.
16273 Calls `org-timestamp-down' or `org-priority-down', depending on context.
16274 See the individual commands for more information."
16275 (interactive "P")
16276 (cond
16277 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
16278 ((org-on-heading-p) (call-interactively 'org-priority-down))
16279 (t (call-interactively 'org-next-item))))
16281 (defun org-shiftright ()
16282 "Next TODO keyword or timestamp one day later, depending on context."
16283 (interactive)
16284 (cond
16285 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
16286 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
16287 (t (org-shiftcursor-error))))
16289 (defun org-shiftleft ()
16290 "Previous TODO keyword or timestamp one day earlier, depending on context."
16291 (interactive)
16292 (cond
16293 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
16294 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
16295 (t (org-shiftcursor-error))))
16297 (defun org-copy-special ()
16298 "Copy region in table or copy current subtree.
16299 Calls `org-table-copy' or `org-copy-subtree', depending on context.
16300 See the individual commands for more information."
16301 (interactive)
16302 (call-interactively
16303 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
16305 (defun org-cut-special ()
16306 "Cut region in table or cut current subtree.
16307 Calls `org-table-copy' or `org-cut-subtree', depending on context.
16308 See the individual commands for more information."
16309 (interactive)
16310 (call-interactively
16311 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
16313 (defun org-paste-special (arg)
16314 "Paste rectangular region into table, or past subtree relative to level.
16315 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
16316 See the individual commands for more information."
16317 (interactive "P")
16318 (if (org-at-table-p)
16319 (org-table-paste-rectangle)
16320 (org-paste-subtree arg)))
16322 (defun org-ctrl-c-ctrl-c (&optional arg)
16323 "Set tags in headline, or update according to changed information at point.
16325 This command does many different things, depending on context:
16327 - If the cursor is in a headline, prompt for tags and insert them
16328 into the current line, aligned to `org-tags-column'. When called
16329 with prefix arg, realign all tags in the current buffer.
16331 - If the cursor is in one of the special #+KEYWORD lines, this
16332 triggers scanning the buffer for these lines and updating the
16333 information.
16335 - If the cursor is inside a table, realign the table. This command
16336 works even if the automatic table editor has been turned off.
16338 - If the cursor is on a #+TBLFM line, re-apply the formulas to
16339 the entire table.
16341 - If the cursor is inside a table created by the table.el package,
16342 activate that table.
16344 - If the current buffer is a remember buffer, close note and file it.
16345 with a prefix argument, file it without further interaction to the default
16346 location.
16348 - If the cursor is on a <<<target>>>, update radio targets and corresponding
16349 links in this buffer.
16351 - If the cursor is on a numbered item in a plain list, renumber the
16352 ordered list."
16353 (interactive "P")
16354 (let ((org-enable-table-editor t))
16355 (cond
16356 ((or org-clock-overlays
16357 org-occur-highlights
16358 org-latex-fragment-image-overlays)
16359 (org-remove-clock-overlays)
16360 (org-remove-occur-highlights)
16361 (org-remove-latex-fragment-image-overlays)
16362 (message "Temporary highlights/overlays removed from current buffer"))
16363 ((and (local-variable-p 'org-finish-function (current-buffer))
16364 (fboundp org-finish-function))
16365 (funcall org-finish-function))
16366 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
16367 ((org-on-heading-p) (call-interactively 'org-set-tags))
16368 ((org-at-table.el-p)
16369 (require 'table)
16370 (beginning-of-line 1)
16371 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
16372 (call-interactively 'table-recognize-table))
16373 ((org-at-table-p)
16374 (org-table-maybe-eval-formula)
16375 (if arg
16376 (call-interactively 'org-table-recalculate)
16377 (org-table-maybe-recalculate-line))
16378 (call-interactively 'org-table-align))
16379 ((org-at-item-checkbox-p)
16380 (call-interactively 'org-toggle-checkbox))
16381 ((org-at-item-p)
16382 (call-interactively 'org-renumber-ordered-list))
16383 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
16384 (cond
16385 ((equal (match-string 1) "TBLFM")
16386 ;; Recalculate the table before this line
16387 (save-excursion
16388 (beginning-of-line 1)
16389 (skip-chars-backward " \r\n\t")
16390 (if (org-at-table-p)
16391 (org-call-with-arg 'org-table-recalculate t))))
16393 (call-interactively 'org-mode-restart))))
16394 (t (error "C-c C-c can do nothing useful at this location.")))))
16396 (defun org-mode-restart ()
16397 "Restart Org-mode, to scan again for special lines.
16398 Also updates the keyword regular expressions."
16399 (interactive)
16400 (let ((org-inhibit-startup t)) (org-mode))
16401 (message "Org-mode restarted to refresh keyword and special line setup"))
16403 (defun org-return ()
16404 "Goto next table row or insert a newline.
16405 Calls `org-table-next-row' or `newline', depending on context.
16406 See the individual commands for more information."
16407 (interactive)
16408 (cond
16409 ((org-at-table-p)
16410 (org-table-justify-field-maybe)
16411 (call-interactively 'org-table-next-row))
16412 (t (newline))))
16414 (defun org-meta-return (&optional arg)
16415 "Insert a new heading or wrap a region in a table.
16416 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
16417 See the individual commands for more information."
16418 (interactive "P")
16419 (cond
16420 ((org-at-table-p)
16421 (call-interactively 'org-table-wrap-region))
16422 (t (call-interactively 'org-insert-heading))))
16424 ;;; Menu entries
16426 ;; Define the Org-mode menus
16427 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
16428 '("Tbl"
16429 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
16430 ["Next Field" org-cycle (org-at-table-p)]
16431 ["Previous Field" org-shifttab (org-at-table-p)]
16432 ["Next Row" org-return (org-at-table-p)]
16433 "--"
16434 ["Blank Field" org-table-blank-field (org-at-table-p)]
16435 ["Edit Field" org-table-edit-field (org-at-table-p)]
16436 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
16437 "--"
16438 ("Column"
16439 ["Move Column Left" org-metaleft (org-at-table-p)]
16440 ["Move Column Right" org-metaright (org-at-table-p)]
16441 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
16442 ["Insert Column" org-shiftmetaright (org-at-table-p)]
16443 "--"
16444 ["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])
16445 ("Row"
16446 ["Move Row Up" org-metaup (org-at-table-p)]
16447 ["Move Row Down" org-metadown (org-at-table-p)]
16448 ["Delete Row" org-shiftmetaup (org-at-table-p)]
16449 ["Insert Row" org-shiftmetadown (org-at-table-p)]
16450 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
16451 "--"
16452 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
16453 ("Rectangle"
16454 ["Copy Rectangle" org-copy-special (org-at-table-p)]
16455 ["Cut Rectangle" org-cut-special (org-at-table-p)]
16456 ["Paste Rectangle" org-paste-special (org-at-table-p)]
16457 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
16458 "--"
16459 ("Calculate"
16460 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
16461 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
16462 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
16463 "--"
16464 ["Recalculate line" org-table-recalculate (org-at-table-p)]
16465 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
16466 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
16467 "--"
16468 ["Sum Column/Rectangle" org-table-sum
16469 (or (org-at-table-p) (org-region-active-p))]
16470 ["Which Column?" org-table-current-column (org-at-table-p)])
16471 ["Debug Formulas"
16472 (setq org-table-formula-debug (not org-table-formula-debug))
16473 :style toggle :selected org-table-formula-debug]
16474 "--"
16475 ["Create" org-table-create (and (not (org-at-table-p))
16476 org-enable-table-editor)]
16477 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
16478 ["Import from File" org-table-import (not (org-at-table-p))]
16479 ["Export to File" org-table-export (org-at-table-p)]
16480 "--"
16481 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
16483 (easy-menu-define org-org-menu org-mode-map "Org menu"
16484 '("Org"
16485 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
16486 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
16487 ["Sparse Tree" org-occur t]
16488 ["Show All" show-all t]
16489 "--"
16490 ["New Heading" org-insert-heading t]
16491 ("Navigate Headings"
16492 ["Up" outline-up-heading t]
16493 ["Next" outline-next-visible-heading t]
16494 ["Previous" outline-previous-visible-heading t]
16495 ["Next Same Level" outline-forward-same-level t]
16496 ["Previous Same Level" outline-backward-same-level t]
16497 "--"
16498 ["Jump" org-goto t])
16499 ("Edit Structure"
16500 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
16501 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
16502 "--"
16503 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
16504 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
16505 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
16506 "--"
16507 ["Promote Heading" org-metaleft (not (org-at-table-p))]
16508 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
16509 ["Demote Heading" org-metaright (not (org-at-table-p))]
16510 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
16511 "--"
16512 ["Convert to odd levels" org-convert-to-odd-levels t]
16513 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
16514 ("Archive"
16515 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
16516 ["Check and Tag Children" (org-toggle-archive-tag (4))
16517 :active t :keys "C-u C-c C-x C-a"]
16518 ["Sparse trees open ARCHIVE trees"
16519 (setq org-sparse-tree-open-archived-trees
16520 (not org-sparse-tree-open-archived-trees))
16521 :style toggle :selected org-sparse-tree-open-archived-trees]
16522 ["Cycling opens ARCHIVE trees"
16523 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
16524 :style toggle :selected org-cycle-open-archived-trees]
16525 ["Agenda includes ARCHIVE trees"
16526 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
16527 :style toggle :selected (not org-agenda-skip-archived-trees)]
16528 "--"
16529 ["Move Subtree to Archive" org-archive-subtree t]
16530 ["Check and Move Children" (org-archive-subtree '(4))
16531 :active t :keys "C-u C-c $"])
16532 "--"
16533 ("TODO Lists"
16534 ["TODO/DONE/-" org-todo t]
16535 ("Select keyword"
16536 ["Next keyword" org-shiftright (org-on-heading-p)]
16537 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16538 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))])
16539 ["Show TODO Tree" org-show-todo-tree t]
16540 ["Global TODO list" org-todo-list t]
16541 "--"
16542 ["Set Priority" org-priority t]
16543 ["Priority Up" org-shiftup t]
16544 ["Priority Down" org-shiftdown t]
16545 "--"
16546 ; ["Insert Checkbox" org-insert-todo-heading (org-in-item-p)]
16547 ; ["Toggle Checkbox" org-ctrl-c-ctrl-c (org-at-item-checkbox-p)]
16548 ; ["Insert [n/m] cookie" (progn (insert "[/]") (org-update-checkbox-count))
16549 ; (or (org-on-heading-p) (org-at-item-p))]
16550 ; ["Insert [%] cookie" (progn (insert "[%]") (org-update-checkbox-count))
16551 ; (or (org-on-heading-p) (org-at-item-p))]
16552 ; ["Update Statistics" org-update-checkbox-count t]
16554 ("Dates and Scheduling"
16555 ["Timestamp" org-time-stamp t]
16556 ["Timestamp (inactive)" org-time-stamp-inactive t]
16557 ("Change Date"
16558 ["1 Day Later" org-timestamp-up-day t]
16559 ["1 Day Earlier" org-timestamp-down-day t]
16560 ["1 ... Later" org-shiftup t]
16561 ["1 ... Earlier" org-shiftdown t])
16562 ["Compute Time Range" org-evaluate-time-range t]
16563 ["Schedule Item" org-schedule t]
16564 ["Deadline" org-deadline t]
16565 "--"
16566 ["Goto Calendar" org-goto-calendar t]
16567 ["Date from Calendar" org-date-from-calendar t])
16568 ("Logging work"
16569 ["Clock in" org-clock-in t]
16570 ["Clock out" org-clock-out t]
16571 ["Clock cancel" org-clock-cancel t]
16572 ["Display times" org-clock-display t]
16573 ["Create clock table" org-clock-report t]
16574 "--"
16575 ["Record DONE time"
16576 (progn (setq org-log-done (not org-log-done))
16577 (message "Switching to %s will %s record a timestamp"
16578 org-done-string
16579 (if org-log-done "automatically" "not")))
16580 :style toggle :selected org-log-done])
16581 "--"
16582 ["Agenda Command..." org-agenda t]
16583 ("File List for Agenda")
16584 ("Special views current file"
16585 ["TODO Tree" org-show-todo-tree t]
16586 ["Check Deadlines" org-check-deadlines t]
16587 ["Timeline" org-timeline t]
16588 ["Tags Tree" org-tags-sparse-tree t])
16589 "--"
16590 ("Hyperlinks"
16591 ["Store Link (Global)" org-store-link t]
16592 ["Insert Link" org-insert-link t]
16593 ["Follow Link" org-open-at-point t]
16594 "--"
16595 ["Descriptive Links"
16596 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16597 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
16598 ["Literal Links"
16599 (progn
16600 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16601 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
16602 "--"
16603 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
16604 (save-excursion (goto-char (point-min))
16605 (re-search-forward "<[a-z]+:" nil t))])
16606 "--"
16607 ["Export/Publish..." org-export t]
16608 ("LaTeX"
16609 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16610 :selected org-cdlatex-mode]
16611 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16612 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16613 ["Modify math symbol" org-cdlatex-math-modify
16614 (org-inside-LaTeX-fragment-p)]
16615 ["Export LaTeX fragments as images"
16616 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
16617 :style toggle :selected org-export-with-LaTeX-fragments])
16618 "--"
16619 ("Documentation"
16620 ["Show Version" org-version t]
16621 ["Info Documentation" org-info t])
16622 ("Customize"
16623 ["Browse Org Group" org-customize t]
16624 "--"
16625 ["Expand This Menu" org-create-customize-menu
16626 (fboundp 'customize-menu-create)])
16627 "--"
16628 ["Refresh setup" org-mode-restart t]
16631 (defun org-info (&optional node)
16632 "Read documentation for Org-mode in the info system.
16633 With optional NODE, go directly to that node."
16634 (interactive)
16635 (require 'info)
16636 (Info-goto-node (format "(org)%s" (or node ""))))
16638 (defun org-install-agenda-files-menu ()
16639 (let ((bl (buffer-list)))
16640 (save-excursion
16641 (while bl
16642 (set-buffer (pop bl))
16643 (if (org-mode-p) (setq bl nil)))
16644 (when (org-mode-p)
16645 (easy-menu-change
16646 '("Org") "File List for Agenda"
16647 (append
16648 (list
16649 ["Edit File List" (org-edit-agenda-file-list) t]
16650 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16651 ["Remove Current File from List" org-remove-file t]
16652 ["Cycle through agenda files" org-cycle-agenda-files t]
16653 "--")
16654 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16656 ;;; Documentation
16658 (defun org-customize ()
16659 "Call the customize function with org as argument."
16660 (interactive)
16661 (customize-browse 'org))
16663 (defun org-create-customize-menu ()
16664 "Create a full customization menu for Org-mode, insert it into the menu."
16665 (interactive)
16666 (if (fboundp 'customize-menu-create)
16667 (progn
16668 (easy-menu-change
16669 '("Org") "Customize"
16670 `(["Browse Org group" org-customize t]
16671 "--"
16672 ,(customize-menu-create 'org)
16673 ["Set" Custom-set t]
16674 ["Save" Custom-save t]
16675 ["Reset to Current" Custom-reset-current t]
16676 ["Reset to Saved" Custom-reset-saved t]
16677 ["Reset to Standard Settings" Custom-reset-standard t]))
16678 (message "\"Org\"-menu now contains full customization menu"))
16679 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16681 ;;; Miscellaneous stuff
16683 (defun org-context ()
16684 "Return a list of contexts of the current cursor position.
16685 If several contexts apply, all are returned.
16686 Each context entry is a list with a symbol naming the context, and
16687 two positions indicating start and end of the context. Possible
16688 contexts are:
16690 :headline anywhere in a headline
16691 :headline-stars on the leading stars in a headline
16692 :todo-keyword on a TODO keyword (including DONE) in a headline
16693 :tags on the TAGS in a headline
16694 :priority on the priority cookie in a headline
16695 :item on the first line of a plain list item
16696 :item-bullet on the bullet/number of a plain list item
16697 :checkbox on the checkbox in a plain list item
16698 :table in an org-mode table
16699 :table-special on a special filed in a table
16700 :table-table in a table.el table
16701 :link on a hyperline
16702 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16703 :target on a <<target>>
16704 :radio-target on a <<<radio-target>>>
16705 :latex-fragment on a LaTeX fragment
16706 :latex-preview on a LaTeX fragment with overlayed preview image
16708 This function expects the position to be visible because it uses font-lock
16709 faces as a help to recognize the following contexts: :table-special, :link,
16710 and :keyword."
16711 (let* ((f (get-text-property (point) 'face))
16712 (faces (if (listp f) f (list f)))
16713 (p (point)) clist o)
16714 ;; First the large context
16715 (cond
16716 ((org-on-heading-p)
16717 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16718 (when (progn
16719 (beginning-of-line 1)
16720 (looking-at org-todo-line-tags-regexp))
16721 (push (org-point-in-group p 1 :headline-stars) clist)
16722 (push (org-point-in-group p 2 :todo-keyword) clist)
16723 (push (org-point-in-group p 4 :tags) clist))
16724 (goto-char p)
16725 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
16726 (if (looking-at "\\[#[A-Z]\\]")
16727 (push (org-point-in-group p 0 :priority) clist)))
16729 ((org-at-item-p)
16730 (push (org-point-in-group p 2 :item-bullet) clist)
16731 (push (list :item (point-at-bol)
16732 (save-excursion (org-end-of-item) (point)))
16733 clist)
16734 (and (org-at-item-checkbox-p)
16735 (push (org-point-in-group p 0 :checkbox) clist)))
16737 ((org-at-table-p)
16738 (push (list :table (org-table-begin) (org-table-end)) clist)
16739 (if (memq 'org-formula faces)
16740 (push (list :table-special
16741 (previous-single-property-change p 'face)
16742 (next-single-property-change p 'face)) clist)))
16743 ((org-at-table-p 'any)
16744 (push (list :table-table) clist)))
16745 (goto-char p)
16747 ;; Now the small context
16748 (cond
16749 ((org-at-timestamp-p)
16750 (push (org-point-in-group p 0 :timestamp) clist))
16751 ((memq 'org-link faces)
16752 (push (list :link
16753 (previous-single-property-change p 'face)
16754 (next-single-property-change p 'face)) clist))
16755 ((memq 'org-special-keyword faces)
16756 (push (list :keyword
16757 (previous-single-property-change p 'face)
16758 (next-single-property-change p 'face)) clist))
16759 ((org-on-target-p)
16760 (push (org-point-in-group p 0 :target) clist)
16761 (goto-char (1- (match-beginning 0)))
16762 (if (looking-at org-radio-target-regexp)
16763 (push (org-point-in-group p 0 :radio-target) clist))
16764 (goto-char p))
16765 ((setq o (car (delq nil
16766 (mapcar
16767 (lambda (x)
16768 (if (memq x org-latex-fragment-image-overlays) x))
16769 (org-overlays-at (point))))))
16770 (push (list :latex-fragment
16771 (org-overlay-start o) (org-overlay-end o)) clist)
16772 (push (list :latex-preview
16773 (org-overlay-start o) (org-overlay-end o)) clist))
16774 ((org-inside-LaTeX-fragment-p)
16775 ;; FIXME: positions wrong.
16776 (push (list :latex-fragment (point) (point)) clist)))
16778 (setq clist (nreverse (delq nil clist)))
16779 clist))
16781 (defun org-point-in-group (point group &optional context)
16782 "Check if POINT is in match-group GROUP.
16783 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16784 match. If the match group does ot exist or point is not inside it,
16785 return nil."
16786 (and (match-beginning group)
16787 (>= point (match-beginning group))
16788 (<= point (match-end group))
16789 (if context
16790 (list context (match-beginning group) (match-end group))
16791 t)))
16793 (defun org-move-line-down (arg)
16794 "Move the current line down. With prefix argument, move it past ARG lines."
16795 (interactive "p")
16796 (let ((col (current-column))
16797 beg end pos)
16798 (beginning-of-line 1) (setq beg (point))
16799 (beginning-of-line 2) (setq end (point))
16800 (beginning-of-line (+ 1 arg))
16801 (setq pos (move-marker (make-marker) (point)))
16802 (insert (delete-and-extract-region beg end))
16803 (goto-char pos)
16804 (move-to-column col)))
16806 (defun org-move-line-up (arg)
16807 "Move the current line up. With prefix argument, move it past ARG lines."
16808 (interactive "p")
16809 (let ((col (current-column))
16810 beg end pos)
16811 (beginning-of-line 1) (setq beg (point))
16812 (beginning-of-line 2) (setq end (point))
16813 (beginning-of-line (- arg))
16814 (setq pos (move-marker (make-marker) (point)))
16815 (insert (delete-and-extract-region beg end))
16816 (goto-char pos)
16817 (move-to-column col)))
16819 ;; Paragraph filling stuff.
16820 ;; We want this to be just right, so use the full arsenal.
16822 (defun org-set-autofill-regexps ()
16823 (interactive)
16824 ;; In the paragraph separator we include headlines, because filling
16825 ;; text in a line directly attached to a headline would otherwise
16826 ;; fill the headline as well.
16827 (org-set-local 'comment-start-skip "^#+[ \t]*")
16828 (org-set-local 'paragraph-separate "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
16829 ;; The paragraph starter includes hand-formatted lists.
16830 (org-set-local 'paragraph-start
16831 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
16832 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16833 ;; But only if the user has not turned off tables or fixed-width regions
16834 (org-set-local
16835 'auto-fill-inhibit-regexp
16836 (concat "\\*\\|#"
16837 "\\|[ \t]*" org-keyword-time-regexp
16838 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16839 (concat
16840 "\\|[ \t]*["
16841 (if org-enable-table-editor "|" "")
16842 (if org-enable-fixed-width-editor ":" "")
16843 "]"))))
16844 ;; We use our own fill-paragraph function, to make sure that tables
16845 ;; and fixed-width regions are not wrapped. That function will pass
16846 ;; through to `fill-paragraph' when appropriate.
16847 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16848 ; Adaptive filling: To get full control, first make sure that
16849 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16850 (org-set-local 'adaptive-fill-regexp "\000")
16851 (org-set-local 'adaptive-fill-function
16852 'org-adaptive-fill-function))
16854 (defun org-fill-paragraph (&optional justify)
16855 "Re-align a table, pass through to fill-paragraph if no table."
16856 (let ((table-p (org-at-table-p))
16857 (table.el-p (org-at-table.el-p)))
16858 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
16859 (table.el-p t) ; skip table.el tables
16860 (table-p (org-table-align) t) ; align org-mode tables
16861 (t nil)))) ; call paragraph-fill
16863 ;; For reference, this is the default value of adaptive-fill-regexp
16864 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16866 (defun org-adaptive-fill-function ()
16867 "Return a fill prefix for org-mode files.
16868 In particular, this makes sure hanging paragraphs for hand-formatted lists
16869 work correctly."
16870 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
16871 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
16873 ;; Functions needed for Emacs/XEmacs region compatibility
16875 (defun org-add-hook (hook function &optional append local)
16876 "Add-hook, compatible with both Emacsen."
16877 (if (and local (featurep 'xemacs))
16878 (add-local-hook hook function append)
16879 (add-hook hook function append local)))
16881 (defun org-region-active-p ()
16882 "Is `transient-mark-mode' on and the region active?
16883 Works on both Emacs and XEmacs."
16884 (if org-ignore-region
16886 (if (featurep 'xemacs)
16887 (and zmacs-regions (region-active-p))
16888 (and transient-mark-mode mark-active))))
16890 (defun org-add-to-invisibility-spec (arg)
16891 "Add elements to `buffer-invisibility-spec'.
16892 See documentation for `buffer-invisibility-spec' for the kind of elements
16893 that can be added."
16894 (cond
16895 ((fboundp 'add-to-invisibility-spec)
16896 (add-to-invisibility-spec arg))
16897 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
16898 (setq buffer-invisibility-spec (list arg)))
16900 (setq buffer-invisibility-spec
16901 (cons arg buffer-invisibility-spec)))))
16903 (defun org-remove-from-invisibility-spec (arg)
16904 "Remove elements from `buffer-invisibility-spec'."
16905 (if (fboundp 'remove-from-invisibility-spec)
16906 (remove-from-invisibility-spec arg)
16907 (if (consp buffer-invisibility-spec)
16908 (setq buffer-invisibility-spec
16909 (delete arg buffer-invisibility-spec)))))
16911 (defun org-in-invisibility-spec-p (arg)
16912 "Is ARG a member of `buffer-invisibility-spec'?"
16913 (if (consp buffer-invisibility-spec)
16914 (member arg buffer-invisibility-spec)
16915 nil))
16917 (defun org-image-file-name-regexp ()
16918 "Return regexp matching the file names of images."
16919 (if (fboundp 'image-file-name-regexp)
16920 (image-file-name-regexp)
16921 (let ((image-file-name-extensions
16922 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16923 "xbm" "xpm" "pbm" "pgm" "ppm")))
16924 (concat "\\."
16925 (regexp-opt (nconc (mapcar 'upcase
16926 image-file-name-extensions)
16927 image-file-name-extensions)
16929 "\\'"))))
16931 ;; Functions extending outline functionality
16933 ;; C-a should go to the beginning of a *visible* line, also in the
16934 ;; new outline.el. I guess this should be patched into Emacs?
16935 (defun org-beginning-of-line ()
16936 "Go to the beginning of the current line. If that is invisible, continue
16937 to a visible line beginning. This makes the function of C-a more intuitive."
16938 (interactive)
16939 (beginning-of-line 1)
16940 (if (bobp)
16942 (backward-char 1)
16943 (if (org-invisible-p)
16944 (while (and (not (bobp)) (org-invisible-p))
16945 (backward-char 1)
16946 (beginning-of-line 1))
16947 (forward-char 1))))
16949 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16951 (defun org-invisible-p ()
16952 "Check if point is at a character currently not visible."
16953 ;; Early versions of noutline don't have `outline-invisible-p'.
16954 (if (fboundp 'outline-invisible-p)
16955 (outline-invisible-p)
16956 (get-char-property (point) 'invisible)))
16958 (defun org-invisible-p2 ()
16959 "Check if point is at a character currently not visible."
16960 (save-excursion
16961 (if (and (eolp) (not (bobp))) (backward-char 1))
16962 ;; Early versions of noutline don't have `outline-invisible-p'.
16963 (if (fboundp 'outline-invisible-p)
16964 (outline-invisible-p)
16965 (get-char-property (point) 'invisible))))
16967 (defalias 'org-back-to-heading 'outline-back-to-heading)
16968 (defalias 'org-on-heading-p 'outline-on-heading-p)
16970 (defun org-on-target-p ()
16971 (let ((pos (point)))
16972 (save-excursion
16973 (skip-chars-forward "<")
16974 (and (re-search-backward "<<" nil t)
16975 (or (looking-at org-radio-target-regexp)
16976 (looking-at org-target-regexp))
16977 (<= (match-beginning 0) pos)
16978 (>= (1+ (match-end 0)) pos)))))
16980 (defun org-up-heading-all (arg)
16981 "Move to the heading line of which the present line is a subheading.
16982 This function considers both visible and invisible heading lines.
16983 With argument, move up ARG levels."
16984 (if (fboundp 'outline-up-heading-all)
16985 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16986 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16988 (defun org-show-hidden-entry ()
16989 "Show an entry where even the heading is hidden."
16990 (save-excursion
16991 (org-show-entry)))
16993 (defun org-flag-heading (flag &optional entry)
16994 "Flag the current heading. FLAG non-nil means make invisible.
16995 When ENTRY is non-nil, show the entire entry."
16996 (save-excursion
16997 (org-back-to-heading t)
16998 ;; Check if we should show the entire entry
16999 (if entry
17000 (progn
17001 (org-show-entry)
17002 (save-excursion
17003 (and (outline-next-heading)
17004 (org-flag-heading nil))))
17005 (outline-flag-region (max 1 (1- (point)))
17006 (save-excursion (outline-end-of-heading) (point))
17007 flag))))
17009 (defun org-end-of-subtree (&optional invisible-OK)
17010 ;; This is an exact copy of the original function, but it uses
17011 ;; `org-back-to-heading', to make it work also in invisible
17012 ;; trees. And is uses an invisible-OK argument.
17013 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
17014 (org-back-to-heading invisible-OK)
17015 (let ((first t)
17016 (level (funcall outline-level)))
17017 (while (and (not (eobp))
17018 (or first (> (funcall outline-level) level)))
17019 (setq first nil)
17020 (outline-next-heading))
17021 (if (memq (preceding-char) '(?\n ?\^M))
17022 (progn
17023 ;; Go to end of line before heading
17024 (forward-char -1)
17025 (if (memq (preceding-char) '(?\n ?\^M))
17026 ;; leave blank line before heading
17027 (forward-char -1)))))
17028 (point))
17030 (defun org-show-subtree ()
17031 "Show everything after this heading at deeper levels."
17032 (outline-flag-region
17033 (point)
17034 (save-excursion
17035 (outline-end-of-subtree) (outline-next-heading) (point))
17036 nil))
17038 (defun org-show-entry ()
17039 "Show the body directly following this heading.
17040 Show the heading too, if it is currently invisible."
17041 (interactive)
17042 (save-excursion
17043 (org-back-to-heading t)
17044 (outline-flag-region
17045 (max 1 (1- (point)))
17046 (save-excursion
17047 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
17048 (or (match-beginning 1) (point-max)))
17049 nil)))
17051 (defun org-make-options-regexp (kwds)
17052 "Make a regular expression for keyword lines."
17053 (concat
17055 "#?[ \t]*\\+\\("
17056 (mapconcat 'regexp-quote kwds "\\|")
17057 "\\):[ \t]*"
17058 "\\(.+\\)"))
17060 ;; Make `bookmark-jump' show the jump location if it was hidden.
17061 (eval-after-load "bookmark"
17062 '(if (boundp 'bookmark-after-jump-hook)
17063 ;; We can use the hook
17064 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
17065 ;; Hook not available, use advice
17066 (defadvice bookmark-jump (after org-make-visible activate)
17067 "Make the position visible."
17068 (org-bookmark-jump-unhide))))
17070 (defun org-bookmark-jump-unhide ()
17071 "Unhide the current position, to show the bookmark location."
17072 (and (org-mode-p)
17073 (or (org-invisible-p)
17074 (save-excursion (goto-char (max (point-min) (1- (point))))
17075 (org-invisible-p)))
17076 (org-show-hierarchy-above 'bookmark-jump)))
17078 ;;; Experimental code
17080 ;(add-hook 'org-load-hook
17081 ; (lambda ()
17082 ; (defun outline-show-heading ()
17083 ; "Show the current heading and move to its end."
17084 ; (outline-flag-region
17085 ; (- (point)
17086 ; (cond
17087 ; ((bobp) 0)
17088 ; ((equal (buffer-substring
17089 ; (max (point-min) (- (point) 3)) (point))
17090 ; "\n\n\n")
17091 ; 2)
17092 ; (t 1)))
17093 ; (progn (outline-end-of-heading) (point))
17094 ; nil))))
17098 ;;; Finish up
17100 (provide 'org)
17102 (run-hooks 'org-load-hook)
17104 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
17105 ;;; org.el ends here