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.
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/
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)
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 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
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 a NOTES file that contains
34 ;; information about projects as plain text. Org-mode is implemented on top
35 ;; of outline-mode - ideal to keep the content of large files well structured.
36 ;; It supports ToDo items, deadlines and time stamps, which can be extracted
37 ;; to create a daily/weekly agenda that also integrates the diary of the Emacs
38 ;; calendar. Tables are easily created with a built-in table editor. Plain
39 ;; text URL-like links connect to websites, emails (VM, RMAIL, WANDERLUST),
40 ;; Usenet messages (Gnus), BBDB entries, and any files related to the
41 ;; projects. For printing and sharing of notes, an Org-mode file (or a part
42 ;; of it) can be exported as a structured ASCII file, or as HTML.
46 ;; If Org-mode is part of the Emacs distribution or an XEmacs package, you
47 ;; only need to copy the following lines to your .emacs file. The last two
48 ;; lines define *global* keys for the commands `org-store-link' and
49 ;; `org-agenda' - please choose suitable keys yourself.
51 ;; (add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
52 ;; (define-key global-map "\C-cl" 'org-store-link)
53 ;; (define-key global-map "\C-ca" 'org-agenda)
55 ;; If you have downloaded Org-mode from the Web, you must byte-compile
56 ;; org.el and put it on your load path. In addition to the Emacs Lisp
57 ;; lines above, you also need to add the following lines to .emacs:
59 ;; (autoload 'org-mode "org" "Org mode" t)
60 ;; (autoload 'org-diary "org" "Diary entries from Org mode")
61 ;; (autoload 'org-agenda "org" "Multi-file agenda from Org mode" t)
62 ;; (autoload 'org-store-link "org" "Store a link to the current location" t)
63 ;; (autoload 'orgtbl-mode "org" "Org tables as a minor mode" t)
64 ;; (autoload 'turn-on-orgtbl "org" "Org tables as a minor mode")
66 ;; This setup will put all files with extension ".org" into Org-mode. As
67 ;; an alternative, make the first line of a file look like this:
69 ;; MY PROJECTS -*- mode: org; -*-
71 ;; which will select Org-mode for this buffer no matter what the file's
76 ;; The documentation of Org-mode can be found in the TeXInfo file. The
77 ;; distribution also contains a PDF version of it. At the homepage of
78 ;; Org-mode, you can read the same text online as HTML. There is also an
79 ;; excellent reference card made by Philip Rooke. This card can be found
80 ;; in the etc/ directory of Emacs 22.
82 ;; Changes since version 4.00:
83 ;; ---------------------------
85 ;; - Revision of the font-lock faces section, with better tty support.
86 ;; - TODO keywords in Agenda buffer are fontified.
87 ;; - Export converts links between .org files to links between .html files.
88 ;; - Better support for bold/italic/underline emphasis.
98 ;; - In agenda buffer, mouse-1 no longer follows link.
99 ;; See `org-agenda-mouse-1-follows-link' and `org-mouse-1-follows-link'.
102 ;; - Links use now the [[link][description]] format by default.
103 ;; When inserting links, the user is prompted for a description.
104 ;; - If a link has a description, only the description is displayed
105 ;; the link part is hidden. Use C-c C-l to edit the link part.
106 ;; - TAGS are now bold, but in the same color as the headline.
107 ;; - The width of a table column can be limited by using a field "<N>".
108 ;; - New structure for the customization tree.
112 ;; - The list of agenda files can be maintainted in an external file.
116 ;; - Templates for remember buffer. Note that the remember setup changes.
117 ;; To set up templates, see `org-remember-templates'.
118 ;; - The time in new time stamps can be rounded, see new option
119 ;; `org-time-stamp-rounding-minutes'.
120 ;; - Bug fixes (there are *always* more bugs).
127 ;; - Small improvements to font-lock support.
128 ;; - MHE support finalized.
132 ;; - Improved MHE support
136 ;; - Leading stars in headlines can be hidden, so make the outline look
138 ;; - Mouse-1 can be used to follow links.
141 ;; - HTML exporter treats targeted internal links.
145 ;; - Changes to internal link system (thanks to David Wainberg for ideas).
146 ;; - in-file links: [[Search String]] instead of <file:::Search String>
147 ;; - automatic links to "radio targets".
148 ;; - CamelCase not longer active by default, configure org-activate-camels
149 ;; if you want to turn it back on.
150 ;; - After following a link, `C-c &' jumps back to it.
151 ;; - MH-E link support (thanks to Thomas Baumann).
152 ;; - Special table lines are no longer exported.
153 ;; - Bug fixes and minor improvements.
156 ;; - Cleanup tags display in agenda.
160 ;; - Table alignment fixed for use with wide characters.
161 ;; - `C-c -' leaves cursor in current table line.
162 ;; - The current TAG can be incorporated into the agenda prefix.
163 ;; See option `org-agenda-prefix-format' for details.
166 ;; - Minor bug fixes and improvements around tag searches.
167 ;; - XEmacs compatibility fixes.
170 ;; - Tags can also be set remotely from agenda buffer.
171 ;; - Boolean logic for tag searches.
172 ;; - Additional agenda commands can be configured through the variable
173 ;; `org-agenda-custom-commands'.
174 ;; - Minor bug fixes.
185 (defvar calc-embedded-close-formula) ; defined by the calc package
186 (defvar calc-embedded-open-formula) ; defined by the calc package
187 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
189 ;;; Customization variables
191 (defvar org-version "4.25"
192 "The version number of the file org.el.")
193 (defun org-version ()
195 (message "Org-mode version %s" org-version))
197 ;; The following constant is for compatibility with different versions
199 (defconst org-noutline-p (featurep 'noutline)
200 "Are we using the new outline mode?")
201 (defconst org-xemacs-p (featurep 'xemacs)) ;; FIXME: used by external code?
202 (defconst org-format-transports-properties-p
204 (add-text-properties 0 1 '(test t) x)
205 (get-text-property 0 'test (format "%s" x)))
206 "Does format transport text properties?")
209 "Outline-based notes management and organizer."
215 (defgroup org-startup nil
216 "Options concerning startup of Org-mode."
220 (defcustom org-startup-folded t
221 "Non-nil means, entering Org-mode will switch to OVERVIEW.
222 This can also be configured on a per-file basis by adding one of
223 the following lines anywhere in the buffer:
230 (const :tag "nofold: show all" nil)
231 (const :tag "fold: overview" t)
232 (const :tag "content: all headlines" content)))
234 (defcustom org-startup-truncated t
235 "Non-nil means, entering Org-mode will set `truncate-lines'.
236 This is useful since some lines containing links can be very long and
237 uninteresting. Also tables look terrible when wrapped."
241 (defcustom org-startup-align-all-tables nil
242 "Non-nil means, align all tables when visiting a file.
243 This is useful when the column width in tables is forced with <N> cookies
244 in table fields. Such tables will look correct only after the first re-align.
245 This can also be configured on a per-file basis by adding one of
246 the following lines anywhere in the buffer:
252 (defcustom org-startup-with-deadline-check nil
253 "Non-nil means, entering Org-mode will run the deadline check.
254 This means, if you start editing an org file, you will get an
255 immediate reminder of any due deadlines.
256 This can also be configured on a per-file basis by adding one of
257 the following lines anywhere in the buffer:
259 #+STARTUP: nodlcheck"
263 (defcustom org-insert-mode-line-in-empty-file nil
264 "Non-nil means insert the first line setting Org-mode in empty files.
265 When the function `org-mode' is called interactively in an empty file, this
266 normally means that the file name does not automatically trigger Org-mode.
267 To ensure that the file will always be in Org-mode in the future, a
268 line enforcing Org-mode will be inserted into the buffer, if this option
273 (defcustom org-CUA-compatible nil
274 "Non-nil means use alternative key bindings for S-<cursor movement>.
275 Org-mode used S-<cursor movement> for changing timestamps and priorities.
276 S-<cursor movement> is also used for example by `CUA-mode' to select text.
277 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
278 alternative bindings. Setting this variable to t will replace the following
279 keys both in Org-mode and in the Org-agenda buffer.
287 If you do not like the alternative keys, take a look at the variable
290 This option is only relevant at load-time of Org-mode. Changing it requires
291 a restart of Emacs to become effective."
295 (defvar org-disputed-keys
296 '((S-up [(shift up)] [(meta ?p)])
297 (S-down [(shift down)] [(meta ?n)])
298 (S-left [(shift left)] [(meta ?-)])
299 (S-right [(shift right)] [(meta ?+)])
300 (S-return [(shift return)] [(control shift return)]))
301 "Keys for which Org-mode and other modes compete.
302 This is an alist, cars are symbols for lookup, 1st element is the default key,
303 second element will be used when `org-CUA-compatible' is t.")
306 "Select a key according to `org-CUA-compatible'."
307 (nth (if org-CUA-compatible 2 1)
308 (or (assq key org-disputed-keys)
309 (error "Invalid Key %s in `org-key'" key))))
311 (defcustom org-ellipsis nil
312 "The ellipsis to use in the Org-mode outline.
313 When nil, just use the standard three dots. When a string, use that instead,
314 and just in Org-mode (which will then use its own display table).
315 Changing this requires executing `M-x org-mode' in a buffer to become
318 :type '(choice (const :tag "Default" nil)
319 (string :tag "String" :value "...#")))
321 (defvar org-display-table nil
322 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
324 (defgroup org-keywords nil
325 "Keywords in Org-mode."
329 (defcustom org-deadline-string "DEADLINE:"
330 "String to mark deadline entries.
331 A deadline is this string, followed by a time stamp. Should be a word,
332 terminated by a colon. You can insert a schedule keyword and
333 a timestamp with \\[org-deadline].
334 Changes become only effective after restarting Emacs."
338 (defcustom org-scheduled-string "SCHEDULED:"
339 "String to mark scheduled TODO entries.
340 A schedule is this string, followed by a time stamp. Should be a word,
341 terminated by a colon. You can insert a schedule keyword and
342 a timestamp with \\[org-schedule].
343 Changes become only effective after restarting Emacs."
347 (defcustom org-closed-string "CLOSED:"
348 "String used as the prefix for timestamps logging closing a TODO entry."
352 (defcustom org-comment-string "COMMENT"
353 "Entries starting with this keyword will never be exported.
354 An entry can be toggled between COMMENT and normal with
355 \\[org-toggle-comment].
356 Changes become only effective after restarting Emacs."
360 (defcustom org-quote-string "QUOTE"
361 "Entries starting with this keyword will be exported in fixed-width font.
362 Quoting applies only to the text in the entry following the headline, and does
363 not extend beyond the next headline, even if that is lower level.
364 An entry can be toggled between QUOTE and normal with
365 \\[org-toggle-fixed-width-section]."
369 (defgroup org-structure nil
370 "Options concerning the general structure of Org-mode files."
374 (defgroup org-cycle nil
375 "Options concerning visibility cycling in Org-mode."
377 :group 'org-structure)
379 (defcustom org-cycle-emulate-tab t
380 "Where should `org-cycle' emulate TAB.
382 white Only in completely white lines
383 t Everywhere except in headlines"
385 :type '(choice (const :tag "Never" nil)
386 (const :tag "Only in completely white lines" white)
387 (const :tag "Everywhere except in headlines" t)
390 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
391 "Hook that is run after `org-cycle' has changed the buffer visibility.
392 The function(s) in this hook must accept a single argument which indicates
393 the new state that was set by the most recent `org-cycle' command. The
394 argument is a symbol. After a global state change, it can have the values
395 `overview', `content', or `all'. After a local state change, it can have
396 the values `folded', `children', or `subtree'."
400 (defgroup org-edit-structure nil
401 "Options concerning structure editing in Org-mode."
402 :tag "Org Edit Structure"
403 :group 'org-structure)
405 (defcustom org-odd-levels-only nil
406 "Non-nil means, skip even levels and only use odd levels for the outline.
407 This has the effect that two stars are being added/taken away in
408 promotion/demotion commands. It also influences how levels are
409 handled by the exporters.
410 Changing it requires restart of `font-lock-mode' to become effective
411 for fontification also in regions already fontified.
412 You may also set this on a per-file basis by adding one of the following
417 :group 'org-edit-structure
418 :group 'org-font-lock
421 (defcustom org-adapt-indentation t
422 "Non-nil means, adapt indentation when promoting and demoting.
423 When this is set and the *entire* text in an entry is indented, the
424 indentation is increased by one space in a demotion command, and
425 decreased by one in a promotion command. If any line in the entry
426 body starts at column 0, indentation is not changed at all."
427 :group 'org-edit-structure
430 (defcustom org-enable-fixed-width-editor t
431 "Non-nil means, lines starting with \":\" are treated as fixed-width.
432 This currently only means, they are never auto-wrapped.
433 When nil, such lines will be treated like ordinary lines.
434 See also the QUOTE keyword."
435 :group 'org-edit-structure
438 (defgroup org-sparse-trees nil
439 "Options concerning sparse trees in Org-mode."
440 :tag "Org Sparse Trees"
441 :group 'org-structure)
443 (defcustom org-highlight-sparse-tree-matches t
444 "Non-nil means, highlight all matches that define a sparse tree.
445 The highlights will automatically disappear the next time the buffer is
446 changed by an edit command."
447 :group 'org-sparse-trees
450 (defcustom org-show-hierarchy-above t
451 "Non-nil means, show full hierarchy when showing a spot in the tree.
452 Turning this off makes sparse trees more compact, but also less clear."
453 :group 'org-sparse-trees
456 (defcustom org-show-following-heading t
457 "Non-nil means, show heading following match in `org-occur'.
458 When doing an `org-occur' it is useful to show the headline which
459 follows the match, even if they do not match the regexp. This makes it
460 easier to edit directly inside the sparse tree. However, if you use
461 `org-occur' mainly as an overview, the following headlines are
462 unnecessary clutter."
463 :group 'org-sparse-trees
466 (defcustom org-occur-hook '(org-first-headline-recenter)
467 "Hook that is run after `org-occur' has constructed a sparse tree.
468 This can be used to recenter the window to show as much of the structure
470 :group 'org-sparse-trees
473 (defgroup org-plain-lists nil
474 "Options concerning plain lists in Org-mode."
475 :tag "Org Plain lists"
476 :group 'org-structure)
478 (defcustom org-cycle-include-plain-lists nil
479 "Non-nil means, include plain lists into visibility cycling.
480 This means that during cycling, plain list items will *temporarily* be
481 interpreted as outline headlines with a level given by 1000+i where i is the
482 indentation of the bullet. In all other operations, plain list items are
483 not seen as headlines. For example, you cannot assign a TODO keyword to
485 :group 'org-plain-lists
489 (defcustom org-plain-list-ordered-item-terminator t
490 "The character that makes a line with leading number an ordered list item.
491 Valid values are ?. and ?\). To get both terminators, use t. While
492 ?. may look nicer, it creates the danger that a line with leading
493 number may be incorrectly interpreted as an item. ?\) therefore is
495 :group 'org-plain-lists
496 :type '(choice (const :tag "dot like in \"2.\"" ?.)
497 (const :tag "paren like in \"2)\"" ?\))
498 (const :tab "both" t)))
500 (defcustom org-auto-renumber-ordered-lists t
501 "Non-nil means, automatically renumber ordered plain lists.
502 Renumbering happens when the sequence have been changed with
503 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
504 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
505 :group 'org-plain-lists
508 (defgroup org-archive nil
509 "Options concerning archiving in Org-mode."
511 :group 'org-structure)
513 (defcustom org-archive-location "%s_archive::"
514 "The location where subtrees should be archived.
515 This string consists of two parts, separated by a double-colon.
517 The first part is a file name - when omitted, archiving happens in the same
518 file. %s will be replaced by the current file name (without directory part).
519 Archiving to a different file is useful to keep archived entries from
520 contributing to the Org-mode Agenda.
522 The part after the double colon is a headline. The archived entries will be
523 filed under that headline. When omitted, the subtrees are simply filed away
524 at the end of the file, as top-level entries.
526 Here are a few examples:
528 If the current file is Projects.org, archive in file
529 Projects.org_archive, as top-level trees. This is the default.
531 \"::* Archived Tasks\"
532 Archive in the current file, under the top-level headline
533 \"* Archived Tasks\".
535 \"~/org/archive.org::\"
536 Archive in file ~/org/archive.org (absolute path), as top-level trees.
538 \"basement::** Finished Tasks\"
539 Archive in file ./basement (relative path), as level 3 trees
540 below the level 2 heading \"** Finished Tasks\".
542 You may set this option on a per-file basis by adding to the buffer a
545 #+ARCHIVE: basement::** Finished Tasks"
549 (defcustom org-archive-mark-done t
550 "Non-nil means, mark archived entries as DONE."
554 (defcustom org-archive-stamp-time t
555 "Non-nil means, add a time stamp to archived entries.
556 The time stamp will be added directly after the TODO state keyword in the
557 first line, so it is probably best to use this in combinations with
558 `org-archive-mark-done'."
562 (defgroup org-table nil
563 "Options concerning tables in Org-mode."
567 (defcustom org-enable-table-editor 'optimized
568 "Non-nil means, lines starting with \"|\" are handled by the table editor.
569 When nil, such lines will be treated like ordinary lines.
571 When equal to the symbol `optimized', the table editor will be optimized to
573 - Use automatic overwrite mode in front of whitespace in table fields.
574 This make the structure of the table stay in tact as long as the edited
575 field does not exceed the column width.
576 - Minimize the number of realigns. Normally, the table is aligned each time
577 TAB or RET are pressed to move to another field. With optimization this
578 happens only if changes to a field might have changed the column width.
579 Optimization requires replacing the functions `self-insert-command',
580 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
581 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
582 very good at guessing when a re-align will be necessary, but you can always
583 force one with \\[org-ctrl-c-ctrl-c].
585 If you would like to use the optimized version in Org-mode, but the
586 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
588 This variable can be used to turn on and off the table editor during a session,
589 but in order to toggle optimization, a restart is required.
591 See also the variable `org-table-auto-blank-field'."
594 (const :tag "off" nil)
596 (const :tag "on, optimized" optimized)))
598 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
599 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
600 In the optimized version, the table editor takes over all simple keys that
601 normally just insert a character. In tables, the characters are inserted
602 in a way to minimize disturbing the table structure (i.e. in overwrite mode
603 for empty fields). Outside tables, the correct binding of the keys is
606 The default for this option is t if the optimized version is also used in
607 Org-mode. See the variable `org-enable-table-editor' for details. Changing
608 this variable requires a restart of Emacs to become effective."
612 (defgroup org-table-settings nil
613 "Settings for tables in Org-mode."
614 :tag "Org Table Settings"
617 (defcustom org-table-default-size "5x2"
618 "The default size for newly created tables, Columns x Rows."
619 :group 'org-table-settings
622 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
623 "Regular expression for recognizing numbers in table columns.
624 If a table column contains mostly numbers, it will be aligned to the
625 right. If not, it will be aligned to the left.
627 The default value of this option is a regular expression which allows
628 anything which looks remotely like a number as used in scientific
629 context. For example, all of the following will be considered a
631 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
633 Other options offered by the customize interface are more restrictive."
634 :group 'org-table-settings
636 (const :tag "Positive Integers"
638 (const :tag "Integers"
640 (const :tag "Floating Point Numbers"
641 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
642 (const :tag "Floating Point Number or Integer"
643 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
644 (const :tag "Exponential, Floating point, Integer"
645 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
646 (const :tag "Very General Number-Like"
647 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
648 (string :tag "Regexp:")))
650 (defcustom org-table-number-fraction 0.5
651 "Fraction of numbers in a column required to make the column align right.
652 In a column all non-white fields are considered. If at least this
653 fraction of fields is matched by `org-table-number-fraction',
654 alignment to the right border applies."
655 :group 'org-table-settings
658 (defgroup org-table-editing nil
659 "Bahavior of tables during editing in Org-mode."
660 :tag "Org Table Editing"
663 (defcustom org-table-automatic-realign t
664 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
665 When nil, aligning is only done with \\[org-table-align], or after column
667 :group 'org-table-editing
670 (defcustom org-table-limit-column-width t ;kw
671 "Non-nil means, allow to limit the width of table columns with <N> fields."
672 :group 'org-table-editing
675 (defcustom org-table-auto-blank-field t
676 "Non-nil means, automatically blank table field when starting to type into it.
677 This only happens when typing immediately after a field motion
678 command (TAB, S-TAB or RET).
679 Only relevant when `org-enable-table-editor' is equal to `optimized'."
680 :group 'org-table-editing
683 (defcustom org-table-tab-jumps-over-hlines t
684 "Non-nil means, tab in the last column of a table with jump over a hline.
685 If a horizontal separator line is following the current line,
686 `org-table-next-field' can either create a new row before that line, or jump
687 over the line. When this option is nil, a new line will be created before
689 :group 'org-table-editing
692 (defcustom org-table-tab-recognizes-table.el t
693 "Non-nil means, TAB will automatically notice a table.el table.
694 When it sees such a table, it moves point into it and - if necessary -
695 calls `table-recognize-table'."
696 :group 'org-table-editing
699 (defgroup org-table-calculation nil
700 "Options concerning tables in Org-mode."
701 :tag "Org Table Calculation"
704 (defcustom org-table-copy-increment t
705 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
706 :group 'org-table-calculation
709 (defcustom org-calc-default-modes
710 '(calc-internal-prec 12
711 calc-float-format (float 5)
714 calc-symbolic-mode nil
715 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
716 calc-display-working-message t
718 "List with Calc mode settings for use in calc-eval for table formulas.
719 The list must contain alternating symbols (Calc modes variables and values).
720 Don't remove any of the default settings, just change the values. Org-mode
721 relies on the variables to be present in the list."
722 :group 'org-table-calculation
725 (defcustom org-table-formula-evaluate-inline t
726 "Non-nil means, TAB and RET evaluate a formula in current table field.
727 If the current field starts with an equal sign, it is assumed to be a formula
728 which should be evaluated as described in the manual and in the documentation
729 string of the command `org-table-eval-formula'. This feature requires the
731 When this variable is nil, formula calculation is only available through
732 the command \\[org-table-eval-formula]."
733 :group 'org-table-calculation
737 (defcustom org-table-formula-use-constants t
738 "Non-nil means, interpret constants in formulas in tables.
739 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
740 by the value given in `org-table-formula-constants', or by a value obtained
741 from the `constants.el' package."
742 :group 'org-table-calculation
745 (defcustom org-table-formula-constants nil
746 "Alist with constant names and values, for use in table formulas.
747 The car of each element is a name of a constant, without the `$' before it.
748 The cdr is the value as a string. For example, if you'd like to use the
749 speed of light in a formula, you would configure
751 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
753 and then use it in an equation like `$1*$c'."
754 :group 'org-table-calculation
756 (cons (string :tag "name")
757 (string :tag "value"))))
759 (defcustom org-table-formula-numbers-only nil
760 "Non-nil means, calculate only with numbers in table formulas.
761 Then all input fields will be converted to a number, and the result
762 must also be a number. When nil, calc's full potential is available
763 in table calculations, including symbolics etc."
764 :group 'org-table-calculation
767 (defcustom org-table-allow-automatic-line-recalculation t
768 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
769 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
770 :group 'org-table-calculation
773 (defgroup org-link nil
774 "Options concerning links in Org-mode."
778 (defcustom org-descriptive-links t
779 "Non-nil means, hide link part and only show description of bracket links.
780 Bracket links are like [[link][descritpion]]. This variable sets the initial
781 state in new org-mode buffers. The setting can then be toggled on a
782 per-buffer basis from the Org->Hyperlinks menu."
786 (defcustom org-link-style 'bracket
787 "The style of links to be inserted with \\[org-insert-link].
789 bracket [[link][description]]. This is recommended
790 plain Description \\n link. The old way, no longer recommended."
793 (const :tag "Bracket (recommended)" bracket)
794 (const :tag "Plain (no longer recommended)" plain)))
796 (defcustom org-link-format "%s"
797 "Default format for external, URL-like linkes in the buffer.
798 This is a format string for printf, %s will be replaced by the link text.
799 The recommended value is just \"%s\", since links will be protected by
800 enclosing them in double brackets. If you prefer plain links (see variable
801 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
802 additional URL: prefix, so the format would be \"<URL:%s>\"."
805 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
806 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
807 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
808 (string :tag "Other" :value "<%s>")))
810 (defcustom org-activate-links '(bracket angle plain radio tag date)
811 "Types of links that should be activated in Org-mode files.
812 This is a list of symbols, each leading to the activation of a certain link
813 type. In principle, it does not hurt to turn on most link types - there may
814 be a small gain when turning off unused link types. The types are:
816 bracket The recommended [[link][description]] or [[link]] links with hiding.
817 angular Links in angular brackes that may contain whitespace like
818 <bbdb:Carsten Dominik>.
819 plain Plain links in normal text, no whitespace, like http://google.com.
820 radio Text that is matched by a radio target, see manual for details.
821 tag Tag settings in a headline (link to tag search).
822 date Time stamps (link to calendar).
823 camel CamelCase words defining text searches.
825 Changing this variable requires a restart of Emacs to become effective."
827 :type '(set (const :tag "Double bracket links (new style)" bracket)
828 (const :tag "Angular bracket links (old style)" angular)
829 (const :tag "plain text links" plain)
830 (const :tag "Radio target matches" radio)
831 (const :tag "Tags" tag)
832 (const :tag "Timestamps" date)
833 (const :tag "CamelCase words" camel)))
835 (defgroup org-link-store nil
836 "Options concerning storing links in Org-mode"
837 :tag "Org Store Link"
840 (defcustom org-context-in-file-links t
841 "Non-nil means, file links from `org-store-link' contain context.
842 A search string will be added to the file name with :: as separator and
843 used to find the context when the link is activated by the command
845 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
846 negates this setting for the duration of the command."
847 :group 'org-link-store
850 (defcustom org-file-link-context-use-camel-case nil
851 "Non-nil means, use CamelCase to store a search context in a file link.
852 When nil, the search string simply consists of the words of the string.
853 CamelCase is deprecated, and support for it may be dropped in the future."
854 :group 'org-link-store
857 (defcustom org-keep-stored-link-after-insertion nil
858 "Non-nil means, keep link in list for entire session.
860 The command `org-store-link' adds a link pointing to the current
861 location to an internal list. These links accumulate during a session.
862 The command `org-insert-link' can be used to insert links into any
863 Org-mode file (offering completion for all stored links). When this
864 option is nil, every link which has been inserted once using \\[org-insert-link]
865 will be removed from the list, to make completing the unused links
867 :group 'org-link-store
870 (defcustom org-usenet-links-prefer-google nil
871 "Non-nil means, `org-store-link' will create web links to Google groups.
872 When nil, Gnus will be used for such links.
873 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
874 negates this setting for the duration of the command."
875 :group 'org-link-store
878 (defgroup org-link-follow nil
879 "Options concerning following links in Org-mode"
880 :tag "Org Follow Link"
883 (defcustom org-tab-follows-link nil
884 "Non-nil means, on links TAB will follow the link.
885 Needs to be set before org.el is loaded."
886 :group 'org-link-follow
889 (defcustom org-return-follows-link nil
890 "Non-nil means, on links RET will follow the link.
891 Needs to be set before org.el is loaded."
892 :group 'org-link-follow
895 (defcustom org-mouse-1-follows-link t
896 "Non-nil means, mouse-1 on a link will follow the link.
897 A longer mouse click will still set point. Does not wortk on XEmacs.
898 Needs to be set before org.el is loaded."
899 :group 'org-link-follow
902 (defcustom org-mark-ring-length 4
903 "Number of different positions to be recorded in the ring
904 Changing this requires a restart of Emacs to work correctly."
905 :group 'org-link-follow
908 (defcustom org-link-frame-setup
909 '((vm . vm-visit-folder-other-frame)
910 (gnus . gnus-other-frame)
911 (file . find-file-other-window))
912 "Setup the frame configuration for following links.
913 When following a link with Emacs, it may often be useful to display
914 this link in another window or frame. This variable can be used to
915 set this up for the different types of links.
918 `vm-visit-folder-other-frame'
924 `find-file-other-window'
925 `find-file-other-frame'
926 For the calendar, use the variable `calendar-setup'.
927 For BBDB, it is currently only possible to display the matches in
929 :group 'org-link-follow
933 (const vm-visit-folder)
934 (const vm-visit-folder-other-window)
935 (const vm-visit-folder-other-frame)))
939 (const gnus-other-frame)))
943 (const find-file-other-window)
944 (const find-file-other-frame)))))
946 (defcustom org-open-non-existing-files nil
947 "Non-nil means, `org-open-file' will open non-existing file.
948 When nil, an error will be generated."
949 :group 'org-link-follow
952 (defcustom org-confirm-shell-links 'yes-or-no-p
953 "Non-nil means, ask for confirmation before executing shell links.
954 Shell links can be dangerous, just thing about a link
956 [[shell:rm -rf ~/*][Google Search]]
958 This link would show up in your Org-mode document as \"Google Search\"
959 but really it would remove your entire home directory. Dangerous indeed.
960 Therefore I *definitely* advise agains setting this varaiable to nil.
961 Just change it to `y-or-n-p' of you want to confirm with a single key press
962 rather than having to type \"yes\"."
963 :group 'org-link-follow
965 (const :tag "with yes-or-no (safer)" yes-or-no-p)
966 (const :tag "with y-or-n (faster)" y-or-n-p)
967 (const :tag "no confirmation (dangerous)" nil)))
969 (defconst org-file-apps-defaults-gnu
971 "Default file applications on a UNIX or GNU/Linux system.
972 See `org-file-apps'.")
974 (defconst org-file-apps-defaults-macosx
982 "Default file applications on a MacOS X system.
983 The system \"open\" is known as a default, but we use X11 applications
984 for some files for which the OS does not have a good default.
985 See `org-file-apps'.")
987 (defconst org-file-apps-defaults-windowsnt
988 '((t . (w32-shell-execute "open" file)))
989 "Default file applications on a Windows NT system.
990 The system \"open\" is used for most files.
991 See `org-file-apps'.")
993 (defcustom org-file-apps
1001 "External applications for opening `file:path' items in a document.
1002 Org-mode uses system defaults for different file types, but
1003 you can use this variable to set the application for a given file
1004 extension. The entries in this list are cons cells with a file extension
1005 and the corresponding command. Possible values for the command are:
1006 `emacs' The file will be visited by the current Emacs process.
1007 `default' Use the default application for this file type.
1008 string A command to be executed by a shell; %s will be replaced
1009 by the path to the file.
1010 sexp A Lisp form which will be evaluated. The file path will
1011 be available in the Lisp variable `file'.
1012 For more examples, see the system specific constants
1013 `org-file-apps-defaults-macosx'
1014 `org-file-apps-defaults-windowsnt'
1015 `org-file-apps-defaults-gnu'."
1016 :group 'org-link-follow
1018 (cons (choice :value ""
1019 (string :tag "Extension")
1020 (const :tag "Default for unrecognized files" t)
1021 (const :tag "Links to a directory" directory))
1023 (const :tag "Visit with Emacs" emacs)
1024 (const :tag "Use system default" default)
1025 (string :tag "Command")
1026 (sexp :tag "Lisp form")))))
1028 (defcustom org-mhe-search-all-folders nil
1029 "Non-nil means, that the search for the mh-message will be extended to
1030 all folders if the message cannot be found in the folder given in the link.
1031 Searching all folders is very effective with one of the search engines
1032 supported by MH-E, but will be slow with pick."
1033 :group 'org-link-follow
1036 (defgroup org-remember nil
1037 "Options concerning interaction with remember.el."
1041 (defcustom org-directory "~/org"
1042 "Directory with org files.
1043 This directory will be used as default to prompt for org files.
1044 Used by the hooks for remember.el."
1045 :group 'org-remember
1048 (defcustom org-default-notes-file "~/.notes"
1049 "Default target for storing notes.
1050 Used by the hooks for remember.el. This can be a string, or nil to mean
1051 the value of `remember-data-file'."
1052 :group 'org-remember
1054 (const :tag "Default from remember-data-file" nil)
1057 (defcustom org-remember-templates nil
1058 "Templates for the creation of remember buffers.
1059 When nil, just let remember make the buffer.
1060 When not nil, this is a list of 3-element lists. In each entry, the first
1061 element is a character, a unique key to select this template.
1062 The second element is the template. The third element is optional and can
1063 specify a destination file for remember items created with this template.
1064 The default file is given by `org-default-notes-file'.
1066 The template specifies the structure of the remember buffer. It should have
1067 a first line starting with a star, to act as the org-mode headline.
1068 Furthermore, the following %-escapes will be replaced with content:
1069 %t time stamp, date only
1070 %T time stamp with date and time
1071 %u inactive time stamp, date only
1072 %U inactive time stamp with date and time
1074 %a annotation, normally the link created with org-store-link
1075 %i initial content, the region when remember is called with C-u.
1076 If %i is indented, the entire inserted text will be indented as well.
1077 %? This will be removed, and the cursor placed at this position."
1078 :group 'org-remember
1079 :type '(repeat :tag "enabled"
1080 (list :value (?a "\n" nil)
1081 (character :tag "Selection Key")
1082 (string :tag "Template")
1083 (file :tag "Destination file (optional)"))))
1085 (defcustom org-reverse-note-order nil
1086 "Non-nil means, store new notes at the beginning of a file or entry.
1087 When nil, new notes will be filed to the end of a file or entry."
1088 :group 'org-remember
1090 (const :tag "Reverse always" t)
1091 (const :tag "Reverse never" nil)
1092 (repeat :tag "By file name regexp"
1093 (cons regexp boolean))))
1095 (defgroup org-todo nil
1096 "Options concerning TODO items in Org-mode."
1100 (defcustom org-todo-keywords '("TODO" "DONE")
1101 "List of TODO entry keywords.
1102 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1103 considered to mean that the entry is \"done\". All the other mean that
1104 action is required, and will make the entry show up in todo lists, diaries
1106 The command \\[org-todo] cycles an entry through these states, and an
1107 additional state where no keyword is present. For details about this
1108 cycling, see also the variable `org-todo-interpretation'
1109 Changes become only effective after restarting Emacs."
1111 :group 'org-keywords
1112 :type '(repeat (string :tag "Keyword")))
1114 (defcustom org-todo-interpretation 'sequence
1115 "Controls how TODO keywords are interpreted.
1116 This variable is only relevant if `org-todo-keywords' contains more than two
1117 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1119 When `sequence', \\[org-todo] will always switch to the next state in the
1120 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1121 to state when executed several times in direct succession. Otherwise, it
1122 switches directly to DONE from any state.
1123 See the manual for more information."
1125 :group 'org-keywords
1126 :type '(choice (const sequence)
1129 (defcustom org-after-todo-state-change-hook nil
1130 "Hook which is run after the state of a TODO item was changed.
1131 The new state (a string with a TODO keyword, or nil) is available in the
1132 Lisp variable `state'."
1136 (defcustom org-log-done nil
1137 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1138 When the state of an entry is changed from nothing to TODO, remove a previous
1143 (defgroup org-priorities nil
1144 "Priorities in Org-mode."
1145 :tag "Org Priorities"
1148 (defcustom org-default-priority ?B
1149 "The default priority of TODO items.
1150 This is the priority an item get if no explicit priority is given."
1151 :group 'org-priorities
1154 (defcustom org-lowest-priority ?C
1155 "The lowest priority of TODO items. A character like ?A, ?B etc."
1156 :group 'org-priorities
1159 (defgroup org-time nil
1160 "Options concerning time stamps and deadlines in Org-mode."
1164 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1165 "Formats for `format-time-string' which are used for time stamps.
1166 It is not recommended to change this constant.")
1168 (defcustom org-time-stamp-rounding-minutes 0
1169 "Number of minutes to round time stamps to upon insertion.
1170 When zero, insert the time unmodified. Useful rounding numbers
1171 should be factors of 60, so for example 5, 10, 15.
1172 When this is not zero, you can still force an exact time-stamp by using
1173 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1177 (defcustom org-deadline-warning-days 30
1178 "No. of days before expiration during which a deadline becomes active.
1179 This variable governs the display in the org file."
1183 (defcustom org-popup-calendar-for-date-prompt t
1184 "Non-nil means, pop up a calendar when prompting for a date.
1185 In the calendar, the date can be selected with mouse-1. However, the
1186 minibuffer will also be active, and you can simply enter the date as well.
1187 When nil, only the minibuffer will be available."
1191 (defcustom org-calendar-follow-timestamp-change t
1192 "Non-nil means, make the calendar window follow timestamp changes.
1193 When a timestamp is modified and the calendar window is visible, it will be
1194 moved to the new date."
1198 (defgroup org-tags nil
1199 "Options concerning tags in Org-mode."
1203 (defcustom org-tags-column 48
1204 "The column to which tags should be indented in a headline.
1205 If this number is positive, it specifies the column. If it is negative,
1206 it means that the tags should be flushright to that column. For example,
1207 -79 works well for a normal 80 character screen."
1211 (defcustom org-auto-align-tags t
1212 "Non-nil means, realign tags after pro/demotion of TODO state change.
1213 These operations change the length of a headline and therefore shift
1214 the tags around. With this options turned on, after each such operation
1215 the tags are again aligned to `org-tags-column'."
1219 (defcustom org-use-tag-inheritance t
1220 "Non-nil means, tags in levels apply also for sublevels.
1221 When nil, only the tags directly given in a specific line apply there.
1222 If you turn off this option, you very likely want to turn on the
1223 companion option `org-tags-match-list-sublevels'."
1227 (defcustom org-tags-match-list-sublevels nil
1228 "Non-nil means list also sublevels of headlines matching tag search.
1229 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1230 the sublevels of a headline matching a tag search often also match
1231 the same search. Listing all of them can create very long lists.
1232 Setting this variable to nil causes subtrees of a match to be skipped.
1233 This option is off by default, because inheritance in on. If you turn
1234 inheritance off, you very likely want to turn this option on.
1236 As a special case, if the tag search is restricted to TODO items, the
1237 value of this variable is ignored and sublevels are always checked, to
1238 make sure all corresponding TODO items find their way into the list."
1242 (defvar org-tags-history nil
1243 "History of minibuffer reads for tags.")
1244 (defvar org-last-tags-completion-table nil
1245 "The last used completion table for tags.")
1247 (defgroup org-agenda nil
1248 "Options concerning agenda display Org-mode."
1252 (defvar org-category nil
1253 "Variable used by org files to set a category for agenda display.
1254 Such files should use a file variable to set it, for example
1256 -*- mode: org; org-category: \"ELisp\"
1258 or contain a special line
1262 If the file does not specify a category, then file's base name
1264 (make-variable-buffer-local 'org-category)
1266 (defcustom org-agenda-files nil
1267 "The files to be used for agenda display.
1268 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1269 \\[org-remove-file]. You can also use customize to edit the list.
1271 If the value of the variable is not a list but a single file name, then
1272 the list of agenda files is actually stored and maintained in that file, one
1273 agenda file per line."
1276 (repeat :tag "List of files" file)
1277 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1279 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1280 "Custom commands for the agenda.
1281 These commands will be offered on the splash screen displayed by the
1282 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
1284 key The key (a single char as a string) to be associated with the command.
1285 type The command type, any of the following symbols:
1286 todo Entries with a specific TODO keyword, in all agenda files.
1287 tags Tags match in all agenda files.
1288 todo-tree Sparse tree of specific TODO keyword in *current* file.
1289 tags-tree Sparse tree with all tags matches in *current* file.
1290 occur-tree Occur sparse tree for current file.
1291 match What to search for:
1292 - a single keyword for TODO keyword searches
1293 - a tags match expression for tags searches
1294 - a regular expression for occur searches"
1297 (list (string :tag "Key")
1299 (const :tag "Tags search in all agenda files" tags)
1300 (const :tag "TODO keyword search in all agenda files" todo)
1301 (const :tag "Tags sparse tree in current buffer" tags-tree)
1302 (const :tag "TODO keyword tree in current buffer" todo-tree)
1303 (const :tag "Occur tree in current buffer" occur-tree))
1304 (string :tag "Match"))))
1306 (defcustom org-agenda-include-all-todo t
1307 "Non-nil means, the agenda will always contain all TODO entries.
1308 When nil, date-less entries will only be shown if `org-agenda' is called
1309 with a prefix argument.
1310 When non-nil, the TODO entries will be listed at the top of the agenda, before
1311 the entries for specific days."
1315 (defcustom org-agenda-include-diary nil
1316 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1320 (defcustom org-calendar-to-agenda-key [?c]
1321 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1322 The command `org-calendar-goto-agenda' will be bound to this key. The
1323 default is the character `c' because then `c' can be used to switch back and
1324 forth between agenda and calendar."
1328 (defgroup org-agenda-window-setup nil
1329 "Options concerning setting up the Agenda window in Org Mode."
1330 :tag "Org Agenda Window Setup"
1333 (defcustom org-agenda-mouse-1-follows-link nil
1334 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1335 A longer mouse click will still set point. Does not wortk on XEmacs.
1336 Needs to be set before org.el is loaded."
1337 :group 'org-agenda-setup
1340 (defcustom org-select-timeline-window t
1341 "Non-nil means, after creating a timeline, move cursor into Timeline window.
1342 When nil, cursor will remain in the current window."
1343 :group 'org-agenda-setup
1346 (defcustom org-select-agenda-window t
1347 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1348 When nil, cursor will remain in the current window."
1349 :group 'org-agenda-setup
1352 (defcustom org-fit-agenda-window t
1353 "Non-nil means, change window size of agenda to fit content."
1354 :group 'org-agenda-setup
1357 (defgroup org-agenda-display nil
1358 "Options concerning what to display initially in Agenda."
1359 :tag "Org Agenda Display"
1362 (defcustom org-agenda-show-all-dates t
1363 "Non-nil means, `org-agenda' shows every day in the selected range.
1364 When nil, only the days which actually have entries are shown."
1365 :group 'org-agenda-display
1368 (defcustom org-agenda-start-on-weekday 1
1369 "Non-nil means, start the overview always on the specified weekday.
1370 0 denotes Sunday, 1 denotes Monday etc.
1371 When nil, always start on the current day."
1372 :group 'org-agenda-display
1373 :type '(choice (const :tag "Today" nil)
1374 (number :tag "Weekday No.")))
1376 (defcustom org-agenda-ndays 7
1377 "Number of days to include in overview display.
1379 :group 'org-agenda-display
1382 (defcustom org-agenda-use-time-grid t
1383 "Non-nil means, show a time grid in the agenda schedule.
1384 A time grid is a set of lines for specific times (like every two hours between
1385 8:00 and 20:00). The items scheduled for a day at specific times are
1386 sorted in between these lines.
1387 For details about when the grid will be shown, and what it will look like, see
1388 the variable `org-agenda-time-grid'."
1389 :group 'org-agenda-display
1392 (defcustom org-agenda-time-grid
1393 '((daily today require-timed)
1395 (800 1000 1200 1400 1600 1800 2000))
1397 "The settings for time grid for agenda display.
1398 This is a list of three items. The first item is again a list. It contains
1399 symbols specifying conditions when the grid should be displayed:
1401 daily if the agenda shows a single day
1402 weekly if the agenda shows an entire week
1403 today show grid on current date, independent of daily/weekly display
1404 require-timed show grid only if at least on item has a time specification
1406 The second item is a string which will be places behing the grid time.
1408 The third item is a list of integers, indicating the times that should have
1410 :group 'org-agenda-display
1413 (set :greedy t :tag "Grid Display Options"
1414 (const :tag "Show grid in single day agenda display" daily)
1415 (const :tag "Show grid in weekly agenda display" weekly)
1416 (const :tag "Always show grid for today" today)
1417 (const :tag "Show grid only if any timed entries are present"
1419 (const :tag "Skip grid times already present in an entry"
1421 (string :tag "Grid String")
1422 (repeat :tag "Grid Times" (integer :tag "Time"))))
1424 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
1425 "Sorting structure for the agenda items of a single day.
1426 This is a list of symbols which will be used in sequence to determine
1427 if an entry should be listed before another entry. The following
1428 symbols are recognized:
1430 time-up Put entries with time-of-day indications first, early first
1431 time-down Put entries with time-of-day indications first, late first
1432 category-keep Keep the default order of categories, corresponding to the
1433 sequence in `org-agenda-files'.
1434 category-up Sort alphabetically by category, A-Z.
1435 category-down Sort alphabetically by category, Z-A.
1436 priority-up Sort numerically by priority, high priority last.
1437 priority-down Sort numerically by priority, high priority first.
1439 The different possibilities will be tried in sequence, and testing stops
1440 if one comparison returns a \"not-equal\". For example, the default
1441 '(time-up category-keep priority-down)
1442 means: Pull out all entries having a specified time of day and sort them,
1443 in order to make a time schedule for the current day the first thing in the
1444 agenda listing for the day. Of the entries without a time indication, keep
1445 the grouped in categories, don't sort the categories, but keep them in
1446 the sequence given in `org-agenda-files'. Within each category sort by
1449 Leaving out `category-keep' would mean that items will be sorted across
1450 categories by priority."
1451 :group 'org-agenda-display
1456 (const category-keep)
1458 (const category-down)
1460 (const priority-down))))
1462 (defcustom org-sort-agenda-notime-is-late t
1463 "Non-nil means, items without time are considered late.
1464 This is only relevant for sorting. When t, items which have no explicit
1465 time like 15:30 will be considered as 24:01, i.e. later than any items which
1466 do have a time. When nil, the default time is before 0:00. You can use this
1467 option to decide if the schedule for today should come before or after timeless
1469 :group 'org-agenda-display
1473 (defgroup org-agenda-prefix nil
1474 "Options concerning the entry prefix in the Org-mode agenda display."
1475 :tag "Org Agenda Prefix"
1478 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
1479 "Format specification for the prefix of items in the agenda buffer.
1480 This format works similar to a printf format, with the following meaning:
1482 %c the category of the item, \"Diary\" for entries from the diary, or
1483 as given by the CATEGORY keyword or derived from the file name.
1484 %T the first tag of the item.
1485 %t the time-of-day specification if one applies to the entry, in the
1487 %s Scheduling/Deadline information, a short string
1489 All specifiers work basically like the standard `%s' of printf, but may
1490 contain two additional characters: A question mark just after the `%' and
1491 a whitespace/punctuation character just before the final letter.
1493 If the first character after `%' is a question mark, the entire field
1494 will only be included if the corresponding value applies to the
1495 current entry. This is useful for fields which should have fixed
1496 width when present, but zero width when absent. For example,
1497 \"%?-12t\" will result in a 12 character time field if a time of the
1498 day is specified, but will completely disappear in entries which do
1501 If there is punctuation or whitespace character just before the final
1502 format letter, this character will be appended to the field value if
1503 the value is not empty. For example, the format \"%-12:c\" leads to
1504 \"Diary: \" if the category is \"Diary\". If the category were be
1505 empty, no additional colon would be interted.
1507 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1508 - Indent the line with two space characters
1509 - Give the category in a 12 chars wide field, padded with whitespace on
1510 the right (because of `-'). Append a colon if there is a category
1512 - If there is a time-of-day, put it into a 12 chars wide field. If no
1513 time, don't put in an empty field, just skip it (because of '?').
1514 - Finally, put the scheduling information and append a whitespace.
1516 As another example, if you don't want the time-of-day of entries in
1517 the prefix, you could use:
1519 (setq org-agenda-prefix-format \" %-11:c% s\")
1521 See also the variables `org-agenda-remove-times-when-in-prefix' and
1522 `org-agenda-remove-tags-when-in-prefix'."
1524 :group 'org-agenda-prefix)
1526 (defcustom org-timeline-prefix-format " % s"
1527 "Like `org-agenda-prefix-format', but for the timeline of a single file."
1529 :group 'org-agenda-prefix)
1531 (defvar org-prefix-format-compiled nil
1532 "The compiled version of the most recently used prefix format.
1533 Depending on which command was used last, this may be the compiled version
1534 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
1536 ;; FIXME: There seem to be situations where this does no work.
1537 (defcustom org-agenda-remove-times-when-in-prefix t
1538 "Non-nil means, remove duplicate time specifications in agenda items.
1539 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1540 time-of-day specification in a headline or diary entry is extracted and
1541 placed into the prefix. If this option is non-nil, the original specification
1542 \(a timestamp or -range, or just a plain time(range) specification like
1543 11:30-4pm) will be removed for agenda display. This makes the agenda less
1545 The option can be t or nil. It may also be the symbol `beg', indicating
1546 that the time should only be removed what it is located at the beginning of
1547 the headline/diary entry."
1548 :group 'org-agenda-prefix
1550 (const :tag "Always" t)
1551 (const :tag "Never" nil)
1552 (const :tag "When at beginning of entry" beg)))
1554 (defcustom org-agenda-remove-tags-when-in-prefix nil
1555 "Non-nil means, remove the tags from the headline copy in the agenda.
1556 When this is the symbol `prefix', only remove tags when
1557 `org-agenda-prefix-format' contains a `%T' specifier."
1558 :group 'org-agenda-prefix
1560 (const :tag "Always" t)
1561 (const :tag "Never" nil)
1562 (const :tag "When prefix format contains %T" prefix)))
1564 (defgroup org-export nil
1565 "Options for exporting org-listings."
1569 (defgroup org-export-general nil
1570 "General options for exporting Org-mode files."
1571 :tag "Org Export General"
1574 (defcustom org-export-language-setup
1575 '(("en" "Author" "Date" "Table of Contents")
1576 ("da" "Ophavsmand" "Dato" "Indhold")
1577 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1578 ("es" "Autor" "Fecha" "\xccndice")
1579 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1580 ("it" "Autore" "Data" "Indice")
1581 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1582 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1583 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1584 "Terms used in export text, translated to different languages.
1585 Use the variable `org-export-default-language' to set the language,
1586 or use the +OPTION lines for a per-file setting."
1587 :group 'org-export-general
1590 (string :tag "HTML language tag")
1591 (string :tag "Author")
1592 (string :tag "Date")
1593 (string :tag "Table of Contents"))))
1595 (defcustom org-export-default-language "en"
1596 "The default language of HTML export, as a string.
1597 This should have an association in `org-export-language-setup'."
1598 :group 'org-export-general
1601 (defcustom org-export-headline-levels 3
1602 "The last level which is still exported as a headline.
1603 Inferior levels will produce itemize lists when exported.
1604 Note that a numeric prefix argument to an exporter function overrides
1607 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1608 :group 'org-export-general
1611 (defcustom org-export-with-section-numbers t
1612 "Non-nil means, add section numbers to headlines when exporting.
1614 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1615 :group 'org-export-general
1618 (defcustom org-export-with-toc t
1619 "Non-nil means, create a table of contents in exported files.
1620 The TOC contains headlines with levels up to`org-export-headline-levels'.
1622 Headlines which contain any TODO items will be marked with \"(*)\" in
1623 ASCII export, and with red color in HTML output.
1625 In HTML output, the TOC will be clickable.
1627 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1628 :group 'org-export-general
1631 (defcustom org-export-mark-todo-in-toc nil
1632 "Non-nil means, mark TOC lines that contain any open TODO items."
1633 :group 'org-export-general
1636 (defcustom org-export-preserve-breaks nil
1637 "Non-nil means, preserve all line breaks when exporting.
1638 Normally, in HTML output paragraphs will be reformatted. In ASCII
1639 export, line breaks will always be preserved, regardless of this variable.
1641 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1642 :group 'org-export-general
1645 (defgroup org-export-translation nil
1646 "Options for translating special ascii sequences for the export backends."
1647 :tag "Org Export Translation"
1650 (defcustom org-export-with-emphasize t
1651 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1652 If the export target supports emphasizing text, the word will be
1653 typeset in bold, italic, or underlined, respectively. Works only for
1654 single words, but you can say: I *really* *mean* *this*.
1655 Not all export backends support this.
1657 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1658 :group 'org-export-translation
1661 (defcustom org-export-with-sub-superscripts t
1662 "Non-nil means, interpret \"_\" and \"^\" for export.
1663 When this option is turned on, you can use TeX-like syntax for sub- and
1664 superscripts. Several characters after \"_\" or \"^\" will be
1665 considered as a single item - so grouping with {} is normally not
1666 needed. For example, the following things will be parsed as single
1667 sub- or superscripts.
1669 10^24 or 10^tau several digits will be considered 1 item.
1670 10^-12 or 10^-tau a leading sign with digits or a word
1671 x^2-y^3 will be read as x^2 - y^3, because items are
1672 terminated by almost any nonword/nondigit char.
1673 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1675 Still, ambiguity is possible - so when in doubt use {} to enclose the
1677 Not all export backends support this, but HTML does.
1679 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1680 :group 'org-export-translation
1683 (defcustom org-export-with-TeX-macros t
1684 "Non-nil means, interpret simple TeX-like macros when exporting.
1685 For example, HTML export converts \\alpha to α and \\AA to Å.
1686 No only real TeX macros will work here, but the standard HTML entities
1687 for math can be used as macro names as well. For a list of supported
1688 names in HTML export, see the constant `org-html-entities'.
1689 Not all export backends support this.
1691 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1692 :group 'org-export-translation
1695 (defcustom org-export-with-fixed-width t
1696 "Non-nil means, lines starting with \":\" will be in fixed width font.
1697 This can be used to have pre-formatted text, fragments of code etc. For
1699 : ;; Some Lisp examples
1702 will be looking just like this in also HTML. See also the QUOTE keyword.
1703 Not all export backends support this.
1705 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1706 :group 'org-export-translation
1709 (defcustom org-match-sexp-depth 3
1710 "Number of stacked braces for sub/superscript matching.
1711 This has to be set before loading org.el to be effective."
1712 :group 'org-export-translation
1715 (defgroup org-export-tables nil
1716 "Options for exporting tables in Org-mode."
1717 :tag "Org Export Tables"
1720 (defcustom org-export-with-tables t
1721 "If non-nil, lines starting with \"|\" define a table.
1724 | Name | Address | Birthday |
1725 |-------------+----------+-----------|
1726 | Arthur Dent | England | 29.2.2100 |
1728 Not all export backends support this.
1730 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1731 :group 'org-export-tables
1734 (defcustom org-export-highlight-first-table-line t
1735 "Non-nil means, highlight the first table line.
1736 In HTML export, this means use <th> instead of <td>.
1737 In tables created with table.el, this applies to the first table line.
1738 In Org-mode tables, all lines before the first horizontal separator
1739 line will be formatted with <th> tags."
1740 :group 'org-export-tables
1743 (defcustom org-export-table-remove-special-lines t
1744 "Remove special lines and marking characters in calculating tables.
1745 This removes the special marking character column from tables that are set
1746 up for spreadsheet calculations. It also removes the entire lines
1747 marked with `!', `_', or `^'. The lines with `$' are kept, because
1748 the values of constants may be useful to have."
1749 :group 'org-export-tables
1752 (defcustom org-export-prefer-native-exporter-for-tables nil
1753 "Non-nil means, always export tables created with table.el natively.
1754 Natively means, use the HTML code generator in table.el.
1755 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1756 the table does not use row- or column-spanning). This has the
1757 advantage, that the automatic HTML conversions for math symbols and
1758 sub/superscripts can be applied. Org-mode's HTML generator is also
1760 :group 'org-export-tables
1763 (defgroup org-export-ascii nil
1764 "Options specific for ASCII export of Org-mode files."
1765 :tag "Org Export ASCII"
1768 (defcustom org-export-ascii-show-new-buffer t
1769 "Non-nil means, popup buffer containing the exported ASCII text.
1770 Otherwise the buffer will just be saved to a file and stay hidden."
1771 :group 'org-export-ascii
1774 (defgroup org-export-xml nil
1775 "Options specific for XML export of Org-mode files."
1776 :tag "Org Export XML"
1779 (defcustom org-export-xml-type 'xoxo ;kw, if we have only one.
1780 "The kind of XML to be produced by the XML exporter.
1782 xoxo The XOXO exporter."
1783 :group 'org-export-xml
1785 (const :tag "XOXO" xoxo)))
1787 (defgroup org-export-html nil
1788 "Options specific for HTML export of Org-mode files."
1789 :tag "Org Export HTML"
1792 (defcustom org-export-html-style
1793 "<style type=\"text/css\">
1795 font-family: Times, serif;
1798 .title { text-align: center; }
1799 .todo, .deadline { color: red; }
1800 .done { color: green; }
1801 .target { background-color: lavender; }
1803 border: 1pt solid #AEBDCC;
1804 background-color: #F3F5F7;
1806 font-family: courier, monospace;
1808 table { border-collapse: collapse; }
1810 vertical-align: top;
1811 border: 1pt solid #ADB9CC;
1814 "The default style specification for exported HTML files.
1815 Since there are different ways of setting style information, this variable
1816 needs to contain the full HTML structure to provide a style, including the
1817 surrounding HTML tags. The style specifications should include definitions
1818 for new classes todo, done, title, and deadline. For example, legal values
1821 <style type=\"text/css\">
1822 p { font-weight: normal; color: gray; }
1823 h1 { color: black; }
1824 .title { text-align: center; }
1825 .todo, .deadline { color: red; }
1826 .done { color: green; }
1829 or, if you want to keep the style in a file,
1831 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1833 As the value of this option simply gets inserted into the HTML <head> header,
1834 you can \"misuse\" it to add arbitrary text to the header."
1835 :group 'org-export-html
1838 (defcustom org-export-html-link-org-files-as-html t
1839 "Non-nil means, make file links to `file.org' point to `file.html'.
1840 When org-mode is exporting an org-mode file to HTML, links to
1841 non-html files are directly put into a href tag in HTML.
1842 However, links to other Org-mode files (recognized by the
1843 extension `.org.) should become links to the corresponding html
1844 file, assuming that the linked org-mode file will also be
1846 When nil, the links still point to the plain `.org' file."
1847 :group 'org-export-html
1850 (defcustom org-export-html-inline-images t
1851 "Non-nil means, inline images into exported HTML pages.
1852 The link will still be to the original location of the image file.
1853 So if you are moving the page, lets say to your public HTML site,
1854 you will have to move the image and maybe change the link."
1855 :group 'org-export-html
1858 (defcustom org-export-html-expand t
1859 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1860 When nil, these tags will be exported as plain text and therefore
1861 not be interpreted by a browser.
1863 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1864 :group 'org-export-html
1867 (defcustom org-export-html-table-tag
1868 "<table border=1 cellspacing=0 cellpadding=6>"
1869 "The HTML tag used to start a table.
1870 This must be a <table> tag, but you may change the options like
1871 borders and spacing."
1872 :group 'org-export-html
1875 (defcustom org-export-html-with-timestamp nil
1876 "If non-nil, write `org-export-html-html-helper-timestamp'
1877 into the exported HTML text. Otherwise, the buffer will just be saved
1879 :group 'org-export-html
1882 (defcustom org-export-html-html-helper-timestamp
1883 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1884 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1885 :group 'org-export-html
1888 (defcustom org-export-html-show-new-buffer nil
1889 "Non-nil means, popup buffer containing the exported html text.
1890 Otherwise, the buffer will just be saved to a file and stay hidden."
1891 :group 'org-export-html
1894 (defgroup org-export-icalendar nil
1895 "Options specific for iCalendar export of Org-mode files."
1896 :tag "Org Export iCalendar"
1899 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1900 "The file name for the iCalendar file covering all agenda files.
1901 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1902 :group 'org-export-icalendar
1905 (defcustom org-icalendar-include-todo nil
1906 "Non-nil means, export to iCalendar files should also cover TODO items."
1907 :group 'org-export-icalendar
1910 (defcustom org-icalendar-combined-name "OrgMode"
1911 "Calendar name for the combined iCalendar representing all agenda files."
1912 :group 'org-export-icalendar
1915 (defgroup org-font-lock nil
1916 "Font-lock settings for highlighting in Org-mode."
1917 :tag "Org Font Lock"
1920 (defcustom org-level-color-stars-only nil
1921 "Non-nil means fontify only the stars in each headline.
1922 When nil, the entire headline is fontified.
1923 Changing it requires restart of `font-lock-mode' to become effective
1924 also in regions already fontified."
1925 :group 'org-font-lock
1928 (defcustom org-hide-leading-stars nil
1929 "Non-nil means, hide the first N-1 stars in a headline.
1930 This works by using the face `org-hide' for these stars. This
1931 face is white for a light background, and black for a dark
1932 background. You may have to customize the face `org-hide' to
1934 Changing it requires restart of `font-lock-mode' to become effective
1935 also in regions already fontified.
1936 You may also set this on a per-file basis by adding one of the following
1937 lines to the buffer:
1939 #+STARTUP: hidestars
1940 #+STARTUP: showstars"
1941 :group 'org-font-lock
1944 (defcustom org-fontify-done-headline nil
1945 "Non-nil means, change the face of a headline if it is marked DONE.
1946 Normally, only the TODO/DONE keyword indicates the state of a headline.
1947 When this is non-nil, the headline after the keyword is set to the
1948 `org-headline-done' as an additional indication."
1949 :group 'org-font-lock
1952 (defcustom org-fontify-emphasized-text t
1953 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
1954 Changing this variable requires a restart of Emacs to take effect."
1955 :group 'org-font-lock
1958 (defgroup org-faces nil
1959 "Faces in Org-mode."
1961 :group 'org-font-lock)
1963 (defun org-compatible-face (specs)
1964 "Make a compatible face specification.
1965 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
1966 For them we convert a (min-colors 8) entry to a `tty' entry and move it
1967 to the top of the list. The `min-colors' attribute will be removed from
1968 any other entries, and any resulting duplicates will be removed entirely."
1969 (if (or (featurep 'xemacs) (< emacs-major-version 22))
1971 (while (setq e (pop specs))
1973 ((memq (car e) '(t default)) (push e r))
1974 ((setq a (member '(min-colors 8) (car e)))
1975 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
1977 ((setq a (assq 'min-colors (car e)))
1978 (setq e (cons (delq a (car e)) (cdr e)))
1979 (or (assoc (car e) r) (push e r)))
1980 (t (or (assoc (car e) r) (push e r)))))
1985 '((((background light)) (:foreground "white"))
1986 (((background dark)) (:foreground "black")))
1987 "Face used to hide leading stars in headlines.
1988 The forground color of this face should be equal to the background
1989 color of the frame."
1992 (defface org-level-1 ;; font-lock-function-name-face
1993 (org-compatible-face
1994 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
1995 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
1996 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
1997 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
1998 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2000 "Face used for level 1 headlines."
2003 (defface org-level-2 ;; font-lock-variable-name-face
2004 (org-compatible-face
2005 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2006 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2007 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2008 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2010 "Face used for level 2 headlines."
2013 (defface org-level-3 ;; font-lock-keyword-face
2014 (org-compatible-face
2015 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2016 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2017 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2018 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2019 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2020 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2022 "Face used for level 3 headlines."
2025 (defface org-level-4 ;; font-lock-comment-face
2026 (org-compatible-face
2027 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2028 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2029 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2030 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2031 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2032 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2034 "Face used for level 4 headlines."
2037 (defface org-level-5 ;; font-lock-type-face
2038 (org-compatible-face
2039 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2040 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2041 (((class color) (min-colors 8)) (:foreground "green"))))
2042 "Face used for level 5 headlines."
2045 (defface org-level-6 ;; font-lock-constant-face
2046 (org-compatible-face
2047 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2048 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2049 (((class color) (min-colors 8)) (:foreground "magenta"))))
2050 "Face used for level 6 headlines."
2053 (defface org-level-7 ;; font-lock-builtin-face
2054 (org-compatible-face
2055 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2056 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2057 (((class color) (min-colors 8)) (:foreground "blue")))) ;; FIXME: for dark bg?
2058 "Face used for level 7 headlines."
2061 (defface org-level-8 ;; font-lock-string-face
2062 (org-compatible-face
2063 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2064 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2065 (((class color) (min-colors 8)) (:foreground "green"))))
2066 "Face used for level 8 headlines."
2069 (defface org-special-keyword ;; font-lock-string-face
2070 (org-compatible-face
2071 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2072 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2074 "Face used for special keywords."
2077 (defface org-warning ;; font-lock-warning-face
2078 (org-compatible-face
2079 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2080 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2081 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2082 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2084 "Face for deadlines and TODO keywords."
2087 (defface org-headline-done ;; font-lock-string-face
2088 (org-compatible-face
2089 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2090 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2091 (((class color) (min-colors 8) (background light)) (:bold nil))))
2092 "Face used to indicate that a headline is DONE.
2093 This face is only used if `org-fontify-done-headline' is set."
2097 '((((class color) (background light)) (:foreground "Purple" :underline t))
2098 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2104 '((((class color) (background light)) (:foreground "Purple" :underline t))
2105 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2115 (defface org-todo ;; font-lock-warning-face
2116 (org-compatible-face
2117 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2118 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2119 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2120 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2121 (t (:inverse-video t :bold t))))
2122 "Face for TODO keywords."
2125 (defface org-done ;; font-lock-type-face
2126 (org-compatible-face
2127 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2128 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2129 (((class color) (min-colors 8)) (:foreground "green"))
2131 "Face used for DONE."
2134 (defface org-table ;; font-lock-function-name-face
2135 (org-compatible-face
2136 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2137 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2138 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2139 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2140 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2141 (((class color) (min-colors 8) (background dark)))))
2142 "Face used for tables."
2145 (defface org-formula
2146 (org-compatible-face
2147 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2148 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2149 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2150 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2151 (t (:bold t :italic t))))
2152 "Face for formulas."
2155 (defface org-scheduled-today
2156 (org-compatible-face
2157 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2158 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2159 (((class color) (min-colors 8)) (:foreground "green"))
2160 (t (:bold t :italic t))))
2161 "Face for items scheduled for a certain day."
2164 (defface org-scheduled-previously
2165 (org-compatible-face
2166 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2167 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2168 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2169 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2171 "Face for items scheduled previously, and not yet done."
2174 (defface org-time-grid ;; font-lock-variable-name-face
2175 (org-compatible-face
2176 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2177 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2178 (((class color) (min-colors 8)) (:foreground "yellow" :weight light)))) ; FIXME: turn off???
2179 "Face used for time grids."
2182 (defconst org-level-faces
2183 '(org-level-1 org-level-2 org-level-3 org-level-4
2184 org-level-5 org-level-6 org-level-7 org-level-8
2186 (defconst org-n-levels (length org-level-faces))
2188 (defconst org-bold-re
2189 (if (featurep 'xemacs)
2190 "\\([ ]\\|^\\)\\(\\*\\(\\w[a-zA-Z0-9-_ ]*?\\w\\)\\*\\)\\([ ,.]\\|$\\)"
2191 "\\([ ]\\|^\\)\\(\\*\\(\\w[[:word:] -_]*?\\w\\)\\*\\)\\([ ,.]\\|$\\)")
2192 "Regular expression for bold emphasis.")
2193 (defconst org-italic-re
2194 (if (featurep 'xemacs)
2195 "\\([ ]\\|^\\)\\(/\\(\\w[a-zA-Z0-9-_ ]*?\\w\\)/\\)\\([ ,.]\\|$\\)"
2196 "\\([ ]\\|^\\)\\(/\\(\\w[[:word:] -_]*?\\w\\)/\\)\\([ ,.]\\|$\\)")
2197 "Regular expression for italic emphasis.")
2198 (defconst org-underline-re
2199 (if (featurep 'xemacs)
2200 "\\([ ]\\|^\\)\\(_\\(\\w[a-zA-Z0-9-_ ]*?\\w\\)_\\)\\([ ,.]\\|$\\)"
2201 "\\([ ]\\|^\\)\\(_\\(\\w[[:word:] -_]*?\\w\\)_\\)\\([ ,.]\\|$\\)")
2202 "Regular expression for underline emphasis.")
2204 ;; Variables for pre-computed regular expressions, all buffer local
2205 (defvar org-done-string nil
2206 "The last string in `org-todo-keywords', indicating an item is DONE.")
2207 (make-variable-buffer-local 'org-done-string)
2208 (defvar org-todo-regexp nil
2209 "Matches any of the TODO state keywords.")
2210 (make-variable-buffer-local 'org-todo-regexp)
2211 (defvar org-not-done-regexp nil
2212 "Matches any of the TODO state keywords except the last one.")
2213 (make-variable-buffer-local 'org-not-done-regexp)
2214 (defvar org-todo-line-regexp nil
2215 "Matches a headline and puts TODO state into group 2 if present.")
2216 (make-variable-buffer-local 'org-todo-line-regexp)
2217 (defvar org-nl-done-regexp nil
2218 "Matches newline followed by a headline with the DONE keyword.")
2219 (make-variable-buffer-local 'org-nl-done-regexp)
2220 (defvar org-looking-at-done-regexp nil
2221 "Matches the DONE keyword a point.")
2222 (make-variable-buffer-local 'org-looking-at-done-regexp)
2223 (defvar org-todo-kwd-priority-p nil
2224 "Do TODO items have priorities?")
2225 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2226 (defvar org-todo-kwd-max-priority nil
2227 "Maximum priority of TODO items.")
2228 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2229 (defvar org-ds-keyword-length 12
2230 "Maximum length of the Deadline and SCHEDULED keywords.")
2231 (make-variable-buffer-local 'org-ds-keyword-length)
2232 (defvar org-deadline-regexp nil
2233 "Matches the DEADLINE keyword.")
2234 (make-variable-buffer-local 'org-deadline-regexp)
2235 (defvar org-deadline-time-regexp nil
2236 "Matches the DEADLINE keyword together with a time stamp.")
2237 (make-variable-buffer-local 'org-deadline-time-regexp)
2238 (defvar org-deadline-line-regexp nil
2239 "Matches the DEADLINE keyword and the rest of the line.")
2240 (make-variable-buffer-local 'org-deadline-line-regexp)
2241 (defvar org-scheduled-regexp nil
2242 "Matches the SCHEDULED keyword.")
2243 (make-variable-buffer-local 'org-scheduled-regexp)
2244 (defvar org-scheduled-time-regexp nil
2245 "Matches the SCHEDULED keyword together with a time stamp.")
2246 (make-variable-buffer-local 'org-scheduled-time-regexp)
2248 (defun org-set-regexps-and-options ()
2249 "Precompute regular expressions for current buffer."
2250 (when (eq major-mode 'org-mode)
2251 (let ((re (org-make-options-regexp
2252 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2253 "STARTUP" "ARCHIVE")))
2255 kwds int key value cat arch)
2259 (goto-char (point-min))
2260 (while (re-search-forward re nil t)
2261 (setq key (match-string 1) value (match-string 2))
2263 ((equal key "CATEGORY")
2264 (if (string-match "[ \t]+$" value)
2265 (setq value (replace-match "" t t value)))
2266 (setq cat (intern value)))
2267 ((equal key "SEQ_TODO")
2269 kwds (append kwds (org-split-string value splitre))))
2270 ((equal key "PRI_TODO")
2272 kwds (append kwds (org-split-string value splitre))))
2273 ((equal key "TYP_TODO")
2275 kwds (append kwds (org-split-string value splitre))))
2276 ((equal key "STARTUP")
2277 (let ((opts (org-split-string value splitre))
2278 (set '(("fold" org-startup-folded t)
2279 ("overview" org-startup-folded t)
2280 ("nofold" org-startup-folded nil)
2281 ("showall" org-startup-folded nil)
2282 ("content" org-startup-folded content)
2283 ("hidestars" org-hide-leading-stars t)
2284 ("showstars" org-hide-leading-stars nil)
2285 ("odd" org-odd-levels-only t)
2286 ("oddeven" org-odd-levels-only nil)
2287 ("align" org-startup-align-all-tables t)
2288 ("noalign" org-startup-align-all-tables nil)
2289 ("dlcheck" org-startup-with-deadline-check t)
2290 ("nodlcheck" org-startup-with-deadline-check nil)))
2292 (while (setq l (assoc (pop opts) set))
2293 (setq var (nth 1 l) val (nth 2 l))
2294 (set (make-local-variable var) val))))
2295 ((equal key "ARCHIVE")
2296 (string-match " *$" value)
2297 (setq arch (replace-match "" t t value))
2298 (remove-text-properties 0 (length arch)
2299 '(face t fontified t) arch)))
2301 (and cat (set (make-local-variable 'org-category) cat))
2302 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
2303 (and arch (set (make-local-variable 'org-archive-location) arch))
2304 (and int (set (make-local-variable 'org-todo-interpretation) int)))
2305 ;; Compute the regular expressions and other local variables
2306 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2307 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2308 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2309 (length org-scheduled-string)))
2311 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2313 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2317 (mapconcat 'regexp-quote
2318 (nreverse (cdr (reverse org-todo-keywords)))
2321 org-todo-line-regexp
2322 (concat "^\\(\\*+\\)[ \t]*\\("
2323 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2326 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2327 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2328 org-deadline-regexp (concat "\\<" org-deadline-string)
2329 org-deadline-time-regexp
2330 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2331 org-deadline-line-regexp
2332 (concat "\\<\\(" org-deadline-string "\\).*")
2333 org-scheduled-regexp
2334 (concat "\\<" org-scheduled-string)
2335 org-scheduled-time-regexp
2336 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
2337 (org-set-font-lock-defaults)))
2339 ;; Tell the compiler about dynamically scoped variables,
2340 ;; and variables from other packages
2341 (defvar zmacs-regions) ; XEmacs regions
2342 (defvar original-date) ; dynamically scoped in calendar
2343 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
2344 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
2345 (defvar org-html-entities) ; defined later in this file
2346 (defvar org-goto-start-pos) ; dynamically scoped parameter
2347 (defvar org-time-was-given) ; dynamically scoped parameter
2348 (defvar org-ts-what) ; dynamically scoped parameter
2349 (defvar mark-active) ; Emacs only, not available in XEmacs.
2350 (defvar timecnt) ; dynamically scoped parameter
2351 (defvar levels-open) ; dynamically scoped parameter
2352 (defvar title) ; dynamically scoped parameter
2353 (defvar author) ; dynamically scoped parameter
2354 (defvar email) ; dynamically scoped parameter
2355 (defvar text) ; dynamically scoped parameter
2356 (defvar entry) ; dynamically scoped parameter
2357 (defvar date) ; dynamically scoped parameter
2358 (defvar language) ; dynamically scoped parameter
2359 (defvar options) ; dynamically scoped parameter
2360 (defvar ans1) ; dynamically scoped parameter
2361 (defvar ans2) ; dynamically scoped parameter
2362 (defvar starting-day) ; local variable
2363 (defvar include-all-loc) ; local variable
2364 (defvar vm-message-pointer) ; from vm
2365 (defvar vm-folder-directory) ; from vm
2366 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
2367 (defvar wl-summary-buffer-folder-name) ; from wanderlust
2368 (defvar gnus-group-name) ; from gnus
2369 (defvar gnus-article-current) ; from gnus
2370 (defvar w3m-current-url) ; from w3m
2371 (defvar mh-progs) ; from MH-E
2372 (defvar mh-current-folder) ; from MH-E
2373 (defvar mh-show-folder-buffer) ; from MH-E
2374 (defvar mh-index-folder) ; from MH-E
2375 (defvar mh-searcher) ; from MH-E
2376 (defvar org-selected-point) ; dynamically scoped parameter
2377 (defvar calendar-mode-map) ; from calendar.el
2378 (defvar last-arg) ; local variable
2379 (defvar remember-save-after-remembering) ; from remember.el
2380 (defvar remember-data-file) ; from remember.el
2381 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
2382 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
2383 (defvar orgtbl-mode) ; defined later in this file
2386 (defvar org-mode-map (copy-keymap outline-mode-map)
2387 "Keymap for Org-mode.")
2389 (defvar org-struct-menu) ; defined later in this file
2390 (defvar org-org-menu) ; defined later in this file
2391 (defvar org-tbl-menu) ; defined later in this file
2393 ;; We use a before-change function to check if a table might need
2395 (defvar org-table-may-need-update t
2396 "Indicates that a table might need an update.
2397 This variable is set by `org-before-change-function'.
2398 `org-table-align' sets it back to nil.")
2399 (defvar org-mode-hook nil)
2400 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2401 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2405 (define-derived-mode org-mode outline-mode "Org"
2406 "Outline-based notes management and organizer, alias
2407 \"Carsten's outline-mode for keeping track of everything.\"
2409 Org-mode develops organizational tasks around a NOTES file which
2410 contains information about projects as plain text. Org-mode is
2411 implemented on top of outline-mode, which is ideal to keep the content
2412 of large files well structured. It supports ToDo items, deadlines and
2413 time stamps, which magically appear in the diary listing of the Emacs
2414 calendar. Tables are easily created with a built-in table editor.
2415 Plain text URL-like links connect to websites, emails (VM), Usenet
2416 messages (Gnus), BBDB entries, and any files related to the project.
2417 For printing and sharing of notes, an Org-mode file (or a part of it)
2418 can be exported as a structured ASCII or HTML file.
2420 The following commands are available:
2423 (easy-menu-add org-org-menu)
2424 (easy-menu-add org-tbl-menu)
2425 (org-install-agenda-files-menu)
2426 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
2427 (org-add-to-invisibility-spec '(org-cwidth))
2428 (setq outline-regexp "\\*+")
2429 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2430 (setq outline-level 'org-outline-level)
2431 (when (and org-ellipsis (stringp org-ellipsis))
2432 (unless org-display-table
2433 (setq org-display-table (make-display-table)))
2434 (set-display-table-slot org-display-table
2435 4 (string-to-vector org-ellipsis))
2436 (setq buffer-display-table org-display-table))
2437 (org-set-regexps-and-options)
2438 (if org-startup-truncated (setq truncate-lines t))
2439 (set (make-local-variable 'font-lock-unfontify-region-function)
2440 'org-unfontify-region)
2441 ;; Activate before-change-function
2442 (set (make-local-variable 'org-table-may-need-update) t)
2443 (org-add-hook 'before-change-functions 'org-before-change-function nil
2445 ;; Paragraphs and auto-filling
2446 (org-set-autofill-regexps)
2447 (org-update-radio-target-regexp)
2448 ;; Settings for Calc embedded mode
2449 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2450 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2451 (if (and org-insert-mode-line-in-empty-file
2453 (= (point-min) (point-max)))
2454 (insert " -*- mode: org -*-\n\n"))
2456 ;; Get rid of Outline menus, they are not needed
2457 ;; Need to do this here because define-derived-mode sets up
2458 ;; the keymap so late.
2459 (if (featurep 'xemacs)
2461 (delete-menu-item '("Headings"))
2462 (delete-menu-item '("Show"))
2463 (delete-menu-item '("Hide"))
2464 (set-menubar-dirty-flag))
2465 (define-key org-mode-map [menu-bar headings] 'undefined)
2466 (define-key org-mode-map [menu-bar hide] 'undefined)
2467 (define-key org-mode-map [menu-bar show] 'undefined))
2469 (unless org-inhibit-startup
2470 (if org-startup-align-all-tables
2471 (org-table-map-tables 'org-table-align))
2472 (if org-startup-with-deadline-check
2473 (call-interactively 'org-check-deadlines)
2475 ((eq org-startup-folded t)
2477 ((eq org-startup-folded 'content)
2478 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2479 (org-cycle '(4)) (org-cycle '(4))))))))
2481 (defsubst org-current-line (&optional pos)
2482 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2484 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2486 "Properties to remove when a string without properties is wanted.")
2488 (defsubst org-match-string-no-properties (num &optional string)
2489 (if (featurep 'xemacs)
2490 (let ((s (match-string num string)))
2491 (remove-text-properties 0 (length s) org-rm-props s)
2493 (match-string-no-properties num string)))
2495 (defsubst org-no-properties (s)
2496 (remove-text-properties 0 (length s) org-rm-props s)
2499 (defun org-current-time ()
2500 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
2501 (if (> org-time-stamp-rounding-minutes 0)
2502 (let ((r org-time-stamp-rounding-minutes)
2503 (time (decode-time)))
2505 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
2509 (defun org-add-props (string plist &rest props)
2510 "Add text properties to entire string, from beginning to end.
2511 PLIST may be a list of properties, PROPS are individual properties and values
2512 that will be added to PLIST. Returns the string that was modified."
2513 (add-text-properties
2514 0 (length string) (if props (append plist props) plist) string)
2516 (put 'org-add-props 'lisp-indent-function 2)
2521 (defvar org-mouse-map (make-sparse-keymap))
2522 (define-key org-mouse-map
2523 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
2524 (define-key org-mouse-map
2525 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
2526 (when org-mouse-1-follows-link
2527 (define-key org-mouse-map [follow-link] 'mouse-face))
2528 (when org-tab-follows-link
2529 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2530 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2531 (when org-return-follows-link
2532 (define-key org-mouse-map [(return)] 'org-open-at-point)
2533 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2535 (require 'font-lock)
2537 (defconst org-non-link-chars "]\t\n\r<>")
2538 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
2539 "wl" "mhe" "rmail" "gnus" "shell"))
2540 (defconst org-link-re-with-space
2542 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2543 "\\([^" org-non-link-chars " ]"
2544 "[^" org-non-link-chars "]*"
2545 "[^" org-non-link-chars " ]\\)>?")
2546 "Matches a link with spaces, optional angular brackets around it.")
2548 (defconst org-link-re-with-space2
2550 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2551 "\\([^" org-non-link-chars " ]"
2553 "[^" org-non-link-chars " ]\\)>?")
2554 "Matches a link with spaces, optional angular brackets around it.")
2556 (defconst org-angle-link-re
2558 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2559 "\\([^" org-non-link-chars " ]"
2560 "[^" org-non-link-chars "]*"
2562 "Matches link with angular brackets, spaces are allowed.")
2563 (defconst org-plain-link-re
2565 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2566 "\\([^]\t\n\r<>,;() ]+\\)")
2567 "Matches plain link, without spaces.")
2569 (defconst org-bracket-link-regexp
2570 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
2571 "Matches a link in double brackets.")
2573 (defconst org-bracket-link-analytic-regexp
2576 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
2579 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
2588 (defconst org-ts-lengths
2589 (cons (length (format-time-string (car org-time-stamp-formats)))
2590 (length (format-time-string (cdr org-time-stamp-formats))))
2591 "This holds the lengths of the two different time formats.")
2592 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2593 "Regular expression for fast time stamp matching.")
2594 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2595 "Regular expression for fast time stamp matching.")
2596 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2597 "Regular expression matching time strings for analysis.")
2598 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2599 "Regular expression matching time stamps, with groups.")
2600 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2601 "Regular expression matching a time stamp range.")
2602 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2603 org-ts-regexp "\\)?")
2604 "Regular expression matching a time stamp or time stamp range.")
2606 (defun org-activate-plain-links (limit)
2607 "Run through the buffer and add overlays to links."
2608 (if (re-search-forward org-plain-link-re limit t)
2610 (add-text-properties (match-beginning 0) (match-end 0)
2611 (list 'mouse-face 'highlight
2612 'keymap org-mouse-map
2616 (defun org-activate-angle-links (limit)
2617 "Run through the buffer and add overlays to links."
2618 (if (re-search-forward org-angle-link-re limit t)
2620 (add-text-properties (match-beginning 0) (match-end 0)
2621 (list 'mouse-face 'highlight
2622 'keymap org-mouse-map
2626 (defun org-activate-bracket-links (limit)
2627 "Run through the buffer and add overlays to bracketed links."
2628 (if (re-search-forward org-bracket-link-regexp limit t)
2629 (let* ((help (concat "LINK: "
2630 (org-match-string-no-properties 1)))
2631 ;; FIXME: above we should remove the escapes.
2632 (ip (list 'invisible 'org-link 'intangible t 'rear-nonsticky t
2633 'keymap org-mouse-map 'mouse-face 'highlight
2635 (vp (list 'rear-nonsticky t
2636 'keymap org-mouse-map 'mouse-face 'highlight
2638 ;; We need to remove the invisible property here. Table narrowing
2639 ;; may have made some of this invisible.
2640 (remove-text-properties (match-beginning 0) (match-end 0)
2644 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
2645 (add-text-properties (match-beginning 3) (match-end 3) vp)
2646 (add-text-properties (match-end 3) (match-end 0) ip))
2647 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
2648 (add-text-properties (match-beginning 1) (match-end 1) vp)
2649 (add-text-properties (match-end 1) (match-end 0) ip))
2652 (defun org-activate-dates (limit)
2653 "Run through the buffer and add overlays to dates."
2654 (if (re-search-forward org-tsr-regexp limit t)
2656 (add-text-properties (match-beginning 0) (match-end 0)
2657 (list 'mouse-face 'highlight
2658 'keymap org-mouse-map))
2661 (defvar org-target-link-regexp nil
2662 "Regular expression matching radio targets in plain text.")
2663 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
2664 "Regular expression matching a link target.")
2665 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
2666 "Regular expression matching a link target.")
2668 (defun org-activate-target-links (limit)
2669 "Run through the buffer and add overlays to target matches."
2670 (when org-target-link-regexp
2671 (let ((case-fold-search t))
2672 (if (re-search-forward org-target-link-regexp limit t)
2674 (add-text-properties (match-beginning 0) (match-end 0)
2675 (list 'mouse-face 'highlight
2676 'keymap org-mouse-map
2677 'help-echo "Radio target link"
2678 'org-linked-text t))
2681 (defun org-update-radio-target-regexp ()
2682 "Find all radio targets in this file and update the regular expression."
2684 (when (memq 'radio org-activate-links)
2685 (setq org-target-link-regexp
2686 (org-make-target-link-regexp (org-all-targets 'radio)))
2687 (org-restart-font-lock)))
2689 (defun org-hide-wide-columns (limit)
2691 (setq s (text-property-any (point) (or limit (point-max))
2694 (setq e (next-single-property-change s 'org-cwidth))
2695 (add-text-properties s e '(invisible org-cwidth intangible t))
2699 (defun org-restart-font-lock ()
2700 "Restart font-lock-mode, to force refontification."
2701 (when (and (boundp 'font-lock-mode) font-lock-mode)
2703 (font-lock-mode 1)))
2705 (defun org-all-targets (&optional radio)
2706 "Return a list of all targets in this file.
2707 With optional argument RADIO, only find radio targets."
2708 (let ((re (if radio org-radio-target-regexp org-target-regexp))
2711 (goto-char (point-min))
2712 (while (re-search-forward re nil t)
2713 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
2716 (defun org-make-target-link-regexp (targets)
2717 "Make regular expression matching all strings in TARGETS.
2718 The regular expression finds the targets also if there is a line break
2725 (while (string-match " +" x)
2726 (setq x (replace-match "\\s-+" t t x)))
2732 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2733 "Matches CamelCase words, possibly with a star before it.")
2735 (defun org-activate-camels (limit)
2736 "Run through the buffer and add overlays to dates."
2737 (if (re-search-forward org-camel-regexp limit t)
2739 (add-text-properties (match-beginning 0) (match-end 0)
2740 (list 'mouse-face 'highlight
2741 'keymap org-mouse-map))
2744 (defun org-activate-tags (limit)
2745 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
2747 (add-text-properties (match-beginning 1) (match-end 1)
2748 (list 'mouse-face 'highlight
2749 'keymap org-mouse-map))
2752 (defun org-font-lock-level ()
2754 (org-back-to-heading t)
2755 (- (match-end 0) (match-beginning 0))))
2757 (defun org-outline-level ()
2759 (looking-at outline-regexp)
2760 (if (match-beginning 1)
2761 (+ (org-get-string-indentation (match-string 1)) 1000)
2762 (- (match-end 0) (match-beginning 0)))))
2764 (defvar org-font-lock-keywords nil)
2766 (defun org-set-font-lock-defaults ()
2767 (let* ((em org-fontify-emphasized-text)
2768 (lk org-activate-links)
2769 (org-font-lock-extra-keywords
2771 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
2772 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
2773 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2775 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
2776 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
2777 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
2778 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
2779 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
2780 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
2781 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
2782 (if org-table-limit-column-width
2783 '(org-hide-wide-columns (0 nil append)))
2784 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2786 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2787 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2788 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2789 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2790 ; (if em '("\\(\\W\\|^\\)\\(\\*\\w+\\*\\)\\(\\W\\|$\\)" 2 'bold prepend))
2791 ; (if em '("\\(\\W\\|^\\)\\(/\\w+/\\)\\(\\W\\|$\\)" 2 'italic prepend))
2792 ; (if em '("\\(\\W\\|^\\)\\(_\\w+_\\)\\(\\W\\|$\\)" 2 'underline prepend))
2793 (if em (list org-bold-re 2 ''bold 'prepend))
2794 (if em (list org-italic-re 2 ''italic 'prepend))
2795 (if em (list org-underline-re 2 ''underline 'prepend))
2796 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2797 "\\|" org-quote-string "\\)\\>")
2798 '(1 'org-special-keyword t))
2799 '("^#.*" (0 'font-lock-comment-face t))
2800 (if org-fontify-done-headline
2801 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2802 '(1 'org-done t) '(2 'org-headline-done t))
2803 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2805 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2806 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2807 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2808 (if org-format-transports-properties-p
2809 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
2811 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
2812 ;; Now set the full font-lock-keywords
2813 (set (make-local-variable 'org-font-lock-keywords)
2814 org-font-lock-extra-keywords)
2815 (set (make-local-variable 'font-lock-defaults)
2816 '(org-font-lock-keywords t nil nil backward-paragraph))
2817 (kill-local-variable 'font-lock-keywords) nil))
2822 (defun org-get-level-face (n)
2823 "Get the right face for match N in font-lock matching of healdines."
2824 (setq org-l (- (match-end 2) (match-beginning 1)))
2825 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
2826 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
2827 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
2829 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
2831 (t (if org-level-color-stars-only nil org-f))))
2833 (defun org-unfontify-region (beg end &optional maybe_loudly)
2834 "Remove fontification and activation overlays from links."
2835 (font-lock-default-unfontify-region beg end)
2836 (let* ((buffer-undo-list t)
2837 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2838 (inhibit-modification-hooks t)
2839 deactivate-mark buffer-file-name buffer-file-truename)
2840 (remove-text-properties beg end
2841 '(mouse-face nil keymap nil org-linked-text nil
2842 invisible nil intangible nil))))
2843 ;;; Visibility cycling
2845 (defvar org-cycle-global-status nil)
2846 (defvar org-cycle-subtree-status nil)
2847 (defun org-cycle (&optional arg)
2848 "Visibility cycling for Org-mode.
2850 - When this function is called with a prefix argument, rotate the entire
2851 buffer through 3 states (global cycling)
2852 1. OVERVIEW: Show only top-level headlines.
2853 2. CONTENTS: Show all headlines of all levels, but no body text.
2854 3. SHOW ALL: Show everything.
2856 - When point is at the beginning of a headline, rotate the subtree started
2857 by this line through 3 different states (local cycling)
2858 1. FOLDED: Only the main headline is shown.
2859 2. CHILDREN: The main headline and the direct children are shown.
2860 From this state, you can move to one of the children
2861 and zoom in further.
2862 3. SUBTREE: Show the entire subtree, including body text.
2864 - When there is a numeric prefix, go up to a heading with level ARG, do
2865 a `show-subtree' and return to the previous cursor position. If ARG
2866 is negative, go up that many levels.
2868 - When point is not at the beginning of a headline, execute
2869 `indent-relative', like TAB normally does. See the option
2870 `org-cycle-emulate-tab' for details.
2872 - Special case: if point is the the beginning of the buffer and there is
2873 no headline in line 1, this function will act as if called with prefix arg."
2876 (if (or (and (bobp) (not (looking-at outline-regexp)))
2878 ;; special case: use global cycling
2881 (let ((outline-regexp
2882 (if org-cycle-include-plain-lists
2883 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2888 ((org-at-table-p 'any)
2889 ;; Enter the table or move to the next field in the table
2890 (or (org-table-recognize-table.el)
2892 (if arg (org-table-edit-field t)
2893 (org-table-justify-field-maybe)
2894 (org-table-next-field)))))
2896 ((eq arg t) ;; Global cycling
2899 ((and (eq last-command this-command)
2900 (eq org-cycle-global-status 'overview))
2901 ;; We just created the overview - now do table of contents
2902 ;; This can be slow in very large buffers, so indicate action
2903 (message "CONTENTS...")
2905 ;; Visit all headings and show their offspring
2906 (goto-char (point-max))
2908 (while (and (progn (condition-case nil
2909 (outline-previous-visible-heading 1)
2910 (error (goto-char (point-min))))
2912 (looking-at outline-regexp))
2914 (if (bobp) (throw 'exit nil))))
2915 (message "CONTENTS...done"))
2916 (setq org-cycle-global-status 'contents)
2917 (run-hook-with-args 'org-cycle-hook 'contents))
2919 ((and (eq last-command this-command)
2920 (eq org-cycle-global-status 'contents))
2921 ;; We just showed the table of contents - now show everything
2923 (message "SHOW ALL")
2924 (setq org-cycle-global-status 'all)
2925 (run-hook-with-args 'org-cycle-hook 'all))
2928 ;; Default action: go to overview
2930 (message "OVERVIEW")
2931 (setq org-cycle-global-status 'overview)
2932 (run-hook-with-args 'org-cycle-hook 'overview))))
2935 ;; Show-subtree, ARG levels up from here.
2937 (org-back-to-heading)
2938 (outline-up-heading (if (< arg 0) (- arg)
2939 (- (funcall outline-level) arg)))
2940 (org-show-subtree)))
2942 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2943 ;; At a heading: rotate between three different views
2944 (org-back-to-heading)
2945 (let ((goal-column 0) eoh eol eos)
2946 ;; First, some boundaries
2948 (org-back-to-heading)
2950 (beginning-of-line 2)
2951 (while (and (not (eobp)) ;; this is like `next-line'
2952 (get-char-property (1- (point)) 'invisible))
2953 (beginning-of-line 2)) (setq eol (point)))
2954 (outline-end-of-heading) (setq eoh (point))
2955 (org-end-of-subtree t) (setq eos (point))
2956 (outline-next-heading))
2957 ;; Find out what to do next and set `this-command'
2960 ;; Nothing is hidden behind this heading
2961 (message "EMPTY ENTRY")
2962 (setq org-cycle-subtree-status nil))
2964 ;; Entire subtree is hidden in one line: open it
2967 (message "CHILDREN")
2968 (setq org-cycle-subtree-status 'children)
2969 (run-hook-with-args 'org-cycle-hook 'children))
2970 ((and (eq last-command this-command)
2971 (eq org-cycle-subtree-status 'children))
2972 ;; We just showed the children, now show everything.
2975 (setq org-cycle-subtree-status 'subtree)
2976 (run-hook-with-args 'org-cycle-hook 'subtree))
2978 ;; Default action: hide the subtree.
2981 (setq org-cycle-subtree-status 'folded)
2982 (run-hook-with-args 'org-cycle-hook 'folded)))))
2985 (buffer-read-only (org-back-to-heading))
2986 ((if (and (eq org-cycle-emulate-tab 'white)
2987 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2989 (eq org-cycle-emulate-tab t))
2990 (if (and (looking-at "[ \n\r\t]")
2991 (string-match "^[ \t]*$" (buffer-substring
2992 (point-at-bol) (point))))
2994 (beginning-of-line 1)
2995 (and (looking-at "[ \t]+") (replace-match ""))))
2999 (org-back-to-heading)
3002 (defun org-optimize-window-after-visibility-change (state)
3003 "Adjust the window after a change in outline visibility.
3004 This function is the default value of the hook `org-cycle-hook'."
3005 (when (get-buffer-window (current-buffer))
3007 ((eq state 'overview) (org-first-headline-recenter 1))
3008 ((eq state 'content) nil)
3009 ((eq state 'all) nil)
3010 ((eq state 'folded) nil)
3011 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3012 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3014 (defun org-subtree-end-visible-p ()
3015 "Is the end of the current subtree visible?"
3016 (pos-visible-in-window-p
3017 (save-excursion (org-end-of-subtree t) (point))))
3019 (defun org-first-headline-recenter (&optional N)
3020 "Move cursor to the first headline and recenter the headline.
3021 Optional argument N means, put the headline into the Nth line of the window."
3022 (goto-char (point-min))
3023 (when (re-search-forward (concat "^" outline-regexp) nil t)
3025 (recenter (prefix-numeric-value N))))
3027 (defvar org-goto-window-configuration nil)
3028 (defvar org-goto-marker nil)
3029 (defvar org-goto-map (make-sparse-keymap))
3030 (let ((cmds '(isearch-forward isearch-backward)) cmd)
3031 (while (setq cmd (pop cmds))
3032 (substitute-key-definition cmd cmd org-goto-map global-map)))
3033 (define-key org-goto-map "\C-m" 'org-goto-ret)
3034 (define-key org-goto-map [(left)] 'org-goto-left)
3035 (define-key org-goto-map [(right)] 'org-goto-right)
3036 (define-key org-goto-map [(?q)] 'org-goto-quit)
3037 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
3038 (define-key org-goto-map "\C-i" 'org-cycle)
3039 (define-key org-goto-map [(tab)] 'org-cycle)
3040 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
3041 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
3042 (define-key org-goto-map "n" 'outline-next-visible-heading)
3043 (define-key org-goto-map "p" 'outline-previous-visible-heading)
3044 (define-key org-goto-map "f" 'outline-forward-same-level)
3045 (define-key org-goto-map "b" 'outline-backward-same-level)
3046 (define-key org-goto-map "u" 'outline-up-heading)
3047 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
3048 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
3049 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
3050 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
3051 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
3052 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3053 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
3055 (defconst org-goto-help
3056 "Select a location to jump to, press RET
3057 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
3060 "Go to a different location of the document, keeping current visibility.
3062 When you want to go to a different location in a document, the fastest way
3063 is often to fold the entire buffer and then dive into the tree. This
3064 method has the disadvantage, that the previous location will be folded,
3065 which may not be what you want.
3067 This command works around this by showing a copy of the current buffer in
3068 overview mode. You can dive into the tree in that copy, to find the
3069 location you want to reach. When pressing RET, the command returns to the
3070 original buffer in which the visibility is still unchanged. It then jumps
3071 to the new location, making it and the headline hierarchy above it visible."
3073 (let* ((org-goto-start-pos (point))
3075 (org-get-location (current-buffer) org-goto-help)))
3078 (org-mark-ring-push org-goto-start-pos)
3079 (goto-char selected-point)
3080 (if (or (org-invisible-p) (org-invisible-p2))
3081 (org-show-hierarchy-above)))
3084 (defun org-get-location (buf help)
3085 "Let the user select a location in the Org-mode buffer BUF.
3086 This function uses a recursive edit. It returns the selected position
3088 (let (org-selected-point)
3090 (save-window-excursion
3091 (delete-other-windows)
3092 (switch-to-buffer (get-buffer-create "*org-goto*"))
3093 (with-output-to-temp-buffer "*Help*"
3095 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
3096 (setq buffer-read-only nil)
3098 (insert-buffer-substring buf)
3099 (let ((org-startup-truncated t)
3100 (org-startup-folded t)
3101 (org-startup-align-all-tables nil)
3102 (org-startup-with-deadline-check nil))
3104 (setq buffer-read-only t)
3105 (if (boundp 'org-goto-start-pos)
3106 (goto-char org-goto-start-pos)
3107 (goto-char (point-min)))
3108 (org-beginning-of-line)
3109 (message "Select location and press RET")
3110 ;; now we make sure that during selection, ony very few keys work
3111 ;; and that it is impossible to switch to another window.
3112 (let ((gm (current-global-map))
3113 (overriding-local-map org-goto-map))
3116 (use-global-map org-goto-map)
3118 (use-global-map gm)))))
3119 (kill-buffer "*org-goto*")
3120 org-selected-point))
3122 ;; FIXME: It may not be a good idea to temper with the prefix argument...
3123 (defun org-goto-ret (&optional arg)
3124 "Finish `org-goto' by going to the new location."
3126 (setq org-selected-point (point)
3127 current-prefix-arg arg)
3130 (defun org-goto-left ()
3131 "Finish `org-goto' by going to the new location."
3133 (if (org-on-heading-p)
3135 (beginning-of-line 1)
3136 (setq org-selected-point (point)
3137 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3139 (error "Not on a heading")))
3141 (defun org-goto-right ()
3142 "Finish `org-goto' by going to the new location."
3144 (if (org-on-heading-p)
3146 (outline-end-of-subtree)
3147 (or (eobp) (forward-char 1))
3148 (setq org-selected-point (point)
3149 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3151 (error "Not on a heading")))
3153 (defun org-goto-quit ()
3154 "Finish `org-goto' without cursor motion."
3156 (setq org-selected-point nil)
3159 ;;; Promotion, Demotion, Inserting new headlines
3161 (defvar org-ignore-region nil
3162 "To temporarily disable the active region.")
3164 (defun org-insert-heading (&optional force-heading)
3165 "Insert a new heading or item with same depth at point."
3167 (when (or force-heading (not (org-insert-item)))
3168 (let* ((head (save-excursion
3170 (org-back-to-heading)
3171 (error (outline-next-heading)))
3172 (prog1 (match-string 0)
3173 (funcall outline-level)))))
3175 ((and (org-on-heading-p) (bolp)
3176 (save-excursion (backward-char 1) (not (org-invisible-p))))
3182 (run-hooks 'org-insert-heading-hook))))
3184 (defun org-insert-item ()
3185 "Insert a new item at the current level.
3186 Return t when things worked, nil when we are not in an item."
3187 (when (save-excursion
3190 (org-beginning-of-item)
3194 (let* ((bul (match-string 0))
3195 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
3197 (eowcol (save-excursion (goto-char eow) (current-column))))
3199 ((and (org-at-item-p) (<= (point) eow))
3200 ;; before the bullet
3201 (beginning-of-line 1)
3204 (beginning-of-line 1))
3208 (org-maybe-renumber-ordered-list)
3211 (defun org-insert-todo-heading (arg)
3212 "Insert a new heading with the same level and TODO state as current heading.
3213 If the heading has no TODO state, or if the state is DONE, use the first
3214 state (TODO by default). Also with prefix arg, force first state."
3216 (org-insert-heading)
3218 (org-back-to-heading)
3219 (outline-previous-heading)
3220 (looking-at org-todo-line-regexp))
3222 (not (match-beginning 2))
3223 (equal (match-string 2) org-done-string))
3224 (insert (car org-todo-keywords) " ")
3225 (insert (match-string 2) " ")))
3227 (defun org-promote-subtree ()
3228 "Promote the entire subtree.
3229 See also `org-promote'."
3232 (org-map-tree 'org-promote)))
3234 (defun org-demote-subtree ()
3235 "Demote the entire subtree. See `org-demote'.
3236 See also `org-promote'."
3239 (org-map-tree 'org-demote)))
3241 (defun org-do-promote ()
3242 "Promote the current heading higher up the tree.
3243 If the region is active in `transient-mark-mode', promote all headings
3247 (if (org-region-active-p)
3248 (org-map-region 'org-promote (region-beginning) (region-end))
3250 (org-fix-position-after-promote))
3252 (defun org-do-demote ()
3253 "Demote the current heading lower down the tree.
3254 If the region is active in `transient-mark-mode', demote all headings
3258 (if (org-region-active-p)
3259 (org-map-region 'org-demote (region-beginning) (region-end))
3261 (org-fix-position-after-promote))
3263 (defun org-fix-position-after-promote ()
3264 "Make sure that after pro/demotion cursor position is right."
3265 (and (equal (char-after) ?\ )
3266 (equal (char-before) ?*)
3269 (defun org-get-legal-level (level change)
3270 "Rectify a level change under the influence of `org-odd-levels-only'
3271 LEVEL is a current level, CHANGE is by how much the level should be
3272 modified. Even if CHANGE is nil, LEVEL may be returned modified because
3273 even level numbers will become the next higher odd number."
3274 (if org-odd-levels-only
3275 (cond ((not change) (1+ (* 2 (/ level 2))))
3276 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
3277 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
3278 (max 1 (+ level change))))
3280 (defun org-promote ()
3281 "Promote the current heading higher up the tree.
3282 If the region is active in `transient-mark-mode', promote all headings
3284 (org-back-to-heading t)
3285 (let* ((level (save-match-data (funcall outline-level)))
3286 (up-head (make-string (org-get-legal-level level -1) ?*))
3287 (diff (abs (- level (length up-head)))))
3288 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
3289 (replace-match up-head nil t)
3290 ;; Fixup tag positioning
3291 (and org-auto-align-tags (org-set-tags nil t))
3292 (if org-adapt-indentation
3293 (org-fixup-indentation (if (> diff 1) "^ " "^ ") ""
3294 (if (> diff 1) "^ ? ?\\S-" "^ ?\\S-")))))
3296 (defun org-demote ()
3297 "Demote the current heading lower down the tree.
3298 If the region is active in `transient-mark-mode', demote all headings
3300 (org-back-to-heading t)
3301 (let* ((level (save-match-data (funcall outline-level)))
3302 (down-head (make-string (org-get-legal-level level 1) ?*))
3303 (diff (abs (- level (length down-head)))))
3304 (replace-match down-head nil t)
3305 ;; Fixup tag positioning
3306 (and org-auto-align-tags (org-set-tags nil t))
3307 (if org-adapt-indentation
3308 (org-fixup-indentation "^ " (if (> diff 1) " " " ") "^\\S-"))))
3310 (defun org-map-tree (fun)
3311 "Call FUN for every heading underneath the current one."
3312 (org-back-to-heading)
3313 (let ((level (funcall outline-level)))
3317 (outline-next-heading)
3318 (> (funcall outline-level) level))
3322 (defun org-map-region (fun beg end)
3323 "Call FUN for every heading between BEG and END."
3324 (let ((org-ignore-region t))
3326 (setq end (copy-marker end))
3328 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
3332 (outline-next-heading)
3337 (defun org-fixup-indentation (from to prohibit)
3338 "Change the indentation in the current entry by re-replacing FROM with TO.
3339 However, if the regexp PROHIBIT matches at all, don't do anything.
3340 This is being used to change indentation along with the length of the
3341 heading marker. But if there are any lines which are not indented, nothing
3344 (let ((end (save-excursion (outline-next-heading)
3346 (unless (save-excursion (re-search-forward prohibit end t))
3347 (while (re-search-forward from end t)
3349 (beginning-of-line 2)))
3350 (move-marker end nil))))
3352 ;;; Vertical tree motion, cutting and pasting of subtrees
3354 (defun org-move-subtree-up (&optional arg)
3355 "Move the current subtree up past ARG headlines of the same level."
3357 (org-move-subtree-down (- (prefix-numeric-value arg))))
3359 (defun org-move-subtree-down (&optional arg)
3360 "Move the current subtree down past ARG headlines of the same level."
3362 (setq arg (prefix-numeric-value arg))
3363 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
3364 'outline-get-last-sibling))
3365 (ins-point (make-marker))
3369 (org-back-to-heading)
3372 (save-excursion (outline-end-of-heading)
3373 (setq folded (org-invisible-p)))
3374 (outline-end-of-subtree))
3375 (outline-next-heading)
3377 ;; Find insertion point, with error handling
3380 (or (and (funcall movfunc) (looking-at outline-regexp))
3381 (progn (goto-char beg)
3382 (error "Cannot move past superior level or buffer limit")))
3383 (setq cnt (1- cnt)))
3385 ;; Moving forward - still need to move over subtree
3386 (progn (outline-end-of-subtree)
3387 (outline-next-heading)
3388 (if (not (or (looking-at (concat "^" outline-regexp))
3391 (move-marker ins-point (point))
3392 (setq txt (buffer-substring beg end))
3393 (delete-region beg end)
3395 (goto-char ins-point)
3396 (if folded (hide-subtree))
3397 (move-marker ins-point nil)))
3399 (defvar org-subtree-clip ""
3400 "Clipboard for cut and paste of subtrees.
3401 This is actually only a copy of the kill, because we use the normal kill
3402 ring. We need it to check if the kill was created by `org-copy-subtree'.")
3404 (defvar org-subtree-clip-folded nil
3405 "Was the last copied subtree folded?
3406 This is used to fold the tree back after pasting.")
3408 (defun org-cut-subtree ()
3409 "Cut the current subtree into the clipboard.
3410 This is a short-hand for marking the subtree and then cutting it."
3412 (org-copy-subtree 'cut))
3414 (defun org-copy-subtree (&optional cut)
3415 "Cut the current subtree into the clipboard.
3416 This is a short-hand for marking the subtree and then copying it.
3417 If CUT is non nil, actually cut the subtree."
3419 (let (beg end folded)
3420 (org-back-to-heading)
3423 (save-excursion (outline-end-of-heading)
3424 (setq folded (org-invisible-p)))
3425 (outline-end-of-subtree))
3426 (if (equal (char-after) ?\n) (forward-char 1))
3430 (setq org-subtree-clip-folded folded)
3431 (if cut (kill-region beg end) (copy-region-as-kill beg end))
3432 (setq org-subtree-clip (current-kill 0))
3433 (message "%s: Subtree with %d characters"
3434 (if cut "Cut" "Copied")
3435 (length org-subtree-clip)))))
3437 (defun org-paste-subtree (&optional level tree)
3438 "Paste the clipboard as a subtree, with modification of headline level.
3439 The entire subtree is promoted or demoted in order to match a new headline
3440 level. By default, the new level is derived from the visible headings
3441 before and after the insertion point, and taken to be the inferior headline
3442 level of the two. So if the previous visible heading is level 3 and the
3443 next is level 4 (or vice versa), level 4 will be used for insertion.
3444 This makes sure that the subtree remains an independent subtree and does
3445 not swallow low level entries.
3447 You can also force a different level, either by using a numeric prefix
3448 argument, or by inserting the heading marker by hand. For example, if the
3449 cursor is after \"*****\", then the tree will be shifted to level 5.
3451 If you want to insert the tree as is, just use \\[yank].
3453 If optional TREE is given, use this text instead of the kill ring."
3455 (unless (org-kill-is-subtree-p tree)
3457 (substitute-command-keys
3458 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
3459 (let* ((txt (or tree (current-kill 0)))
3460 (^re (concat "^\\(" outline-regexp "\\)"))
3461 (re (concat "\\(" outline-regexp "\\)"))
3462 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
3464 (old-level (if (string-match ^re txt)
3465 (- (match-end 0) (match-beginning 0))
3467 (force-level (cond (level (prefix-numeric-value level))
3469 ^re_ (buffer-substring (point-at-bol) (point)))
3470 (- (match-end 0) (match-beginning 0)))
3472 (previous-level (save-excursion
3475 (outline-previous-visible-heading 1)
3477 (- (match-end 0) (match-beginning 0))
3480 (next-level (save-excursion
3483 (outline-next-visible-heading 1)
3485 (- (match-end 0) (match-beginning 0))
3488 (new-level (or force-level (max previous-level next-level)))
3489 (shift (if (or (= old-level -1)
3491 (= old-level new-level))
3493 (- new-level old-level)))
3495 (delta (if (> shift 0) -1 1))
3496 (func (if (> shift 0) 'org-demote 'org-promote))
3497 (org-odd-levels-only nil)
3499 ;; Remove the forces level indicator
3501 (delete-region (point-at-bol) (point)))
3502 ;; Make sure we start at the beginning of an empty line
3503 (if (not (bolp)) (insert "\n"))
3504 (if (not (looking-at "[ \t]*$"))
3505 (progn (insert "\n") (backward-char 1)))
3511 ;; Shift if necessary
3513 (message "Pasted at level %d, without shift" new-level)
3515 (narrow-to-region beg end)
3516 (while (not (= shift 0))
3517 (org-map-region func (point-min) (point-max))
3518 (setq shift (+ delta shift)))
3519 (goto-char (point-min))
3520 (message "Pasted at level %d, with shift by %d levels"
3522 (if (and (eq org-subtree-clip (current-kill 0))
3523 org-subtree-clip-folded)
3524 ;; The tree was folded before it was killed/copied
3527 (defun org-kill-is-subtree-p (&optional txt)
3528 "Check if the current kill is an outline subtree, or a set of trees.
3529 Returns nil if kill does not start with a headline, or if the first
3530 headline level is not the largest headline level in the tree.
3531 So this will actually accept several entries of equal levels as well,
3532 which is OK for `org-paste-subtree'.
3533 If optional TXT is given, check this string instead of the current kill."
3534 (let* ((kill (or txt (current-kill 0) ""))
3535 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
3536 (- (match-end 0) (match-beginning 0))))
3537 (re (concat "^" outline-regexp))
3539 (if (not start-level)
3540 nil ;; does not even start with a heading
3542 (while (setq start (string-match re kill (1+ start)))
3543 (if (< (- (match-end 0) (match-beginning 0)) start-level)
3547 ;;; Plain list items
3549 (defun org-at-item-p ()
3550 "Is point in a line starting a hand-formatted item?"
3551 (let ((llt org-plain-list-ordered-item-terminator))
3553 (goto-char (point-at-bol))
3556 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3557 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3558 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3559 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
3561 (defun org-get-indentation ()
3562 "Get the indentation of the current line, interpreting tabs."
3564 (beginning-of-line 1)
3565 (skip-chars-forward " \t")
3568 (defun org-beginning-of-item ()
3569 "Go to the beginning of the current hand-formatted item.
3570 If the cursor is not in an item, throw an error."
3572 (limit (save-excursion (org-back-to-heading)
3573 (beginning-of-line 2) (point)))
3576 (beginning-of-line 1)
3577 (beginning-of-line 1)
3578 (skip-chars-forward " \t")
3579 (setq ind (current-column))
3582 (beginning-of-line 0)
3583 (if (< (point) limit) (throw 'exit nil))
3584 (unless (looking-at " \t]*$")
3585 (skip-chars-forward " \t")
3586 (setq ind1 (current-column))
3588 (throw 'exit (org-at-item-p))))))
3591 (error "Not in an item")))))
3593 (defun org-end-of-item ()
3594 "Go to the end of the current hand-formatted item.
3595 If the cursor is not in an item, throw an error."
3597 (limit (save-excursion (outline-next-heading) (point)))
3598 (ind (save-excursion
3599 (org-beginning-of-item)
3600 (skip-chars-forward " \t")
3605 (beginning-of-line 2)
3606 (if (>= (point) limit) (throw 'exit t))
3607 (unless (looking-at "[ \t]*$")
3608 (skip-chars-forward " \t")
3609 (setq ind1 (current-column))
3610 (if (<= ind1 ind) (throw 'exit t)))))
3611 (beginning-of-line 1)
3613 (error "Not in an item"))))
3615 (defun org-move-item-down (arg)
3616 "Move the plain list item at point down, i.e. swap with following item.
3617 Subitems (items with larger indentation) are considered part of the item,
3618 so this really moves item trees."
3620 (let (beg end ind ind1 (pos (point)) txt)
3621 (org-beginning-of-item)
3623 (setq ind (org-get-indentation))
3626 (setq ind1 (org-get-indentation))
3627 (if (and (org-at-item-p) (= ind ind1))
3630 (setq txt (buffer-substring beg end))
3632 (delete-region beg end))
3636 (org-maybe-renumber-ordered-list))
3638 (error "Cannot move this item further down"))))
3640 (defun org-move-item-up (arg)
3641 "Move the plain list item at point up, i.e. swap with previous item.
3642 Subitems (items with larger indentation) are considered part of the item,
3643 so this really moves item trees."
3645 (let (beg end ind ind1 (pos (point)) txt)
3646 (org-beginning-of-item)
3648 (setq ind (org-get-indentation))
3654 (beginning-of-line 0)
3655 (if (looking-at "[ \t]*$")
3657 (if (<= (setq ind1 (org-get-indentation)) ind)
3660 (org-beginning-of-item)
3661 (error (goto-char beg)
3662 (error "Cannot move this item further up")))
3663 (setq ind1 (org-get-indentation))
3664 (if (and (org-at-item-p) (= ind ind1))
3666 (setq txt (buffer-substring beg end))
3668 (delete-region beg end))
3672 (org-maybe-renumber-ordered-list))
3674 (error "Cannot move this item further up"))))
3676 (defun org-maybe-renumber-ordered-list ()
3677 "Renumber the ordered list at point if setup allows it.
3678 This tests the user option `org-auto-renumber-ordered-lists' before
3679 doing the renumbering."
3680 (and org-auto-renumber-ordered-lists
3683 (org-renumber-ordered-list 1)))
3685 (defun org-get-string-indentation (s)
3686 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3687 (let ((n -1) (i 0) (w tab-width) c)
3689 (while (< (setq n (1+ n)) (length s))
3691 (cond ((= c ?\ ) (setq i (1+ i)))
3692 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3693 (t (throw 'exit t)))))
3696 (defun org-renumber-ordered-list (arg)
3697 "Renumber an ordered plain list.
3698 Cursor next to be in the first line of an item, the line that starts
3699 with something like \"1.\" or \"2)\"."
3701 (unless (and (org-at-item-p)
3702 (match-beginning 3))
3703 (error "This is not an ordered list"))
3704 (let ((line (org-current-line))
3705 (col (current-column))
3706 (ind (org-get-string-indentation
3707 (buffer-substring (point-at-bol) (match-beginning 3))))
3708 ;; (term (substring (match-string 3) -1))
3710 ;; find where this list begins
3714 (beginning-of-line 0)
3715 (if (looking-at "[ \t]*$") (throw 'next t))
3716 (skip-chars-forward " \t") (setq ind1 (current-column))
3717 (if (or (< ind1 ind)
3719 (not (org-at-item-p))))
3721 ;; Walk forward and replace these numbers
3725 (beginning-of-line 2)
3726 (if (eobp) (throw 'exit nil))
3727 (if (looking-at "[ \t]*$") (throw 'next nil))
3728 (skip-chars-forward " \t") (setq ind1 (current-column))
3729 (if (> ind1 ind) (throw 'next t))
3730 (if (< ind1 ind) (throw 'exit t))
3731 (if (not (org-at-item-p)) (throw 'exit nil))
3732 (if (not (match-beginning 3))
3733 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3734 (delete-region (match-beginning 3) (1- (match-end 3)))
3735 (goto-char (match-beginning 3))
3736 (insert (format "%d" (setq n (1+ n)))))))
3738 (move-to-column col)))
3740 (defvar org-last-indent-begin-marker (make-marker))
3741 (defvar org-last-indent-end-marker (make-marker))
3743 (defun org-outdent-item (arg)
3744 "Outdent a local list item."
3746 (org-indent-item (- arg)))
3748 (defun org-indent-item (arg)
3749 "Indent a local list item."
3751 (unless (org-at-item-p)
3752 (error "Not on an item"))
3753 (let (beg end ind ind1)
3754 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3755 (setq beg org-last-indent-begin-marker
3756 end org-last-indent-end-marker)
3757 (org-beginning-of-item)
3758 (setq beg (move-marker org-last-indent-begin-marker (point)))
3760 (setq end (move-marker org-last-indent-end-marker (point))))
3762 (skip-chars-forward " \t") (setq ind (current-column))
3763 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3764 (while (< (point) end)
3765 (beginning-of-line 1)
3766 (skip-chars-forward " \t") (setq ind1 (current-column))
3767 (delete-region (point-at-bol) (point))
3768 (indent-to-column (+ ind1 arg))
3769 (beginning-of-line 2))
3774 (defun org-archive-subtree ()
3775 "Move the current subtree to the archive.
3776 The archive can be a certain top-level heading in the current file, or in
3777 a different file. The tree will be moved to that location, the subtree
3778 heading be marked DONE, and the current time will be added."
3780 ;; Save all relevant TODO keyword-relatex variables
3781 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3782 (tr-org-todo-keywords org-todo-keywords)
3783 (tr-org-todo-interpretation org-todo-interpretation)
3784 (tr-org-done-string org-done-string)
3785 (tr-org-todo-regexp org-todo-regexp)
3786 (tr-org-todo-line-regexp org-todo-line-regexp)
3787 (this-buffer (current-buffer))
3788 file heading buffer level newfile-p)
3789 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3791 (setq file (format (match-string 1 org-archive-location)
3792 (file-name-nondirectory buffer-file-name))
3793 heading (match-string 2 org-archive-location)))
3794 (error "Invalid `org-archive-location'"))
3795 (if (> (length file) 0)
3796 (setq newfile-p (not (file-exists-p file))
3797 buffer (find-file-noselect file))
3798 (setq buffer (current-buffer)))
3800 (error "Cannot access file \"%s\"" file))
3801 (if (and (> (length heading) 0)
3802 (string-match "^\\*+" heading))
3803 (setq level (match-end 0))
3804 (setq heading nil level 0))
3806 ;; We first only copy, in case something goes wrong
3807 ;; we need to protect this-command, to avoid kill-region sets it,
3808 ;; which would lead to duplication of subtrees
3809 (let (this-command) (org-copy-subtree))
3811 ;; Enforce org-mode for the archive buffer
3812 (if (not (eq major-mode 'org-mode))
3813 ;; Force the mode for future visits.
3814 (let ((org-insert-mode-line-in-empty-file t))
3815 (call-interactively 'org-mode)))
3817 (goto-char (point-max))
3818 (insert (format "\nArchived entries from file %s\n\n"
3819 (buffer-file-name this-buffer))))
3820 ;; Force the TODO keywords of the original buffer
3821 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3822 (org-todo-keywords tr-org-todo-keywords)
3823 (org-todo-interpretation tr-org-todo-interpretation)
3824 (org-done-string tr-org-done-string)
3825 (org-todo-regexp tr-org-todo-regexp)
3826 (org-todo-line-regexp tr-org-todo-line-regexp))
3827 (goto-char (point-min))
3830 (if (re-search-forward
3831 (concat "\\(^\\|\r\\)"
3832 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3834 (goto-char (match-end 0))
3835 ;; Heading not found, just insert it at the end
3836 (goto-char (point-max))
3837 (or (bolp) (insert "\n"))
3838 (insert "\n" heading "\n")
3840 ;; Make the heading visible, and the following as well
3841 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3842 (if (re-search-forward
3843 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3845 (progn (goto-char (match-beginning 0)) (insert "\n")
3846 (beginning-of-line 0))
3847 (goto-char (point-max)) (insert "\n")))
3848 (goto-char (point-max)) (insert "\n"))
3850 (org-paste-subtree (1+ level))
3851 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3852 (if org-archive-mark-done
3853 (org-todo (length org-todo-keywords)))
3854 ;; Move cursor to right after the TODO keyword
3855 (when org-archive-stamp-time
3856 (beginning-of-line 1)
3857 (looking-at org-todo-line-regexp)
3858 (goto-char (or (match-end 2) (match-beginning 3)))
3859 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3862 ;; Save the buffer, if it is not the same buffer.
3863 (if (not (eq this-buffer buffer)) (save-buffer))))
3864 ;; Here we are back in the original buffer. Everything seems to have
3865 ;; worked. So now cut the tree and finish up.
3866 (let (this-command) (org-cut-subtree))
3867 (if (looking-at "[ \t]*$") (kill-line))
3868 (message "Subtree archived %s"
3869 (if (eq this-buffer buffer)
3870 (concat "under heading: " heading)
3871 (concat "in file: " (abbreviate-file-name file))))))
3875 (defun org-complete (&optional arg)
3876 "Perform completion on word at point.
3877 At the beginning of a headline, this completes TODO keywords as given in
3878 `org-todo-keywords'.
3879 If the current word is preceded by a backslash, completes the TeX symbols
3880 that are supported for HTML support.
3881 If the current word is preceded by \"#+\", completes special words for
3882 setting file options.
3883 At all other locations, this simply calls `ispell-complete-word'."
3886 (let* ((end (point))
3887 (beg1 (save-excursion
3888 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3889 (skip-chars-backward "a-zA-Z_@0-9")
3891 (beg (save-excursion
3892 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3893 (skip-chars-backward "a-zA-Z0-9_:$")
3895 (camel (equal (char-before beg) ?*))
3896 (tag (equal (char-before beg1) ?:))
3897 (texp (equal (char-before beg) ?\\))
3898 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3901 (completion-ignore-case opt)
3908 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3909 (cons (match-string 2 x) (match-string 1 x)))
3910 (org-split-string (org-get-current-options) "\n")))
3914 ((string-match "\\`\\*+[ \t]*\\'"
3915 (buffer-substring (point-at-bol) beg))
3917 (mapcar 'list org-todo-keywords))
3921 (goto-char (point-min))
3922 (while (re-search-forward org-todo-line-regexp nil t)
3924 (if org-file-link-context-use-camel-case
3925 (org-make-org-heading-camel (match-string 3) t)
3926 (org-make-org-heading-search-string
3927 (match-string 3) t)))
3930 (tag (setq type :tag beg beg1)
3931 (org-get-buffer-tags))
3932 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3933 (pattern (buffer-substring-no-properties beg end))
3934 (completion (try-completion pattern table)))
3935 (cond ((eq completion t)
3936 (if (equal type :opt)
3937 (insert (substring (cdr (assoc (upcase pattern) table))
3938 (length pattern)))))
3940 (message "Can't find completion for \"%s\"" pattern)
3942 ((not (string= pattern completion))
3943 (delete-region beg end)
3944 (if (string-match " +$" completion)
3945 (setq completion (replace-match "" t t completion)))
3947 (if (get-buffer-window "*Completions*")
3948 (delete-window (get-buffer-window "*Completions*")))
3949 (if (assoc completion table)
3950 (if (eq type :todo) (insert " ")
3951 (if (eq type :tag) (insert ":"))))
3952 (if (and (equal type :opt) (assoc completion table))
3953 (message "%s" (substitute-command-keys
3954 "Press \\[org-complete] again to insert example settings"))))
3956 (message "Making completion list...")
3957 (let ((list (sort (all-completions pattern table) 'string<)))
3958 (with-output-to-temp-buffer "*Completions*"
3960 ;; Protection needed for XEmacs and emacs 21
3961 (display-completion-list list pattern)
3962 (error (display-completion-list list)))))
3963 (message "Making completion list...%s" "done"))))))
3965 ;;; Comments, TODO and DEADLINE
3967 (defun org-toggle-comment ()
3968 "Change the COMMENT state of an entry."
3971 (org-back-to-heading)
3972 (if (looking-at (concat outline-regexp
3973 "\\( +\\<" org-comment-string "\\>\\)"))
3974 (replace-match "" t t nil 1)
3975 (if (looking-at outline-regexp)
3977 (goto-char (match-end 0))
3978 (insert " " org-comment-string))))))
3980 (defvar org-last-todo-state-is-todo nil
3981 "This is non-nil when the last TODO state change led to a TODO state.
3982 If the last change removed the TODO tag or switched to DONE, then
3985 (defun org-todo (&optional arg)
3986 "Change the TODO state of an item.
3987 The state of an item is given by a keyword at the start of the heading,
3989 *** TODO Write paper
3992 The different keywords are specified in the variable `org-todo-keywords'.
3993 By default the available states are \"TODO\" and \"DONE\".
3994 So for this example: when the item starts with TODO, it is changed to DONE.
3995 When it starts with DONE, the DONE is removed. And when neither TODO nor
3996 DONE are present, add TODO at the beginning of the heading.
3998 With prefix arg, use completion to determine the new state. With numeric
3999 prefix arg, switch to that state."
4002 (org-back-to-heading)
4003 (if (looking-at outline-regexp) (goto-char (match-end 0)))
4004 (or (looking-at (concat " +" org-todo-regexp " *"))
4006 (let* ((this (match-string 1))
4007 (completion-ignore-case t)
4008 (member (member this org-todo-keywords))
4012 ;; Read a state with completion
4013 (completing-read "State: " (mapcar (lambda(x) (list x))
4018 (if tail (car tail) nil)
4019 (car org-todo-keywords)))
4021 (if (equal member org-todo-keywords)
4024 (nth (- (length org-todo-keywords) (length tail) 2)
4028 ;; user requests a specific state
4029 (nth (1- (prefix-numeric-value arg))
4031 ((null member) (car org-todo-keywords))
4032 ((null tail) nil) ;; -> first entry
4033 ((eq org-todo-interpretation 'sequence)
4035 ((memq org-todo-interpretation '(type priority))
4036 (if (eq this-command last-command)
4038 (if (> (length tail) 0) org-done-string nil)))
4040 (next (if state (concat " " state " ") " ")))
4041 (replace-match next t t)
4042 (setq org-last-todo-state-is-todo
4043 (not (equal state org-done-string)))
4045 (if (equal state org-done-string)
4049 ;; Fixup tag positioning
4050 (and org-auto-align-tags (org-set-tags nil t))
4051 (run-hooks 'org-after-todo-state-change-hook)))
4052 ;; Fixup cursor location if close to the keyword
4053 (if (and (outline-on-heading-p)
4055 (save-excursion (beginning-of-line 1)
4056 (looking-at org-todo-line-regexp))
4057 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
4059 (goto-char (or (match-end 2) (match-end 1)))
4062 (defun org-log-done (&optional undone)
4063 "Add a time stamp logging that a TODO entry has been closed.
4064 When UNDONE is non-nil, remove such a time stamp again."
4068 (org-back-to-heading t)
4070 (looking-at (concat outline-regexp " *"))
4071 (goto-char (match-end 0))
4072 (setq col (current-column))
4073 (outline-next-heading)
4076 (when (re-search-forward (concat
4078 (regexp-quote org-closed-string)
4079 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
4080 (delete-region (match-beginning 1) (match-end 1)))
4082 (org-back-to-heading t)
4083 (skip-chars-forward "^\n\r")
4084 (goto-char (min (1+ (point)) (point-max)))
4085 (when (not (member (char-before) '(?\r ?\n)))
4088 (insert org-closed-string " "
4090 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
4094 (defun org-show-todo-tree (arg)
4095 "Make a compact tree which shows all headlines marked with TODO.
4096 The tree will show the lines where the regexp matches, and all higher
4097 headlines above the match.
4098 With \\[universal-argument] prefix, also show the DONE entries.
4099 With a numeric prefix N, construct a sparse tree for the Nth element
4100 of `org-todo-keywords'."
4102 (let ((case-fold-search nil)
4104 (cond ((null arg) org-not-done-regexp)
4105 ((equal arg '(4)) org-todo-regexp)
4106 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
4107 (regexp-quote (nth (1- (prefix-numeric-value arg))
4108 org-todo-keywords)))
4109 (t (error "Invalid prefix argument: %s" arg)))))
4110 (message "%d TODO entries found"
4111 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
4113 (defun org-deadline ()
4114 "Insert the DEADLINE: string to make a deadline.
4115 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
4116 to modify it to the correct date."
4119 org-deadline-string " "
4120 (format-time-string (car org-time-stamp-formats)
4121 (org-read-date nil 'to-time)))
4122 (message "%s" (substitute-command-keys
4123 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
4125 (defun org-schedule ()
4126 "Insert the SCHEDULED: string to schedule a TODO item.
4127 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
4128 to modify it to the correct date."
4131 org-scheduled-string " "
4132 (format-time-string (car org-time-stamp-formats)
4133 (org-read-date nil 'to-time)))
4134 (message "%s" (substitute-command-keys
4135 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
4138 (defun org-occur (regexp &optional callback)
4139 "Make a compact tree which shows all matches of REGEXP.
4140 The tree will show the lines where the regexp matches, and all higher
4141 headlines above the match. It will also show the heading after the match,
4142 to make sure editing the matching entry is easy.
4143 If CALLBACK is non-nil, it is a function which is called to confirm
4144 that the match should indeed be shown."
4145 (interactive "sRegexp: ")
4146 (org-remove-occur-highlights nil nil t)
4147 (setq regexp (org-check-occur-regexp regexp))
4150 (goto-char (point-min))
4152 (while (re-search-forward regexp nil t)
4153 (when (or (not callback)
4154 (save-match-data (funcall callback)))
4156 (org-highlight-new-match (match-beginning 0) (match-end 0))
4157 (org-show-hierarchy-above))))
4158 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
4160 (run-hooks 'org-occur-hook)
4162 (message "%d match(es) for regexp %s" cnt regexp))
4165 (defun org-show-hierarchy-above ()
4166 "Make sure point and the headings hierarchy above is visible."
4168 (if (org-on-heading-p t)
4169 (org-flag-heading nil) ; only show the heading
4170 (and (or (org-invisible-p) (org-invisible-p2))
4171 (org-show-hidden-entry))) ; show entire entry
4173 (and org-show-following-heading
4174 (outline-next-heading)
4175 (org-flag-heading nil))) ; show the next heading
4176 (when org-show-hierarchy-above
4177 (save-excursion ; show all higher headings
4178 (while (and (condition-case nil
4179 (progn (org-up-heading-all 1) t)
4182 (org-flag-heading nil))))))
4184 ;; Overlay compatibility functions
4185 (defun org-make-overlay (beg end &optional buffer)
4186 (if (featurep 'xemacs)
4187 (make-extent beg end buffer)
4188 (make-overlay beg end buffer)))
4189 (defun org-delete-overlay (ovl)
4190 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4191 (defun org-detatch-overlay (ovl)
4192 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4193 (defun org-move-overlay (ovl beg end &optional buffer)
4194 (if (featurep 'xemacs)
4195 (set-extent-endpoints ovl beg end buffer)
4196 (move-overlay ovl beg end buffer)))
4197 (defun org-overlay-put (ovl prop value)
4198 (if (featurep 'xemacs)
4199 (set-extent-property ovl prop value)
4200 (overlay-put ovl prop value)))
4202 (defvar org-occur-highlights nil)
4203 (defun org-highlight-new-match (beg end)
4204 "Highlight from BEG to END and mark the highlight is an occur headline."
4205 (let ((ov (org-make-overlay beg end)))
4206 (org-overlay-put ov 'face 'secondary-selection)
4207 (push ov org-occur-highlights)))
4209 (defun org-remove-occur-highlights (&optional beg end noremove)
4210 "Remove the occur highlights from the buffer.
4211 BEG and END are ignored. If NOREMOVE is nil, remove this function
4212 from the `before-change-functions' in the current buffer."
4214 (mapc 'org-delete-overlay org-occur-highlights)
4215 (setq org-occur-highlights nil)
4217 (remove-hook 'before-change-functions
4218 'org-remove-occur-highlights 'local)))
4222 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
4223 "Regular expression matching the priority indicator.")
4225 (defvar org-remove-priority-next-time nil)
4227 (defun org-priority-up ()
4228 "Increase the priority of the current item."
4232 (defun org-priority-down ()
4233 "Decrease the priority of the current item."
4235 (org-priority 'down))
4237 (defun org-priority (&optional action)
4238 "Change the priority of an item by ARG.
4239 ACTION can be set, up, or down."
4241 (setq action (or action 'set))
4242 (let (current new news have remove)
4244 (org-back-to-heading)
4245 (if (looking-at org-priority-regexp)
4246 (setq current (string-to-char (match-string 2))
4248 (setq current org-default-priority))
4251 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
4252 (setq new (read-char-exclusive))
4253 (cond ((equal new ?\ ) (setq remove t))
4254 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
4255 (error "Priority must be between `%c' and `%c'"
4256 ?A org-lowest-priority))))
4258 (setq new (1- current)))
4260 (setq new (1+ current)))
4261 (t (error "Invalid action")))
4262 (setq new (min (max ?A (upcase new)) org-lowest-priority))
4263 (setq news (format "%c" new))
4266 (replace-match "" t t nil 1)
4267 (replace-match news t t nil 2))
4269 (error "No priority cookie found in line")
4270 (looking-at org-todo-line-regexp)
4273 (goto-char (match-end 2))
4274 (insert " [#" news "]"))
4275 (goto-char (match-beginning 3))
4276 (insert "[#" news "] ")))))
4278 (message "Priority removed")
4279 (message "Priority of current item set to %s" news))))
4282 (defun org-get-priority (s)
4283 "Find priority cookie and return priority."
4285 (if (not (string-match org-priority-regexp s))
4286 (* 1000 (- org-lowest-priority org-default-priority))
4287 (* 1000 (- org-lowest-priority
4288 (string-to-char (match-string 2 s)))))))
4292 (defvar org-last-changed-timestamp nil)
4294 (defun org-time-stamp (arg)
4295 "Prompt for a date/time and insert a time stamp.
4296 If the user specifies a time like HH:MM, or if this command is called
4297 with a prefix argument, the time stamp will contain date and time.
4298 Otherwise, only the date will be included. All parts of a date not
4299 specified by the user will be filled in from the current date/time.
4300 So if you press just return without typing anything, the time stamp
4301 will represent the current date/time. If there is already a timestamp
4302 at the cursor, it will be modified."
4304 (let ((fmt (if arg (cdr org-time-stamp-formats)
4305 (car org-time-stamp-formats)))
4306 (org-time-was-given nil)
4309 ((and (org-at-timestamp-p)
4310 (eq last-command 'org-time-stamp)
4311 (eq this-command 'org-time-stamp))
4313 (setq time (let ((this-command this-command))
4314 (org-read-date arg 'totime)))
4315 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4316 (insert (format-time-string fmt time)))
4317 ((org-at-timestamp-p)
4318 (setq time (let ((this-command this-command))
4319 (org-read-date arg 'totime)))
4320 (and (org-at-timestamp-p) (replace-match
4321 (setq org-last-changed-timestamp
4322 (format-time-string fmt time))
4324 (message "Timestamp updated"))
4326 (setq time (let ((this-command this-command))
4327 (org-read-date arg 'totime)))
4328 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4329 (insert (format-time-string fmt time))))))
4331 (defun org-time-stamp-inactive (&optional arg)
4332 "Insert an inactive time stamp.
4333 An inactive time stamp is enclosed in square brackets instead of angle
4334 brackets. It is inactive in the sense that it does not trigger agenda entries,
4335 does not link to the calendar and cannot be changed with the S-cursor keys.
4336 So these are more for recording a certain time/date."
4338 (let ((fmt (if arg (cdr org-time-stamp-formats)
4339 (car org-time-stamp-formats)))
4340 (org-time-was-given nil)
4342 (setq time (org-read-date arg 'totime))
4343 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4344 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
4345 (insert (format-time-string fmt time))))
4347 (defvar org-date-ovl (org-make-overlay 1 1))
4348 (org-overlay-put org-date-ovl 'face 'org-warning)
4349 (org-detatch-overlay org-date-ovl)
4351 (defun org-read-date (&optional with-time to-time)
4352 "Read a date and make things smooth for the user.
4353 The prompt will suggest to enter an ISO date, but you can also enter anything
4354 which will at least partially be understood by `parse-time-string'.
4355 Unrecognized parts of the date will default to the current day, month, year,
4356 hour and minute. For example,
4357 3-2-5 --> 2003-02-05
4358 feb 15 --> currentyear-02-15
4359 sep 12 9 --> 2009-09-12
4360 12:45 --> today 12:45
4361 22 sept 0:34 --> currentyear-09-22 0:34
4362 12 --> currentyear-currentmonth-12
4363 Fri --> nearest Friday (today or later)
4365 The function understands only English month and weekday abbreviations,
4366 but this can be configured with the variables `parse-time-months' and
4367 `parse-time-weekdays'.
4369 While prompting, a calendar is popped up - you can also select the
4370 date with the mouse (button 1). The calendar shows a period of three
4371 months. To scroll it to other months, use the keys `>' and `<'.
4372 If you don't like the calendar, turn it off with
4373 \(setq org-popup-calendar-for-date-prompt nil)
4375 With optional argument TO-TIME, the date will immediately be converted
4376 to an internal time.
4377 With an optional argument WITH-TIME, the prompt will suggest to also
4378 insert a time. Note that when WITH-TIME is not set, you can still
4379 enter a time, and this function will inform the calling routine about
4380 this change. The calling routine may then choose to change the format
4381 used to insert the time stamp into the buffer to include the time."
4382 (require 'parse-time)
4383 (let* ((org-time-stamp-rounding-minutes
4384 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
4385 (ct (org-current-time))
4387 ;; Default time is either today, or, when entering a range,
4391 (concat org-ts-regexp "--\\=") ; FIXME: exactly two minuses?
4395 (mapcar (lambda(x) (or x 0))
4396 (parse-time-string (match-string 1))))
4398 (calendar-move-hook nil)
4399 (view-diary-entries-initially nil)
4400 (timestr (format-time-string
4401 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
4402 (prompt (format "YYYY-MM-DD [%s]: " timestr))
4404 second minute hour day month year tl wday wday1)
4406 (if org-popup-calendar-for-date-prompt
4408 (save-window-excursion
4410 (calendar-forward-day (- (time-to-days default-time)
4411 (calendar-absolute-from-gregorian
4412 (calendar-current-date))))
4413 (org-eval-in-calendar nil)
4414 (let* ((old-map (current-local-map))
4415 (map (copy-keymap calendar-mode-map))
4416 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
4417 (define-key map (kbd "RET") 'org-calendar-select)
4418 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
4419 'org-calendar-select-mouse)
4420 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
4421 'org-calendar-select-mouse)
4422 (define-key minibuffer-local-map [(meta shift left)]
4423 (lambda () (interactive)
4424 (org-eval-in-calendar '(calendar-backward-month 1))))
4425 (define-key minibuffer-local-map [(meta shift right)]
4426 (lambda () (interactive)
4427 (org-eval-in-calendar '(calendar-forward-month 1))))
4428 (define-key minibuffer-local-map [(shift up)]
4429 (lambda () (interactive)
4430 (org-eval-in-calendar '(calendar-backward-week 1))))
4431 (define-key minibuffer-local-map [(shift down)]
4432 (lambda () (interactive)
4433 (org-eval-in-calendar '(calendar-forward-week 1))))
4434 (define-key minibuffer-local-map [(shift left)]
4435 (lambda () (interactive)
4436 (org-eval-in-calendar '(calendar-backward-day 1))))
4437 (define-key minibuffer-local-map [(shift right)]
4438 (lambda () (interactive)
4439 (org-eval-in-calendar '(calendar-forward-day 1))))
4440 (define-key minibuffer-local-map ">"
4441 (lambda () (interactive)
4442 (org-eval-in-calendar '(scroll-calendar-left 1))))
4443 (define-key minibuffer-local-map "<"
4444 (lambda () (interactive)
4445 (org-eval-in-calendar '(scroll-calendar-right 1))))
4449 (setq ans (read-string prompt "" nil nil))
4450 (if (not (string-match "\\S-" ans)) (setq ans nil))
4451 (setq ans (or ans1 ans ans2)))
4452 (use-local-map old-map)))))
4453 ;; Naked prompt only
4454 (setq ans (read-string prompt "" nil timestr)))
4455 (org-detatch-overlay org-date-ovl)
4458 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
4460 (setq year (if (match-end 2)
4461 (string-to-number (match-string 2 ans))
4462 (string-to-number (format-time-string "%Y")))
4463 month (string-to-number (match-string 3 ans))
4464 day (string-to-number (match-string 4 ans)))
4465 (if (< year 100) (setq year (+ 2000 year)))
4466 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
4468 (setq tl (parse-time-string ans)
4469 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
4470 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
4471 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
4472 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
4473 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
4474 second (or (nth 0 tl) 0)
4476 (when (and wday (not (nth 3 tl)))
4477 ;; Weekday was given, but no day, so pick that day in the week
4478 ;; on or after the derived date.
4479 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
4480 (unless (equal wday wday1)
4481 (setq day (+ day (% (- wday wday1 -7) 7)))))
4482 (if (and (boundp 'org-time-was-given)
4484 (setq org-time-was-given t))
4485 (if (< year 100) (setq year (+ 2000 year)))
4487 (encode-time second minute hour day month year)
4488 (if (or (nth 1 tl) (nth 2 tl))
4489 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
4490 (format "%04d-%02d-%02d" year month day)))))
4492 (defun org-eval-in-calendar (form)
4493 "Eval FORM in the calendar window and return to current window.
4494 Also, store the cursor date in variable ans2."
4495 (let ((sw (selected-window)))
4496 (select-window (get-buffer-window "*Calendar*"))
4498 (when (calendar-cursor-to-date)
4499 (let* ((date (calendar-cursor-to-date))
4500 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4501 (setq ans2 (format-time-string "%Y-%m-%d" time))))
4502 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
4503 (select-window sw)))
4505 (defun org-calendar-select ()
4506 "Return to `org-read-date' with the date currently selected.
4507 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4509 (when (calendar-cursor-to-date)
4510 (let* ((date (calendar-cursor-to-date))
4511 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4512 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4513 (if (active-minibuffer-window) (exit-minibuffer))))
4515 (defun org-calendar-select-mouse (ev)
4516 "Return to `org-read-date' with the date currently selected.
4517 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4519 (mouse-set-point ev)
4520 (when (calendar-cursor-to-date)
4521 (let* ((date (calendar-cursor-to-date))
4522 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4523 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4524 (if (active-minibuffer-window) (exit-minibuffer))))
4526 (defun org-check-deadlines (ndays)
4527 "Check if there are any deadlines due or past due.
4528 A deadline is considered due if it happens within `org-deadline-warning-days'
4529 days from today's date. If the deadline appears in an entry marked DONE,
4530 it is not shown. The prefix arg NDAYS can be used to test that many
4531 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
4533 (let* ((org-warn-days
4535 ((equal ndays '(4)) 100000)
4536 (ndays (prefix-numeric-value ndays))
4537 (t org-deadline-warning-days)))
4538 (case-fold-search nil)
4539 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
4542 (and (let ((d1 (time-to-days (current-time)))
4544 (org-time-string-to-time (match-string 1)))))
4545 (< (- d2 d1) org-warn-days))
4546 (not (org-entry-is-done-p))))))
4547 (message "%d deadlines past-due or due within %d days"
4548 (org-occur regexp callback)
4551 (defun org-evaluate-time-range (&optional to-buffer)
4552 "Evaluate a time range by computing the difference between start and end.
4553 Normally the result is just printed in the echo area, but with prefix arg
4554 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
4555 If the time range is actually in a table, the result is inserted into the
4557 For time difference computation, a year is assumed to be exactly 365
4558 days in order to avoid rounding problems."
4561 (unless (org-at-date-range-p)
4562 (goto-char (point-at-bol))
4563 (re-search-forward org-tr-regexp (point-at-eol) t))
4564 (if (not (org-at-date-range-p))
4565 (error "Not at a time-stamp range, and none found in current line")))
4566 (let* ((ts1 (match-string 1))
4567 (ts2 (match-string 2))
4568 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
4569 (match-end (match-end 0))
4570 (time1 (org-time-string-to-time ts1))
4571 (time2 (org-time-string-to-time ts2))
4572 (t1 (time-to-seconds time1))
4573 (t2 (time-to-seconds time2))
4574 (diff (abs (- t2 t1)))
4575 (negative (< (- t2 t1) 0))
4576 ;; (ys (floor (* 365 24 60 60)))
4579 (fy "%dy %dd %02d:%02d")
4581 (fd "%dd %02d:%02d")
4586 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4588 d (floor (/ diff ds)) diff (mod diff ds)
4589 h (floor (/ diff hs)) diff (mod diff hs)
4590 m (floor (/ diff 60)))
4591 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4593 d (floor (+ (/ diff ds) 0.5))
4596 (message (org-make-tdiff-string y d h m))
4597 (when (org-at-table-p)
4598 (goto-char match-end)
4600 (and (looking-at " *|") (goto-char (match-end 0))))
4602 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
4604 (if negative (insert " -"))
4605 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
4606 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
4607 (insert " " (format fh h m))))
4608 (if align (org-table-align))
4609 (message "Time difference inserted"))))
4611 (defun org-make-tdiff-string (y d h m)
4614 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
4616 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
4618 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
4620 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
4622 (apply 'format fmt (nreverse l))))
4624 (defun org-time-string-to-time (s)
4625 (apply 'encode-time (org-parse-time-string s)))
4627 (defun org-parse-time-string (s &optional nodefault)
4628 "Parse the standard Org-mode time string.
4629 This should be a lot faster than the normal `parse-time-string'.
4630 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
4631 hour and minute fields will be nil if not given."
4632 (if (string-match org-ts-regexp1 s)
4634 (if (or (match-beginning 8) (not nodefault))
4635 (string-to-number (or (match-string 8 s) "0")))
4636 (if (or (match-beginning 7) (not nodefault))
4637 (string-to-number (or (match-string 7 s) "0")))
4638 (string-to-number (match-string 4 s))
4639 (string-to-number (match-string 3 s))
4640 (string-to-number (match-string 2 s))
4644 (defun org-timestamp-up (&optional arg)
4645 "Increase the date item at the cursor by one.
4646 If the cursor is on the year, change the year. If it is on the month or
4647 the day, change that.
4648 With prefix ARG, change by that many units."
4650 (org-timestamp-change (prefix-numeric-value arg)))
4652 (defun org-timestamp-down (&optional arg)
4653 "Decrease the date item at the cursor by one.
4654 If the cursor is on the year, change the year. If it is on the month or
4655 the day, change that.
4656 With prefix ARG, change by that many units."
4658 (org-timestamp-change (- (prefix-numeric-value arg))))
4660 (defun org-timestamp-up-day (&optional arg)
4661 "Increase the date in the time stamp by one day.
4662 With prefix ARG, change that many days."
4664 (if (and (not (org-at-timestamp-p))
4667 (org-timestamp-change (prefix-numeric-value arg) 'day)))
4669 (defun org-timestamp-down-day (&optional arg)
4670 "Decrease the date in the time stamp by one day.
4671 With prefix ARG, change that many days."
4673 (if (and (not (org-at-timestamp-p))
4676 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
4678 (defsubst org-pos-in-match-range (pos n)
4679 (and (match-beginning n)
4680 (<= (match-beginning n) pos)
4681 (>= (match-end n) pos)))
4683 (defun org-at-timestamp-p ()
4684 "Determine if the cursor is in or at a timestamp."
4686 (let* ((tsr org-ts-regexp2)
4688 (ans (or (looking-at tsr)
4690 (skip-chars-backward "^<\n\r\t")
4691 (if (> (point) 1) (backward-char 1))
4692 (and (looking-at tsr)
4693 (> (- (match-end 0) pos) -1))))))
4694 (and (boundp 'org-ts-what)
4697 ((org-pos-in-match-range pos 2) 'year)
4698 ((org-pos-in-match-range pos 3) 'month)
4699 ((org-pos-in-match-range pos 7) 'hour)
4700 ((org-pos-in-match-range pos 8) 'minute)
4701 ((or (org-pos-in-match-range pos 4)
4702 (org-pos-in-match-range pos 5)) 'day)
4706 (defun org-timestamp-change (n &optional what)
4707 "Change the date in the time stamp at point.
4708 The date will be changed by N times WHAT. WHAT can be `day', `month',
4709 `year', `minute', `second'. If WHAT is not given, the cursor position
4710 in the timestamp determines what will be changed."
4711 (let ((fmt (car org-time-stamp-formats))
4715 (if (not (org-at-timestamp-p))
4716 (error "Not at a timestamp"))
4717 (setq org-ts-what (or what org-ts-what))
4718 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4719 (- (match-end 0) (match-beginning 0))))
4721 (cdr org-time-stamp-formats)
4722 (car org-time-stamp-formats)))
4723 (setq ts (match-string 0))
4725 (setq time0 (org-parse-time-string ts))
4729 (list (or (car time0) 0))
4730 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4731 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4732 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4733 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4734 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4736 (if (eq what 'calendar)
4740 (set-buffer "*Calendar*")
4741 (calendar-cursor-to-date)))))
4742 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4743 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4744 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4745 (setcar time0 (or (car time0) 0))
4746 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4747 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4748 (setq time (apply 'encode-time time0))))
4749 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4751 ;; Try to recenter the calendar window, if any
4752 (if (and org-calendar-follow-timestamp-change
4753 (get-buffer-window "*Calendar*" t)
4754 (memq org-ts-what '(day month year)))
4755 (org-recenter-calendar (time-to-days time)))))
4757 (defun org-recenter-calendar (date)
4758 "If the calendar is visible, recenter it to DATE."
4759 (let* ((win (selected-window))
4760 (cwin (get-buffer-window "*Calendar*" t))
4761 (calendar-move-hook nil))
4763 (select-window cwin)
4764 (calendar-goto-date (if (listp date) date
4765 (calendar-gregorian-from-absolute date)))
4766 (select-window win))))
4768 (defun org-goto-calendar (&optional arg)
4769 "Go to the Emacs calendar at the current date.
4770 If there is a time stamp in the current line, go to that date.
4771 A prefix ARG can be used to force the current date."
4773 (let ((tsr org-ts-regexp) diff
4774 (calendar-move-hook nil)
4775 (view-diary-entries-initially nil))
4776 (if (or (org-at-timestamp-p)
4778 (beginning-of-line 1)
4779 (looking-at (concat ".*" tsr))))
4780 (let ((d1 (time-to-days (current-time)))
4782 (org-time-string-to-time (match-string 1)))))
4783 (setq diff (- d2 d1))))
4785 (calendar-goto-today)
4786 (if (and diff (not arg)) (calendar-forward-day diff))))
4788 (defun org-date-from-calendar ()
4789 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4790 If there is already a time stamp at the cursor position, update it."
4792 (org-timestamp-change 0 'calendar))
4794 ;;; Agenda, and Diary Integration
4798 (defvar org-agenda-mode-map (make-sparse-keymap)
4799 "Keymap for `org-agenda-mode'.")
4801 (defvar org-agenda-menu) ; defined later in this file.
4802 (defvar org-agenda-follow-mode nil)
4803 (defvar org-agenda-show-log nil)
4804 (defvar org-agenda-buffer-name "*Org Agenda*")
4805 (defvar org-agenda-redo-command nil)
4806 (defvar org-agenda-mode-hook nil)
4807 (defvar org-agenda-type nil)
4808 (defvar org-agenda-force-single-file nil)
4811 (defun org-agenda-mode ()
4812 "Mode for time-sorted view on action items in Org-mode files.
4814 The following commands are available:
4816 \\{org-agenda-mode-map}"
4818 (kill-all-local-variables)
4819 (setq major-mode 'org-agenda-mode)
4820 (setq mode-name "Org-Agenda")
4821 (use-local-map org-agenda-mode-map)
4822 (easy-menu-add org-agenda-menu)
4823 (if org-startup-truncated (setq truncate-lines t))
4824 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4825 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4826 (unless org-agenda-keep-modes
4827 (setq org-agenda-follow-mode nil
4828 org-agenda-show-log nil))
4830 '("Agenda") "Agenda Files"
4834 (if (get 'org-agenda-files 'org-restrict)
4835 "Restricted to single file"
4837 '(org-edit-agenda-file-list)
4838 (not (get 'org-agenda-files 'org-restrict)))
4840 (mapcar 'org-file-menu-entry (org-agenda-files))))
4841 (org-agenda-set-mode-name)
4843 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4844 (list 'org-agenda-mode-hook)))
4846 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4847 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
4848 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4849 (define-key org-agenda-mode-map " " 'org-agenda-show)
4850 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4851 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4852 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
4853 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4854 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
4855 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4856 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4857 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4858 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4859 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4860 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4861 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4863 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4864 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4865 (while l (define-key org-agenda-mode-map
4866 (int-to-string (pop l)) 'digit-argument)))
4868 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4869 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
4870 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4871 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4872 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4873 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4874 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4875 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4876 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
4877 (define-key org-agenda-mode-map "n" 'next-line)
4878 (define-key org-agenda-mode-map "p" 'previous-line)
4879 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4880 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4881 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4882 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4883 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4884 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4885 (eval-after-load "calendar"
4886 '(define-key calendar-mode-map org-calendar-to-agenda-key
4887 'org-calendar-goto-agenda))
4888 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4889 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4890 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4891 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4892 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4893 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4894 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4895 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4896 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4897 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4898 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4899 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4900 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4901 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4902 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4903 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4904 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4905 "Local keymap for agenda entries from Org-mode.")
4907 (define-key org-agenda-keymap
4908 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4909 (define-key org-agenda-keymap
4910 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4911 (when org-agenda-mouse-1-follows-link
4912 (define-key org-agenda-keymap [follow-link] 'mouse-face))
4913 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4917 ["Show" org-agenda-show t]
4918 ["Go To (other window)" org-agenda-goto t]
4919 ["Go To (one window)" org-agenda-switch-to t]
4920 ["Follow Mode" org-agenda-follow-mode
4921 :style toggle :selected org-agenda-follow-mode :active t]
4923 ["Cycle TODO" org-agenda-todo t]
4925 ["Show all Tags" org-agenda-show-tags t]
4926 ["Set Tags" org-agenda-set-tags t])
4928 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
4929 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
4931 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
4933 ["Set Priority" org-agenda-priority t]
4934 ["Increase Priority" org-agenda-priority-up t]
4935 ["Decrease Priority" org-agenda-priority-down t]
4936 ["Show Priority" org-agenda-show-priority t])
4938 ;; ["New agenda command" org-agenda t]
4939 ["Rebuild buffer" org-agenda-redo t]
4941 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
4942 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
4943 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
4945 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
4946 :style radio :selected (equal org-agenda-ndays 1)]
4947 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
4948 :style radio :selected (equal org-agenda-ndays 7)]
4950 ["Show Logbook entries" org-agenda-log-mode
4951 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
4952 ["Include Diary" org-agenda-toggle-diary
4953 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
4954 ["Use Time Grid" org-agenda-toggle-time-grid
4955 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
4957 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
4958 ("Calendar Commands"
4959 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
4960 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
4961 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
4962 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
4963 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
4964 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4966 ["Quit" org-agenda-quit t]
4967 ["Exit and Release Buffers" org-agenda-exit t]
4971 (defun org-agenda (arg)
4972 "Dispatch agenda commands to collect entries to the agenda buffer.
4973 Prompts for a character to select a command. Any prefix arg will be passed
4974 on to the selected command. The default selections are:
4976 a Call `org-agenda' to display the agenda for the current day or week.
4977 t Call `org-todo-list' to display the global todo list.
4978 T Call `org-todo-list' to display the global todo list, select only
4979 entries with a specific TODO keyword (the user gets a prompt).
4980 m Call `org-tags-view' to display headlines with tags matching
4981 a condition (the user is prompted for the condition).
4982 M Like `m', but select only TODO entries, no ordinary headlines.
4984 More commands can be added by configuring the variable
4985 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
4986 searches can be pre-defined in this way.
4988 If the current buffer is in Org-mode and visiting a file, you can also
4989 first press `1' to indicate that the agenda should be temporarily (until the
4990 next use of \\[org-agenda]) restricted to the current file."
4993 (let ((restrict-ok (and buffer-file-name (eq major-mode 'org-mode)))
4994 (custom org-agenda-custom-commands)
4995 c entry key type string)
4996 (put 'org-agenda-files 'org-restrict nil)
4997 (save-window-excursion
4998 (delete-other-windows)
4999 (switch-to-buffer-other-window " *Agenda Commands*")
5002 "Press key for an agenda command:
5003 --------------------------------
5004 a Agenda for current week or day
5005 t List of all TODO entries T Entries with special TODO kwd
5006 m Match a TAGS query M Like m, but only TODO entries
5007 C Configure your own agenda commands")
5008 (while (setq entry (pop custom))
5009 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
5010 (insert (format "\n%-4s%-14s: %s"
5013 ((eq type 'tags) "Tags query")
5014 ((eq type 'todo) "TODO keyword")
5015 ((eq type 'tags-tree) "Tags tree")
5016 ((eq type 'todo-tree) "TODO kwd tree")
5017 ((eq type 'occur-tree) "Occur tree")
5019 (org-add-props string nil 'face 'org-warning))))
5020 (goto-char (point-min))
5021 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
5022 (message "Press key for agenda command%s"
5023 (if restrict-ok ", or [1] to restrict to current file" ""))
5024 (setq c (read-char-exclusive))
5028 (put 'org-agenda-files 'org-restrict (list buffer-file-name))
5029 (error "Cannot restrict agenda to current buffer"))
5030 (message "Press key for agenda command%s"
5031 (if restrict-ok " (restricted to current file)" ""))
5032 (setq c (read-char-exclusive))
5034 (require 'calendar) ; FIXME: can we avoid this for some commands?
5035 ;; For example the todo list should not need it (but does...)
5037 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
5038 ((equal c ?a) (call-interactively 'org-agenda-list))
5039 ((equal c ?t) (call-interactively 'org-todo-list))
5041 (setq current-prefix-arg (or arg '(4)))
5042 (call-interactively 'org-todo-list))
5043 ((equal c ?m) (call-interactively 'org-tags-view))
5045 (setq current-prefix-arg (or arg '(4)))
5046 (call-interactively 'org-tags-view))
5047 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
5048 (setq type (nth 1 entry) string (nth 2 entry))
5051 (org-tags-view current-prefix-arg string))
5053 (org-todo-list string))
5054 ((eq type 'tags-tree)
5055 (org-check-for-org-mode)
5056 (org-tags-sparse-tree current-prefix-arg string))
5057 ((eq type 'todo-tree)
5058 (org-check-for-org-mode)
5059 (org-occur (concat "^" outline-regexp "[ \t]*"
5060 (regexp-quote string) "\\>")))
5061 ((eq type 'occur-tree)
5062 (org-check-for-org-mode)
5064 (t (error "Invalid custom agenda command type %s" type))))
5065 (t (error "Invalid key"))))))
5067 (defun org-check-for-org-mode ()
5068 "Make sure current buffer is in org-mode. Error if not."
5069 (or (eq major-mode 'org-mode)
5070 (error "Cannot execute org-mode agenda command on buffer in %s."
5073 (defun org-fit-agenda-window ()
5074 "Fit the window to the buffer size."
5075 (and org-fit-agenda-window
5076 (fboundp 'fit-window-to-buffer)
5077 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
5078 (/ (frame-height) 2))))
5080 (defun org-agenda-files (&optional unrestricted)
5081 "Get the list of agenda files.
5082 Optional UNRESTRICTED means return the full list even if a restriction
5083 is currently in place."
5085 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
5086 ((stringp org-agenda-files) (org-read-agenda-file-list))
5087 ((listp org-agenda-files) org-agenda-files)
5088 (t (error "Invalid value of `org-agenda-files'"))))
5090 (defvar org-window-configuration)
5092 (defun org-edit-agenda-file-list ()
5093 "Edit the list of agenda files.
5094 Depending on setup, this either uses customize to edit the variable
5095 `org-agenda-files', or it visits the file that is holding the list. In the
5096 latter case, the buffer is set up in a way that saving it automatically kills
5097 the buffer and restores the previous window configuration."
5099 (if (stringp org-agenda-files)
5100 (let ((cw (current-window-configuration)))
5101 (find-file org-agenda-files)
5102 (set (make-local-variable 'org-window-configuration) cw)
5103 (org-add-hook 'after-save-hook
5105 (set-window-configuration
5106 (prog1 org-window-configuration
5107 (kill-buffer (current-buffer))))
5108 (org-install-agenda-files-menu)
5109 (message "New agenda file list installed"))
5111 (message (substitute-command-keys
5112 "Edit list and finish with \\[save-buffer]")))
5113 (customize-variable 'org-agenda-files)))
5115 (defun org-store-new-agenda-file-list (list)
5116 "Set new value for the agenda file list and save it correcly."
5117 (if (stringp org-agenda-files)
5118 (let ((f org-agenda-files) b)
5119 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
5121 (insert (mapconcat 'identity list "\n") "\n")))
5122 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5123 (setq org-agenda-files list)
5124 (customize-save-variable 'org-agenda-files org-agenda-files))))
5126 (defun org-read-agenda-file-list ()
5127 "Read the list of agenda files from a file."
5128 (when (stringp org-agenda-files)
5130 (insert-file-contents org-agenda-files)
5131 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
5133 (defvar org-agenda-markers nil
5134 "List of all currently active markers created by `org-agenda'.")
5135 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
5136 "Creation time of the last agenda marker.")
5138 (defun org-agenda-new-marker (&optional pos)
5139 "Return a new agenda marker.
5140 Org-mode keeps a list of these markers and resets them when they are
5142 (let ((m (copy-marker (or pos (point)))))
5143 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
5144 (push m org-agenda-markers)
5147 (defun org-agenda-maybe-reset-markers (&optional force)
5148 "Reset markers created by `org-agenda'. But only if they are old enough."
5150 (> (- (time-to-seconds (current-time))
5151 org-agenda-last-marker-time)
5153 (while org-agenda-markers
5154 (move-marker (pop org-agenda-markers) nil))))
5156 (defvar org-agenda-new-buffers nil
5157 "Buffers created to visit agenda files.")
5159 (defun org-get-agenda-file-buffer (file)
5160 "Get a buffer visiting FILE. If the buffer needs to be created, add
5161 it to the list of buffers which might be released later."
5162 (let ((buf (find-buffer-visiting file)))
5164 buf ; just return it
5165 ;; Make a new buffer and remember it
5166 (setq buf (find-file-noselect file))
5167 (if buf (push buf org-agenda-new-buffers))
5170 (defun org-release-buffers (blist)
5171 "Release all buffers in list, asking the user for confirmation when needed.
5172 When a buffer is unmodified, it is just killed. When modified, it is saved
5173 \(if the user agrees) and then killed."
5175 (while (setq buf (pop blist))
5176 (setq file (buffer-file-name buf))
5177 (when (and (buffer-modified-p buf)
5179 (y-or-n-p (format "Save file %s? " file)))
5180 (with-current-buffer buf (save-buffer)))
5181 (kill-buffer buf))))
5183 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
5185 (defun org-timeline (&optional include-all keep-modes)
5186 "Show a time-sorted view of the entries in the current org file.
5187 Only entries with a time stamp of today or later will be listed. With
5188 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
5189 under the current date.
5190 If the buffer contains an active region, only check the region for
5194 (org-agenda-maybe-reset-markers 'force)
5195 (org-compile-prefix-format org-timeline-prefix-format)
5197 (dotodo include-all)
5198 (doclosed org-agenda-show-log)
5199 (org-agenda-keep-modes keep-modes)
5200 (entry buffer-file-name)
5201 (org-agenda-files (list buffer-file-name))
5202 (date (calendar-current-date))
5203 (win (selected-window))
5205 (beg (if (org-region-active-p) (region-beginning) (point-min)))
5206 (end (if (org-region-active-p) (region-end) (point-max)))
5207 (day-numbers (org-get-all-dates beg end 'no-ranges
5208 t doclosed)) ; always include today
5209 (today (time-to-days (current-time)))
5210 (org-respect-restriction t)
5214 (setq org-agenda-redo-command
5216 (list 'switch-to-buffer-other-window (current-buffer))
5217 (list 'org-timeline (list 'quote include-all) t)))
5219 ;; Remove past dates from the list of dates.
5220 (setq day-numbers (delq nil (mapcar (lambda(x)
5221 (if (>= x today) x nil))
5223 (switch-to-buffer-other-window
5224 (get-buffer-create org-agenda-buffer-name))
5225 (setq buffer-read-only nil)
5227 (org-agenda-mode) (setq buffer-read-only nil)
5228 (set (make-local-variable 'org-agenda-type) 'timeline)
5229 (if doclosed (push :closed args))
5230 (push :timestamp args)
5231 (if dotodo (push :todo args))
5232 (while (setq d (pop day-numbers))
5233 (if (and (>= d today)
5238 (insert (make-string 79 ?-) "\n")))
5239 (setq date (calendar-gregorian-from-absolute d))
5241 (setq rtn (apply 'org-agenda-get-day-entries
5243 (if (or rtn (equal d today))
5245 (insert (calendar-day-name date) " "
5246 (number-to-string (extract-calendar-day date)) " "
5247 (calendar-month-name (extract-calendar-month date)) " "
5248 (number-to-string (extract-calendar-year date)) "\n")
5249 (put-text-property s (1- (point)) 'face
5252 (put-text-property s (1- (point)) 'org-today t))
5253 (insert (org-finalize-agenda-entries rtn) "\n")
5254 (put-text-property s (1- (point)) 'day d))))
5255 (goto-char (point-min))
5256 (setq buffer-read-only t)
5257 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5259 (when (not org-select-timeline-window)
5264 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
5265 "Produce a weekly view from all files in variable `org-agenda-files'.
5266 The view will be for the current week, but from the overview buffer you
5267 will be able to go to other weeks.
5268 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
5269 also be shown, under the current date.
5270 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
5271 on the days are also shown. See the variable `org-log-done' for how
5273 START-DAY defaults to TODAY, or to the most recent match for the weekday
5274 given in `org-agenda-start-on-weekday'.
5275 NDAYS defaults to `org-agenda-ndays'."
5277 (org-agenda-maybe-reset-markers 'force)
5278 (org-compile-prefix-format org-agenda-prefix-format)
5280 (let* ((org-agenda-start-on-weekday
5281 (if (or (equal ndays 1)
5282 (and (null ndays) (equal 1 org-agenda-ndays)))
5283 nil org-agenda-start-on-weekday))
5284 (org-agenda-keep-modes keep-modes)
5285 (thefiles (org-agenda-files))
5287 (win (selected-window))
5288 (today (time-to-days (current-time)))
5289 (sd (or start-day today))
5290 (start (if (or (null org-agenda-start-on-weekday)
5291 (< org-agenda-ndays 7))
5293 (let* ((nt (calendar-day-of-week
5294 (calendar-gregorian-from-absolute sd)))
5295 (n1 org-agenda-start-on-weekday)
5297 (- sd (+ (if (< d 0) 7 0) d)))))
5298 (day-numbers (list start))
5299 (inhibit-redisplay t)
5300 s e rtn rtnall file date d start-pos end-pos todayp nd)
5301 (setq org-agenda-redo-command
5302 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
5303 ;; Make the list of days
5304 (setq ndays (or ndays org-agenda-ndays)
5307 (push (1+ (car day-numbers)) day-numbers)
5308 (setq ndays (1- ndays)))
5309 (setq day-numbers (nreverse day-numbers))
5310 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
5312 (delete-other-windows)
5313 (switch-to-buffer-other-window
5314 (get-buffer-create org-agenda-buffer-name))))
5315 (setq buffer-read-only nil)
5317 (org-agenda-mode) (setq buffer-read-only nil)
5318 (set (make-local-variable 'org-agenda-type) 'agenda)
5319 (set (make-local-variable 'starting-day) (car day-numbers))
5320 (set (make-local-variable 'include-all-loc) include-all)
5321 (when (and (or include-all org-agenda-include-all-todo)
5322 (member today day-numbers))
5323 (setq files thefiles
5325 (while (setq file (pop files))
5327 (org-check-agenda-file file)
5328 (setq date (calendar-gregorian-from-absolute today)
5329 rtn (org-agenda-get-day-entries
5331 (setq rtnall (append rtnall rtn))))
5333 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
5334 (add-text-properties (point-min) (1- (point))
5335 (list 'face 'org-level-3))
5336 (insert (org-finalize-agenda-entries rtnall) "\n")))
5337 (while (setq d (pop day-numbers))
5338 (setq date (calendar-gregorian-from-absolute d)
5340 (if (or (setq todayp (= d today))
5341 (and (not start-pos) (= d sd)))
5342 (setq start-pos (point))
5343 (if (and start-pos (not end-pos))
5344 (setq end-pos (point))))
5345 (setq files thefiles
5347 (while (setq file (pop files))
5349 (org-check-agenda-file file)
5350 (if org-agenda-show-log
5351 (setq rtn (org-agenda-get-day-entries
5353 :deadline :scheduled :timestamp :closed))
5354 (setq rtn (org-agenda-get-day-entries
5356 :deadline :scheduled :timestamp)))
5357 (setq rtnall (append rtnall rtn))))
5358 (if org-agenda-include-diary
5360 (require 'diary-lib)
5361 (setq rtn (org-get-entries-from-diary date))
5362 (setq rtnall (append rtnall rtn))))
5363 (if (or rtnall org-agenda-show-all-dates)
5365 (insert (format "%-9s %2d %s %4d\n"
5366 (calendar-day-name date)
5367 (extract-calendar-day date)
5368 (calendar-month-name (extract-calendar-month date))
5369 (extract-calendar-year date)))
5370 (put-text-property s (1- (point)) 'face
5373 (org-finalize-agenda-entries
5374 (org-agenda-add-time-grid-maybe
5377 (put-text-property s (1- (point)) 'day d))))
5378 (goto-char (point-min))
5379 (setq buffer-read-only t)
5380 (org-fit-agenda-window)
5381 (unless (and (pos-visible-in-window-p (point-min))
5382 (pos-visible-in-window-p (point-max)))
5383 (goto-char (1- (point-max)))
5385 (if (not (pos-visible-in-window-p (or start-pos 1)))
5387 (goto-char (or start-pos 1))
5389 (goto-char (or start-pos 1))
5390 (if (not org-select-agenda-window) (select-window win))
5393 (defvar org-select-this-todo-keyword nil)
5396 (defun org-todo-list (arg &optional keep-modes)
5397 "Show all TODO entries from all agenda file in a single list.
5398 The prefix arg can be used to select a specific TODO keyword and limit
5399 the list to these. When using \\[universal-argument], you will be prompted
5400 for a keyword. A numeric prefix directly selects the Nth keyword in
5401 `org-todo-keywords'."
5403 (org-agenda-maybe-reset-markers 'force)
5404 (org-compile-prefix-format org-agenda-prefix-format)
5405 (let* ((org-agenda-keep-modes keep-modes)
5406 (today (time-to-days (current-time)))
5407 (date (calendar-gregorian-from-absolute today))
5408 (win (selected-window))
5409 (kwds org-todo-keywords)
5410 (completion-ignore-case t)
5411 (org-select-this-todo-keyword
5412 (if (stringp arg) arg
5413 (and arg (integerp arg) (> arg 0)
5414 (nth (1- arg) org-todo-keywords))))
5415 rtn rtnall files file pos)
5416 (when (equal arg '(4))
5417 (setq org-select-this-todo-keyword
5418 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
5420 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
5421 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
5423 (delete-other-windows)
5424 (switch-to-buffer-other-window
5425 (get-buffer-create org-agenda-buffer-name))))
5426 (setq buffer-read-only nil)
5428 (org-agenda-mode) (setq buffer-read-only nil)
5429 (set (make-local-variable 'org-agenda-type) 'todo)
5430 (set (make-local-variable 'last-arg) arg)
5431 (set (make-local-variable 'org-todo-keywords) kwds)
5432 (set (make-local-variable 'org-agenda-redo-command)
5433 '(org-todo-list (or current-prefix-arg last-arg) t))
5434 (setq files (org-agenda-files)
5436 (while (setq file (pop files))
5438 (org-check-agenda-file file)
5439 (setq rtn (org-agenda-get-day-entries file date :todo))
5440 (setq rtnall (append rtnall rtn))))
5441 (insert "Global list of TODO items of type: ")
5442 (add-text-properties (point-min) (1- (point))
5443 (list 'face 'org-level-3))
5445 (insert (or org-select-this-todo-keyword "ALL") "\n")
5446 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
5449 "Available with `N r': (0)ALL "
5451 (mapconcat (lambda (x)
5452 (format "(%d)%s" (setq n (1+ n)) x))
5453 org-todo-keywords " "))
5455 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
5457 (insert (org-finalize-agenda-entries rtnall) "\n"))
5458 (goto-char (point-min))
5459 (setq buffer-read-only t)
5460 (org-fit-agenda-window)
5461 (if (not org-select-agenda-window) (select-window win))))
5463 (defun org-check-agenda-file (file)
5464 "Make sure FILE exists. If not, ask user what to do."
5465 (when (not (file-exists-p file))
5466 (message "non-existent file %s. [R]emove from list or [A]bort?"
5467 (abbreviate-file-name file))
5468 (let ((r (downcase (read-char-exclusive))))
5471 (org-remove-file file)
5472 (throw 'nextfile t))
5473 (t (error "Abort"))))))
5475 (defun org-agenda-check-type (error &rest types)
5476 "Check if agenda buffer is of allowed type.
5477 If ERROR is non-nil, throw an error, otherwise just return nil."
5478 (if (memq org-agenda-type types)
5481 (error "Now allowed in %s-type agenda buffers" org-agenda-type)
5484 (defun org-agenda-quit ()
5485 "Exit agenda by removing the window or the buffer."
5487 (let ((buf (current-buffer)))
5488 (if (not (one-window-p)) (delete-window))
5490 (org-agenda-maybe-reset-markers 'force)))
5492 (defun org-agenda-exit ()
5493 "Exit agenda by removing the window or the buffer.
5494 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
5495 Org-mode buffers visited directly by the user will not be touched."
5497 (org-release-buffers org-agenda-new-buffers)
5498 (setq org-agenda-new-buffers nil)
5501 (defun org-agenda-redo ()
5503 When this is the global TODO list, a prefix argument will be interpreted."
5505 (message "Rebuilding agenda buffer...")
5506 (eval org-agenda-redo-command)
5507 (message "Rebuilding agenda buffer...done"))
5509 (defun org-agenda-goto-today ()
5512 (org-agenda-check-type t 'timeline 'agenda)
5513 (if (boundp 'starting-day)
5514 (let ((cmd (car org-agenda-redo-command))
5515 (iall (nth 1 org-agenda-redo-command))
5516 (nday (nth 3 org-agenda-redo-command))
5517 (keep (nth 4 org-agenda-redo-command)))
5518 (eval (list cmd iall nil nday keep)))
5519 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5522 (defun org-agenda-later (arg)
5523 "Go forward in time by `org-agenda-ndays' days.
5524 With prefix ARG, go forward that many times `org-agenda-ndays'."
5526 (org-agenda-check-type t 'agenda)
5527 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5528 (+ starting-day (* arg org-agenda-ndays)) nil t))
5530 (defun org-agenda-earlier (arg)
5531 "Go back in time by `org-agenda-ndays' days.
5532 With prefix ARG, go back that many times `org-agenda-ndays'."
5534 (org-agenda-check-type t 'agenda)
5535 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5536 (- starting-day (* arg org-agenda-ndays)) nil t))
5538 (defun org-agenda-week-view ()
5539 "Switch to weekly view for agenda."
5541 (org-agenda-check-type t 'agenda)
5542 (setq org-agenda-ndays 7)
5543 (org-agenda-list include-all-loc
5544 (or (get-text-property (point) 'day)
5547 (org-agenda-set-mode-name)
5548 (message "Switched to week view"))
5550 (defun org-agenda-day-view ()
5551 "Switch to daily view for agenda."
5553 (org-agenda-check-type t 'agenda)
5554 (setq org-agenda-ndays 1)
5555 (org-agenda-list include-all-loc
5556 (or (get-text-property (point) 'day)
5559 (org-agenda-set-mode-name)
5560 (message "Switched to day view"))
5562 (defun org-agenda-next-date-line (&optional arg)
5563 "Jump to the next line indicating a date in agenda buffer."
5565 (org-agenda-check-type t 'agenda 'timeline)
5566 (beginning-of-line 1)
5567 (if (looking-at "^\\S-") (forward-char 1))
5568 (if (not (re-search-forward "^\\S-" nil t arg))
5571 (error "No next date after this line in this buffer")))
5572 (goto-char (match-beginning 0)))
5574 (defun org-agenda-previous-date-line (&optional arg)
5575 "Jump to the previous line indicating a date in agenda buffer."
5577 (org-agenda-check-type t 'agenda 'timeline)
5578 (beginning-of-line 1)
5579 (if (not (re-search-backward "^\\S-" nil t arg))
5580 (error "No previous date before this line in this buffer")))
5582 ;; Initialize the highlight
5583 (defvar org-hl (org-make-overlay 1 1))
5584 (org-overlay-put org-hl 'face 'highlight)
5586 (defun org-highlight (begin end &optional buffer)
5587 "Highlight a region with overlay."
5588 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
5589 org-hl begin end (or buffer (current-buffer))))
5591 (defun org-unhighlight ()
5592 "Detach overlay INDEX."
5593 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
5596 (defun org-agenda-follow-mode ()
5597 "Toggle follow mode in an agenda buffer."
5599 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
5600 (org-agenda-set-mode-name)
5601 (message "Follow mode is %s"
5602 (if org-agenda-follow-mode "on" "off")))
5604 (defun org-agenda-log-mode ()
5605 "Toggle log mode in an agenda buffer."
5607 (org-agenda-check-type t 'agenda 'timeline)
5608 (setq org-agenda-show-log (not org-agenda-show-log))
5609 (org-agenda-set-mode-name)
5611 (message "Log mode is %s"
5612 (if org-agenda-show-log "on" "off")))
5614 (defun org-agenda-toggle-diary ()
5615 "Toggle diary inclusion in an agenda buffer."
5617 (org-agenda-check-type t 'agenda)
5618 (setq org-agenda-include-diary (not org-agenda-include-diary))
5620 (org-agenda-set-mode-name)
5621 (message "Diary inclusion turned %s"
5622 (if org-agenda-include-diary "on" "off")))
5624 (defun org-agenda-toggle-time-grid ()
5625 "Toggle time grid in an agenda buffer."
5627 (org-agenda-check-type t 'agenda)
5628 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
5630 (org-agenda-set-mode-name)
5631 (message "Time-grid turned %s"
5632 (if org-agenda-use-time-grid "on" "off")))
5634 (defun org-agenda-set-mode-name ()
5635 "Set the mode name to indicate all the small mode settings."
5637 (concat "Org-Agenda"
5638 (if (equal org-agenda-ndays 1) " Day" "")
5639 (if (equal org-agenda-ndays 7) " Week" "")
5640 (if org-agenda-follow-mode " Follow" "")
5641 (if org-agenda-include-diary " Diary" "")
5642 (if org-agenda-use-time-grid " Grid" "")
5643 (if org-agenda-show-log " Log" "")))
5644 (force-mode-line-update))
5646 (defun org-agenda-post-command-hook ()
5647 (and (eolp) (not (bolp)) (backward-char 1))
5648 (if (and org-agenda-follow-mode
5649 (get-text-property (point) 'org-marker))
5652 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
5654 (defun org-get-entries-from-diary (date)
5655 "Get the (Emacs Calendar) diary entries for DATE."
5656 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
5657 (diary-display-hook '(fancy-diary-display))
5658 (list-diary-entries-hook
5659 (cons 'org-diary-default-entry list-diary-entries-hook))
5660 (diary-file-name-prefix-function nil) ; turn this feature off
5661 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
5663 (org-disable-agenda-to-diary t))
5665 (save-window-excursion
5666 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
5667 (if (not (get-buffer fancy-diary-buffer))
5669 (with-current-buffer fancy-diary-buffer
5670 (setq buffer-read-only nil)
5671 (if (= (point-max) 1)
5674 ;; Omit the date and other unnecessary stuff
5675 (org-agenda-cleanup-fancy-diary)
5676 ;; Add prefix to each line and extend the text properties
5677 (if (= (point-max) 1)
5679 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
5680 (set-buffer-modified-p nil)
5681 (kill-buffer fancy-diary-buffer)))
5683 (setq entries (org-split-string entries "\n"))
5687 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
5688 ;; Extend the text properties to the beginning of the line
5689 (org-add-props x (text-properties-at (1- (length x)) x)))
5692 (defun org-agenda-cleanup-fancy-diary ()
5693 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
5694 This gets rid of the date, the underline under the date, and
5695 the dummy entry installed by `org-mode' to ensure non-empty diary for each
5696 date. It also removes lines that contain only whitespace."
5697 (goto-char (point-min))
5698 (if (looking-at ".*?:[ \t]*")
5701 (re-search-forward "\n=+$" nil t)
5703 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
5704 (re-search-forward "\n=+$" nil t)
5705 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
5706 (goto-char (point-min))
5707 (while (re-search-forward "^ +\n" nil t)
5709 (goto-char (point-min))
5710 (if (re-search-forward "^Org-mode dummy\n?" nil t)
5711 (replace-match "")))
5713 ;; Make sure entries from the diary have the right text properties.
5714 (eval-after-load "diary-lib"
5715 '(if (boundp 'diary-modify-entry-list-string-function)
5716 ;; We can rely on the hook, nothing to do
5718 ;; Hook not avaiable, must use advice to make this work
5719 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
5720 "Make the position visible."
5721 (if (and org-disable-agenda-to-diary ;; called from org-agenda
5724 (setq string (org-modify-diary-entry-string string))))))
5726 (defun org-modify-diary-entry-string (string)
5727 "Add text properties to string, allowing org-mode to act on it."
5728 (org-add-props string nil
5729 'mouse-face 'highlight
5730 'keymap org-agenda-keymap
5731 'help-echo (format "mouse-2 or RET jump to diary file %s"
5732 (abbreviate-file-name buffer-file-name))
5733 'org-agenda-diary-link t
5734 'org-marker (org-agenda-new-marker (point-at-bol))))
5736 (defun org-diary-default-entry ()
5737 "Add a dummy entry to the diary.
5738 Needed to avoid empty dates which mess up holiday display."
5739 ;; Catch the error if dealing with the new add-to-diary-alist
5740 (when org-disable-agenda-to-diary
5742 (add-to-diary-list original-date "Org-mode dummy" "")
5744 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5746 (defun org-cycle-agenda-files ()
5747 "Cycle through the files in `org-agenda-files'.
5748 If the current buffer visits an agenda file, find the next one in the list.
5749 If the current buffer does not, find the first agenda file."
5751 (let* ((fs (org-agenda-files t))
5752 (files (append fs (list (car fs))))
5753 (tcf (if buffer-file-name (file-truename buffer-file-name)))
5755 (unless files (error "No agenda files"))
5757 (while (setq file (pop files))
5758 (if (equal (file-truename file) tcf)
5760 (find-file (car files))
5762 (find-file (car fs)))))
5764 (defun org-agenda-file-to-end ()
5765 "Move/add the current file to the end of the agenda file list.
5766 If the file is not present in the list, it is appended to the list. If it is
5767 present, it is moved there."
5769 (org-agenda-file-to-front 'to-end))
5771 (defun org-agenda-file-to-front (&optional to-end)
5772 "Move/add the current file to the top of the agenda file list.
5773 If the file is not present in the list, it is added to the front. If it is
5774 present, it is moved there. With optional argument TO-END, add/move to the
5777 (let ((file-alist (mapcar (lambda (x)
5778 (cons (file-truename x) x))
5779 (org-agenda-files t)))
5780 (ctf (file-truename buffer-file-name))
5782 (setq x (assoc ctf file-alist) had x)
5784 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
5786 (setq file-alist (append (delq x file-alist) (list x)))
5787 (setq file-alist (cons x (delq x file-alist))))
5788 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
5789 (org-install-agenda-files-menu)
5790 (message "File %s to %s of agenda file list"
5791 (if had "moved" "added") (if to-end "end" "front"))))
5793 (defun org-remove-file (&optional file)
5794 "Remove current file from the list of files in variable `org-agenda-files'.
5795 These are the files which are being checked for agenda entries.
5796 Optional argument FILE means, use this file instead of the current."
5798 (let* ((file (or file buffer-file-name))
5799 (true-file (file-truename file))
5800 (afile (abbreviate-file-name file))
5801 (files (delq nil (mapcar
5803 (if (equal true-file
5806 (org-agenda-files t)))))
5807 (if (not (= (length files) (length (org-agenda-files t))))
5809 (org-store-new-agenda-file-list files)
5810 (org-install-agenda-files-menu)
5811 (message "Removed file: %s" afile))
5812 (message "File was not in list: %s" afile))))
5814 (defun org-file-menu-entry (file)
5815 (vector file (list 'find-file file) t))
5817 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5818 "Return a list of all relevant day numbers from BEG to END buffer positions.
5819 If NO-RANGES is non-nil, include only the start and end dates of a range,
5820 not every single day in the range. If FORCE-TODAY is non-nil, make
5821 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5822 inactive time stamps (those in square brackets) are included."
5823 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5824 dates date day day1 day2 ts1 ts2)
5826 (setq dates (list (time-to-days (current-time)))))
5829 (while (re-search-forward re end t)
5830 (setq day (time-to-days (org-time-string-to-time
5831 (substring (match-string 1) 0 10))))
5832 (or (memq day dates) (push day dates)))
5835 (while (re-search-forward org-tr-regexp end t)
5836 (setq ts1 (substring (match-string 1) 0 10)
5837 ts2 (substring (match-string 2) 0 10)
5838 day1 (time-to-days (org-time-string-to-time ts1))
5839 day2 (time-to-days (org-time-string-to-time ts2)))
5840 (while (< (setq day1 (1+ day1)) day2)
5841 (or (memq day1 dates) (push day1 dates)))))
5845 (defun org-diary (&rest args)
5846 "Return diary information from org-files.
5847 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5848 It accesses org files and extracts information from those files to be
5849 listed in the diary. The function accepts arguments specifying what
5850 items should be listed. The following arguments are allowed:
5852 :timestamp List the headlines of items containing a date stamp or
5853 date range matching the selected date. Deadlines will
5854 also be listed, on the expiration day.
5856 :deadline List any deadlines past due, or due within
5857 `org-deadline-warning-days'. The listing occurs only
5858 in the diary for *today*, not at any other date. If
5859 an entry is marked DONE, it is no longer listed.
5861 :scheduled List all items which are scheduled for the given date.
5862 The diary for *today* also contains items which were
5863 scheduled earlier and are not yet marked DONE.
5865 :todo List all TODO items from the org-file. This may be a
5866 long list - so this is not turned on by default.
5867 Like deadlines, these entries only show up in the
5868 diary for *today*, not at any other date.
5870 The call in the diary file should look like this:
5872 &%%(org-diary) ~/path/to/some/orgfile.org
5874 Use a separate line for each org file to check. Or, if you omit the file name,
5875 all files listed in `org-agenda-files' will be checked automatically:
5879 If you don't give any arguments (as in the example above), the default
5880 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5883 &%%(org-diary :deadline :timestamp :scheduled)
5885 The function expects the lisp variables `entry' and `date' to be provided
5886 by the caller, because this is how the calendar works. Don't use this
5887 function from a program - use `org-agenda-get-day-entries' instead."
5888 (org-agenda-maybe-reset-markers)
5889 (org-compile-prefix-format org-agenda-prefix-format)
5890 (setq args (or args '(:deadline :scheduled :timestamp)))
5891 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5893 (org-agenda-files t)))
5895 ;; If this is called during org-agenda, don't return any entries to
5896 ;; the calendar. Org Agenda will list these entries itself.
5897 (if org-disable-agenda-to-diary (setq files nil))
5898 (while (setq file (pop files))
5899 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5900 (setq results (append results rtn)))
5902 (concat (org-finalize-agenda-entries results) "\n"))))
5903 (defvar org-category-table nil)
5904 (defun org-get-category-table ()
5905 "Get the table of categories and positions in current buffer."
5908 (goto-char (point-min))
5909 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5910 (push (cons (point) (org-trim (match-string 2))) tbl)))
5912 (defun org-get-category (&optional pos)
5913 "Get the category applying to position POS."
5914 (if (not org-category-table)
5916 ((null org-category)
5918 (if buffer-file-name
5919 (file-name-sans-extension
5920 (file-name-nondirectory buffer-file-name))
5922 ((symbolp org-category) (symbol-name org-category))
5924 (let ((tbl org-category-table)
5925 (pos (or pos (point))))
5926 (while (and tbl (> (caar tbl) pos))
5928 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5929 org-category-table))))))
5931 (defun org-agenda-get-day-entries (file date &rest args)
5932 "Does the work for `org-diary' and `org-agenda'.
5933 FILE is the path to a file to be checked for entries. DATE is date like
5934 the one returned by `calendar-current-date'. ARGS are symbols indicating
5935 which kind of entries should be extracted. For details about these, see
5936 the documentation of `org-diary'."
5937 (setq args (or args '(:deadline :scheduled :timestamp)))
5938 (let* ((org-startup-with-deadline-check nil)
5939 (org-startup-folded nil)
5940 (org-startup-align-all-tables nil)
5941 (buffer (if (file-exists-p file)
5942 (org-get-agenda-file-buffer file)
5943 (error "No such file %s" file)))
5946 ;; If file does not exist, make sure an error message ends up in diary
5947 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5948 (with-current-buffer buffer
5949 (unless (eq major-mode 'org-mode)
5950 (error "Agenda file %s is not in `org-mode'" file))
5951 (setq org-category-table (org-get-category-table))
5952 (let ((case-fold-search nil))
5955 (if org-respect-restriction
5956 (if (org-region-active-p)
5957 ;; Respect a region to restrict search
5958 (narrow-to-region (region-beginning) (region-end)))
5959 ;; If we work for the calendar or many files,
5960 ;; get rid of any restriction
5962 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5963 (while (setq arg (pop args))
5965 ((and (eq arg :todo)
5966 (equal date (calendar-current-date)))
5967 (setq rtn (org-agenda-get-todos))
5968 (setq results (append results rtn)))
5969 ((eq arg :timestamp)
5970 (setq rtn (org-agenda-get-blocks))
5971 (setq results (append results rtn))
5972 (setq rtn (org-agenda-get-timestamps))
5973 (setq results (append results rtn)))
5974 ((eq arg :scheduled)
5975 (setq rtn (org-agenda-get-scheduled))
5976 (setq results (append results rtn)))
5978 (setq rtn (org-agenda-get-closed))
5979 (setq results (append results rtn)))
5980 ((and (eq arg :deadline)
5981 (equal date (calendar-current-date)))
5982 (setq rtn (org-agenda-get-deadlines))
5983 (setq results (append results rtn))))))))
5986 (defun org-entry-is-done-p ()
5987 "Is the current entry marked DONE?"
5989 (and (re-search-backward "[\r\n]\\*" nil t)
5990 (looking-at org-nl-done-regexp))))
5992 (defun org-at-date-range-p ()
5993 "Is the cursor inside a date range?"
5997 (let ((pos (point)))
5998 (skip-chars-backward "^<\r\n")
5999 (skip-chars-backward "<")
6000 (and (looking-at org-tr-regexp)
6001 (>= (match-end 0) pos)
6003 (skip-chars-backward "^<\r\n")
6004 (skip-chars-backward "<")
6005 (and (looking-at org-tr-regexp)
6006 (>= (match-end 0) pos)
6010 (defun org-agenda-get-todos ()
6011 "Return the TODO information for agenda display."
6012 (let* ((props (list 'face nil
6013 'done-face 'org-done
6014 'org-not-done-regexp org-not-done-regexp
6015 'mouse-face 'highlight
6016 'keymap org-agenda-keymap
6018 (format "mouse-2 or RET jump to org file %s"
6019 (abbreviate-file-name buffer-file-name))))
6020 (regexp (concat "[\n\r]\\*+ *\\("
6021 (if org-select-this-todo-keyword
6022 (concat "\\<\\(" org-select-this-todo-keyword
6024 org-not-done-regexp)
6026 marker priority category tags
6028 (goto-char (point-min))
6029 (while (re-search-forward regexp nil t)
6030 (goto-char (match-beginning 1))
6031 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
6032 category (org-get-category)
6033 tags (org-get-tags-at (point))
6034 txt (org-format-agenda-item "" (match-string 1) category tags)
6036 (+ (org-get-priority txt)
6037 (if org-todo-kwd-priority-p
6038 (- org-todo-kwd-max-priority -2
6040 (member (match-string 2) org-todo-keywords)))
6042 (org-add-props txt props
6043 'org-marker marker 'org-hd-marker marker
6044 'priority priority 'category category)
6046 (goto-char (match-end 1)))
6049 (defconst org-agenda-no-heading-message
6050 "No heading for this item in buffer or region.")
6052 (defun org-agenda-get-timestamps ()
6053 "Return the date stamp information for agenda display."
6054 (let* ((props (list 'face nil
6055 'org-not-done-regexp org-not-done-regexp
6056 'mouse-face 'highlight
6057 'keymap org-agenda-keymap
6059 (format "mouse-2 or RET jump to org file %s"
6060 (abbreviate-file-name buffer-file-name))))
6061 (regexp (regexp-quote
6064 (car org-time-stamp-formats)
6065 (apply 'encode-time ; DATE bound by calendar
6066 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
6068 marker hdmarker deadlinep scheduledp donep tmp priority category
6069 ee txt timestr tags)
6070 (goto-char (point-min))
6071 (while (re-search-forward regexp nil t)
6072 (if (not (save-match-data (org-at-date-range-p)))
6074 (setq marker (org-agenda-new-marker (match-beginning 0))
6075 category (org-get-category (match-beginning 0))
6076 tmp (buffer-substring (max (point-min)
6077 (- (match-beginning 0)
6078 org-ds-keyword-length))
6079 (match-beginning 0))
6080 timestr (buffer-substring (match-beginning 0) (point-at-eol))
6081 deadlinep (string-match org-deadline-regexp tmp)
6082 scheduledp (string-match org-scheduled-regexp tmp)
6083 donep (org-entry-is-done-p))
6084 (if (string-match ">" timestr)
6085 ;; substring should only run to end of time stamp
6086 (setq timestr (substring timestr 0 (match-end 0))))
6088 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6090 (goto-char (match-end 1))
6091 (setq hdmarker (org-agenda-new-marker)
6092 tags (org-get-tags-at))
6093 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6094 (setq txt (org-format-agenda-item
6096 (if deadlinep "Deadline: " "")
6097 (if scheduledp "Scheduled: " ""))
6098 (match-string 1) category tags timestr)))
6099 (setq txt org-agenda-no-heading-message))
6100 (setq priority (org-get-priority txt))
6101 (org-add-props txt props
6102 'org-marker marker 'org-hd-marker hdmarker)
6104 (org-add-props txt nil
6105 'face (if donep 'org-done 'org-warning)
6106 'undone-face 'org-warning 'done-face 'org-done
6107 'category category 'priority (+ 100 priority))
6109 (org-add-props txt nil
6110 'face 'org-scheduled-today
6111 'undone-face 'org-scheduled-today 'done-face 'org-done
6112 'category category 'priority (+ 99 priority))
6113 (org-add-props txt nil 'priority priority 'category category)))
6115 (outline-next-heading))))
6118 (defun org-agenda-get-closed ()
6119 "Return the logged TODO entries for agenda display."
6120 (let* ((props (list 'mouse-face 'highlight
6121 'org-not-done-regexp org-not-done-regexp
6122 'keymap org-agenda-keymap
6124 (format "mouse-2 or RET jump to org file %s"
6125 (abbreviate-file-name buffer-file-name))))
6127 "\\<" org-closed-string " *\\["
6131 (car org-time-stamp-formats)
6132 (apply 'encode-time ; DATE bound by calendar
6133 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
6135 marker hdmarker priority category tags
6137 (goto-char (point-min))
6138 (while (re-search-forward regexp nil t)
6139 (if (not (save-match-data (org-at-date-range-p)))
6141 (setq marker (org-agenda-new-marker (match-beginning 0))
6142 category (org-get-category (match-beginning 0))
6143 timestr (buffer-substring (match-beginning 0) (point-at-eol))
6144 ;; donep (org-entry-is-done-p)
6146 (if (string-match "\\]" timestr)
6147 ;; substring should only run to end of time stamp
6148 (setq timestr (substring timestr 0 (match-end 0))))
6150 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6152 (goto-char (match-end 1))
6153 (setq hdmarker (org-agenda-new-marker)
6154 tags (org-get-tags-at))
6155 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6156 (setq txt (org-format-agenda-item
6158 (match-string 1) category tags timestr)))
6159 (setq txt org-agenda-no-heading-message))
6160 (setq priority 100000)
6161 (org-add-props txt props
6162 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
6163 'priority priority 'category category
6164 'undone-face 'org-warning 'done-face 'org-done)
6166 (outline-next-heading))))
6169 (defun org-agenda-get-deadlines ()
6170 "Return the deadline information for agenda display."
6171 (let* ((wdays org-deadline-warning-days)
6172 (props (list 'mouse-face 'highlight
6173 'org-not-done-regexp org-not-done-regexp
6174 'keymap org-agenda-keymap
6176 (format "mouse-2 or RET jump to org file %s"
6177 (abbreviate-file-name buffer-file-name))))
6178 (regexp org-deadline-time-regexp)
6179 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
6180 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
6181 d2 diff pos pos1 category tags
6183 (goto-char (point-min))
6184 (while (re-search-forward regexp nil t)
6185 (setq pos (1- (match-beginning 1))
6187 (org-time-string-to-time (match-string 1)))
6189 ;; When to show a deadline in the calendar:
6190 ;; If the expiration is within wdays warning time.
6191 ;; Past-due deadlines are only shown on the current date
6192 (if (and (< diff wdays) todayp (not (= diff 0)))
6194 (setq category (org-get-category))
6195 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
6197 (goto-char (match-end 0))
6198 (setq pos1 (match-end 1))
6199 (setq tags (org-get-tags-at pos1))
6200 (setq head (buffer-substring-no-properties
6202 (progn (skip-chars-forward "^\r\n")
6204 (if (string-match org-looking-at-done-regexp head)
6206 (setq txt (org-format-agenda-item
6207 (format "In %3d d.: " diff) head category tags))))
6208 (setq txt org-agenda-no-heading-message))
6210 (org-add-props txt props
6211 'org-marker (org-agenda-new-marker pos)
6212 'org-hd-marker (org-agenda-new-marker pos1)
6213 'priority (+ (- 10 diff) (org-get-priority txt))
6215 'face (cond ((<= diff 0) 'org-warning)
6216 ((<= diff 5) 'org-scheduled-previously)
6219 ((<= diff 0) 'org-warning)
6220 ((<= diff 5) 'org-scheduled-previously)
6222 'done-face 'org-done)
6226 (defun org-agenda-get-scheduled ()
6227 "Return the scheduled information for agenda display."
6228 (let* ((props (list 'face 'org-scheduled-previously
6229 'org-not-done-regexp org-not-done-regexp
6230 'undone-face 'org-scheduled-previously
6231 'done-face 'org-done
6232 'mouse-face 'highlight
6233 'keymap org-agenda-keymap
6235 (format "mouse-2 or RET jump to org file %s"
6236 (abbreviate-file-name buffer-file-name))))
6237 (regexp org-scheduled-time-regexp)
6238 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
6239 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
6240 d2 diff pos pos1 category tags
6242 (goto-char (point-min))
6243 (while (re-search-forward regexp nil t)
6244 (setq pos (1- (match-beginning 1))
6246 (org-time-string-to-time (match-string 1)))
6248 ;; When to show a scheduled item in the calendar:
6249 ;; If it is on or past the date.
6250 (if (and (< diff 0) todayp)
6252 (setq category (org-get-category))
6253 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
6255 (goto-char (match-end 0))
6256 (setq pos1 (match-end 1))
6257 (setq tags (org-get-tags-at))
6258 (setq head (buffer-substring-no-properties
6260 (progn (skip-chars-forward "^\r\n") (point))))
6261 (if (string-match org-looking-at-done-regexp head)
6263 (setq txt (org-format-agenda-item
6264 (format "Sched.%2dx: " (- 1 diff)) head
6266 (setq txt org-agenda-no-heading-message))
6268 (org-add-props txt props
6269 'org-marker (org-agenda-new-marker pos)
6270 'org-hd-marker (org-agenda-new-marker pos1)
6271 'priority (+ (- 5 diff) (org-get-priority txt))
6276 (defun org-agenda-get-blocks ()
6277 "Return the date-range information for agenda display."
6278 (let* ((props (list 'face nil
6279 'org-not-done-regexp org-not-done-regexp
6280 'mouse-face 'highlight
6281 'keymap org-agenda-keymap
6283 (format "mouse-2 or RET jump to org file %s"
6284 (abbreviate-file-name buffer-file-name))))
6285 (regexp org-tr-regexp)
6286 (d0 (calendar-absolute-from-gregorian date))
6287 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
6288 (goto-char (point-min))
6289 (while (re-search-forward regexp nil t)
6290 (setq timestr (match-string 0)
6293 d1 (time-to-days (org-time-string-to-time s1))
6294 d2 (time-to-days (org-time-string-to-time s2)))
6295 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
6296 ;; Only allow days between the limits, because the normal
6297 ;; date stamps will catch the limits.
6299 (setq marker (org-agenda-new-marker (point)))
6300 (setq category (org-get-category))
6301 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6303 (setq hdmarker (org-agenda-new-marker (match-end 1)))
6304 (goto-char (match-end 1))
6305 (setq tags (org-get-tags-at))
6306 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6307 (setq txt (org-format-agenda-item
6308 (format (if (= d1 d2) "" "(%d/%d): ")
6309 (1+ (- d0 d1)) (1+ (- d2 d1)))
6310 (match-string 1) category tags
6311 (if (= d0 d1) timestr))))
6312 (setq txt org-agenda-no-heading-message))
6313 (org-add-props txt props
6314 'org-marker marker 'org-hd-marker hdmarker
6315 'priority (org-get-priority txt) 'category category)
6317 (outline-next-heading))
6318 ;; Sort the entries by expiration date.
6321 (defconst org-plain-time-of-day-regexp
6324 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
6327 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
6329 "Regular expression to match a plain time or time range.
6330 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
6331 groups carry important information:
6333 1 the first time, range or not
6334 8 the second time, if it is a range.")
6336 (defconst org-stamp-time-of-day-regexp
6338 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
6339 "\\([012][0-9]:[0-5][0-9]\\)>"
6341 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
6342 "Regular expression to match a timestamp time or time range.
6343 After a match, the following groups carry important information:
6345 1 date plus weekday, for backreferencing to make sure both times on same day
6346 2 the first time, range or not
6347 4 the second time, if it is a range.")
6349 (defvar org-prefix-has-time nil
6350 "A flag, set by `org-compile-prefix-format'.
6351 The flag is set if the currently compiled format contains a `%t'.")
6352 (defvar org-prefix-has-tag nil
6353 "A flag, set by `org-compile-prefix-format'.
6354 The flag is set if the currently compiled format contains a `%T'.")
6356 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
6357 "Format TXT to be inserted into the agenda buffer.
6358 In particular, it adds the prefix and corresponding text properties. EXTRA
6359 must be a string and replaces the `%s' specifier in the prefix format.
6360 CATEGORY (string, symbol or nil) may be used to overrule the default
6361 category taken from local variable or file name. It will replace the `%c'
6362 specifier in the format. DOTIME, when non-nil, indicates that a
6363 time-of-day should be extracted from TXT for sorting of this entry, and for
6364 the `%t' specifier in the format. When DOTIME is a string, this string is
6365 searched for a time before TXT is. NOPREFIX is a flag and indicates that
6366 only the correctly processes TXT should be returned - this is used by
6367 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
6369 ;; Diary entries sometimes have extra whitespace at the beginning
6370 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
6371 (let* ((category (or category
6373 (if buffer-file-name
6374 (file-name-sans-extension
6375 (file-name-nondirectory buffer-file-name))
6377 (tag (if tags (nth (1- (length tags)) tags) ""))
6378 time ;; needed for the eval of the prefix format
6379 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
6380 (time-of-day (and dotime (org-get-time-of-day ts)))
6381 stamp plain s0 s1 s2 rtn)
6382 (when (and dotime time-of-day org-prefix-has-time)
6383 ;; Extract starting and ending time and move them to prefix
6384 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
6385 (setq plain (string-match org-plain-time-of-day-regexp ts)))
6386 (setq s0 (match-string 0 ts)
6387 s1 (match-string (if plain 1 2) ts)
6388 s2 (match-string (if plain 8 4) ts))
6390 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
6391 ;; them, we might want to remove them there to avoid duplication.
6392 ;; The user can turn this off with a variable.
6393 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
6394 (string-match (concat (regexp-quote s0) " *") txt)
6395 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
6396 (= (match-beginning 0) 0)
6398 (setq txt (replace-match "" nil nil txt))))
6399 ;; Normalize the time(s) to 24 hour
6400 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
6401 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
6403 (when (and (or (eq org-agenda-remove-tags-when-in-prefix t)
6404 (and org-agenda-remove-tags-when-in-prefix
6405 org-prefix-has-tag))
6406 (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" txt))
6407 (setq txt (replace-match "" t t txt)))
6409 ;; Create the final string
6412 ;; Prepare the variables needed in the eval of the compiled format
6413 (setq time (cond (s2 (concat s1 "-" s2))
6414 (s1 (concat s1 "......"))
6417 category (if (symbolp category) (symbol-name category) category))
6418 ;; Evaluate the compiled format
6419 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
6421 ;; And finally add the text properties
6422 (org-add-props rtn nil
6423 'category (downcase category) 'tags tags
6424 'prefix-length (- (length rtn) (length txt))
6425 'time-of-day time-of-day
6428 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
6430 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
6431 ((and todayp (member 'today (car org-agenda-time-grid))))
6432 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
6433 ((member 'weekly (car org-agenda-time-grid)))
6434 (t (throw 'exit list)))
6435 (let* ((have (delq nil (mapcar
6436 (lambda (x) (get-text-property 1 'time-of-day x))
6438 (string (nth 1 org-agenda-time-grid))
6439 (gridtimes (nth 2 org-agenda-time-grid))
6440 (req (car org-agenda-time-grid))
6441 (remove (member 'remove-match req))
6443 (if (and (member 'require-timed req) (not have))
6444 ;; don't show empty grid
6446 (while (setq time (pop gridtimes))
6447 (unless (and remove (member time have))
6448 (setq time (int-to-string time))
6449 (push (org-format-agenda-item
6451 (concat (substring time 0 -2) ":" (substring time -2)))
6454 1 (length (car new)) 'face 'org-time-grid (car new))))
6455 (if (member 'time-up org-agenda-sorting-strategy)
6457 (append list new)))))
6459 (defun org-compile-prefix-format (format)
6460 "Compile the prefix format into a Lisp form that can be evaluated.
6461 The resulting form is returned and stored in the variable
6462 `org-prefix-format-compiled'."
6463 (setq org-prefix-has-time nil org-prefix-has-tag nil)
6464 (let ((start 0) varform vars var (s format)e c f opt)
6465 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
6467 (setq var (cdr (assoc (match-string 4 s)
6468 '(("c" . category) ("t" . time) ("s" . extra)
6470 c (or (match-string 3 s) "")
6471 opt (match-beginning 1)
6472 start (1+ (match-beginning 0)))
6473 (if (equal var 'time) (setq org-prefix-has-time t))
6474 (if (equal var 'tag) (setq org-prefix-has-tag t))
6475 (setq f (concat "%" (match-string 2 s) "s"))
6478 `(if (equal "" ,var)
6480 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
6481 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
6482 (setq s (replace-match "%s" t nil s))
6483 (push varform vars))
6484 (setq vars (nreverse vars))
6485 (setq org-prefix-format-compiled `(format ,s ,@vars))))
6487 (defun org-get-time-of-day (s &optional string)
6488 "Check string S for a time of day.
6489 If found, return it as a military time number between 0 and 2400.
6490 If not found, return nil.
6491 The optional STRING argument forces conversion into a 5 character wide string
6497 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
6499 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
6500 (let* ((t0 (+ (* 100
6501 (+ (string-to-number (match-string 1 s))
6502 (if (and (match-beginning 4)
6503 (equal (downcase (match-string 4 s)) "pm"))
6505 (if (match-beginning 3)
6506 (string-to-number (match-string 3 s))
6509 (if (< t0 100) "0" "") (if (< t0 10) "0" "")
6510 (int-to-string t0))))
6511 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
6513 (defun org-finalize-agenda-entries (list)
6514 "Sort and concatenate the agenda items."
6515 (setq list (mapcar 'org-agenda-highlight-todo list))
6516 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
6518 (defun org-agenda-highlight-todo (x)
6522 (beginning-of-line 1)
6523 (setq re (get-text-property (point) 'org-not-done-regexp))
6524 (goto-char (+ (point) (get-text-property (point) 'prefix-length)))
6525 (and (looking-at (concat "[ \t]*" re))
6526 (add-text-properties (match-beginning 0) (match-end 0)
6528 (setq re (get-text-property 0 'org-not-done-regexp x))
6529 (and re (string-match re x)
6530 (add-text-properties (match-beginning 0) (match-end 0)
6531 '(face org-todo) x))
6534 (defsubst org-cmp-priority (a b)
6535 "Compare the priorities of string A and B."
6536 (let ((pa (or (get-text-property 1 'priority a) 0))
6537 (pb (or (get-text-property 1 'priority b) 0)))
6538 (cond ((> pa pb) +1)
6542 (defsubst org-cmp-category (a b)
6543 "Compare the string values of categories of strings A and B."
6544 (let ((ca (or (get-text-property 1 'category a) ""))
6545 (cb (or (get-text-property 1 'category b) "")))
6546 (cond ((string-lessp ca cb) -1)
6547 ((string-lessp cb ca) +1)
6550 (defsubst org-cmp-time (a b)
6551 "Compare the time-of-day values of strings A and B."
6552 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
6553 (ta (or (get-text-property 1 'time-of-day a) def))
6554 (tb (or (get-text-property 1 'time-of-day b) def)))
6555 (cond ((< ta tb) -1)
6559 (defun org-entries-lessp (a b)
6560 "Predicate for sorting agenda entries."
6561 ;; The following variables will be used when the form is evaluated.
6562 (let* ((time-up (org-cmp-time a b))
6563 (time-down (if time-up (- time-up) nil))
6564 (priority-up (org-cmp-priority a b))
6565 (priority-down (if priority-up (- priority-up) nil))
6566 (category-up (org-cmp-category a b))
6567 (category-down (if category-up (- category-up) nil))
6568 (category-keep (if category-up +1 nil)))
6570 (eval (cons 'or org-agenda-sorting-strategy))
6571 '((-1 . t) (1 . nil) (nil . nil))))))
6573 (defun org-agenda-show-priority ()
6574 "Show the priority of the current item.
6575 This priority is composed of the main priority given with the [#A] cookies,
6576 and by additional input from the age of a schedules or deadline entry."
6578 (let* ((pri (get-text-property (point-at-bol) 'priority)))
6579 (message "Priority is %d" (if pri pri -1000))))
6581 (defun org-agenda-show-tags ()
6582 "Show the tags applicable to the current item."
6584 (let* ((tags (get-text-property (point-at-bol) 'tags)))
6586 (message "Tags are :%s:" (mapconcat 'identity tags ":"))
6587 (message "No tags associated with this line"))))
6589 (defun org-agenda-goto (&optional highlight)
6590 "Go to the Org-mode file which contains the item at point."
6592 (let* ((marker (or (get-text-property (point) 'org-marker)
6593 (org-agenda-error)))
6594 (buffer (marker-buffer marker))
6595 (pos (marker-position marker)))
6596 (switch-to-buffer-other-window buffer)
6599 (when (eq major-mode 'org-mode)
6600 (org-show-hidden-entry)
6602 (and (outline-next-heading)
6603 (org-flag-heading nil)))) ; show the next heading
6604 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
6606 (defun org-agenda-switch-to ()
6607 "Go to the Org-mode file which contains the item at point."
6609 (let* ((marker (or (get-text-property (point) 'org-marker)
6610 (org-agenda-error)))
6611 (buffer (marker-buffer marker))
6612 (pos (marker-position marker)))
6613 (switch-to-buffer buffer)
6614 (delete-other-windows)
6617 (when (eq major-mode 'org-mode)
6618 (org-show-hidden-entry)
6620 (and (outline-next-heading)
6621 (org-flag-heading nil)))))) ; show the next heading
6623 (defun org-agenda-goto-mouse (ev)
6624 "Go to the Org-mode file which contains the item at the mouse click."
6626 (mouse-set-point ev)
6629 (defun org-agenda-show ()
6630 "Display the Org-mode file which contains the item at point."
6632 (let ((win (selected-window)))
6634 (select-window win)))
6636 (defun org-agenda-recenter (arg)
6637 "Display the Org-mode file which contains the item at point and recenter."
6639 (let ((win (selected-window)))
6642 (select-window win)))
6644 (defun org-agenda-show-mouse (ev)
6645 "Display the Org-mode file which contains the item at the mouse click."
6647 (mouse-set-point ev)
6650 (defun org-agenda-check-no-diary ()
6651 "Check if the entry is a diary link and abort if yes."
6652 (if (get-text-property (point) 'org-agenda-diary-link)
6653 (org-agenda-error)))
6655 (defun org-agenda-error ()
6656 (error "Command not allowed in this line"))
6658 (defvar org-last-heading-marker (make-marker)
6659 "Marker pointing to the headline that last changed its TODO state
6660 by a remote command from the agenda.")
6662 (defun org-agenda-todo (&optional arg)
6663 "Cycle TODO state of line at point, also in Org-mode file.
6664 This changes the line at point, all other lines in the agenda referring to
6665 the same tree node, and the headline of the tree node in the Org-mode file."
6667 (org-agenda-check-no-diary)
6668 (let* ((col (current-column))
6669 (marker (or (get-text-property (point) 'org-marker)
6670 (org-agenda-error)))
6671 (buffer (marker-buffer marker))
6672 (pos (marker-position marker))
6673 (hdmarker (get-text-property (point) 'org-hd-marker))
6674 (buffer-read-only nil)
6676 (with-current-buffer buffer
6679 (org-show-hidden-entry)
6681 (and (outline-next-heading)
6682 (org-flag-heading nil))) ; show the next heading
6684 (and (bolp) (forward-char 1))
6685 (setq newhead (org-get-heading))
6687 (org-back-to-heading)
6688 (move-marker org-last-heading-marker (point))))
6689 (beginning-of-line 1)
6691 (org-agenda-change-all-lines newhead hdmarker 'fixface))
6692 (move-to-column col)))
6694 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
6695 "Change all lines in the agenda buffer which match HDMARKER.
6696 The new content of the line will be NEWHEAD (as modified by
6697 `org-format-agenda-item'). HDMARKER is checked with
6698 `equal' against all `org-hd-marker' text properties in the file.
6699 If FIXFACE is non-nil, the face of each item is modified acording to
6700 the new TODO state."
6701 (let* (props m pl undone-face done-face finish new dotime cat tags)
6702 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
6704 (goto-char (point-max))
6705 (beginning-of-line 1)
6707 (setq finish (bobp))
6708 (when (and (setq m (get-text-property (point) 'org-hd-marker))
6710 (setq props (text-properties-at (point))
6711 dotime (get-text-property (point) 'dotime)
6712 cat (get-text-property (point) 'category)
6713 tags (get-text-property (point) 'tags)
6714 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
6715 pl (get-text-property (point) 'prefix-length)
6716 undone-face (get-text-property (point) 'undone-face)
6717 done-face (get-text-property (point) 'done-face))
6719 (if (looking-at ".*")
6721 (replace-match new t t)
6722 (beginning-of-line 1)
6723 (add-text-properties (point-at-bol) (point-at-eol) props)
6725 (add-text-properties
6726 (point-at-bol) (point-at-eol)
6728 (if org-last-todo-state-is-todo
6729 undone-face done-face)))
6730 (org-agenda-highlight-todo 'line))
6731 (beginning-of-line 1))
6732 (error "Line update did not work")))
6733 (beginning-of-line 0)))))
6735 (defun org-agenda-priority-up ()
6736 "Increase the priority of line at point, also in Org-mode file."
6738 (org-agenda-priority 'up))
6740 (defun org-agenda-priority-down ()
6741 "Decrease the priority of line at point, also in Org-mode file."
6743 (org-agenda-priority 'down))
6745 (defun org-agenda-priority (&optional force-direction)
6746 "Set the priority of line at point, also in Org-mode file.
6747 This changes the line at point, all other lines in the agenda referring to
6748 the same tree node, and the headline of the tree node in the Org-mode file."
6750 (org-agenda-check-no-diary)
6751 (let* ((marker (or (get-text-property (point) 'org-marker)
6752 (org-agenda-error)))
6753 (buffer (marker-buffer marker))
6754 (pos (marker-position marker))
6755 (hdmarker (get-text-property (point) 'org-hd-marker))
6756 (buffer-read-only nil)
6758 (with-current-buffer buffer
6761 (org-show-hidden-entry)
6763 (and (outline-next-heading)
6764 (org-flag-heading nil))) ; show the next heading
6765 (funcall 'org-priority force-direction)
6767 (setq newhead (org-get-heading)))
6768 (org-agenda-change-all-lines newhead hdmarker)
6769 (beginning-of-line 1)))
6771 (defun org-get-tags-at (&optional pos)
6772 "Get a list of all headline targs applicable at POS.
6773 POS defaults to point. If tags are inherited, the list contains
6774 the targets in the same sequence as the headlines appear, i.e.
6775 the tags of the current headline come last."
6779 (goto-char (or pos (point)))
6781 (org-back-to-heading t)
6784 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
6785 (setq tags (append (org-split-string (match-string 1) ":") tags)))
6786 (or org-use-tag-inheritance (error ""))
6787 (org-up-heading-all 1))
6792 (defun org-agenda-set-tags ()
6793 "Set tags for the current headline."
6795 (org-agenda-check-no-diary)
6796 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
6797 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
6798 (org-agenda-error)))
6799 (buffer (marker-buffer hdmarker))
6800 (pos (marker-position hdmarker))
6801 (buffer-read-only nil)
6803 (with-current-buffer buffer
6806 (org-show-hidden-entry)
6808 (and (outline-next-heading)
6809 (org-flag-heading nil))) ; show the next heading
6810 (call-interactively 'org-set-tags)
6812 (setq newhead (org-get-heading)))
6813 (org-agenda-change-all-lines newhead hdmarker)
6814 (beginning-of-line 1)))
6816 (defun org-agenda-date-later (arg &optional what)
6817 "Change the date of this item to one day later."
6819 (org-agenda-check-type t 'agenda 'timeline)
6820 (org-agenda-check-no-diary)
6821 (let* ((marker (or (get-text-property (point) 'org-marker)
6822 (org-agenda-error)))
6823 (buffer (marker-buffer marker))
6824 (pos (marker-position marker)))
6825 (with-current-buffer buffer
6828 (if (not (org-at-timestamp-p))
6829 (error "Cannot find time stamp"))
6830 (org-timestamp-change arg (or what 'day))
6831 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6833 (defun org-agenda-date-earlier (arg &optional what)
6834 "Change the date of this item to one day earlier."
6836 (org-agenda-date-later (- arg) what))
6838 (defun org-agenda-date-prompt (arg)
6839 "Change the date of this item. Date is prompted for, with default today.
6840 The prefix ARG is passed to the `org-time-stamp' command and can therefore
6841 be used to request time specification in the time stamp."
6843 (org-agenda-check-type t 'agenda 'timeline)
6844 (org-agenda-check-no-diary)
6845 (let* ((marker (or (get-text-property (point) 'org-marker)
6846 (org-agenda-error)))
6847 (buffer (marker-buffer marker))
6848 (pos (marker-position marker)))
6849 (with-current-buffer buffer
6852 (if (not (org-at-timestamp-p))
6853 (error "Cannot find time stamp"))
6854 (org-time-stamp arg)
6855 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6857 (defun org-get-heading ()
6858 "Return the heading of the current entry, without the stars."
6860 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
6861 (if (and (re-search-backward "[\r\n]\\*" nil t)
6862 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
6866 (defun org-agenda-diary-entry ()
6867 "Make a diary entry, like the `i' command from the calendar.
6868 All the standard commands work: block, weekly etc."
6870 (org-agenda-check-type t 'agenda 'timeline)
6871 (require 'diary-lib)
6873 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
6874 (read-char-exclusive)))
6875 (cmd (cdr (assoc char
6876 '((?d . insert-diary-entry)
6877 (?w . insert-weekly-diary-entry)
6878 (?m . insert-monthly-diary-entry)
6879 (?y . insert-yearly-diary-entry)
6880 (?a . insert-anniversary-diary-entry)
6881 (?b . insert-block-diary-entry)
6882 (?c . insert-cyclic-diary-entry)))))
6883 (oldf (symbol-function 'calendar-cursor-to-date))
6885 (mark (or (mark t) (point))))
6887 (error "No command associated with <%c>" char))
6888 (unless (and (get-text-property point 'day)
6889 (or (not (equal ?b char))
6890 (get-text-property mark 'day)))
6891 (error "Don't know which date to use for diary entry"))
6892 ;; We implement this by hacking the `calendar-cursor-to-date' function
6893 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
6894 (let ((calendar-mark-ring
6895 (list (calendar-gregorian-from-absolute
6896 (or (get-text-property mark 'day)
6897 (get-text-property point 'day))))))
6900 (fset 'calendar-cursor-to-date
6901 (lambda (&optional error)
6902 (calendar-gregorian-from-absolute
6903 (get-text-property point 'day))))
6904 (call-interactively cmd))
6905 (fset 'calendar-cursor-to-date oldf)))))
6908 (defun org-agenda-execute-calendar-command (cmd)
6909 "Execute a calendar command from the agenda, with the date associated to
6910 the cursor position."
6911 (org-agenda-check-type t 'agenda 'timeline)
6912 (require 'diary-lib)
6913 (unless (get-text-property (point) 'day)
6914 (error "Don't know which date to use for calendar command"))
6915 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
6917 (date (calendar-gregorian-from-absolute
6918 (get-text-property point 'day)))
6919 (displayed-day (extract-calendar-day date))
6920 (displayed-month (extract-calendar-month date))
6921 (displayed-year (extract-calendar-year date)))
6924 (fset 'calendar-cursor-to-date
6925 (lambda (&optional error)
6926 (calendar-gregorian-from-absolute
6927 (get-text-property point 'day))))
6928 (call-interactively cmd))
6929 (fset 'calendar-cursor-to-date oldf))))
6931 (defun org-agenda-phases-of-moon ()
6932 "Display the phases of the moon for the 3 months around the cursor date."
6934 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
6936 (defun org-agenda-holidays ()
6937 "Display the holidays for the 3 months around the cursor date."
6939 (org-agenda-execute-calendar-command 'list-calendar-holidays))
6941 (defun org-agenda-sunrise-sunset (arg)
6942 "Display sunrise and sunset for the cursor date.
6943 Latitude and longitude can be specified with the variables
6944 `calendar-latitude' and `calendar-longitude'. When called with prefix
6945 argument, latitude and longitude will be prompted for."
6947 (let ((calendar-longitude (if arg nil calendar-longitude))
6948 (calendar-latitude (if arg nil calendar-latitude))
6949 (calendar-location-name
6950 (if arg "the given coordinates" calendar-location-name)))
6951 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
6953 (defun org-agenda-goto-calendar ()
6954 "Open the Emacs calendar with the date at the cursor."
6956 (org-agenda-check-type t 'agenda 'timeline)
6957 (let* ((day (or (get-text-property (point) 'day)
6958 (error "Don't know which date to open in calendar")))
6959 (date (calendar-gregorian-from-absolute day))
6960 (calendar-move-hook nil)
6961 (view-diary-entries-initially nil))
6963 (calendar-goto-date date)))
6965 (defun org-calendar-goto-agenda ()
6966 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
6967 This is a command that has to be installed in `calendar-mode-map'."
6969 (org-agenda-list nil (calendar-absolute-from-gregorian
6970 (calendar-cursor-to-date))
6973 (defun org-agenda-convert-date ()
6975 (org-agenda-check-type t 'agenda 'timeline)
6976 (let ((day (get-text-property (point) 'day))
6979 (error "Don't know which date to convert"))
6980 (setq date (calendar-gregorian-from-absolute day))
6982 "Gregorian: " (calendar-date-string date) "\n"
6983 "ISO: " (calendar-iso-date-string date) "\n"
6984 "Day of Yr: " (calendar-day-of-year-string date) "\n"
6985 "Julian: " (calendar-julian-date-string date) "\n"
6986 "Astron. JD: " (calendar-astro-date-string date)
6987 " (Julian date number at noon UTC)\n"
6988 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
6989 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
6990 "French: " (calendar-french-date-string date) "\n"
6991 "Mayan: " (calendar-mayan-date-string date) "\n"
6992 "Coptic: " (calendar-coptic-date-string date) "\n"
6993 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
6994 "Persian: " (calendar-persian-date-string date) "\n"
6995 "Chinese: " (calendar-chinese-date-string date) "\n"))
6996 (with-output-to-temp-buffer "*Dates*"
6998 (if (fboundp 'fit-window-to-buffer)
6999 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
7003 (defun org-scan-tags (action matcher &optional todo-only)
7004 "Scan headline tags with inheritance and produce output ACTION.
7005 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
7006 evaluated, testing if a given set of tags qualifies a headline for
7007 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
7008 are included in the output."
7009 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
7010 (mapconcat 'regexp-quote
7011 (nreverse (cdr (reverse org-todo-keywords)))
7013 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
7014 (props (list 'face nil
7015 'done-face 'org-done
7017 'mouse-face 'highlight
7018 'keymap org-agenda-keymap
7020 (format "mouse-2 or RET jump to org file %s"
7021 (abbreviate-file-name buffer-file-name))))
7023 tags tags-list tags-alist (llast 0) rtn level category i txt
7027 (goto-char (point-min))
7028 (when (eq action 'sparse-tree) (hide-sublevels 1))
7029 (while (re-search-forward re nil t)
7030 (setq todo (if (match-end 1) (match-string 2))
7031 tags (if (match-end 4) (match-string 4)))
7032 (goto-char (setq lspos (1+ (match-beginning 0))))
7033 (setq level (funcall outline-level)
7034 category (org-get-category))
7035 (setq i llast llast level)
7036 ;; remove tag lists from same and sublevels
7038 (when (setq entry (assoc i tags-alist))
7039 (setq tags-alist (delete entry tags-alist)))
7043 (setq tags (mapcar 'downcase (org-split-string tags ":"))
7045 (cons (cons level tags) tags-alist)))
7046 ;; compile tags for current headline
7048 (if org-use-tag-inheritance
7049 (apply 'append (mapcar 'cdr tags-alist))
7051 (when (and (or (not todo-only) todo)
7053 ;; list this headline
7054 (if (eq action 'sparse-tree)
7056 (org-show-hierarchy-above))
7057 (setq txt (org-format-agenda-item
7060 (if org-tags-match-list-sublevels
7061 (make-string (1- level) ?.) "")
7063 category tags-list))
7065 (setq marker (org-agenda-new-marker))
7066 (org-add-props txt props
7067 'org-marker marker 'org-hd-marker marker 'category category)
7069 ;; if we are to skip sublevels, jump to end of subtree
7071 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
7074 (defun org-tags-sparse-tree (&optional arg match)
7075 "Create a sparse tree according to tags search string MATCH.
7076 MATCH can contain positive and negative selection of tags, like
7077 \"+WORK+URGENT-WITHBOSS\"."
7079 (let ((org-show-following-heading nil)
7080 (org-show-hierarchy-above nil))
7081 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
7083 (defun org-make-tags-matcher (match)
7084 "Create the TAGS matcher form for the tags-selecting string MATCH."
7086 ;; Get a new match request, with completion
7087 (setq org-last-tags-completion-table
7088 (or (org-get-buffer-tags)
7089 org-last-tags-completion-table))
7090 (setq match (completing-read
7091 "Tags: " 'org-tags-completion-function nil nil nil
7092 'org-tags-history)))
7093 ;; parse the string and create a lisp form
7094 (let ((match0 match) minus tag mm matcher orterms term orlist)
7095 (setq orterms (org-split-string match "|"))
7096 (while (setq term (pop orterms))
7097 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
7098 (setq minus (and (match-end 1)
7099 (equal (match-string 1 term) "-"))
7100 tag (match-string 2 term)
7101 term (substring term (match-end 0))
7102 mm (list 'member (downcase tag) 'tags-list)
7103 mm (if minus (list 'not mm) mm))
7105 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
7108 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
7109 ;; Return the string and lisp forms of the matcher
7110 (cons match0 matcher)))
7113 (defun org-tags-view (&optional todo-only match keep-modes)
7114 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
7115 The prefix arg TODO-ONLY limits the search to TODO entries."
7117 (org-agenda-maybe-reset-markers 'force)
7118 (org-compile-prefix-format org-agenda-prefix-format)
7119 (let* ((org-agenda-keep-modes keep-modes)
7120 (org-tags-match-list-sublevels
7121 (if todo-only t org-tags-match-list-sublevels))
7122 (win (selected-window))
7123 (completion-ignore-case t)
7124 rtn rtnall files file pos matcher
7126 (setq matcher (org-make-tags-matcher match)
7127 match (car matcher) matcher (cdr matcher))
7128 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
7130 (delete-other-windows)
7131 (switch-to-buffer-other-window
7132 (get-buffer-create org-agenda-buffer-name))))
7133 (setq buffer-read-only nil)
7135 (org-agenda-mode) (setq buffer-read-only nil)
7136 (set (make-local-variable 'org-agenda-type) 'tags)
7137 (set (make-local-variable 'org-agenda-redo-command)
7138 (list 'org-tags-view (list 'quote todo-only)
7139 (list 'if 'current-prefix-arg nil match) t))
7140 (setq files (org-agenda-files)
7142 (while (setq file (pop files))
7144 (org-check-agenda-file file)
7145 (setq buffer (if (file-exists-p file)
7146 (org-get-agenda-file-buffer file)
7147 (error "No such file %s" file)))
7149 ;; If file does not exist, merror message to agenda
7151 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
7152 rtnall (append rtnall rtn))
7153 (with-current-buffer buffer
7154 (unless (eq major-mode 'org-mode)
7155 (error "Agenda file %s is not in `org-mode'" file))
7158 (if org-respect-restriction
7159 (if (org-region-active-p)
7160 ;; Respect a region to restrict search
7161 (narrow-to-region (region-beginning) (region-end)))
7162 ;; If we work for the calendar or many files,
7163 ;; get rid of any restriction
7165 (setq rtn (org-scan-tags 'agenda matcher todo-only))
7166 (setq rtnall (append rtnall rtn))))))))
7167 (insert "Headlines with TAGS match: ")
7168 (add-text-properties (point-min) (1- (point))
7169 (list 'face 'org-level-3))
7172 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
7174 (insert "Press `C-u r' to search again with new search string\n")
7175 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
7177 (insert (mapconcat 'identity rtnall "\n")))
7178 (goto-char (point-min))
7179 (setq buffer-read-only t)
7180 (org-fit-agenda-window)
7181 (if (not org-select-agenda-window) (select-window win))))
7183 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
7184 (defun org-set-tags (&optional arg just-align)
7185 "Set the tags for the current headline.
7186 With prefix ARG, realign all tags in headings in the current buffer."
7188 (let* (;(inherit (org-get-inherited-tags))
7189 (re (concat "^" outline-regexp))
7190 (col (current-column))
7191 (current (org-get-tags))
7192 tags hd empty invis)
7195 (goto-char (point-min))
7196 (while (re-search-forward re nil t)
7197 (org-set-tags nil t))
7198 (message "All tags realigned to column %d" org-tags-column))
7201 (setq org-last-tags-completion-table
7202 (or (org-get-buffer-tags)
7203 org-last-tags-completion-table))
7205 (let ((org-add-colon-after-tag-completion t))
7206 (completing-read "Tags: " 'org-tags-completion-function
7207 nil nil current 'org-tags-history)))
7208 (while (string-match "[-+&]+" tags)
7209 (setq tags (replace-match ":" t t tags))))
7210 ;; FIXME: still optimize this by not checking when JUST-ALIGN?
7211 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
7212 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
7213 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
7214 (if (equal current "")
7217 (or empty (insert-before-markers " ")))
7218 (beginning-of-line 1)
7219 (setq invis (org-invisible-p))
7220 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
7221 (setq hd (match-string 1))
7222 (delete-region (match-beginning 0) (match-end 0))
7223 (insert-before-markers (org-trim hd) (if empty "" " ")))
7224 (unless (equal tags "")
7225 (move-to-column (max (current-column)
7226 (if (> org-tags-column 0)
7228 (- (- org-tags-column) (length tags))))
7230 (insert-before-markers tags)
7231 (if (and (not invis) (org-invisible-p))
7232 (outline-flag-region (point-at-bol) (point) nil)))
7233 (move-to-column col))))
7235 (defun org-tags-completion-function (string predicate &optional flag)
7236 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
7237 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
7238 (setq s1 (match-string 1 string)
7239 s2 (match-string 2 string))
7240 (setq s1 "" s2 string))
7244 (setq rtn (try-completion s2 ctable))
7246 (concat s1 s2 (substring rtn (length s2))
7247 (if (and org-add-colon-after-tag-completion
7253 (all-completions s2 ctable)
7260 (defun org-get-tags ()
7261 "Get the TAGS string in the current headline."
7262 (unless (org-on-heading-p)
7263 (error "Not on a heading"))
7265 (beginning-of-line 1)
7266 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
7267 (org-match-string-no-properties 1)
7270 (defun org-get-buffer-tags ()
7271 "Get a table of all tags used in the buffer, for completion."
7274 (goto-char (point-min))
7275 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
7276 (mapc (lambda (x) (add-to-list 'tags x))
7277 (org-split-string (org-match-string-no-properties 1) ":"))))
7278 (mapcar 'list tags)))
7282 (defun org-find-file-at-mouse (ev)
7283 "Open file link or URL at mouse."
7285 (mouse-set-point ev)
7286 (org-open-at-point 'in-emacs))
7288 (defun org-open-at-mouse (ev)
7289 "Open file link or URL at mouse."
7291 (mouse-set-point ev)
7292 (org-open-at-point))
7294 (defun org-open-at-point (&optional in-emacs)
7295 "Open link at or after point.
7296 If there is no link at point, this function will search forward up to
7297 the end of the current subtree.
7298 Normally, files will be opened by an appropriate application. If the
7299 optional argument IN-EMACS is non-nil, Emacs will visit the file."
7301 (org-remove-occur-highlights nil nil t)
7302 (if (org-at-timestamp-p)
7303 (org-agenda-list nil (time-to-days (org-time-string-to-time
7304 (substring (match-string 1) 0 10)))
7306 (let (type path link line search (pos (point)))
7309 (skip-chars-forward "^]\n\r")
7310 (when (and (re-search-backward "\\[\\[" nil t)
7311 (looking-at org-bracket-link-regexp)
7312 (<= (match-beginning 0) pos)
7313 (>= (match-end 0) pos))
7314 (setq link (org-link-unescape (org-match-string-no-properties 1)))
7315 (while (string-match " *\n *" link)
7316 (setq link (replace-match " " t t link)))
7317 (if (string-match org-link-re-with-space2 link)
7318 (setq type (match-string 1 link)
7319 path (match-string 2 link))
7320 (setq type "thisfile"
7324 (when (get-text-property (point) 'org-linked-text)
7325 (setq type "thisfile"
7326 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7327 (1+ (point)) (point))
7328 path (buffer-substring
7329 (previous-single-property-change pos 'org-linked-text)
7330 (next-single-property-change pos 'org-linked-text)))
7334 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
7335 (if (equal (char-before) ?<) (backward-char 1))
7336 (when (or (looking-at org-angle-link-re)
7337 (looking-at org-plain-link-re)
7338 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
7339 (re-search-forward org-plain-link-re (point-at-eol) t))
7340 (<= (match-beginning 0) pos)
7341 (>= (match-end 0) pos)))
7342 (setq type (match-string 1)
7343 path (match-string 2))
7346 (skip-chars-backward "^ \t\n\r")
7347 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
7349 path (match-string 1))
7350 (while (string-match ":" path)
7351 (setq path (replace-match "+" t t path)))
7354 (skip-chars-backward "a-zA-Z_")
7355 (when (and (memq 'camel org-activate-links)
7356 (looking-at org-camel-regexp))
7357 (setq type "camel" path (match-string 0))
7358 (if (equal (char-before) ?*)
7359 (setq path (concat "*" path))))
7362 (error "No link found"))
7363 ;; Remove any trailing spaces in path
7364 (if (string-match " +\\'" path)
7365 (setq path (replace-match "" t t path)))
7369 ((member type '("http" "https" "ftp" "mailto" "news"))
7370 (browse-url (concat type ":" path)))
7372 ((string= type "tags")
7373 (org-tags-view in-emacs path))
7374 ((or (string= type "camel")
7375 (string= type "thisfile"))
7376 (org-mark-ring-push)
7379 (cond ((equal in-emacs '(4)) 'occur)
7380 ((equal in-emacs '(16)) 'org-occur)
7383 ((string= type "file")
7384 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
7385 (setq line (string-to-number (match-string 1 path))
7386 path (substring path 0 (match-beginning 0)))
7387 (if (string-match "::\\(.+\\)\\'" path)
7388 (setq search (match-string 1 path)
7389 path (substring path 0 (match-beginning 0)))))
7390 (org-open-file path in-emacs line search))
7392 ((string= type "news")
7393 (org-follow-gnus-link path))
7395 ((string= type "bbdb")
7396 (org-follow-bbdb-link path))
7398 ((string= type "gnus")
7399 (let (group article)
7400 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7401 (error "Error in Gnus link"))
7402 (setq group (match-string 1 path)
7403 article (match-string 3 path))
7404 (org-follow-gnus-link group article)))
7406 ((string= type "vm")
7407 (let (folder article)
7408 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7409 (error "Error in VM link"))
7410 (setq folder (match-string 1 path)
7411 article (match-string 3 path))
7412 ;; in-emacs is the prefix arg, will be interpreted as read-only
7413 (org-follow-vm-link folder article in-emacs)))
7415 ((string= type "wl")
7416 (let (folder article)
7417 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7418 (error "Error in Wanderlust link"))
7419 (setq folder (match-string 1 path)
7420 article (match-string 3 path))
7421 (org-follow-wl-link folder article)))
7423 ((string= type "mhe")
7424 (let (folder article)
7425 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7426 (error "Error in MHE link"))
7427 (setq folder (match-string 1 path)
7428 article (match-string 3 path))
7429 (org-follow-mhe-link folder article)))
7431 ((string= type "rmail")
7432 (let (folder article)
7433 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7434 (error "Error in RMAIL link"))
7435 (setq folder (match-string 1 path)
7436 article (match-string 3 path))
7437 (org-follow-rmail-link folder article)))
7439 ((string= type "shell")
7441 (while (string-match "@{" cmd)
7442 (setq cmd (replace-match "<" t t cmd)))
7443 (while (string-match "@}" cmd)
7444 (setq cmd (replace-match ">" t t cmd)))
7445 (if (or (not org-confirm-shell-links)
7446 (funcall org-confirm-shell-links
7447 (format "Execute \"%s\" in shell? "
7448 (org-add-props cmd nil
7449 'face 'org-warning))))
7451 (message "Executing %s..." cmd)
7453 (message "Executing %s...done" cmd))
7457 (browse-url-at-point))))))
7459 (defun org-link-search (s &optional type)
7460 "Search for a link search option.
7461 When S is a CamelCaseWord, search for a target, or for a sentence containing
7462 the words. If S is surrounded by forward slashes, it is interpreted as a
7463 regular expression. In org-mode files, this will create an `org-occur'
7464 sparse tree. In ordinary files, `occur' will be used to list matches.
7465 If the current buffer is in `dired-mode', grep will be used to search
7467 (let ((case-fold-search t)
7468 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7471 words re0 re1 re2 re3 re4 re5 re2a reall camel)
7472 (cond ((save-excursion
7473 (goto-char (point-min))
7476 (concat "<<" (regexp-quote s0) ">>") nil t)
7477 (setq pos (match-beginning 0))))
7478 ;; There is an exact target for this
7480 ((string-match "^/\\(.*\\)/$" s)
7481 ;; A regular expression
7483 ((eq major-mode 'org-mode)
7484 (org-occur (match-string 1 s)))
7485 ;;((eq major-mode 'dired-mode)
7486 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7487 (t (org-do-occur (match-string 1 s)))))
7488 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
7490 ;; A camel or a normal search string
7491 (when (equal (string-to-char s) ?*)
7492 ;; Anchor on headlines, post may include tags.
7493 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
7494 post "[ \t]*\\([ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
7496 (remove-text-properties
7498 '(face nil mouse-face nil keymap nil fontified nil) s)
7499 ;; Make a series of regular expressions to find a match
7502 (org-camel-to-words s)
7503 (org-split-string s "[ \n\r\t]+"))
7504 re0 (concat "<<" (regexp-quote s0) ">>")
7505 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
7506 re2a (concat "\\<" (mapconcat 'downcase words "[ \t\r\n]+") "\\>")
7507 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
7508 re1 (concat pre re2 post)
7509 re3 (concat pre re4 post)
7510 re5 (concat pre ".*" re4)
7511 re2 (concat pre re2)
7512 re2a (concat pre re2a)
7513 re4 (concat pre re4)
7514 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7515 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7519 ((eq type 'org-occur) (org-occur reall))
7520 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7521 (t (goto-char (point-min))
7522 (if (or (org-search-not-link re0 nil t)
7523 (org-search-not-link re1 nil t)
7524 (org-search-not-link re2 nil t)
7525 (org-search-not-link re2a nil t)
7526 (org-search-not-link re3 nil t)
7527 (org-search-not-link re4 nil t)
7528 (org-search-not-link re5 nil t)
7530 (goto-char (match-beginning 0))
7532 (error "No match")))))
7534 ;; Normal string-search
7535 (goto-char (point-min))
7536 (if (search-forward s nil t)
7537 (goto-char (match-beginning 0))
7538 (error "No match"))))
7539 (and (eq major-mode 'org-mode) (org-show-hierarchy-above))))
7541 (defun org-search-not-link (&rest args)
7542 "Execute `re-search-forward', but only accept matches that are not a link."
7544 (let ((pos (point)) p1)
7545 (while (apply 're-search-forward args)
7547 (if (not (save-match-data
7548 (and (re-search-backward "\\[\\[" nil t)
7549 (looking-at org-bracket-link-regexp)
7550 (<= (match-beginning 0) p1)
7551 (>= (match-end 0) p1))))
7552 (progn (goto-char (match-end 0))
7553 (throw 'exit (point)))
7554 (goto-char (match-end 0)))))))
7556 (defun org-do-occur (regexp &optional cleanup)
7557 "Call the Emacs command `occur'.
7558 If CLEANUP is non-nil, remove the printout of the regular expression
7559 in the *Occur* buffer. This is useful if the regex is long and not useful
7563 (let ((cwin (selected-window)) win beg end)
7564 (when (setq win (get-buffer-window "*Occur*"))
7565 (select-window win))
7566 (goto-char (point-min))
7567 (when (re-search-forward "match[a-z]+" nil t)
7568 (setq beg (match-end 0))
7569 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7570 (setq end (1- (match-beginning 0)))))
7571 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
7572 (goto-char (point-min))
7573 (select-window cwin))))
7575 (defvar org-mark-ring nil
7576 "Mark ring for positions before jumps in Org-mode.")
7577 (defvar org-mark-ring-last-goto nil
7578 "Last position in the mark ring used to go back.")
7579 ;; Fill and close the ring
7580 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7581 (loop for i from 1 to org-mark-ring-length do
7582 (push (make-marker) org-mark-ring))
7583 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7586 (defun org-mark-ring-push (&optional pos buffer)
7587 "Put the current position or POS into the mark ring and rotate it."
7589 (setq pos (or pos (point)))
7590 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7591 (move-marker (car org-mark-ring)
7593 (or buffer (current-buffer)))
7595 (substitute-command-keys
7596 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7598 (defun org-mark-ring-goto (&optional n)
7599 "Jump to the previous position in the mark ring.
7600 With prefix arg N, jump back that many stored positions. When
7601 called several times in succession, walk through the entire ring.
7602 Org-mode commands jumping to a different position in the current file,
7603 or to another Org-mode file, automatically push the old position
7607 (if (eq last-command this-command)
7608 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7609 (setq p org-mark-ring))
7610 (setq org-mark-ring-last-goto p)
7612 (switch-to-buffer (marker-buffer m))
7614 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
7616 (defun org-camel-to-words (s)
7617 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
7618 (let ((case-fold-search nil)
7620 (while (string-match "[a-z][A-Z]" s)
7621 (push (substring s 0 (1+ (match-beginning 0))) words)
7622 (setq s (substring s (1+ (match-beginning 0)))))
7623 (nreverse (cons s words))))
7625 (defun org-remove-angle-brackets (s)
7626 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7627 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7629 (defun org-add-angle-brackets (s)
7630 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7631 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7634 (defun org-follow-bbdb-link (name)
7635 "Follow a BBDB link to NAME."
7637 (let ((inhibit-redisplay t)
7638 (bbdb-electric-p nil))
7640 ;; Exact match on name
7641 (bbdb-name (concat "\\`" name "\\'") nil)
7642 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7643 ;; Exact match on name
7644 (bbdb-company (concat "\\`" name "\\'") nil)
7645 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7646 ;; Partial match on name
7647 (bbdb-name name nil)
7648 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7649 ;; Partial match on company
7650 (bbdb-company name nil)
7651 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7652 ;; General match including network address and notes
7654 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
7655 (delete-window (get-buffer-window "*BBDB*"))
7656 (error "No matching BBDB record")))))
7658 (defun org-follow-gnus-link (&optional group article)
7659 "Follow a Gnus link to GROUP and ARTICLE."
7661 (funcall (cdr (assq 'gnus org-link-frame-setup)))
7662 (if group (gnus-fetch-group group))
7664 (or (gnus-summary-goto-article article nil 'force)
7665 (if (fboundp 'gnus-summary-insert-cached-articles)
7667 (gnus-summary-insert-cached-articles)
7668 (gnus-summary-goto-article article nil 'force))
7669 (message "Message could not be found.")))))
7671 (defun org-follow-vm-link (&optional folder article readonly)
7672 "Follow a VM link to FOLDER and ARTICLE."
7674 (setq article (org-add-angle-brackets article))
7675 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
7676 ;; ange-ftp or efs or tramp access
7677 (let ((user (or (match-string 1 folder) (user-login-name)))
7678 (host (match-string 2 folder))
7679 (file (match-string 3 folder)))
7682 ;; use tramp to access the file
7683 (if (featurep 'xemacs)
7684 (setq folder (format "[%s@%s]%s" user host file))
7685 (setq folder (format "/%s@%s:%s" user host file))))
7687 ;; use ange-ftp or efs
7688 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
7689 (setq folder (format "/%s@%s:%s" user host file))))))
7691 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
7694 (vm-select-folder-buffer)
7696 (let ((case-fold-search t))
7697 (goto-char (point-min))
7698 (if (not (re-search-forward
7699 (concat "^" "message-id: *" (regexp-quote article))))
7700 (error "Could not find the specified message in this folder"))
7703 (vm-beginning-of-message)
7706 (defun org-follow-wl-link (folder article)
7707 "Follow a Wanderlust link to FOLDER and ARTICLE."
7708 (setq article (org-add-angle-brackets article))
7709 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
7710 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
7711 (wl-summary-redisplay))
7713 (defun org-follow-rmail-link (folder article)
7714 "Follow an RMAIL link to FOLDER and ARTICLE."
7715 (setq article (org-add-angle-brackets article))
7716 (let (message-number)
7718 (save-window-excursion
7719 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7720 (setq message-number
7723 (goto-char (point-max))
7724 (if (re-search-backward
7725 (concat "^Message-ID:\\s-+" (regexp-quote
7728 (rmail-what-message))))))
7731 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7732 (rmail-show-message message-number)
7734 (error "Message not found"))))
7736 ;; mh-e integration based on planner-mode
7737 (defun org-mhe-get-message-real-folder ()
7738 "Return the name of the current message real folder, so if you use
7739 sequences, it will now work."
7742 (if (equal major-mode 'mh-folder-mode)
7744 ;; Refer to the show buffer
7745 mh-show-folder-buffer))
7747 (if (boundp 'mh-index-folder)
7748 (min (length mh-index-folder) (length folder))))
7750 ;; a simple test on mh-index-data does not work, because
7751 ;; mh-index-data is always nil in a show buffer.
7752 (if (and (boundp 'mh-index-folder)
7753 (string= mh-index-folder (substring folder 0 end-index)))
7754 (if (equal major-mode 'mh-show-mode)
7755 (save-window-excursion
7756 (when (buffer-live-p (get-buffer folder))
7758 (pop-to-buffer folder)
7759 (org-mhe-get-message-folder-from-index)
7762 (org-mhe-get-message-folder-from-index)
7768 (defun org-mhe-get-message-folder-from-index ()
7769 "Returns the name of the message folder in a index folder buffer."
7771 (mh-index-previous-folder)
7772 (re-search-forward "^\\(+.*\\)$" nil t)
7773 (message (match-string 1))))
7775 (defun org-mhe-get-message-folder ()
7776 "Return the name of the current message folder. Be careful if you
7779 (if (equal major-mode 'mh-folder-mode)
7781 ;; Refer to the show buffer
7782 mh-show-folder-buffer)))
7784 (defun org-mhe-get-message-num ()
7785 "Return the number of the current message. Be careful if you
7788 (if (equal major-mode 'mh-folder-mode)
7789 (mh-get-msg-num nil)
7790 ;; Refer to the show buffer
7791 (mh-show-buffer-message-number))))
7793 (defun org-mhe-get-header (header)
7794 "Return a header of the message in folder mode. This will create a
7795 show buffer for the corresponding message. If you have a more clever
7797 (let* ((folder (org-mhe-get-message-folder))
7798 (num (org-mhe-get-message-num))
7799 (buffer (get-buffer-create (concat "show-" folder)))
7801 (with-current-buffer buffer
7802 (mh-display-msg num folder)
7803 (if (equal major-mode 'mh-folder-mode)
7805 (mh-show-header-display))
7807 (setq header-field (mh-get-header-field header))
7808 (if (equal major-mode 'mh-folder-mode)
7813 (defun org-follow-mhe-link (folder article)
7814 "Follow an MHE link to FOLDER and ARTICLE.
7815 If ARTICLE is nil FOLDER is shown. If the configuration variable
7816 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
7817 ARTICLE is searched in all folders. Indexed searches (swish++,
7818 namazu, and others supported by MH-E) will always search in all
7821 (require 'mh-search)
7825 (mh-visit-folder (mh-normalize-folder-name folder))
7826 (setq article (org-add-angle-brackets article))
7828 (if (equal mh-searcher 'pick)
7830 (mh-search folder (list "--message-id" article))
7831 (when (and org-mhe-search-all-folders
7832 (not (org-mhe-get-message-real-folder)))
7834 (mh-search "+" (list "--message-id" article))))
7835 (mh-search "+" article))
7836 (if (org-mhe-get-message-real-folder)
7839 (error "Message not found"))))
7841 (defun org-upgrade-old-links (&optional query-description)
7842 "Transfer old <...> style links to new [[...]] style links.
7843 With arg query-description, ask at each match for a description text to use
7845 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
7847 (goto-char (point-min))
7848 (let ((re (concat "\\([^[]\\)<\\("
7849 "\\(" (mapconcat 'identity org-link-types "\\|")
7851 "[^" org-non-link-chars "]+\\)>"))
7853 (while (re-search-forward re nil t)
7855 l1 (org-match-string-no-properties 2)
7856 l2 (save-match-data (org-link-escape l1)))
7857 (when query-description (setq l1 (read-string "Desc: " l1)))
7859 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
7860 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
7861 (message "%d matches have beed treated" cnt))))
7863 (defun org-open-file (path &optional in-emacs line search)
7864 "Open the file at PATH.
7865 First, this expands any special file name abbreviations. Then the
7866 configuration variable `org-file-apps' is checked if it contains an
7867 entry for this file type, and if yes, the corresponding command is launched.
7868 If no application is found, Emacs simply visits the file.
7869 With optional argument IN-EMACS, Emacs will visit the file.
7870 Optional LINE specifies a line to go to, optional SEARCH a string to
7871 search for. If LINE or SEARCH is given, the file will always be
7873 If the file does not exist, an error is thrown."
7874 (setq in-emacs (or in-emacs line search))
7875 (let* ((file (if (equal path "")
7877 (convert-standard-filename (org-expand-file-name path))))
7878 (dirp (file-directory-p file))
7879 (dfile (downcase file))
7880 (old-buffer (current-buffer))
7882 (old-mode major-mode)
7884 (if (and (not (file-exists-p file))
7885 (not org-open-non-existing-files))
7886 (error "No such file: %s" file))
7887 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7888 (setq ext (match-string 1 dfile))
7889 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7890 (setq ext (match-string 1 dfile))))
7891 (setq apps (append org-file-apps (org-default-apps)))
7894 (setq cmd (or (and dirp (cdr (assoc 'directory apps)))
7895 (cdr (assoc ext apps))
7896 (cdr (assoc t apps)))))
7897 (when (eq cmd 'mailcap)
7899 (mailcap-parse-mailcaps)
7900 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7901 (command (mailcap-mime-info mime-type)))
7902 (if (stringp command)
7904 (setq cmd 'emacs))))
7906 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7907 ; (setq cmd (format cmd (concat "\"" file "\"")))
7908 ;; FIXME: normalize use of quotes
7909 (if (string-match "['\"]%s['\"]" cmd)
7910 (setq cmd (replace-match "'%s'" t t cmd)))
7911 (setq cmd (format cmd file))
7912 (save-window-excursion
7913 (shell-command (concat cmd " &"))))
7916 (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
7917 (funcall (cdr (assq 'file org-link-frame-setup)) file))
7918 (if line (goto-line line)
7919 (if search (org-link-search search))))
7922 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7923 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
7924 (or (not (equal old-buffer (current-buffer)))
7925 (not (equal old-pos (point))))
7926 (org-mark-ring-push old-pos old-buffer))))
7928 (defun org-default-apps ()
7929 "Return the default applications for this operating system."
7931 ((eq system-type 'darwin)
7932 org-file-apps-defaults-macosx)
7933 ((eq system-type 'windows-nt)
7934 org-file-apps-defaults-windowsnt)
7935 (t org-file-apps-defaults-gnu)))
7937 (defun org-expand-file-name (path)
7938 "Replace special path abbreviations and expand the file name."
7939 (expand-file-name path))
7942 (defvar org-insert-link-history nil
7943 "Minibuffer history for links inserted with `org-insert-link'.")
7945 (defvar org-stored-links nil
7946 "Contains the links stored with `org-store-link'.")
7949 (defun org-store-link (arg)
7950 "\\<org-mode-map>Store an org-link to the current location.
7951 This link can later be inserted into an org-buffer with
7952 \\[org-insert-link].
7953 For some link types, a prefix arg is interpreted:
7954 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
7955 For file links, arg negates `org-context-in-file-links'."
7957 (let (link cpltxt desc txt (pos (point)))
7960 ((eq major-mode 'bbdb-mode)
7961 (setq cpltxt (concat
7963 (or (bbdb-record-name (bbdb-current-record))
7964 (bbdb-record-company (bbdb-current-record))))
7965 link (org-make-link cpltxt)))
7967 ((eq major-mode 'calendar-mode)
7968 (let ((cd (calendar-cursor-to-date)))
7971 (car org-time-stamp-formats)
7973 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7976 ((or (eq major-mode 'vm-summary-mode)
7977 (eq major-mode 'vm-presentation-mode))
7978 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
7979 (vm-follow-summary-cursor)
7981 (vm-select-folder-buffer)
7982 (let* ((message (car vm-message-pointer))
7983 (folder buffer-file-name)
7984 (subject (vm-su-subject message))
7985 (author (vm-su-full-name message))
7986 (message-id (vm-su-message-id message)))
7987 (setq message-id (org-remove-angle-brackets message-id))
7988 (setq folder (abbreviate-file-name folder))
7989 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
7991 (setq folder (replace-match "" t t folder)))
7992 (setq cpltxt (concat author " on: " subject))
7993 (setq link (org-make-link "vm:" folder "#" message-id)))))
7995 ((eq major-mode 'wl-summary-mode)
7996 (let* ((msgnum (wl-summary-message-number))
7997 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
7998 msgnum 'message-id))
7999 (wl-message-entity (elmo-msgdb-overview-get-entity
8000 msgnum (wl-summary-buffer-msgdb)))
8001 (author (wl-summary-line-from)) ; FIXME: correct?
8002 (subject "???")) ; FIXME:
8003 (setq message-id (org-remove-angle-brackets message-id))
8004 (setq cpltxt (concat author " on: " subject))
8005 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
8008 ((or (equal major-mode 'mh-folder-mode)
8009 (equal major-mode 'mh-show-mode))
8010 (let ((from-header (org-mhe-get-header "From:"))
8011 (to-header (org-mhe-get-header "To:"))
8012 (subject (org-mhe-get-header "Subject:")))
8013 (setq cpltxt (concat from-header " on: " subject))
8014 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
8015 (org-remove-angle-brackets
8016 (org-mhe-get-header "Message-Id:"))))))
8018 ((eq major-mode 'rmail-mode)
8021 (rmail-narrow-to-non-pruned-header)
8022 (let ((folder buffer-file-name)
8023 (message-id (mail-fetch-field "message-id"))
8024 (author (mail-fetch-field "from"))
8025 (subject (mail-fetch-field "subject")))
8026 (setq message-id (org-remove-angle-brackets message-id))
8027 (setq cpltxt (concat author " on: " subject))
8028 (setq link (org-make-link "rmail:" folder "#" message-id))))))
8030 ((eq major-mode 'gnus-group-mode)
8031 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
8032 (gnus-group-group-name)) ; version
8033 ((fboundp 'gnus-group-name)
8036 (setq cpltxt (concat
8037 (if (org-xor arg org-usenet-links-prefer-google)
8038 "http://groups.google.com/groups?group="
8041 link (org-make-link cpltxt))))
8043 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
8044 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
8045 (gnus-summary-beginning-of-article)
8046 (let* ((group (car gnus-article-current))
8047 (article (cdr gnus-article-current))
8048 (header (gnus-summary-article-header article))
8049 (author (mail-header-from header))
8050 (message-id (mail-header-id header))
8051 (date (mail-header-date header))
8052 (subject (gnus-summary-subject-string)))
8053 (setq cpltxt (concat author " on: " subject))
8054 (if (org-xor arg org-usenet-links-prefer-google)
8058 (format "http://groups.google.com/groups?as_umsgid=%s"
8059 (org-fixup-message-id-for-http message-id))))
8060 (setq link (org-make-link "gnus:" group
8061 "#" (number-to-string article))))))
8063 ((eq major-mode 'w3-mode)
8064 (setq cpltxt (url-view-url t)
8065 link (org-make-link cpltxt)))
8066 ((eq major-mode 'w3m-mode)
8067 (setq cpltxt w3m-current-url
8068 link (org-make-link cpltxt)))
8070 ((eq major-mode 'org-mode)
8071 ;; Just link to current headline
8072 (setq cpltxt (concat "file:"
8073 (abbreviate-file-name buffer-file-name)))
8074 ;; Add a context search string
8075 (when (org-xor org-context-in-file-links arg)
8076 ;; Check if we are on a target
8078 (skip-chars-forward "^>\n\r")
8079 (and (re-search-backward "<<" nil t)
8080 (looking-at "<<\\(.*?\\)>>")
8081 (<= (match-beginning 0) pos)
8082 (>= (match-end 0) pos)))
8083 (setq cpltxt (concat cpltxt "::" (match-string 1)))
8085 ((org-on-heading-p) nil)
8086 ((org-region-active-p)
8087 (buffer-substring (region-beginning) (region-end)))
8088 (t (buffer-substring (point-at-bol) (point-at-eol)))))
8091 (if org-file-link-context-use-camel-case
8092 (org-make-org-heading-camel txt)
8093 (org-make-org-heading-search-string txt)))
8095 (if (string-match "::\\'" cpltxt)
8096 (setq cpltxt (substring cpltxt 0 -2)))
8097 (setq link (org-make-link cpltxt)))
8100 ;; Just link to this file here.
8101 (setq cpltxt (concat "file:"
8102 (abbreviate-file-name buffer-file-name)))
8103 ;; Add a context string
8104 (when (org-xor org-context-in-file-links arg)
8105 (setq txt (if (org-region-active-p)
8106 (buffer-substring (region-beginning) (region-end))
8107 (buffer-substring (point-at-bol) (point-at-eol))))
8110 (if org-file-link-context-use-camel-case
8111 (org-make-org-heading-camel txt)
8112 (org-make-org-heading-search-string txt)))
8114 (setq link (org-make-link cpltxt)))
8117 (error "Cannot link to a buffer which is not visiting a file"))
8119 (t (setq link nil)))
8121 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8122 (setq link (or link cpltxt)
8123 desc (or desc cpltxt))
8124 (if (equal desc "NONE") (setq desc nil))
8126 (if (and (interactive-p) link)
8128 (setq org-stored-links
8129 (cons (list cpltxt link desc) org-stored-links))
8130 (message "Stored: %s" (or cpltxt link)))
8131 (org-make-link-string link desc))))
8133 (defun org-make-org-heading-search-string (&optional string heading)
8134 "Make search string for STRING or current headline."
8136 (let ((s (or string (org-get-heading))))
8137 (unless (and string (not heading))
8138 ;; We are using a headline, clean up garbage in there.
8139 (if (string-match org-todo-regexp s)
8140 (setq s (replace-match "" t t s)))
8141 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
8142 (setq s (replace-match "" t t s)))
8143 (setq s (org-trim s))
8144 (if (string-match (concat "^\\(" org-quote-string "\\|"
8145 org-comment-string "\\)") s)
8146 (setq s (replace-match "" t t s)))
8147 (while (string-match org-ts-regexp s)
8148 (setq s (replace-match "" t t s))))
8149 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
8150 (setq s (replace-match " " t t s)))
8151 (or string (setq s (concat "*" s))) ; Add * for headlines
8152 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8154 (defun org-make-org-heading-camel (&optional string heading)
8155 "Make a CamelCase string for STRING or the current headline."
8157 (let ((s (or string (org-get-heading))))
8158 (unless (and string (not heading))
8159 ;; We are using a headline, clean up garbage in there.
8160 (if (string-match org-todo-regexp s)
8161 (setq s (replace-match "" t t s)))
8162 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
8163 (setq s (replace-match "" t t s)))
8164 (setq s (org-trim s))
8165 (if (string-match (concat "^\\(" org-quote-string "\\|"
8166 org-comment-string "\\)") s)
8167 (setq s (replace-match "" t t s)))
8168 (while (string-match org-ts-regexp s)
8169 (setq s (replace-match "" t t s))))
8170 (while (string-match "[^a-zA-Z_ \t]+" s)
8171 (setq s (replace-match " " t t s)))
8172 (or string (setq s (concat "*" s))) ; Add * for headlines
8173 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
8175 (defun org-make-link (&rest strings)
8176 "Concatenate STRINGS, format resulting string with `org-link-format'."
8177 (format org-link-format (apply 'concat strings)))
8179 (defun org-make-link-string (link &optional description)
8180 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8181 (if (eq org-link-style 'plain)
8182 (if (equal description link)
8184 (concat description "\n" link))
8185 (when (stringp description)
8186 ;; Remove brackets from the description, they are fatal.
8187 (while (string-match "\\[\\|\\]" description)
8188 (setq description (replace-match "" t t description))))
8189 (when (equal (org-link-escape link) description)
8190 ;; No description needed, it is identical
8191 (setq description nil))
8192 (when (and (not description)
8193 (not (equal link (org-link-escape link))))
8194 (setq description link))
8195 (concat "[[" (org-link-escape link) "]"
8196 (if description (concat "[" description "]") "")
8199 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
8200 "Association list of escapes for some characters problematic in links.")
8202 (defun org-link-escape (text)
8203 "Escape charaters in TEXT that are problematic for links."
8205 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
8206 org-link-escape-chars "\\|")))
8207 (while (string-match re text)
8210 (cdr (assoc (match-string 0 text) org-link-escape-chars))
8214 (defun org-link-unescape (text)
8215 "Reverse the action of `org-link-escape'."
8217 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
8218 org-link-escape-chars "\\|")))
8219 (while (string-match re text)
8222 (car (rassoc (match-string 0 text) org-link-escape-chars))
8226 (defun org-xor (a b)
8230 (defun org-get-header (header)
8231 "Find a header field in the current buffer."
8233 (goto-char (point-min))
8234 (let ((case-fold-search t) s)
8237 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
8238 (setq s (match-string 1)))
8239 (while (string-match "\"" s)
8240 (setq s (replace-match "" t t s)))
8241 (if (string-match "[<(].*" s)
8242 (setq s (replace-match "" t t s))))
8243 ((eq header 'message-id)
8244 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
8245 (setq s (match-string 1))))
8246 ((eq header 'subject)
8247 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
8248 (setq s (match-string 1)))))
8249 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
8250 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
8254 (defun org-fixup-message-id-for-http (s)
8255 "Replace special characters in a message id, so it can be used in an http query."
8256 (while (string-match "<" s)
8257 (setq s (replace-match "%3C" t t s)))
8258 (while (string-match ">" s)
8259 (setq s (replace-match "%3E" t t s)))
8260 (while (string-match "@" s)
8261 (setq s (replace-match "%40" t t s)))
8264 (defun org-insert-link (&optional complete-file)
8265 "Insert a link. At the prompt, enter the link.
8267 Completion can be used to select a link previously stored with
8268 `org-store-link'. When the empty string is entered (i.e. if you just
8269 press RET at the prompt), the link defaults to the most recently
8270 stored link. As SPC triggers completion in the minibuffer, you need to
8271 use M-SPC or C-q SPC to force the insertion of a space character.
8273 You will also be prompted for a description, and if one is given, it will
8274 be displayed in the buffer instead of the link.
8276 If there is already a link at point, this command will allow you to edit link
8277 and description parts.
8279 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
8280 selected using completion. The path to the file will be relative to
8281 the current directory if the file is in the current directory or a
8282 subdirectory. Otherwise, the link will be the absolute path as
8283 completed in the minibuffer (i.e. normally ~/path/to/file).
8285 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
8286 is in the current directory or below."
8288 (let (link desc entry remove file (pos (point)))
8291 (skip-chars-forward "^]\n\r")
8292 (and (re-search-backward "\\[\\[" nil t)
8293 (looking-at org-bracket-link-regexp)
8294 (<= (match-beginning 0) pos)
8295 (>= (match-end 0) pos)))
8296 ;; We do have a link at point, and we are going to edit it.
8297 (setq remove (list (match-beginning 0) (match-end 0)))
8298 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8299 (setq link (read-string "Link: "
8301 (org-match-string-no-properties 1)))))
8303 ;; Completing read for file names.
8304 (setq file (read-file-name "File: "))
8305 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8306 (pwd1 (file-name-as-directory (abbreviate-file-name
8307 (expand-file-name ".")))))
8309 ((equal complete-file '(16))
8310 (setq link (org-make-link
8312 (abbreviate-file-name (expand-file-name file)))))
8313 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8314 (setq link (org-make-link "file:" (match-string 1 file))))
8315 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8316 (expand-file-name file))
8317 (setq link (org-make-link
8318 "file:" (match-string 1 (expand-file-name file)))))
8319 (t (setq link (org-make-link "file:" file))))))
8321 ;; Read link, with completion for stored links.
8322 (setq link (org-completing-read
8323 "Link: " org-stored-links nil nil nil
8324 org-insert-link-history
8325 (or (car (car org-stored-links)))))
8326 (setq entry (assoc link org-stored-links))
8327 (if (not org-keep-stored-link-after-insertion)
8328 (setq org-stored-links (delq (assoc link org-stored-links)
8330 (setq link (if entry (nth 1 entry) link)
8331 desc (or desc (nth 2 entry)))))
8333 (if (string-match org-plain-link-re link)
8334 ;; URL-like link, normalize the use of angular brackets.
8335 (setq link (org-make-link (org-remove-angle-brackets link))))
8337 ;; Check if we are linking to the current file. If yes, simplify the link.
8338 (when (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link)
8339 (let* ((path (match-string 1 link))
8340 (case-fold-search nil)
8341 (search (match-string 2 link)))
8342 (when (save-match-data
8343 (equal (file-truename buffer-file-name)
8344 (file-truename path)))
8345 ;; We are linking to this same file, with a search option
8346 (setq link search))))
8347 (setq desc (read-string "Description: " desc))
8348 (unless (string-match "\\S-" desc) (setq desc nil))
8349 (if remove (apply 'delete-region remove))
8350 (insert (org-make-link-string link desc))))
8352 (defun org-completing-read (&rest args)
8353 (let ((minibuffer-local-completion-map
8354 (copy-keymap minibuffer-local-completion-map)))
8355 (define-key minibuffer-local-completion-map " " 'self-insert-command)
8356 (apply 'completing-read args)))
8358 ;;; Hooks for remember.el
8360 (defvar org-finish-function nil)
8363 (defun org-remember-annotation ()
8364 "Return a link to the current location as an annotation for remember.el.
8365 If you are using Org-mode files as target for data storage with
8366 remember.el, then the annotations should include a link compatible with the
8367 conventions in Org-mode. This function returns such a link."
8368 (org-store-link nil))
8370 (defconst org-remember-help
8371 "Select a destination location for the note.
8372 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
8373 RET at beg-of-buf -> Append to file as level 2 headline
8374 RET on headline -> Store as sublevel entry to current headline
8375 <left>/<right> -> before/after current headline, same headings level")
8378 (defun org-remember-apply-template ()
8379 "Initialize *remember* buffer with template, invode `org-mode'.
8380 This function should be placed into `remember-mode-hook' and in fact requires
8381 to be run from that hook to fucntion properly."
8382 (when org-remember-templates
8383 (let* ((entry (if (= (length org-remember-templates) 1)
8384 (cdar org-remember-templates)
8385 (message "Select template: %s"
8387 (lambda (x) (char-to-string (car x)))
8388 org-remember-templates " "))
8389 (cdr (assoc (read-char-exclusive) org-remember-templates))))
8390 (tpl (if (consp (cdr entry)) (cadr entry) (cdr entry)))
8391 (file (if (consp (cdr entry)) (nth 2 entry)))
8392 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
8393 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
8394 (v-u (concat "[" (substring v-t 1 -1) "]"))
8395 (v-U (concat "[" (substring v-T 1 -1) "]"))
8396 (v-a annotation) ; defined in `remember-mode'
8397 (v-i initial) ; defined in `remember-mode'
8398 (v-n user-full-name)
8400 (unless tpl (setq tpl "") (message "No template") (ding))
8401 (insert tpl) (goto-char (point-min))
8402 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
8403 (when (and initial (equal (match-string 0) "%i"))
8405 (let* ((lead (buffer-substring
8406 (point-at-bol) (match-beginning 0))))
8407 (setq v-i (mapconcat 'identity
8408 (org-split-string initial "\n")
8409 (concat "\n" lead))))))
8411 (or (eval (intern (concat "v-" (match-string 1)))) "")
8413 (let ((org-startup-folded nil)
8414 (org-startup-with-deadline-check nil))
8416 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
8417 (set (make-local-variable 'org-default-notes-file) file))
8418 (goto-char (point-min))
8419 (if (re-search-forward "%\\?" nil t) (replace-match ""))
8420 (set (make-local-variable 'org-finish-function) 'remember-buffer))))
8423 (defun org-remember-handler ()
8424 "Store stuff from remember.el into an org file.
8425 First prompts for an org file. If the user just presses return, the value
8426 of `org-default-notes-file' is used.
8427 Then the command offers the headings tree of the selected file in order to
8428 file the text at a specific location.
8429 You can either immediately press RET to get the note appended to the
8430 file, or you can use vertical cursor motion and visibility cycling (TAB) to
8431 find a better place. Then press RET or <left> or <right> in insert the note.
8433 Key Cursor position Note gets inserted
8434 -----------------------------------------------------------------------------
8435 RET buffer-start as level 2 heading at end of file
8436 RET on headline as sublevel of the heading at cursor
8437 RET no heading at cursor position, level taken from context.
8438 Or use prefix arg to specify level manually.
8439 <left> on headline as same level, before current heading
8440 <right> on headline as same level, after current heading
8442 So the fastest way to store the note is to press RET RET to append it to
8443 the default file. This way your current train of thought is not
8444 interrupted, in accordance with the principles of remember.el. But with
8445 little extra effort, you can push it directly to the correct location.
8447 Before being stored away, the function ensures that the text has a
8448 headline, i.e. a first line that starts with a \"*\". If not, a headline
8449 is constructed from the current date and some additional data.
8451 If the variable `org-adapt-indentation' is non-nil, the entire text is
8452 also indented so that it starts in the same column as the headline
8453 \(i.e. after the stars).
8455 See also the variable `org-reverse-note-order'."
8457 (let* ((txt (buffer-substring (point-min) (point-max)))
8458 (fastp current-prefix-arg)
8459 (file (if fastp org-default-notes-file (org-get-org-file)))
8460 (visiting (find-buffer-visiting file))
8461 (org-startup-with-deadline-check nil)
8462 (org-startup-folded nil)
8463 (org-startup-align-all-tables nil)
8464 spos level indent reversed)
8465 ;; Modify text so that it becomes a nice subtree which can be inserted
8466 ;; into an org tree.
8467 (let* ((lines (split-string txt "\n"))
8469 ;; remove empty lines at the beginning
8470 (while (and lines (string-match "^[ \t]*\n" (car lines)))
8471 (setq lines (cdr lines)))
8472 (setq first (car lines) lines (cdr lines))
8473 (if (string-match "^\\*+" first)
8474 ;; Is already a headline
8476 ;; We need to add a headline: Use time and first buffer line
8477 (setq lines (cons first lines)
8478 first (concat "* " (current-time-string)
8479 " (" (remember-buffer-desc) ")")
8481 (if (and org-adapt-indentation indent)
8482 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
8483 (setq txt (concat first "\n"
8484 (mapconcat 'identity lines "\n"))))
8487 (find-file-noselect file))
8488 (with-current-buffer (get-file-buffer file)
8489 (setq reversed (org-notes-order-reversed-p))
8493 ;; Ask the User for a location
8494 (setq spos (if fastp 1 (org-get-location
8496 org-remember-help)))
8497 (if (not spos) (throw 'quit nil)) ; return nil to show we did
8498 ; not handle this note
8501 ;; Put it at the start or end, as level 2
8504 (goto-char (if reversed (point-min) (point-max)))
8505 (if (not (bolp)) (newline))
8506 (org-paste-subtree 2 txt)))
8507 ((and (org-on-heading-p nil) (not current-prefix-arg))
8508 ;; Put it below this entry, at the beg/end of the subtree
8509 (org-back-to-heading)
8510 (setq level (funcall outline-level))
8512 (outline-end-of-heading)
8513 (outline-end-of-subtree))
8514 (if (not (bolp)) (newline))
8515 (beginning-of-line 1)
8516 (org-paste-subtree (1+ level) txt))
8518 ;; Put it right there, with automatic level determined by
8519 ;; org-paste-subtree or from prefix arg
8520 (org-paste-subtree current-prefix-arg txt)))
8521 (when remember-save-after-remembering
8523 (if (not visiting) (kill-buffer (current-buffer)))))))))
8524 t) ;; return t to indicate that we took care of this note.
8526 (defun org-get-org-file ()
8527 "Read a filename, with default directory `org-directory'."
8528 (let ((default (or org-default-notes-file remember-data-file)))
8529 (read-file-name (format "File name [%s]: " default)
8530 (file-name-as-directory org-directory)
8533 (defun org-notes-order-reversed-p ()
8534 "Check if the current file should receive notes in reversed order."
8536 ((not org-reverse-note-order) nil)
8537 ((eq t org-reverse-note-order) t)
8538 ((not (listp org-reverse-note-order)) nil)
8540 (let ((all org-reverse-note-order)
8542 (while (setq entry (pop all))
8543 (if (string-match (car entry) buffer-file-name)
8544 (throw 'exit (cdr entry))))
8549 ;; Watch out: Here we are talking about two different kind of tables.
8550 ;; Most of the code is for the tables created with the Org-mode table editor.
8551 ;; Sometimes, we talk about tables created and edited with the table.el
8552 ;; Emacs package. We call the former org-type tables, and the latter
8553 ;; table.el-type tables.
8556 (defun org-before-change-function (beg end)
8557 "Every change indicates that a table might need an update."
8558 (setq org-table-may-need-update t))
8560 (defconst org-table-line-regexp "^[ \t]*|"
8561 "Detects an org-type table line.")
8562 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8563 "Detects an org-type table line.")
8564 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8565 "Detects a table line marked for automatic recalculation.")
8566 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8567 "Detects a table line marked for automatic recalculation.")
8568 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8569 "Detects a table line marked for automatic recalculation.")
8570 (defconst org-table-hline-regexp "^[ \t]*|-"
8571 "Detects an org-type table hline.")
8572 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8573 "Detects a table-type table hline.")
8574 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8575 "Detects an org-type or table-type table.")
8576 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8577 "Searching from within a table (any type) this finds the first line
8578 outside the table.")
8579 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8580 "Searching from within a table (any type) this finds the first line
8581 outside the table.")
8583 (defun org-table-create-with-table.el ()
8584 "Use the table.el package to insert a new table.
8585 If there is already a table at point, convert between Org-mode tables
8586 and table.el tables."
8590 ((org-at-table.el-p)
8591 (if (y-or-n-p "Convert table to Org-mode table? ")
8592 (org-table-convert)))
8594 (if (y-or-n-p "Convert table to table.el table? ")
8595 (org-table-convert)))
8596 (t (call-interactively 'table-insert))))
8598 (defun org-table-create-or-convert-from-region (arg)
8599 "Convert region to table, or create an empty table.
8600 If there is an active region, convert it to a table. If there is no such
8601 region, create an empty table."
8603 (if (org-region-active-p)
8604 (org-table-convert-region (region-beginning) (region-end) arg)
8605 (org-table-create arg)))
8607 (defun org-table-create (&optional size)
8608 "Query for a size and insert a table skeleton.
8609 SIZE is a string Columns x Rows like for example \"3x2\"."
8612 (setq size (read-string
8613 (concat "Table size Columns x Rows [e.g. "
8614 org-table-default-size "]: ")
8615 "" nil org-table-default-size)))
8617 (let* ((pos (point))
8618 (indent (make-string (current-column) ?\ ))
8619 (split (org-split-string size " *x *"))
8620 (rows (string-to-number (nth 1 split)))
8621 (columns (string-to-number (car split)))
8622 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8624 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8625 (point-at-bol) (point)))
8626 (beginning-of-line 1)
8628 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8629 (dotimes (i rows) (insert line))
8632 ;; Insert a hline after the first row.
8639 (defun org-table-convert-region (beg0 end0 &optional nspace)
8640 "Convert region to a table.
8641 The region goes from BEG0 to END0, but these borders will be moved
8642 slightly, to make sure a beginning of line in the first line is included.
8643 When NSPACE is non-nil, it indicates the minimum number of spaces that
8644 separate columns (default: just one space)."
8646 (let* ((beg (min beg0 end0))
8647 (end (max beg0 end0))
8651 (beginning-of-line 1)
8652 (setq beg (move-marker (make-marker) (point)))
8654 (if (bolp) (backward-char 1) (end-of-line 1))
8655 (setq end (move-marker (make-marker) (point)))
8656 ;; Lets see if this is tab-separated material. If every nonempty line
8657 ;; contains a tab, we will assume that it is tab-separated material
8661 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
8662 (if nspace (setq tabsep nil))
8665 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
8666 (max 1 (prefix-numeric-value nspace)))))
8668 (while (re-search-forward re end t)
8669 (replace-match "|" t t))
8674 (defun org-table-import (file arg)
8675 "Import FILE as a table.
8676 The file is assumed to be tab-separated. Such files can be produced by most
8677 spreadsheet and database applications. If no tabs (at least one per line)
8678 are found, lines will be split on whitespace into fields."
8679 (interactive "f\nP")
8680 (or (bolp) (newline))
8683 (insert-file-contents file)
8684 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8686 (defun org-table-export ()
8687 "Export table as a tab-separated file.
8688 Such a file can be imported into a spreadsheet program like Excel."
8690 (let* ((beg (org-table-begin))
8691 (end (org-table-end))
8692 (table (buffer-substring beg end))
8693 (file (read-file-name "Export table to: "))
8695 (unless (or (not (file-exists-p file))
8696 (y-or-n-p (format "Overwrite file %s? " file)))
8698 (with-current-buffer (find-file-noselect file)
8699 (setq buf (current-buffer))
8703 (goto-char (point-min))
8704 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8705 (replace-match "" t t)
8707 (goto-char (point-min))
8708 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8709 (replace-match "" t t)
8710 (goto-char (min (1+ (point)) (point-max))))
8711 (goto-char (point-min))
8712 (while (re-search-forward "^-[-+]*$" nil t)
8714 (if (looking-at "\n")
8716 (goto-char (point-min))
8717 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8718 (replace-match "\t" t t))
8722 (defvar org-table-aligned-begin-marker (make-marker)
8723 "Marker at the beginning of the table last aligned.
8724 Used to check if cursor still is in that table, to minimize realignment.")
8725 (defvar org-table-aligned-end-marker (make-marker)
8726 "Marker at the end of the table last aligned.
8727 Used to check if cursor still is in that table, to minimize realignment.")
8728 (defvar org-table-last-alignment nil
8729 "List of flags for flushright alignment, from the last re-alignment.
8730 This is being used to correctly align a single field after TAB or RET.")
8731 (defvar org-table-last-column-widths nil
8732 "List of max width of fields in each column.
8733 This is being used to correctly align a single field after TAB or RET.")
8735 (defvar org-last-recalc-line nil)
8736 (defconst org-narrow-column-arrow "=>"
8737 "Used as display property in narrowed table columns.")
8739 (defun org-table-align ()
8740 "Align the table at point by aligning all vertical bars."
8744 (beg (org-table-begin))
8745 (end (org-table-end))
8746 ;; Current cursor position
8747 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8748 (colpos (org-table-current-column))
8749 (winstart (window-start))
8750 text lines (new "") lengths l typenums ty fields maxfields i
8752 (indent "") cnt frac
8758 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8760 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8761 emptystrings xx links narrow fmax fmin f1 len c e)
8763 (remove-text-properties beg end '(org-cwidth t display t))
8764 ;; Check if we have links
8766 (setq links (re-search-forward org-bracket-link-regexp end t))
8767 ;; Make sure the link properties are right FIXME: Can this be optimized????
8768 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8769 ;; Check if we are narrowing any columns
8771 (setq narrow (and org-format-transports-properties-p
8772 (re-search-forward "<[0-9]+>" end t)))
8774 (setq lines (org-split-string
8775 (buffer-substring beg end) "\n"))
8776 ;; Store the indentation of the first line
8777 (if (string-match "^ *" (car lines))
8778 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8779 ;; Mark the hlines by setting the corresponding element to nil
8780 ;; At the same time, we remove trailing space.
8781 (setq lines (mapcar (lambda (l)
8782 (if (string-match "^ *|-" l)
8784 (if (string-match "[ \t]+$" l)
8785 (substring l 0 (match-beginning 0))
8788 ;; Get the data fields by splitting the lines.
8789 (setq fields (mapcar
8791 (org-split-string l " *| *"))
8792 (delq nil (copy-sequence lines))))
8793 ;; How many fields in the longest line?
8795 (setq maxfields (apply 'max (mapcar 'length fields)))
8797 (kill-region beg end)
8798 (org-table-create org-table-default-size)
8799 (error "Empty table - created default table")))
8800 ;; A list of empty string to fill any short rows on output
8801 (setq emptystrings (make-list maxfields ""))
8802 ;; Check for special formatting.
8804 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8805 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8806 ;; Check if there is an explicit width specified
8807 (when (and org-table-limit-column-width narrow)
8808 (setq c column fmax nil)
8811 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8812 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8813 ;; Find fields that are wider than fmax, and shorten them
8815 (loop for xx in column do
8816 (when (and (stringp xx)
8817 (> (org-string-width xx) fmax))
8818 (org-add-props xx nil
8820 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8821 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8823 (error "Cannot narrow field starting with wide link \"%s\""
8824 (match-string 0 xx)))
8825 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8826 (add-text-properties (- f1 2) f1
8827 (list 'display org-narrow-column-arrow)
8829 ;; Get the maximum width for each column
8830 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8831 ;; Get the fraction of numbers, to decide about alignment of the column
8832 (setq cnt 0 frac 0.0)
8833 (loop for x in column do
8836 (setq frac ( / (+ (* frac cnt)
8837 (if (string-match org-table-number-regexp x) 1 0))
8838 (setq cnt (1+ cnt))))))
8839 (push (>= frac org-table-number-fraction) typenums))
8840 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8842 ;; Store the alignment of this table, for later editing of single fields
8843 (setq org-table-last-alignment typenums
8844 org-table-last-column-widths lengths)
8846 ;; With invisible characters, `format' does not get the field width right
8847 ;; So we need to make these fields wide by hand.
8849 (loop for i from 0 upto (1- maxfields) do
8850 (setq len (nth i lengths))
8851 (loop for j from 0 upto (1- (length fields)) do
8852 (setq c (nthcdr i (car (nthcdr j fields))))
8853 (if (and (stringp (car c))
8854 (string-match org-bracket-link-regexp (car c))
8855 (< (org-string-width (car c)) len))
8856 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8858 ;; Compute the formats needed for output of the table
8859 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8860 (while (setq l (pop lengths))
8861 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8862 (setq rfmt (concat rfmt (format rfmt1 ty l))
8863 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8864 (setq rfmt (concat rfmt "\n")
8865 hfmt (concat (substring hfmt 0 -1) "|\n"))
8867 (setq new (mapconcat
8869 (if l (apply 'format rfmt
8870 (append (pop fields) emptystrings))
8873 ;; Replace the old one
8874 (delete-region beg end)
8875 (move-marker end nil)
8876 (move-marker org-table-aligned-begin-marker (point))
8878 (move-marker org-table-aligned-end-marker (point))
8879 (when (and orgtbl-mode (not (eq major-mode 'org-mode)))
8880 (goto-char org-table-aligned-begin-marker)
8881 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8882 ;; Try to move to the old location (approximately)
8884 (set-window-start (selected-window) winstart 'noforce)
8885 (org-table-goto-column colpos)
8886 (setq org-table-may-need-update nil)
8889 (defun org-string-width (s)
8890 "Compute width of string, ignoring invisible characters.
8891 This ignores character with invisibility property `org-link', and also
8892 characters with property `org-cwidth', because these will become invisible
8893 upon the next fontification round."
8895 (when (or (eq t buffer-invisibility-spec)
8896 (assq 'org-link buffer-invisibility-spec))
8897 (while (setq b (text-property-any 0 (length s)
8898 'invisible 'org-link s))
8899 (setq s (concat (substring s 0 b)
8900 (substring s (or (next-single-property-change
8901 b 'invisible s) (length s)))))))
8902 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8903 (setq s (concat (substring s 0 b)
8904 (substring s (or (next-single-property-change
8905 b 'org-cwidth s) (length s))))))
8908 (defun org-table-begin (&optional table-type)
8909 "Find the beginning of the table and return its position.
8910 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8912 (if (not (re-search-backward
8913 (if table-type org-table-any-border-regexp
8914 org-table-border-regexp)
8916 (error "Can't find beginning of table")
8917 (goto-char (match-beginning 0))
8918 (beginning-of-line 2)
8921 (defun org-table-end (&optional table-type)
8922 "Find the end of the table and return its position.
8923 With argument TABLE-TYPE, go to the end of a table.el-type table."
8925 (if (not (re-search-forward
8926 (if table-type org-table-any-border-regexp
8927 org-table-border-regexp)
8929 (goto-char (point-max))
8930 (goto-char (match-beginning 0)))
8933 (defun org-table-justify-field-maybe (&optional new)
8934 "Justify the current field, text to left, number to right.
8935 Optional argument NEW may specify text to replace the current field content."
8937 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8938 ((org-at-table-hline-p))
8940 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8942 (< (point) org-table-aligned-begin-marker)
8943 (>= (point) org-table-aligned-end-marker)))
8944 ;; This is not the same table, force a full re-align
8945 (setq org-table-may-need-update t))
8946 (t ;; realign the current field, based on previous full realign
8947 (let* ((pos (point)) s
8948 (col (org-table-current-column))
8949 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8952 (skip-chars-backward "^|\n")
8953 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8955 (setq s (match-string 1)
8957 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8958 e (not (= (match-beginning 2) (match-end 2))))
8959 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8960 l (if e "|" (setq org-table-may-need-update t) ""))
8963 (if (<= (length new) l)
8964 (setq n (format f new t t)) ;; FIXME: why t t?????
8965 (setq n (concat new "|") org-table-may-need-update t)))
8967 (let (org-table-may-need-update)
8968 (replace-match n))))
8969 (setq org-table-may-need-update t))
8970 (goto-char pos))))))
8972 (defun org-table-next-field ()
8973 "Go to the next field in the current table, creating new lines as needed.
8974 Before doing so, re-align the table if necessary."
8976 (org-table-maybe-eval-formula)
8977 (org-table-maybe-recalculate-line)
8978 (if (and org-table-automatic-realign
8979 org-table-may-need-update)
8981 (let ((end (org-table-end)))
8982 (if (org-at-table-hline-p)
8986 (re-search-forward "|" end)
8987 (if (looking-at "[ \t]*$")
8988 (re-search-forward "|" end))
8989 (if (and (looking-at "-")
8990 org-table-tab-jumps-over-hlines
8991 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8992 (goto-char (match-beginning 1)))
8993 (if (looking-at "-")
8995 (beginning-of-line 0)
8996 (org-table-insert-row 'below))
8997 (if (looking-at " ") (forward-char 1))))
8999 (org-table-insert-row 'below)))))
9001 (defun org-table-previous-field ()
9002 "Go to the previous field in the table.
9003 Before doing so, re-align the table if necessary."
9005 (org-table-justify-field-maybe)
9006 (org-table-maybe-recalculate-line)
9007 (if (and org-table-automatic-realign
9008 org-table-may-need-update)
9010 (if (org-at-table-hline-p)
9012 (re-search-backward "|" (org-table-begin))
9013 (re-search-backward "|" (org-table-begin))
9014 (while (looking-at "|\\(-\\|[ \t]*$\\)")
9015 (re-search-backward "|" (org-table-begin)))
9016 (if (looking-at "| ?")
9017 (goto-char (match-end 0))))
9019 (defun org-table-next-row ()
9020 "Go to the next row (same column) in the current table.
9021 Before doing so, re-align the table if necessary."
9023 (org-table-maybe-eval-formula)
9024 (org-table-maybe-recalculate-line)
9025 (if (or (looking-at "[ \t]*$")
9026 (save-excursion (skip-chars-backward " \t") (bolp)))
9028 (if (and org-table-automatic-realign
9029 org-table-may-need-update)
9031 (let ((col (org-table-current-column)))
9032 (beginning-of-line 2)
9033 (if (or (not (org-at-table-p))
9034 (org-at-table-hline-p))
9036 (beginning-of-line 0)
9037 (org-table-insert-row 'below)))
9038 (org-table-goto-column col)
9039 (skip-chars-backward "^|\n\r")
9040 (if (looking-at " ") (forward-char 1)))))
9042 (defun org-table-copy-down (n)
9043 "Copy a field down in the current column.
9044 If the field at the cursor is empty, copy into it the content of the nearest
9045 non-empty field above. With argument N, use the Nth non-empty field.
9046 If the current field is not empty, it is copied down to the next row, and
9047 the cursor is moved with it. Therefore, repeating this command causes the
9048 column to be filled row-by-row.
9049 If the variable `org-table-copy-increment' is non-nil and the field is an
9050 integer, it will be incremented while copying."
9052 (let* ((colpos (org-table-current-column))
9053 (field (org-table-get-field))
9054 (non-empty (string-match "[^ \t]" field))
9055 (beg (org-table-begin))
9057 (org-table-check-inside-data-field)
9060 (setq txt (org-trim field))
9061 (org-table-next-row)
9062 (org-table-blank-field))
9066 (while (progn (beginning-of-line 1)
9067 (re-search-backward org-table-dataline-regexp
9069 (org-table-goto-column colpos t)
9070 (if (and (looking-at
9071 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
9072 (= (setq n (1- n)) 0))
9073 (throw 'exit (match-string 1))))))))
9076 (if (and org-table-copy-increment
9077 (string-match "^[0-9]+$" txt))
9078 (setq txt (format "%d" (+ (string-to-number txt) 1))))
9080 (org-table-maybe-recalculate-line)
9082 (error "No non-empty field found"))))
9084 (defun org-table-check-inside-data-field ()
9085 "Is point inside a table data field?
9086 I.e. not on a hline or before the first or after the last column?
9087 This actually throws an error, so it aborts the current command."
9088 (if (or (not (org-at-table-p))
9089 (= (org-table-current-column) 0)
9090 (org-at-table-hline-p)
9091 (looking-at "[ \t]*$"))
9092 (error "Not in table data field")))
9094 (defvar org-table-clip nil
9095 "Clipboard for table regions.")
9097 (defun org-table-blank-field ()
9098 "Blank the current table field or active region."
9100 (org-table-check-inside-data-field)
9101 (if (and (interactive-p) (org-region-active-p))
9102 (let (org-table-clip)
9103 (org-table-cut-region (region-beginning) (region-end)))
9104 (skip-chars-backward "^|")
9106 (if (looking-at "|[^|\n]+")
9107 (let* ((pos (match-beginning 0))
9108 (match (match-string 0))
9109 (len (org-string-width match)))
9110 (replace-match (concat "|" (make-string (1- len) ?\ )))
9111 (goto-char (+ 2 pos))
9112 (substring match 1)))))
9114 (defun org-table-get-field (&optional n replace)
9115 "Return the value of the field in column N of current row.
9116 N defaults to current field.
9117 If REPLACE is a string, replace field with this value. The return value
9118 is always the old value."
9119 (and n (org-table-goto-column n))
9120 (skip-chars-backward "^|\n")
9122 (if (looking-at "|[^|\r\n]*")
9123 (let* ((pos (match-beginning 0))
9124 (val (buffer-substring (1+ pos) (match-end 0))))
9126 (replace-match (concat "|" replace)))
9127 (goto-char (min (point-at-eol) (+ 2 pos)))
9129 (forward-char 1) ""))
9131 (defun org-table-current-column ()
9132 "Find out which column we are in.
9133 When called interactively, column is also displayed in echo area."
9135 (if (interactive-p) (org-table-check-inside-data-field))
9137 (let ((cnt 0) (pos (point)))
9138 (beginning-of-line 1)
9139 (while (search-forward "|" pos t)
9140 (setq cnt (1+ cnt)))
9141 (if (interactive-p) (message "This is table column %d" cnt))
9144 (defun org-table-goto-column (n &optional on-delim force)
9145 "Move the cursor to the Nth column in the current table line.
9146 With optional argument ON-DELIM, stop with point before the left delimiter
9148 If there are less than N fields, just go to after the last delimiter.
9149 However, when FORCE is non-nil, create new columns if necessary."
9151 (let ((pos (point-at-eol)))
9152 (beginning-of-line 1)
9154 (while (and (> (setq n (1- n)) -1)
9155 (or (search-forward "|" pos t)
9157 (progn (end-of-line 1)
9158 (skip-chars-backward "^|")
9160 ; (backward-char 2) t)))))
9161 (when (and force (not (looking-at ".*|")))
9162 (save-excursion (end-of-line 1) (insert " | ")))
9165 (if (looking-at " ") (forward-char 1))))))
9167 (defun org-at-table-p (&optional table-type)
9168 "Return t if the cursor is inside an org-type table.
9169 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9170 (if org-enable-table-editor
9172 (beginning-of-line 1)
9173 (looking-at (if table-type org-table-any-line-regexp
9174 org-table-line-regexp)))
9177 (defun org-at-table.el-p ()
9178 "Return t if and only if we are at a table.el table."
9179 (and (org-at-table-p 'any)
9181 (goto-char (org-table-begin 'any))
9182 (looking-at org-table1-hline-regexp))))
9184 (defun org-table-recognize-table.el ()
9185 "If there is a table.el table nearby, recognize it and move into it."
9186 (if org-table-tab-recognizes-table.el
9187 (if (org-at-table.el-p)
9189 (beginning-of-line 1)
9190 (if (looking-at org-table-dataline-regexp)
9192 (if (looking-at org-table1-hline-regexp)
9194 (beginning-of-line 2)
9195 (if (looking-at org-table-any-border-regexp)
9196 (beginning-of-line -1)))))
9197 (if (re-search-forward "|" (org-table-end t) t)
9200 (if (table--at-cell-p (point))
9202 (message "recognizing table.el table...")
9203 (table-recognize-table)
9204 (message "recognizing table.el table...done")))
9205 (error "This should not happen..."))
9210 (defun org-at-table-hline-p ()
9211 "Return t if the cursor is inside a hline in a table."
9212 (if org-enable-table-editor
9214 (beginning-of-line 1)
9215 (looking-at org-table-hline-regexp))
9218 (defun org-table-insert-column ()
9219 "Insert a new column into the table."
9221 (if (not (org-at-table-p))
9222 (error "Not at a table"))
9223 (org-table-find-dataline)
9224 (let* ((col (max 1 (org-table-current-column)))
9225 (beg (org-table-begin))
9226 (end (org-table-end))
9227 ;; Current cursor position
9228 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9231 (while (< (point) end)
9232 (if (org-at-table-hline-p)
9234 (org-table-goto-column col t)
9236 (beginning-of-line 2))
9237 (move-marker end nil)
9239 (org-table-goto-column colpos)
9241 (org-table-modify-formulas 'insert col)))
9243 (defun org-table-find-dataline ()
9244 "Find a dataline in the current table, which is needed for column commands."
9245 (if (and (org-at-table-p)
9246 (not (org-at-table-hline-p)))
9248 (let ((col (current-column))
9249 (end (org-table-end)))
9250 (move-to-column col)
9251 (while (and (< (point) end)
9252 (or (not (= (current-column) col))
9253 (org-at-table-hline-p)))
9254 (beginning-of-line 2)
9255 (move-to-column col))
9256 (if (and (org-at-table-p)
9257 (not (org-at-table-hline-p)))
9260 "Please position cursor in a data line for column operations")))))
9262 (defun org-table-delete-column ()
9263 "Delete a column into the table."
9265 (if (not (org-at-table-p))
9266 (error "Not at a table"))
9267 (org-table-find-dataline)
9268 (org-table-check-inside-data-field)
9269 (let* ((col (org-table-current-column))
9270 (beg (org-table-begin))
9271 (end (org-table-end))
9272 ;; Current cursor position
9273 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9276 (while (< (point) end)
9277 (if (org-at-table-hline-p)
9279 (org-table-goto-column col t)
9280 (and (looking-at "|[^|\n]+|")
9281 (replace-match "|")))
9282 (beginning-of-line 2))
9283 (move-marker end nil)
9285 (org-table-goto-column colpos)
9287 (org-table-modify-formulas 'remove col)))
9289 (defun org-table-move-column-right ()
9290 "Move column to the right."
9292 (org-table-move-column nil))
9293 (defun org-table-move-column-left ()
9294 "Move column to the left."
9296 (org-table-move-column 'left))
9298 (defun org-table-move-column (&optional left)
9299 "Move the current column to the right. With arg LEFT, move to the left."
9301 (if (not (org-at-table-p))
9302 (error "Not at a table"))
9303 (org-table-find-dataline)
9304 (org-table-check-inside-data-field)
9305 (let* ((col (org-table-current-column))
9306 (col1 (if left (1- col) col))
9307 (beg (org-table-begin))
9308 (end (org-table-end))
9309 ;; Current cursor position
9310 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9311 (colpos (if left (1- col) (1+ col))))
9312 (if (and left (= col 1))
9313 (error "Cannot move column further left"))
9314 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9315 (error "Cannot move column further right"))
9317 (while (< (point) end)
9318 (if (org-at-table-hline-p)
9320 (org-table-goto-column col1 t)
9321 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9322 (replace-match "|\\2|\\1|")))
9323 (beginning-of-line 2))
9324 (move-marker end nil)
9326 (org-table-goto-column colpos)
9328 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
9330 (defun org-table-move-row-down ()
9331 "Move table row down."
9333 (org-table-move-row nil))
9334 (defun org-table-move-row-up ()
9335 "Move table row up."
9337 (org-table-move-row 'up))
9339 (defun org-table-move-row (&optional up)
9340 "Move the current table line down. With arg UP, move it up."
9342 (let ((col (current-column))
9346 (beginning-of-line tonew)
9347 (if (not (org-at-table-p))
9350 (error "Cannot move row further")))
9352 (beginning-of-line 1)
9354 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9355 (delete-region (point) (1+ (point-at-eol)))
9356 (beginning-of-line tonew)
9358 (beginning-of-line 0)
9359 (move-to-column col)))
9361 (defun org-table-insert-row (&optional arg)
9362 "Insert a new row above the current line into the table.
9363 With prefix ARG, insert below the current line."
9365 (if (not (org-at-table-p))
9366 (error "Not at a table"))
9367 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9368 (new (org-table-clean-line line)))
9369 ;; Fix the first field if necessary
9370 (if (string-match "^[ \t]*| *[#$] *|" line)
9371 (setq new (replace-match (match-string 0 line) t t new)))
9372 (beginning-of-line (if arg 2 1))
9373 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9374 (beginning-of-line 0)
9375 (re-search-forward "| ?" (point-at-eol) t)
9376 (and org-table-may-need-update (org-table-align))))
9378 (defun org-table-insert-hline (&optional arg)
9379 "Insert a horizontal-line below the current line into the table.
9380 With prefix ARG, insert above the current line."
9382 (if (not (org-at-table-p))
9383 (error "Not at a table"))
9384 (let ((line (org-table-clean-line
9385 (buffer-substring (point-at-bol) (point-at-eol))))
9386 (col (current-column)))
9387 (while (string-match "|\\( +\\)|" line)
9388 (setq line (replace-match
9389 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9390 ?-) "|") t t line)))
9391 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9392 (beginning-of-line (if arg 1 2))
9394 (beginning-of-line (if arg 1 -1))
9395 (move-to-column col)))
9397 (defun org-table-clean-line (s)
9398 "Convert a table line S into a string with only \"|\" and space.
9399 In particular, this does handle wide and invisible characters."
9400 (if (string-match "^[ \t]*|-" s)
9401 ;; It's a hline, just map the characters
9402 (setq s (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) s))
9403 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9404 (setq s (replace-match
9405 (concat "|" (make-string (org-string-width (match-string 1 s))
9410 (defun org-table-kill-row ()
9411 "Delete the current row or horizontal line from the table."
9413 (if (not (org-at-table-p))
9414 (error "Not at a table"))
9415 (let ((col (current-column)))
9416 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9417 (if (not (org-at-table-p)) (beginning-of-line 0))
9418 (move-to-column col)))
9420 (defun org-table-sort-lines (beg end numericp)
9421 "Sort table lines in region.
9422 Point and mark define the first and last line to include. Both point and
9423 mark should be in the column that is used for sorting. For example, to
9424 sort according to column 3, put the mark in the first line to sort, in
9425 table column 3. Put point into the last line to be included in the sorting,
9426 also in table column 3. The command will prompt for the sorting method
9427 \(n for numerical, a for alphanumeric)."
9428 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
9429 (setq numericp (string-match "[nN]" numericp))
9430 (org-table-align) ;; Just to be safe
9431 (let* (bcol ecol cmp column lns)
9433 (org-table-check-inside-data-field)
9434 (setq column (org-table-current-column)
9435 beg (move-marker (make-marker) (point-at-bol)))
9437 (org-table-check-inside-data-field)
9438 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
9441 (org-table-goto-column column)
9442 (skip-chars-backward "^|")
9443 (setq bcol (current-column))
9444 (org-table-goto-column (1+ column))
9445 (skip-chars-backward "^|")
9446 (setq ecol (1- (current-column)))
9447 (setq cmp (if numericp
9448 (lambda (a b) (< (car a) (car b)))
9449 (lambda (a b) (string< (car a) (car b)))))
9450 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
9451 (split-string (buffer-substring beg end) "\n")))
9453 (setq lns (mapcar (lambda(x)
9454 (cons (string-to-number (car x)) (cdr x)))
9456 (delete-region beg end)
9457 (move-marker beg nil)
9458 (move-marker end nil)
9459 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
9460 (message "%d lines sorted %s based on column %d"
9462 (if numericp "numerically" "alphabetically") column)))
9464 (defun org-table-cut-region (beg end)
9465 "Copy region in table to the clipboard and blank all relevant fields."
9467 (org-table-copy-region beg end 'cut))
9469 (defun org-table-copy-region (beg end &optional cut)
9470 "Copy rectangular region in table to clipboard.
9471 A special clipboard is used which can only be accessed
9472 with `org-table-paste-rectangle'."
9474 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9476 (rpl (if cut " " nil)))
9478 (org-table-check-inside-data-field)
9479 (setq l01 (count-lines (point-min) (point))
9480 c01 (org-table-current-column))
9482 (org-table-check-inside-data-field)
9483 (setq l02 (count-lines (point-min) (point))
9484 c02 (org-table-current-column))
9485 (setq l1 (min l01 l02) l2 (max l01 l02)
9486 c1 (min c01 c02) c2 (max c01 c02))
9490 (if (> l1 l2) (throw 'exit t))
9492 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9493 (setq cols nil ic1 c1 ic2 c2)
9494 (while (< ic1 (1+ ic2))
9495 (push (org-table-get-field ic1 rpl) cols)
9496 (setq ic1 (1+ ic1)))
9497 (push (nreverse cols) region)
9498 (setq l1 (1+ l1)))))
9499 (setq org-table-clip (nreverse region))
9500 (if cut (org-table-align))
9503 (defun org-table-paste-rectangle ()
9504 "Paste a rectangular region into a table.
9505 The upper right corner ends up in the current field. All involved fields
9506 will be overwritten. If the rectangle does not fit into the present table,
9507 the table is enlarged as needed. The process ignores horizontal separator
9510 (unless (and org-table-clip (listp org-table-clip))
9511 (error "First cut/copy a region to paste!"))
9512 (org-table-check-inside-data-field)
9513 (let* ((clip org-table-clip)
9514 (line (count-lines (point-min) (point)))
9515 (col (org-table-current-column))
9516 (org-enable-table-editor t)
9517 (org-table-automatic-realign nil)
9519 (while (setq cols (pop clip))
9520 (while (org-at-table-hline-p) (beginning-of-line 2))
9521 (if (not (org-at-table-p))
9522 (progn (end-of-line 0) (org-table-next-field)))
9524 (while (setq field (pop cols))
9525 (org-table-goto-column c nil 'force)
9526 (org-table-get-field nil field)
9528 (beginning-of-line 2))
9530 (org-table-goto-column col)
9533 (defun org-table-convert ()
9534 "Convert from `org-mode' table to table.el and back.
9535 Obviously, this only works within limits. When an Org-mode table is
9536 converted to table.el, all horizontal separator lines get lost, because
9537 table.el uses these as cell boundaries and has no notion of horizontal lines.
9538 A table.el table can be converted to an Org-mode table only if it does not
9539 do row or column spanning. Multiline cells will become multiple cells.
9540 Beware, Org-mode does not test if the table can be successfully converted - it
9541 blindly applies a recipe that works for simple tables."
9544 (if (org-at-table.el-p)
9545 ;; convert to Org-mode table
9546 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9547 (end (move-marker (make-marker) (org-table-end t))))
9548 (table-unrecognize-region beg end)
9550 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9553 (if (org-at-table-p)
9554 ;; convert to table.el table
9555 (let ((beg (move-marker (make-marker) (org-table-begin)))
9556 (end (move-marker (make-marker) (org-table-end))))
9557 ;; first, get rid of all horizontal lines
9559 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9561 ;; insert a hline before first
9563 (org-table-insert-hline 'above)
9564 (beginning-of-line -1)
9565 ;; insert a hline after each line
9566 (while (progn (beginning-of-line 3) (< (point) end))
9567 (org-table-insert-hline))
9569 (setq end (move-marker end (org-table-end)))
9570 ;; replace "+" at beginning and ending of hlines
9571 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9572 (replace-match "\\1+-"))
9574 (while (re-search-forward "-|[ \t]*$" end t)
9575 (replace-match "-+"))
9578 (defun org-table-wrap-region (arg)
9579 "Wrap several fields in a column like a paragraph.
9580 This is useful if you'd like to spread the contents of a field over several
9581 lines, in order to keep the table compact.
9583 If there is an active region, and both point and mark are in the same column,
9584 the text in the column is wrapped to minimum width for the given number of
9585 lines. Generally, this makes the table more compact. A prefix ARG may be
9586 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9587 formats the selected text to two lines. If the region was longer than two
9588 lines, the remaining lines remain empty. A negative prefix argument reduces
9589 the current number of lines by that amount. The wrapped text is pasted back
9590 into the table. If you formatted it to more lines than it was before, fields
9591 further down in the table get overwritten - so you might need to make space in
9594 If there is no region, the current field is split at the cursor position and
9595 the text fragment to the right of the cursor is prepended to the field one
9598 If there is no region, but you specify a prefix ARG, the current field gets
9599 blank, and the content is appended to the field above."
9601 (org-table-check-inside-data-field)
9602 (if (org-region-active-p)
9603 ;; There is a region: fill as a paragraph
9604 (let ((beg (region-beginning))
9606 (org-table-cut-region (region-beginning) (region-end))
9607 (if (> (length (car org-table-clip)) 1)
9608 (error "Region must be limited to single column"))
9609 (setq nlines (if arg
9611 (+ (length org-table-clip) arg)
9613 (length org-table-clip)))
9614 (setq org-table-clip
9615 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9618 (org-table-paste-rectangle))
9619 ;; No region, split the current field at point
9621 ;; combine with field above
9622 (let ((s (org-table-blank-field))
9623 (col (org-table-current-column)))
9624 (beginning-of-line 0)
9625 (while (org-at-table-hline-p) (beginning-of-line 0))
9626 (org-table-goto-column col)
9627 (skip-chars-forward "^|")
9628 (skip-chars-backward " ")
9629 (insert " " (org-trim s))
9632 (when (looking-at "\\([^|]+\\)+|")
9633 (let ((s (match-string 1)))
9634 (replace-match " |")
9635 (goto-char (match-beginning 0))
9636 (org-table-next-row)
9637 (insert (org-trim s) " ")
9638 (org-table-align))))))
9640 (defvar org-field-marker nil)
9642 (defun org-table-edit-field (arg)
9643 "Edit table field in a different window.
9644 This is mainly useful for fields that contain hidden parts.
9645 When called with a \\[universal-argument] prefix, just make the full field visible so that
9646 it can be edited in place."
9649 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9650 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9651 (remove-text-properties b e '(org-cwidth t invisible t
9652 display t intangible t))
9653 (if (and (boundp 'font-lock-mode) font-lock-mode)
9654 (font-lock-fontify-block)))
9655 (let ((pos (move-marker (make-marker) (point)))
9656 (field (org-table-get-field))
9657 (cw (current-window-configuration))
9659 (switch-to-buffer-other-window "*Org tmp*")
9661 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9663 (goto-char (setq p (point-max)))
9664 (insert (org-trim field))
9665 (remove-text-properties p (point-max)
9666 '(invisible t org-cwidth t display t
9669 (set (make-local-variable 'org-finish-function)
9670 'org-table-finish-edit-field)
9671 (set (make-local-variable 'org-window-configuration) cw)
9672 (set (make-local-variable 'org-field-marker) pos)
9673 (message "Edit and finish with C-c C-c"))))
9675 (defun org-table-finish-edit-field ()
9676 "Finish editing a table data field.
9677 Remove all newline characters, insert the result into the table, realign
9678 the table and kill the editing buffer."
9679 (let ((pos org-field-marker)
9680 (cw org-window-configuration)
9681 (cb (current-buffer))
9683 (goto-char (point-min))
9684 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9685 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9686 (replace-match " "))
9687 (setq text (org-trim (buffer-string)))
9688 (set-window-configuration cw)
9690 (select-window (get-buffer-window (marker-buffer pos)))
9692 (move-marker pos nil)
9693 (org-table-check-inside-data-field)
9694 (org-table-get-field nil text)
9696 (message "New field value inserted")))
9699 "Remove whitespace at beginning and end of string."
9700 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
9701 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
9704 (defun org-wrap (string &optional width lines)
9705 "Wrap string to either a number of lines, or a width in characters.
9706 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9707 that costs. If there is a word longer than WIDTH, the text is actually
9708 wrapped to the length of that word.
9709 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9710 many lines, whatever width that takes.
9711 The return value is a list of lines, without newlines at the end."
9712 (let* ((words (org-split-string string "[ \t\n]+"))
9713 (maxword (apply 'max (mapcar 'org-string-width words)))
9716 (org-do-wrap words (max maxword width)))
9719 (setq ll (org-do-wrap words maxword))
9720 (if (<= (length ll) lines)
9723 (while (> (length ll) lines)
9725 (setq ll (org-do-wrap words w)))
9727 (t (error "Cannot wrap this")))))
9730 (defun org-do-wrap (words width)
9731 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9734 (setq line (pop words))
9735 (while (and words (< (+ (length line) (length (car words))) width))
9736 (setq line (concat line " " (pop words))))
9737 (setq lines (push line lines)))
9740 (defun org-split-string (string &optional separators)
9741 "Splits STRING into substrings at SEPARATORS.
9742 No empty strings are returned if there are matches at the beginning
9744 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9748 (while (and (string-match rexp string
9750 (= start (match-beginning 0))
9751 (< start (length string)))
9753 (< (match-beginning 0) (length string)))
9755 (or (eq (match-beginning 0) 0)
9756 (and (eq (match-beginning 0) (match-end 0))
9757 (eq (match-beginning 0) start))
9759 (cons (substring string start (match-beginning 0))
9761 (setq start (match-end 0)))
9762 (or (eq start (length string))
9764 (cons (substring string start)
9768 (defun org-table-map-tables (function)
9769 "Apply FUNCTION to the start of all tables in the buffer."
9773 (goto-char (point-min))
9774 (while (re-search-forward org-table-any-line-regexp nil t)
9775 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9776 (beginning-of-line 1)
9777 (if (looking-at org-table-line-regexp)
9778 (save-excursion (funcall function)))
9779 (re-search-forward org-table-any-border-regexp nil 1))))
9780 (message "Mapping tables: done"))
9782 (defun org-table-sum (&optional beg end nlast)
9783 "Sum numbers in region of current table column.
9784 The result will be displayed in the echo area, and will be available
9785 as kill to be inserted with \\[yank].
9787 If there is an active region, it is interpreted as a rectangle and all
9788 numbers in that rectangle will be summed. If there is no active
9789 region and point is located in a table column, sum all numbers in that
9792 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9793 numbers are assumed to be times as well (in decimal hours) and the
9794 numbers are added as such.
9796 If NLAST is a number, only the NLAST fields will actually be summed."
9799 (let (col (timecnt 0) diff h m s org-table-clip)
9801 ((and beg end)) ; beg and end given explicitly
9802 ((org-region-active-p)
9803 (setq beg (region-beginning) end (region-end)))
9805 (setq col (org-table-current-column))
9806 (goto-char (org-table-begin))
9807 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9808 (error "No table data"))
9809 (org-table-goto-column col)
9810 ;not needed? (skip-chars-backward "^|")
9812 (goto-char (org-table-end))
9813 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9814 (error "No table data"))
9815 (org-table-goto-column col)
9816 ;not needed? (skip-chars-forward "^|")
9817 (setq end (point))))
9818 (let* ((items (apply 'append (org-table-copy-region beg end)))
9819 (items1 (cond ((not nlast) items)
9820 ((>= nlast (length items)) items)
9821 (t (setq items (reverse items))
9822 (setcdr (nthcdr (1- nlast) items) nil)
9824 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9826 (res (apply '+ numbers))
9827 (sres (if (= timecnt 0)
9829 (setq diff (* 3600 res)
9830 h (floor (/ diff 3600)) diff (mod diff 3600)
9831 m (floor (/ diff 60)) diff (mod diff 60)
9833 (format "%d:%02d:%02d" h m s))))
9837 (substitute-command-keys
9838 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9839 (length numbers) sres))))
9842 (defun org-table-get-number-for-summing (s)
9844 (if (string-match "^ *|? *" s)
9845 (setq s (replace-match "" nil nil s)))
9846 (if (string-match " *|? *$" s)
9847 (setq s (replace-match "" nil nil s)))
9848 (setq n (string-to-number s))
9850 ((and (string-match "0" s)
9851 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9852 ((string-match "\\`[ \t]+\\'" s) nil)
9853 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9854 (let ((h (string-to-number (or (match-string 1 s) "0")))
9855 (m (string-to-number (or (match-string 2 s) "0")))
9856 (s (string-to-number (or (match-string 4 s) "0"))))
9857 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
9858 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9862 (defun org-table-get-vertical-vector (desc &optional tbeg col)
9863 "Get a calc vector from a column, accorting to descriptor DESC.
9864 Optional arguments TBEG and COL can give the beginning of the table and
9865 the current column, to avoid unnecessary parsing."
9867 (or tbeg (setq tbeg (org-table-begin)))
9868 (or col (setq col (org-table-current-column)))
9869 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
9871 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
9872 (setq n1 (- (match-end 1) (match-beginning 1)))
9873 (if (match-beginning 3)
9874 (setq n2 (- (match-end 2) (match-beginning 3))))
9875 (setq n (if n2 (max n1 n2) n1))
9876 (setq n1 (if n2 (min n1 n2)))
9878 (while (and (> nn 0)
9879 (re-search-backward org-table-hline-regexp tbeg t))
9880 (push (org-current-line) hline-list)
9882 (setq hline-list (nreverse hline-list))
9883 (goto-line (nth (1- n) hline-list))
9884 (when (re-search-forward org-table-dataline-regexp)
9885 (org-table-goto-column col)
9887 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
9888 (when (re-search-backward org-table-dataline-regexp)
9889 (org-table-goto-column col)
9891 (setq l (apply 'append (org-table-copy-region beg end)))
9892 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
9893 (if (equal x "") "0" x))
9895 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
9896 (setq n1 (string-to-number (match-string 1 desc))
9897 n2 (string-to-number (match-string 2 desc)))
9898 (beginning-of-line 1)
9900 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
9901 (org-table-goto-column col)
9902 (setq beg (point))))
9903 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
9904 (org-table-goto-column col)
9906 (setq l (apply 'append (org-table-copy-region beg end)))
9907 (concat "[" (mapconcat
9908 (lambda (x) (setq x (org-trim x))
9909 (if (equal x "") "0" x))
9911 ((string-match "\\([0-9]+\\)" desc)
9912 (beginning-of-line 1)
9913 (when (re-search-backward org-table-dataline-regexp tbeg t
9914 (string-to-number (match-string 0 desc)))
9915 (org-table-goto-column col)
9916 (org-trim (org-table-get-field))))))))
9918 (defvar org-table-formula-history nil)
9920 (defvar org-table-column-names nil
9921 "Alist with column names, derived from the `!' line.")
9922 (defvar org-table-column-name-regexp nil
9923 "Regular expression matching the current column names.")
9924 (defvar org-table-local-parameters nil
9925 "Alist with parameter names, derived from the `$' line.")
9926 (defvar org-table-named-field-locations nil
9927 "Alist with locations of named fields.")
9929 (defun org-table-get-formula (&optional equation named)
9930 "Read a formula from the minibuffer, offer stored formula as default."
9931 (let* ((name (car (rassoc (list (org-current-line)
9932 (org-table-current-column))
9933 org-table-named-field-locations)))
9936 (error "Not in a named field"))
9937 (int-to-string (org-table-current-column))))
9938 (dummy (and name (not named)
9939 (not (y-or-n-p "Replace named-field formula with column equation? " ))
9941 (org-table-may-need-update nil)
9942 (stored-list (org-table-get-stored-formulas))
9943 (stored (cdr (assoc scol stored-list)))
9945 ((and stored equation (string-match "^ *=? *$" equation))
9950 (format "%s formula $%s=" (if named "Field" "Column") scol)
9951 (or stored "") 'org-table-formula-history
9955 (when (not (string-match "\\S-" eq))
9957 (setq stored-list (delq (assoc scol stored-list) stored-list))
9958 (org-table-store-formulas stored-list)
9959 (error "Formula removed"))
9960 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9961 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9962 (if (and name (not named))
9963 ;; We set the column equation, delete the named one.
9964 (setq stored-list (delq (assoc name stored-list) stored-list)
9967 (setcdr (assoc scol stored-list) eq)
9968 (setq stored-list (cons (cons scol eq) stored-list)))
9969 (if (or mustsave (not (equal stored eq)))
9970 (org-table-store-formulas stored-list))
9973 (defun org-table-store-formulas (alist)
9974 "Store the list of formulas below the current table."
9975 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
9977 (goto-char (org-table-end))
9978 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
9979 (delete-region (point) (match-end 0)))
9981 (mapconcat (lambda (x)
9982 (concat "$" (car x) "=" (cdr x)))
9986 (defun org-table-get-stored-formulas ()
9987 "Return an alist with the t=stored formulas directly after current table."
9989 (let (scol eq eq-alist strings string seen)
9991 (goto-char (org-table-end))
9992 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9993 (setq strings (org-split-string (match-string 2) " *:: *"))
9994 (while (setq string (pop strings))
9995 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
9996 (setq scol (match-string 1 string)
9997 eq (match-string 2 string)
9998 eq-alist (cons (cons scol eq) eq-alist))
9999 (if (member scol seen)
10000 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
10001 (push scol seen))))))
10002 (nreverse eq-alist)))
10004 (defun org-table-modify-formulas (action &rest columns)
10005 "Modify the formulas stored below the current table.
10006 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
10007 expected, for the other actions only a single column number is needed."
10008 (let ((list (org-table-get-stored-formulas))
10009 (nmax (length (org-split-string
10010 (buffer-substring (point-at-bol) (point-at-eol))
10012 col col1 col2 scol si sc1 sc2)
10014 ((null list)) ; No action needed if there are no stored formulas
10015 ((eq action 'remove)
10016 (setq col (car columns)
10017 scol (int-to-string col))
10018 (org-table-replace-in-formulas list scol "INVALID")
10019 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
10020 (loop for i from (1+ col) upto nmax by 1 do
10021 (setq si (int-to-string i))
10022 (org-table-replace-in-formulas list si (int-to-string (1- i)))
10023 (if (assoc si list) (setcar (assoc si list)
10024 (int-to-string (1- i))))))
10025 ((eq action 'insert)
10026 (setq col (car columns))
10027 (loop for i from nmax downto col by 1 do
10028 (setq si (int-to-string i))
10029 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
10030 (if (assoc si list) (setcar (assoc si list)
10031 (int-to-string (1+ i))))))
10033 (setq col1 (car columns) col2 (nth 1 columns)
10034 sc1 (int-to-string col1) sc2 (int-to-string col2))
10035 ;; Hopefully, ZqZtZ will never be a name in a table
10036 (org-table-replace-in-formulas list sc1 "ZqZtZ")
10037 (org-table-replace-in-formulas list sc2 sc1)
10038 (org-table-replace-in-formulas list "ZqZtZ" sc2)
10039 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
10040 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
10041 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
10042 (t (error "Invalid action in `org-table-modify-formulas'")))
10043 (if list (org-table-store-formulas list))))
10045 (defun org-table-replace-in-formulas (list s1 s2)
10047 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
10048 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
10049 re (concat (regexp-quote s1) "\\>"))
10050 (while (setq elt (pop list))
10052 (while (string-match re s)
10053 (setq s (replace-match s2 t t s)))
10056 (defun org-table-get-specials ()
10057 "Get the column names and local parameters for this table."
10059 (let ((beg (org-table-begin)) (end (org-table-end))
10060 names name fields fields1 field cnt c v line col)
10061 (setq org-table-column-names nil
10062 org-table-local-parameters nil
10063 org-table-named-field-locations nil)
10065 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
10066 (setq names (org-split-string (match-string 1) " *| *")
10068 (while (setq name (pop names))
10069 (setq cnt (1+ cnt))
10070 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
10071 (push (cons name (int-to-string cnt)) org-table-column-names))))
10072 (setq org-table-column-names (nreverse org-table-column-names))
10073 (setq org-table-column-name-regexp
10074 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
10076 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
10077 (setq fields (org-split-string (match-string 1) " *| *"))
10078 (while (setq field (pop fields))
10079 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
10080 (push (cons (match-string 1 field) (match-string 2 field))
10081 org-table-local-parameters))))
10083 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10084 (setq c (match-string 1)
10085 fields (org-split-string (match-string 2) " *| *"))
10087 (beginning-of-line (if (equal c "_") 2 0))
10088 (setq line (org-current-line) col 1)
10089 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10090 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10091 (while (and fields1 (setq field (pop fields)))
10092 (setq v (pop fields1) col (1+ col))
10093 (when (and (stringp field) (stringp v)
10094 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10095 (push (cons field v) org-table-local-parameters)
10096 (push (list field line col) org-table-named-field-locations)))))))
10098 (defun org-this-word ()
10099 ;; Get the current word
10101 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
10102 (end (progn (skip-chars-forward "^ \t\n") (point))))
10103 (buffer-substring-no-properties beg end))))
10105 (defun org-table-maybe-eval-formula ()
10106 "Check if the current field starts with \"=\" or \":=\".
10107 If yes, store the formula and apply it."
10108 ;; We already know we are in a table. Get field will only return a formula
10109 ;; when appropriate. It might return a separator line, but no problem.
10110 (when org-table-formula-evaluate-inline
10111 (let* ((field (org-trim (or (org-table-get-field) "")))
10113 (when (string-match "^:?=\\(.*\\)" field)
10114 (setq named (equal (string-to-char field) ?:)
10115 eq (match-string 1 field))
10116 (if (fboundp 'calc-eval)
10117 (org-table-eval-formula (if named '(4) nil) eq))))))
10119 (defvar org-recalc-commands nil
10120 "List of commands triggering the recalculation of a line.
10121 Will be filled automatically during use.")
10123 (defvar org-recalc-marks
10124 '((" " . "Unmarked: no special line, no automatic recalculation")
10125 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10126 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10127 ("!" . "Column name definition line. Reference in formula as $name.")
10128 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10129 ("_" . "Names for values in row below this one.")
10130 ("^" . "Names for values in row above this one.")))
10132 (defun org-table-rotate-recalc-marks (&optional newchar)
10133 "Rotate the recalculation mark in the first column.
10134 If in any row, the first field is not consistent with a mark,
10135 insert a new column for the markers.
10136 When there is an active region, change all the lines in the region,
10137 after prompting for the marking character.
10138 After each change, a message will be displayed indicating the meaning
10141 (unless (org-at-table-p) (error "Not at a table"))
10142 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10143 (beg (org-table-begin))
10144 (end (org-table-end))
10145 (l (org-current-line))
10146 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10147 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10151 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10152 (col (org-table-current-column))
10153 (forcenew (car (assoc newchar org-recalc-marks)))
10156 (message "Change region to what mark? Type # * ! $ or SPC: ")
10157 (setq newchar (char-to-string (read-char-exclusive))
10158 forcenew (car (assoc newchar org-recalc-marks))))
10159 (if (and newchar (not forcenew))
10160 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10162 (if l1 (goto-line l1))
10164 (beginning-of-line 1)
10165 (unless (looking-at org-table-dataline-regexp)
10166 (error "Not at a table data line")))
10168 (org-table-goto-column 1)
10169 (org-table-insert-column)
10170 (org-table-goto-column (1+ col)))
10171 (setq epos (point-at-eol))
10173 (beginning-of-line 1)
10174 (org-table-get-field
10175 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10177 (setq new (or forcenew
10178 (cadr (member (match-string 1) marks))))
10184 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10185 (and (looking-at org-table-dataline-regexp)
10186 (org-table-get-field 1 (concat " " new " "))))
10188 (if (not (= epos (point-at-eol))) (org-table-align))
10190 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
10192 (defun org-table-maybe-recalculate-line ()
10193 "Recompute the current line if marked for it, and if we haven't just done it."
10195 (and org-table-allow-automatic-line-recalculation
10196 (not (and (memq last-command org-recalc-commands)
10197 (equal org-last-recalc-line (org-current-line))))
10198 (save-excursion (beginning-of-line 1)
10199 (looking-at org-table-auto-recalculate-regexp))
10200 (fboundp 'calc-eval)
10201 (org-table-recalculate) t))
10203 (defvar org-table-formula-debug nil
10204 "Non-nil means, debug table formulas.
10205 When nil, simply write \"#ERROR\" in corrupted fields.")
10208 (defsubst org-set-calc-mode (var &optional value)
10210 (setq var (assoc var '(("D" calc-angle-mode deg)
10211 ("R" calc-angle-mode rad)
10212 ("F" calc-prefer-frac t)
10213 ("S" calc-symbolic-mode t)))
10214 value (nth 2 var) var (nth 1 var)))
10215 (if (memq var modes)
10216 (setcar (cdr (memq var modes)) value)
10217 (cons var (cons value modes)))
10220 (defun org-table-eval-formula (&optional arg equation
10221 suppress-align suppress-const
10223 "Replace the table field value at the cursor by the result of a calculation.
10225 This function makes use of Dave Gillespie's Calc package, in my view the
10226 most exciting program ever written for GNU Emacs. So you need to have Calc
10227 installed in order to use this function.
10229 In a table, this command replaces the value in the current field with the
10230 result of a formula. It also installs the formula as the \"current\" column
10231 formula, by storing it in a special line below the table. When called
10232 with a `C-u' prefix, the current field must ba a named field, and the
10233 formula is installed as valid in only this specific field.
10235 When called, the command first prompts for a formula, which is read in
10236 the minibuffer. Previously entered formulas are available through the
10237 history list, and the last used formula is offered as a default.
10238 These stored formulas are adapted correctly when moving, inserting, or
10239 deleting columns with the corresponding commands.
10241 The formula can be any algebraic expression understood by the Calc package.
10242 For details, see the Org-mode manual.
10244 This function can also be called from Lisp programs and offers
10245 additional arguments: EQUATION can be the formula to apply. If this
10246 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10247 used to speed-up recursive calls by by-passing unnecessary aligns.
10248 SUPPRESS-CONST suppresses the interpretation of constants in the
10249 formula, assuming that this has been done already outside the function.
10250 SUPPRESS-STORE means the formula should not be stored, either because
10251 it is already stored, or because it is a modified equation that should
10252 not overwrite the stored one."
10255 (org-table-check-inside-data-field)
10256 (org-table-get-specials)
10258 (ndown (if (integerp arg) arg 1))
10259 (org-table-automatic-realign nil)
10260 (case-fold-search nil)
10262 (formula (if (and equation suppress-store)
10264 (org-table-get-formula equation (equal arg '(4)))))
10265 (n0 (org-table-current-column))
10266 (modes (copy-sequence org-calc-default-modes))
10267 n form fmt x ev orig c)
10268 ;; Parse the format string. Since we have a lot of modes, this is
10269 ;; a lot of work. However, I think calc still uses most of the time.
10270 (if (string-match ";" formula)
10271 (let ((tmp (org-split-string formula ";")))
10272 (setq formula (car tmp)
10273 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10275 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
10276 (setq c (string-to-char (match-string 1 fmt))
10277 n (string-to-number (or (match-string 1 fmt) "")))
10278 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
10279 (setq modes (org-set-calc-mode
10281 (list (cdr (assoc c '((?n . float) (?f . fix)
10282 (?s . sci) (?e . eng))))
10284 (setq fmt (replace-match "" t t fmt)))
10285 (while (string-match "[DRFS]" fmt)
10286 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10287 (setq fmt (replace-match "" t t fmt)))
10288 (unless (string-match "\\S-" fmt)
10290 (if (and (not suppress-const) org-table-formula-use-constants)
10291 (setq formula (org-table-formula-substitute-names formula)))
10292 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10294 (setq fields (org-split-string
10296 (point-at-bol) (point-at-eol)) " *| *"))
10297 (if org-table-formula-numbers-only
10298 (setq fields (mapcar
10299 (lambda (x) (number-to-string (string-to-number x)))
10301 (setq ndown (1- ndown))
10302 (setq form (copy-sequence formula))
10303 ;; Insert the references to fields in same row
10304 (while (string-match "\\$\\([0-9]+\\)?" form)
10305 (setq n (if (match-beginning 1)
10306 (string-to-number (match-string 1 form))
10308 x (nth (1- n) fields))
10309 (unless x (error "Invalid field specifier \"%s\""
10310 (match-string 0 form)))
10311 (if (equal x "") (setq x "0"))
10312 (setq form (replace-match (concat "(" x ")") t t form)))
10313 ;; Insert ranges in current column
10314 (while (string-match "\\&[-I0-9]+" form)
10315 (setq form (replace-match
10317 (org-table-get-vertical-vector (match-string 0 form)
10320 (setq ev (calc-eval (cons form modes)
10321 (if org-table-formula-numbers-only 'num)))
10323 (when org-table-formula-debug
10324 (with-output-to-temp-buffer "*Help*"
10325 (princ (format "Substitution history of formula
10328 $1-> %s\n" orig formula form))
10330 (princ (format " %s^\nError: %s"
10331 (make-string (car ev) ?\-) (nth 1 ev)))
10332 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10334 (if fmt (format fmt (string-to-number ev)) ev)))))
10335 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
10336 (unless (and (interactive-p) (not ndown))
10337 (unless (let (inhibit-redisplay)
10338 (y-or-n-p "Debugging Formula. Continue to next? "))
10341 (delete-window (get-buffer-window "*Help*"))
10343 (if (listp ev) (setq fmt nil ev "#ERROR"))
10344 (org-table-justify-field-maybe
10345 (if fmt (format fmt (string-to-number ev)) ev))
10346 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10347 (call-interactively 'org-return)
10349 (and down (org-table-maybe-recalculate-line))
10350 (or suppress-align (and org-table-may-need-update
10351 (org-table-align)))))
10353 (defun org-table-recalculate (&optional all noalign)
10354 "Recalculate the current table line by applying all stored formulas.
10355 With prefix arg ALL, do this for all lines in the table."
10357 (or (memq this-command org-recalc-commands)
10358 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10359 (unless (org-at-table-p) (error "Not at a table"))
10360 (org-table-get-specials)
10361 (let* ((eqlist (sort (org-table-get-stored-formulas)
10362 (lambda (a b) (string< (car a) (car b)))))
10363 (inhibit-redisplay t)
10364 (line-re org-table-dataline-regexp)
10365 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10366 (thiscol (org-table-current-column))
10367 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
10368 ;; Insert constants in all formulas
10370 (mapcar (lambda (x)
10371 (setcdr x (org-table-formula-substitute-names (cdr x)))
10374 ;; Split the equation list
10375 (while (setq eq (pop eqlist))
10376 (if (<= (string-to-char (car eq)) ?9)
10378 (push eq eqlname)))
10379 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10382 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10383 (goto-char (setq beg (org-table-begin)))
10384 (if (re-search-forward org-table-calculate-mark-regexp end t)
10385 ;; This is a table with marked lines, only compute selected lines
10386 (setq line-re org-table-recalculate-regexp)
10387 ;; Move forward to the first non-header line
10388 (if (and (re-search-forward org-table-dataline-regexp end t)
10389 (re-search-forward org-table-hline-regexp end t)
10390 (re-search-forward org-table-dataline-regexp end t))
10391 (setq beg (match-beginning 0))
10392 nil))) ;; just leave beg where it is
10393 (setq beg (point-at-bol)
10394 end (move-marker (make-marker) (1+ (point-at-eol)))))
10396 (and all (message "Re-applying formulas to full table..."))
10397 (while (re-search-forward line-re end t)
10398 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
10399 ;; Unprotected line, recalculate
10400 (and all (message "Re-applying formulas to full table...(line %d)"
10401 (setq cnt (1+ cnt))))
10402 (setq org-last-recalc-line (org-current-line))
10404 (while (setq entry (pop eql))
10405 (goto-line org-last-recalc-line)
10406 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10407 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
10408 (goto-line thisline)
10409 (org-table-goto-column thiscol)
10410 (or noalign (and org-table-may-need-update (org-table-align))
10411 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10412 ;; Now do the names fields
10413 (while (setq eq (pop eqlname))
10414 (setq name (car eq)
10415 a (assoc name org-table-named-field-locations))
10417 (message "Re-applying formula to named field: %s" name)
10418 (goto-line (nth 1 a))
10419 (org-table-goto-column (nth 2 a))
10420 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
10421 ;; back to initial position
10422 (goto-line thisline)
10423 (org-table-goto-column thiscol)
10424 (or noalign (and org-table-may-need-update (org-table-align))
10425 (and all (message "Re-applying formulas...done")))))
10427 (defun org-table-formula-substitute-names (f)
10428 "Replace $const with values in string F."
10429 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
10430 ;; First, check for column names
10431 (while (setq start (string-match org-table-column-name-regexp f start))
10432 (setq start (1+ start))
10433 (setq a (assoc (match-string 1 f) org-table-column-names))
10434 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10435 ;; Expand ranges to vectors
10436 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
10437 (setq n1 (string-to-number (match-string 1 f))
10438 n2 (string-to-number (match-string 2 f))
10439 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
10440 s (concat "[($" (number-to-string (1- nn1)) ")"))
10441 (loop for i from nn1 upto nn2 do
10442 (setq s (concat s ",($" (int-to-string i) ")")))
10443 (setq s (concat s "]"))
10444 (if (< n2 n1) (setq s (concat "rev(" s ")")))
10445 (setq f (replace-match s t t f)))
10446 ;; Parameters and constants
10448 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
10449 (setq start (1+ start))
10450 (if (setq a (save-match-data
10451 (org-table-get-constant (match-string 1 f))))
10452 (setq f (replace-match (concat "(" a ")") t t f))))
10453 (if org-table-formula-debug
10454 (put-text-property 0 (length f) :orig-formula f1 f))
10457 (defun org-table-get-constant (const)
10458 "Find the value for a parameter or constant in a formula.
10459 Parameters get priority."
10460 (or (cdr (assoc const org-table-local-parameters))
10461 (cdr (assoc const org-table-formula-constants))
10462 (and (fboundp 'constants-get) (constants-get const))
10463 "#UNDEFINED_NAME"))
10465 (defvar org-edit-formulas-map (make-sparse-keymap))
10466 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
10467 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
10468 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
10472 (defun org-table-edit-formulas ()
10473 "Edit the formulas of the current table in a separate buffer."
10475 (unless (org-at-table-p)
10476 (error "Not at a table"))
10477 (org-table-get-specials)
10478 (let ((eql (org-table-get-stored-formulas))
10479 (pos (move-marker (make-marker) (point)))
10480 (wc (current-window-configuration))
10482 (switch-to-buffer-other-window "*Edit Formulas*")
10485 (set (make-local-variable 'org-pos) pos)
10486 (set (make-local-variable 'org-window-configuration) wc)
10487 (use-local-map org-edit-formulas-map)
10488 (setq s "# Edit formulas and finish with `C-c C-c'.
10489 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
10490 # Use `C-c ?' to get information about $name at point.
10491 # To cancel editing, press `C-c C-q'.\n")
10492 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
10494 (while (setq entry (pop eql))
10495 (when (setq loc (assoc (car entry) org-table-named-field-locations))
10496 (setq s (format "# Named formula, referring to column %d in line %d\n"
10497 (nth 2 loc) (nth 1 loc)))
10498 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
10500 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
10501 (remove-text-properties 0 (length s) '(face nil) s)
10503 (goto-char (point-min))
10504 (message "Edit formulas and finish with `C-c C-c'.")))
10506 (defun org-show-variable ()
10507 "Show the location/value of the $ expression at point."
10509 (let (var (pos org-pos) (win (selected-window)) e)
10511 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
10512 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
10513 (setq var (match-string 1))
10514 (error "No variable at point")))
10516 ((setq e (assoc var org-table-named-field-locations))
10517 (switch-to-buffer-other-window (marker-buffer pos))
10518 (goto-line (nth 1 e))
10519 (org-table-goto-column (nth 2 e))
10520 (select-window win)
10521 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10522 ((setq e (assoc var org-table-column-names))
10523 (switch-to-buffer-other-window (marker-buffer pos))
10525 (goto-char (org-table-begin))
10526 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10529 (goto-char (match-beginning 1))
10530 (message "Named column (column %s)" (cdr e)))
10531 (error "Column name not found"))
10532 (select-window win))
10533 ((string-match "^[0-9]$" var)
10535 (switch-to-buffer-other-window (marker-buffer pos))
10537 (goto-char (org-table-begin))
10539 (if (re-search-forward org-table-dataline-regexp
10542 (goto-char (match-beginning 0))
10543 (org-table-goto-column (string-to-number var))
10544 (message "Column %s" var))
10545 (error "Column name not found"))
10546 (select-window win))
10547 ((setq e (assoc var org-table-local-parameters))
10548 (switch-to-buffer-other-window (marker-buffer pos))
10550 (goto-char (org-table-begin))
10551 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10553 (goto-char (match-beginning 1))
10554 (message "Local parameter."))
10555 (error "Parameter not found"))
10556 (select-window win))
10559 ((setq e (assoc var org-table-formula-constants))
10560 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
10561 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10562 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
10563 (t (error "Undefined name $%s" var)))))))
10565 (defun org-finish-edit-formulas (&optional arg)
10566 "Parse the buffer for formula definitions and install them.
10567 With prefix ARG, apply the new formulas to the table."
10569 (let ((pos org-pos) eql)
10570 (goto-char (point-min))
10571 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
10572 (push (cons (match-string 1) (match-string 2)) eql))
10573 (set-window-configuration org-window-configuration)
10574 (select-window (get-buffer-window (marker-buffer pos)))
10576 (unless (org-at-table-p)
10577 (error "Lost table position - cannot install formulae"))
10578 (org-table-store-formulas eql)
10579 (move-marker pos nil)
10580 (kill-buffer "*Edit Formulas*")
10582 (org-table-recalculate 'all)
10583 (message "New formulas installed - press C-u C-c C-c to apply."))))
10585 (defun org-abort-edit-formulas ()
10586 "Abort editing formulas, without installing the changes."
10588 (let ((pos org-pos))
10589 (set-window-configuration org-window-configuration)
10590 (select-window (get-buffer-window (marker-buffer pos)))
10592 (message "Formula editing aborted without installing changes")))
10594 ;;; The orgtbl minor mode
10596 ;; Define a minor mode which can be used in other modes in order to
10597 ;; integrate the org-mode table editor.
10599 ;; This is really a hack, because the org-mode table editor uses several
10600 ;; keys which normally belong to the major mode, for example the TAB and
10601 ;; RET keys. Here is how it works: The minor mode defines all the keys
10602 ;; necessary to operate the table editor, but wraps the commands into a
10603 ;; function which tests if the cursor is currently inside a table. If that
10604 ;; is the case, the table editor command is executed. However, when any of
10605 ;; those keys is used outside a table, the function uses `key-binding' to
10606 ;; look up if the key has an associated command in another currently active
10607 ;; keymap (minor modes, major mode, global), and executes that command.
10608 ;; There might be problems if any of the keys used by the table editor is
10609 ;; otherwise used as a prefix key.
10611 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10612 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
10613 ;; addresses this by checking explicitly for both bindings.
10615 ;; The optimized version (see variable `orgtbl-optimized') takes over
10616 ;; all keys which are bound to `self-insert-command' in the *global map*.
10617 ;; Some modes bind other commands to simple characters, for example
10618 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
10619 ;; active, this binding is ignored inside tables and replaced with a
10620 ;; modified self-insert.
10622 (defvar orgtbl-mode nil
10623 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
10624 table editor in arbitrary modes.")
10625 (make-variable-buffer-local 'orgtbl-mode)
10627 (defvar orgtbl-mode-map (make-keymap)
10628 "Keymap for `orgtbl-mode'.")
10631 (defun turn-on-orgtbl ()
10632 "Unconditionally turn on `orgtbl-mode'."
10636 (defun orgtbl-mode (&optional arg)
10637 "The `org-mode' table editor as a minor mode for use in other modes."
10639 (if (eq major-mode 'org-mode)
10640 ;; Exit without error, in case some hook functions calls this
10641 ;; by accident in org-mode.
10642 (message "Orgtbl-mode is not useful in org-mode, command ignored")
10644 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
10647 (and (orgtbl-setup) (defun orgtbl-setup () nil))
10648 ;; Make sure we are first in minor-mode-map-alist
10649 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
10650 (and c (setq minor-mode-map-alist
10651 (cons c (delq c minor-mode-map-alist)))))
10652 (set (make-local-variable (quote org-table-may-need-update)) t)
10653 (org-add-hook 'before-change-functions 'org-before-change-function
10655 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
10656 auto-fill-inhibit-regexp)
10657 (set (make-local-variable 'auto-fill-inhibit-regexp)
10658 (if auto-fill-inhibit-regexp
10659 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
10661 (org-add-to-invisibility-spec '(org-cwidth))
10662 (easy-menu-add orgtbl-mode-menu)
10663 (run-hooks 'orgtbl-mode-hook))
10664 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
10665 (org-cleanup-narrow-column-properties)
10666 (org-remove-from-invisibility-spec '(org-cwidth))
10667 (remove-hook 'before-change-functions 'org-before-change-function t)
10668 (easy-menu-remove orgtbl-mode-menu)
10669 (force-mode-line-update 'all))))
10671 (defun org-cleanup-narrow-column-properties ()
10672 "Remove all properties related to narrow-column invisibility."
10674 (while (setq s (text-property-any s (point-max)
10675 'display org-narrow-column-arrow))
10676 (remove-text-properties s (1+ s) '(display t)))
10678 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
10679 (remove-text-properties s (1+ s) '(org-cwidth t)))
10681 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
10682 (remove-text-properties s (1+ s) '(invisible t)))))
10684 ;; Install it as a minor mode.
10685 (put 'orgtbl-mode :included t)
10686 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10687 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10689 (defun orgtbl-make-binding (fun n &rest keys)
10690 "Create a function for binding in the table minor mode.
10691 FUN is the command to call inside a table. N is used to create a unique
10692 command name. KEYS are keys that should be checked in for a command
10693 to execute outside of tables."
10696 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10698 (concat "In tables, run `" (symbol-name fun) "'.\n"
10699 "Outside of tables, run the binding of `"
10700 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10705 (list 'call-interactively (list 'quote fun))
10706 (list 'let '(orgtbl-mode)
10707 (list 'call-interactively
10709 (mapcar (lambda (k)
10710 (list 'key-binding k))
10712 '('orgtbl-error))))))))
10714 (defun orgtbl-error ()
10715 "Error when there is no default binding for a table key."
10717 (error "This key is has no function outside tables"))
10719 (defun orgtbl-setup ()
10720 "Setup orgtbl keymaps."
10724 '([(meta shift left)] org-table-delete-column)
10725 '([(meta left)] org-table-move-column-left)
10726 '([(meta right)] org-table-move-column-right)
10727 '([(meta shift right)] org-table-insert-column)
10728 '([(meta shift up)] org-table-kill-row)
10729 '([(meta shift down)] org-table-insert-row)
10730 '([(meta up)] org-table-move-row-up)
10731 '([(meta down)] org-table-move-row-down)
10732 '("\C-c\C-w" org-table-cut-region)
10733 '("\C-c\M-w" org-table-copy-region)
10734 '("\C-c\C-y" org-table-paste-rectangle)
10735 '("\C-c-" org-table-insert-hline)
10736 ; '([(shift tab)] org-table-previous-field)
10737 '("\C-m" org-table-next-row)
10738 (list (org-key 'S-return) 'org-table-copy-down)
10739 '([(meta return)] org-table-wrap-region)
10740 '("\C-c\C-q" org-table-wrap-region)
10741 '("\C-c?" org-table-current-column)
10742 '("\C-c " org-table-blank-field)
10743 '("\C-c+" org-table-sum)
10744 '("\C-c=" org-table-eval-formula)
10745 '("\C-c'" org-table-edit-formulas)
10746 '("\C-c`" org-table-edit-field)
10747 '("\C-c*" org-table-recalculate)
10748 '("\C-c|" org-table-create-or-convert-from-region)
10749 '("\C-c^" org-table-sort-lines)
10750 '([(control ?#)] org-table-rotate-recalc-marks)))
10752 (while (setq elt (pop bindings))
10753 (setq nfunc (1+ nfunc))
10754 (setq key (car elt)
10756 cmd (orgtbl-make-binding fun nfunc key))
10757 (define-key orgtbl-mode-map key cmd))
10758 ;; Special treatment needed for TAB and RET
10759 (define-key orgtbl-mode-map [(return)]
10760 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10761 (define-key orgtbl-mode-map "\C-m"
10762 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10763 (define-key orgtbl-mode-map [(tab)]
10764 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10765 (define-key orgtbl-mode-map "\C-i"
10766 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
10767 (define-key orgtbl-mode-map "\C-i"
10768 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
10769 (define-key orgtbl-mode-map "\C-c\C-c"
10770 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
10771 (when orgtbl-optimized
10772 ;; If the user wants maximum table support, we need to hijack
10773 ;; some standard editing functions
10774 (org-remap orgtbl-mode-map
10775 'self-insert-command 'orgtbl-self-insert-command
10776 'delete-char 'org-delete-char
10777 'delete-backward-char 'org-delete-backward-char)
10778 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
10779 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10781 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10782 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10783 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10784 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10786 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10787 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
10788 ["Copy Field from Above"
10789 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10792 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10793 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10794 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10795 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
10797 ["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])
10799 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10800 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10801 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10802 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10803 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10805 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10807 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10808 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10809 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10810 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10812 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10813 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10814 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10815 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10816 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10817 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10818 ["Sum Column/Rectangle" org-table-sum
10819 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10820 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10822 (setq org-table-formula-debug (not org-table-formula-debug))
10823 :style toggle :selected org-table-formula-debug]
10827 (defun orgtbl-tab (arg)
10828 "Justification and field motion for `orgtbl-mode'."
10830 (if arg (org-table-edit-field t)
10831 (org-table-justify-field-maybe)
10832 (org-table-next-field)))
10834 (defun orgtbl-ret ()
10835 "Justification and field motion for `orgtbl-mode'."
10837 (org-table-justify-field-maybe)
10838 (org-table-next-row))
10840 (defun orgtbl-self-insert-command (N)
10841 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10842 If the cursor is in a table looking at whitespace, the whitespace is
10843 overwritten, and the table is not marked as requiring realignment."
10845 (if (and (org-at-table-p)
10847 (and org-table-auto-blank-field
10848 (member last-command
10849 '(orgtbl-hijacker-command-100
10850 orgtbl-hijacker-command-101
10851 orgtbl-hijacker-command-102
10852 orgtbl-hijacker-command-103
10853 orgtbl-hijacker-command-104
10854 orgtbl-hijacker-command-105))
10855 (org-table-blank-field))
10858 (looking-at "[^|\n]* +|"))
10859 (let (org-table-may-need-update)
10860 (goto-char (1- (match-end 0)))
10861 (delete-backward-char 1)
10862 (goto-char (match-beginning 0))
10863 (self-insert-command N))
10864 (setq org-table-may-need-update t)
10866 (call-interactively (key-binding (vector last-input-event))))))
10868 (defun org-force-self-insert (N)
10869 "Needed to enforce self-insert under remapping."
10871 (self-insert-command N))
10875 (defconst org-level-max 20)
10877 (defun org-export-find-first-heading-line (list)
10878 "Remove all lines from LIST which are before the first headline."
10879 (let ((orig-list list)
10880 (re (concat "^" outline-regexp)))
10882 (not (string-match re (car list))))
10884 (or list orig-list)))
10886 (defun org-skip-comments (lines)
10887 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
10888 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
10889 (re2 "^\\(\\*+\\)[ \t\n\r]")
10891 (while (setq line (pop lines))
10893 ((and (string-match re1 line)
10894 (setq level (- (match-end 1) (match-beginning 1))))
10895 ;; Beginning of a COMMENT subtree. Skip it.
10896 (while (and (setq line (pop lines))
10897 (or (not (string-match re2 line))
10898 (> (- (match-end 1) (match-beginning 1)) level))))
10899 (setq lines (cons line lines)))
10900 ((string-match "^#" line)
10901 ;; an ordinary comment line
10903 ((and org-export-table-remove-special-lines
10904 (string-match "^[ \t]*| *[!_^] *|" line))
10905 ;; a special table line that should be removed
10907 (t (setq rtn (cons line rtn)))))
10912 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
10913 "Characters for underlining headings in ASCII export.")
10915 (defconst org-html-entities
10955 ("Aring") ("AA"."Å")
11044 ("varepsilon"."ε")
11057 ("sigmaf") ("varsigma"."ς")
11065 ("thetasym") ("vartheta"."ϑ")
11068 ("bull") ("bullet"."•")
11069 ("hellip") ("dots"."…")
11079 ("larr") ("leftarrow"."←") ("gets"."←")
11080 ("uarr") ("uparrow"."↑")
11081 ("rarr") ("to"."→") ("rightarrow"."→")
11082 ("darr")("downarrow"."↓")
11083 ("harr") ("leftrightarrow"."↔")
11084 ("crarr") ("hookleftarrow"."↵") ; has round hook, not quite CR
11085 ("lArr") ("Leftarrow"."⇐")
11086 ("uArr") ("Uparrow"."⇑")
11087 ("rArr") ("Rightarrow"."⇒")
11088 ("dArr") ("Downarrow"."⇓")
11089 ("hArr") ("Leftrightarrow"."⇔")
11091 ("part") ("partial"."∂")
11092 ("exist") ("exists"."∃")
11093 ("empty") ("emptyset"."∅")
11095 ("isin") ("in"."∈")
11101 ("lowast") ("ast"."∗")
11103 ("prop") ("proptp"."∝")
11104 ("infin") ("infty"."∞")
11105 ("ang") ("angle"."∠")
11106 ("and") ("vee"."∧")
11107 ("or") ("wedge"."∨")
11113 ("cong") ("simeq"."≅")
11114 ("asymp")("approx"."≈")
11115 ("ne") ("neq"."≠")
11119 ("sub") ("subset"."⊂")
11120 ("sup") ("supset"."⊃")
11127 ("sdot") ("cdot"."⋅")
11134 ("loz") ("Diamond"."◊")
11135 ("spades") ("spadesuit"."♠")
11136 ("clubs") ("clubsuit"."♣")
11137 ("hearts") ("diamondsuit"."♥")
11138 ("diams") ("diamondsuit"."♦")
11172 ("arccos"."arccos")
11173 ("arcsin"."arcsin")
11174 ("arctan"."arctan")
11191 ("liminf"."liminf")
11192 ("limsup"."limsup")
11205 "Entities for TeX->HTML translation.
11206 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
11207 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
11208 In that case, \"\\ent\" will be translated to \"&other;\".
11209 The list contains HTML entities for Latin-1, Greek and other symbols.
11210 It is supplemented by a number of commonly used TeX macros with appropriate
11211 translations. There is currently no way for users to extend this.")
11213 (defun org-cleaned-string-for-export (string)
11214 "Cleanup a buffer substring so that links can be created safely."
11216 (let* ((cb (current-buffer))
11217 (re-radio (and org-target-link-regexp
11218 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
11219 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
11220 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
11223 (set-buffer (get-buffer-create " org-mode-tmp"))
11227 ;; Find targets in comments and move them out of comments,
11228 ;; but mark them as targets that should be invisible
11229 (goto-char (point-min))
11230 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
11231 (replace-match "\\1(INVISIBLE)"))
11232 ;; Find matches for radio targets and turn them into internal links
11233 (goto-char (point-min))
11235 (while (re-search-forward re-radio nil t)
11236 (replace-match "\\1[[\\2]]")))
11237 ;; Find all links that contain a newline and put them into a single line
11238 (goto-char (point-min))
11239 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
11240 (replace-match "\\1 \\3")
11241 (goto-char (match-beginning 0)))
11242 ;; Normalize links: Convert angle and plain links into bracket links
11243 (goto-char (point-min))
11244 (while (re-search-forward re-plain-link nil t)
11247 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
11249 (goto-char (point-min))
11250 (while (re-search-forward re-angle-link nil t)
11253 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
11257 (goto-char (point-min))
11258 (while (re-search-forward "^#.*\n?" nil t)
11259 (replace-match ""))
11260 (setq rtn (buffer-string)))
11261 (kill-buffer " org-mode-tmp")
11264 (defun org-solidify-link-text (s &optional alist)
11265 "Take link text and make a safe target out of it."
11270 (org-split-string s "[ \t\r\n]+") "--"))
11271 (a (assoc rtn alist)))
11272 (or (cdr a) rtn))))
11274 (defun org-convert-to-odd-levels ()
11275 "Convert an org-mode file with all levels allowed to one with odd levels.
11276 This will leave level 1 alone, convert level 2 to level 3, level 3 to
11279 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
11280 (let ((org-odd-levels-only nil) n)
11282 (goto-char (point-min))
11283 (while (re-search-forward "^\\*\\*+" nil t)
11284 (setq n (1- (length (match-string 0))))
11285 (while (>= (setq n (1- n)) 0)
11287 (end-of-line 1))))))
11290 (defun org-convert-to-oddeven-levels ()
11291 "Convert an org-mode file with only odd levels to one with odd and even levels.
11292 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
11293 section with an even level, conversion would destroy the structure of the file. An error
11294 is signaled in this case."
11296 (goto-char (point-min))
11297 ;; First check if there are no even levels
11298 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
11299 (org-show-hierarchy-above)
11300 (error "Not all levels are odd in this file. Conversion not possible."))
11301 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
11302 (let ((org-odd-levels-only nil) n)
11304 (goto-char (point-min))
11305 (while (re-search-forward "^\\*\\*+" nil t)
11306 (setq n (/ (length (match-string 0)) 2))
11307 (while (>= (setq n (1- n)) 0)
11309 (end-of-line 1))))))
11311 (defun org-tr-level (n)
11312 "Make N odd if required."
11313 (if org-odd-levels-only (1+ (/ n 2)) n))
11315 (defvar org-last-level nil) ; dynamically scoped variable
11317 (defun org-export-as-ascii (arg)
11318 "Export the outline as a pretty ASCII file.
11319 If there is an active region, export only the region.
11320 The prefix ARG specifies how many levels of the outline should become
11321 underlined headlines. The default is 3."
11323 (setq-default org-todo-line-regexp org-todo-line-regexp)
11326 (if (org-region-active-p) (region-beginning) (point-min))
11327 (if (org-region-active-p) (region-end) (point-max))))
11328 (lines (org-export-find-first-heading-line
11331 (org-cleaned-string-for-export region)
11333 (org-startup-with-deadline-check nil)
11336 (case-fold-search nil)
11337 (filename (concat (file-name-sans-extension buffer-file-name)
11339 (buffer (find-file-noselect filename))
11340 (levels-open (make-vector org-level-max nil))
11341 (date (format-time-string "%Y/%m/%d" (current-time)))
11342 (time (format-time-string "%X" (org-current-time)))
11343 (author user-full-name)
11344 (title (buffer-name))
11346 (email user-mail-address)
11347 (language org-export-default-language)
11352 (setq org-last-level 1)
11353 (org-init-section-numbers)
11355 (find-file-noselect filename)
11357 ;; Search for the export key lines
11358 (org-parse-key-lines)
11360 (setq lang-words (or (assoc language org-export-language-setup)
11361 (assoc "en" org-export-language-setup)))
11362 (if org-export-ascii-show-new-buffer
11363 (switch-to-buffer-other-window buffer)
11364 (set-buffer buffer))
11367 (if options (org-parse-export-options options))
11368 (setq umax (if arg (prefix-numeric-value arg)
11369 org-export-headline-levels))
11372 (if title (org-insert-centered title ?=))
11374 (if (or author email)
11375 (insert (concat (nth 1 lang-words) ": " (or author "")
11376 (if email (concat " <" email ">") "")
11378 (if (and date time)
11379 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
11380 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
11384 (if org-export-with-toc
11386 (insert (nth 3 lang-words) "\n"
11387 (make-string (length (nth 3 lang-words)) ?=) "\n")
11388 (mapcar '(lambda (line)
11389 (if (string-match org-todo-line-regexp
11391 ;; This is a headline
11393 (setq level (- (match-end 1) (match-beginning 1))
11394 level (org-tr-level level)
11395 txt (match-string 3 line)
11397 (or (and (match-beginning 2)
11398 (not (equal (match-string 2 line)
11401 (and org-export-mark-todo-in-toc
11403 (org-search-todo-below
11404 line lines level))))
11405 (setq txt (org-html-expand-for-ascii txt))
11407 (if org-export-with-section-numbers
11408 (setq txt (concat (org-section-number level)
11410 (if (<= level umax)
11413 (make-string (* (1- level) 4) ?\ )
11414 (format (if todo "%s (*)\n" "%s\n") txt))
11415 (setq org-last-level level))
11419 (org-init-section-numbers)
11420 (while (setq line (pop lines))
11421 ;; Remove the quoted HTML tags.
11422 (setq line (org-html-expand-for-ascii line))
11424 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
11425 (setq line (replace-match "" t t line)))
11426 ;; Replace internal links
11427 (while (string-match org-bracket-link-regexp line)
11428 (setq line (replace-match
11429 (if (match-end 3) "[\\3]" "[\\1]")
11432 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11434 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
11435 txt (match-string 2 line))
11436 (org-ascii-level-start level txt umax))
11437 (t (insert line "\n"))))
11440 (goto-char (point-min))))
11442 (defun org-search-todo-below (line lines level)
11443 "Search the subtree below LINE for any TODO entries."
11444 (let ((rest (cdr (memq line lines)))
11445 (re org-todo-line-regexp)
11448 (while (setq line (pop rest))
11449 (if (string-match re line)
11451 (setq lv (- (match-end 1) (match-beginning 1))
11452 todo (and (match-beginning 2)
11453 (not (equal (match-string 2 line)
11454 org-done-string))))
11456 (if (<= lv level) (throw 'exit nil))
11457 (if todo (throw 'exit t))))))))
11459 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
11460 ;; We could also implement *bold*,/italic/ and _underline_ for ASCII export
11461 (defun org-html-expand-for-ascii (line)
11462 "Handle quoted HTML for ASCII export."
11463 (if org-export-html-expand
11464 (while (string-match "@<[^<>\n]*>" line)
11465 ;; We just remove the tags for now.
11466 (setq line (replace-match "" nil nil line))))
11469 (defun org-insert-centered (s &optional underline)
11470 "Insert the string S centered and underline it with character UNDERLINE."
11471 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
11472 (insert (make-string ind ?\ ) s "\n")
11474 (insert (make-string ind ?\ )
11475 (make-string (string-width s) underline)
11478 (defun org-ascii-level-start (level title umax)
11479 "Insert a new level in ASCII export."
11482 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
11483 (if (or (not (equal (char-before) ?\n))
11484 (not (equal (char-before (1- (point))) ?\n)))
11486 (setq char (nth (- umax level) (reverse org-ascii-underline)))
11487 (if org-export-with-section-numbers
11488 (setq title (concat (org-section-number level) " " title)))
11489 (insert title "\n" (make-string (string-width title) char) "\n"))))
11491 (defun org-export-copy-visible ()
11492 "Copy the visible part of the buffer to another buffer, for printing.
11493 Also removes the first line of the buffer if it specifies a mode,
11494 and all options lines."
11496 (let* ((filename (concat (file-name-sans-extension buffer-file-name)
11498 (buffer (find-file-noselect filename))
11500 (org-make-options-regexp
11501 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
11502 "STARTUP" "ARCHIVE"
11503 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
11504 (if org-noutline-p "\\(\n\\|$\\)" "")))
11506 (with-current-buffer buffer
11510 (setq s (goto-char (point-min)))
11511 (while (not (= (point) (point-max)))
11512 (goto-char (org-find-invisible))
11513 (append-to-buffer buffer s (point))
11514 (setq s (goto-char (org-find-visible)))))
11515 (switch-to-buffer-other-window buffer)
11517 (goto-char (point-min))
11518 (if (looking-at ".*-\\*- mode:.*\n")
11519 (replace-match ""))
11520 (while (re-search-forward ore nil t)
11521 (replace-match ""))
11522 (goto-char (point-min))))
11524 (defun org-find-visible ()
11525 (if (featurep 'noutline)
11527 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
11528 (get-char-property s 'invisible)))
11530 (skip-chars-forward "^\n")
11532 (defun org-find-invisible ()
11533 (if (featurep 'noutline)
11535 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
11536 (not (get-char-property s 'invisible))))
11538 (skip-chars-forward "^\r")
11543 (defun org-get-current-options ()
11544 "Return a string with current options as keyword options.
11545 Does include HTML export options as well as TODO and CATEGORY stuff."
11551 #+TEXT: Some descriptive text to be emitted. Several lines OK.
11552 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
11556 #+STARTUP: %s %s %s %s %s
11559 (buffer-name) (user-full-name) user-mail-address org-export-default-language
11560 org-export-headline-levels
11561 org-export-with-section-numbers
11562 org-export-with-toc
11563 org-export-preserve-breaks
11564 org-export-html-expand
11565 org-export-with-fixed-width
11566 org-export-with-tables
11567 org-export-with-sub-superscripts
11568 org-export-with-emphasize
11569 org-export-with-TeX-macros
11570 (file-name-nondirectory buffer-file-name)
11571 (if (equal org-todo-interpretation 'sequence)
11572 (mapconcat 'identity org-todo-keywords " ")
11573 "TODO FEEDBACK VERIFY DONE")
11574 (if (equal org-todo-interpretation 'type)
11575 (mapconcat 'identity org-todo-keywords " ")
11576 "Me Jason Marie DONE")
11577 (cdr (assoc org-startup-folded
11578 '((nil . "showall") (t . "overview") (content . "content"))))
11579 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
11580 (if org-odd-levels-only "odd" "oddeven")
11581 (if org-hide-leading-stars "hidestars" "showstars")
11582 (if org-startup-align-all-tables "align" "noalign")
11583 org-archive-location
11586 (defun org-insert-export-options-template ()
11587 "Insert into the buffer a template with information for exporting."
11589 (if (not (bolp)) (newline))
11590 (let ((s (org-get-current-options)))
11591 (and (string-match "#\\+CATEGORY" s)
11592 (setq s (substring s 0 (match-beginning 0))))
11595 (defun org-toggle-fixed-width-section (arg)
11596 "Toggle the fixed-width export.
11597 If there is no active region, the QUOTE keyword at the current headline is
11598 inserted or removed. When present, it causes the text between this headline
11599 and the next to be exported as fixed-width text, and unmodified.
11600 If there is an active region, this command adds or removes a colon as the
11601 first character of this line. If the first character of a line is a colon,
11602 this line is also exported in fixed-width font."
11605 (regionp (org-region-active-p))
11606 (beg (if regionp (region-beginning) (point)))
11607 (end (if regionp (region-end)))
11608 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
11609 (re "[ \t]*\\(:\\)")
11614 (setq cc (current-column))
11615 (beginning-of-line 1)
11616 (setq off (looking-at re))
11617 (while (> nlines 0)
11618 (setq nlines (1- nlines))
11619 (beginning-of-line 1)
11622 (move-to-column cc t)
11625 ((and off (looking-at re))
11626 (replace-match "" t t nil 1))
11627 ((not off) (move-to-column cc t) (insert ":")))
11630 (org-back-to-heading)
11631 (if (looking-at (concat outline-regexp
11632 "\\( +\\<" org-quote-string "\\>\\)"))
11633 (replace-match "" t t nil 1)
11634 (if (looking-at outline-regexp)
11636 (goto-char (match-end 0))
11637 (insert " " org-quote-string))))))))
11639 (defun org-export-as-html-and-open (arg)
11640 "Export the outline as HTML and immediately open it with a browser.
11641 If there is an active region, export only the region.
11642 The prefix ARG specifies how many levels of the outline should become
11643 headlines. The default is 3. Lower levels will become bulleted lists."
11645 (org-export-as-html arg 'hidden)
11646 (org-open-file buffer-file-name))
11648 (defun org-export-as-html-batch ()
11649 "Call `org-export-as-html', may be used in batch processing as
11651 --load=$HOME/lib/emacs/org.el
11652 --eval \"(setq org-export-headline-levels 2)\"
11653 --visit=MyFile --funcall org-export-as-html-batch"
11654 (org-export-as-html org-export-headline-levels 'hidden))
11656 (defun org-export-as-html (arg &optional hidden)
11657 "Export the outline as a pretty HTML file.
11658 If there is an active region, export only the region.
11659 The prefix ARG specifies how many levels of the outline should become
11660 headlines. The default is 3. Lower levels will become bulleted lists."
11662 (setq-default org-todo-line-regexp org-todo-line-regexp)
11663 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
11664 (setq-default org-done-string org-done-string)
11665 (let* ((style org-export-html-style)
11666 (odd org-odd-levels-only)
11667 (region-p (org-region-active-p))
11670 (if region-p (region-beginning) (point-min))
11671 (if region-p (region-end) (point-max))))
11673 (org-skip-comments (org-split-string
11674 (org-cleaned-string-for-export region)
11676 (lines (org-export-find-first-heading-line all_lines))
11677 (level 0) (line "") (origline "") txt todo
11679 (filename (concat (file-name-sans-extension buffer-file-name)
11681 (buffer (find-file-noselect filename))
11682 (levels-open (make-vector org-level-max nil))
11683 (date (format-time-string "%Y/%m/%d" (current-time)))
11684 (time (format-time-string "%X" (org-current-time)))
11685 (author user-full-name)
11686 (title (buffer-name))
11688 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
11691 (in-local-list nil)
11692 (local-list-num nil)
11693 (local-list-indent nil)
11694 (llt org-plain-list-ordered-item-terminator)
11695 (email user-mail-address)
11696 (language org-export-default-language)
11699 (target-alist nil) tg
11702 ;; FIXME: The following returns always nil under XEmacs
11703 (coding-system (and (fboundp 'coding-system-get)
11704 (boundp 'buffer-file-coding-system)
11705 buffer-file-coding-system))
11706 (coding-system-for-write (or coding-system coding-system-for-write))
11707 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
11708 (charset (and coding-system
11709 (coding-system-get coding-system 'mime-charset)))
11711 table-buffer table-orig-buffer
11712 ind start-is-num starter
11713 rpl path desc desc1 desc2 link
11715 (message "Exporting...")
11717 (setq org-last-level 1)
11718 (org-init-section-numbers)
11720 ;; Search for the export key lines
11721 (org-parse-key-lines)
11722 (setq lang-words (or (assoc language org-export-language-setup)
11723 (assoc "en" org-export-language-setup)))
11725 ;; Switch to the output buffer
11726 (if (or hidden (not org-export-html-show-new-buffer))
11727 (set-buffer buffer)
11728 (switch-to-buffer-other-window buffer))
11731 (let ((case-fold-search nil)
11732 (org-odd-levels-only odd))
11733 (if options (org-parse-export-options options))
11734 (setq umax (if arg (prefix-numeric-value arg)
11735 org-export-headline-levels))
11739 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
11740 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
11741 <html lang=\"%s\"><head>
11743 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
11744 <meta name=generator content=\"Org-mode\">
11745 <meta name=generated content=\"%s %s\">
11746 <meta name=author content=\"%s\">
11750 language (org-html-expand title) (or charset "iso-8859-1")
11751 date time author style))
11752 (if title (insert (concat "<H1 class=\"title\">"
11753 (org-html-expand title) "</H1>\n")))
11754 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
11755 (if email (insert (concat "<a href=\"mailto:" email "\"><"
11756 email "></a>\n")))
11757 (if (or author email) (insert "<br>\n"))
11758 (if (and date time) (insert (concat (nth 2 lang-words) ": "
11759 date " " time "<br>\n")))
11760 (if text (insert (concat "<p>\n" (org-html-expand text))))
11761 (if org-export-with-toc
11763 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
11766 (mapcar '(lambda (line)
11767 (if (string-match org-todo-line-regexp line)
11768 ;; This is a headline
11770 (setq level (- (match-end 1) (match-beginning 1))
11771 level (org-tr-level level)
11772 txt (save-match-data
11774 (match-string 3 line)))
11776 (or (and (match-beginning 2)
11777 (not (equal (match-string 2 line)
11780 (and org-export-mark-todo-in-toc
11782 (org-search-todo-below
11783 line lines level))))
11784 (if org-export-with-section-numbers
11785 (setq txt (concat (org-section-number level)
11787 (if (<= level umax)
11789 (setq head-count (+ head-count 1))
11790 (if (> level org-last-level)
11792 (setq cnt (- level org-last-level))
11793 (while (>= (setq cnt (1- cnt)) 0)
11796 (if (< level org-last-level)
11798 (setq cnt (- org-last-level level))
11799 (while (>= (setq cnt (1- cnt)) 0)
11802 ;; Check for targets
11803 (while (string-match org-target-regexp line)
11804 (setq tg (match-string 1 line)
11805 line (replace-match
11806 (concat "@<span class=\"target\">" tg "@</span> ")
11808 (push (cons (org-solidify-link-text tg)
11809 (format "sec-%d" head-count))
11811 (while (string-match "<\\(<\\)+\\|>\\(>\\)+" txt)
11812 (setq txt (replace-match "" t t txt)))
11816 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
11817 "<li><a href=\"#sec-%d\">%s</a>\n")
11820 (setq org-last-level level))
11824 (while (> org-last-level 0)
11825 (setq org-last-level (1- org-last-level))
11826 (insert "</ul>\n"))
11828 (setq head-count 0)
11829 (org-init-section-numbers)
11831 (while (setq line (pop lines) origline line)
11834 ;; end of quote section?
11835 (when (and inquote (string-match "^\\*+" line))
11836 (insert "</pre>\n")
11837 (setq inquote nil))
11838 ;; inside a quote section?
11840 (insert (org-html-protect line) "\n")
11841 (throw 'nextline nil))
11844 (when (and org-export-with-fixed-width
11845 (string-match "^[ \t]*:\\(.*\\)" line))
11846 (when (not infixed)
11848 (insert "<pre>\n"))
11849 (insert (org-html-protect (match-string 1 line)) "\n")
11851 (not (string-match "^[ \t]*\\(:.*\\)"
11854 (insert "</pre>\n"))
11855 (throw 'nextline nil))
11858 ;; make targets to anchors
11859 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
11862 (setq line (replace-match
11863 (concat "@<a name=\""
11864 (org-solidify-link-text (match-string 1 line))
11867 ((and org-export-with-toc (equal (string-to-char line) ?*))
11868 (setq line (replace-match
11869 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
11870 ; (concat "@<i>" (match-string 1 line) "@</i> ")
11873 (setq line (replace-match
11874 (concat "@<a name=\""
11875 (org-solidify-link-text (match-string 1 line))
11876 "\" class=\"target\">" (match-string 1 line) "@</a> ")
11879 ;; replace "&" by "&", "<" and ">" by "<" and ">"
11880 ;; handle @<..> HTML tags (replace "@>..<" by "<..>")
11881 (setq line (org-html-expand line))
11883 ;; Format the links
11885 (while (string-match org-bracket-link-analytic-regexp line start)
11886 (setq start (match-beginning 0))
11887 (setq type (if (match-end 2) (match-string 2 line) "internal"))
11888 (setq path (match-string 3 line))
11889 (setq desc1 (if (match-end 5) (match-string 5 line))
11890 desc2 (if (match-end 2) (concat type ":" path) path)
11891 desc (or desc1 desc2))
11893 ((equal type "internal")
11897 (org-solidify-link-text path target-alist)
11898 "\">" desc "</a>")))
11899 ((member type '("http" "https" "ftp" "mailto" "news"))
11901 (setq link (concat type ":" path))
11902 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
11903 ((string= type "file")
11905 (let* ((filename path)
11906 (abs-p (file-name-absolute-p filename))
11907 thefile file-is-image-p search)
11909 (if (string-match "::\\(.*\\)" filename)
11910 (setq search (match-string 1 filename)
11911 filename (replace-match "" nil nil filename)))
11912 (setq file-is-image-p
11913 (string-match (org-image-file-name-regexp) filename))
11914 (setq thefile (if abs-p (expand-file-name filename) filename))
11915 (when (and org-export-html-link-org-files-as-html
11916 (string-match "\\.org$" thefile))
11917 (setq thefile (concat (substring thefile 0
11918 (match-beginning 0))
11921 ;; make sure this is can be used as target search
11922 (not (string-match "^[0-9]*$" search))
11923 (not (string-match "^\\*" search))
11924 (not (string-match "^/.*/$" search)))
11925 (setq thefile (concat thefile "#"
11926 (org-solidify-link-text
11927 (org-link-unescape search)))))))
11928 (setq rpl (if (and org-export-html-inline-images
11930 (concat "<img src=\"" thefile "\"/>")
11931 (concat "<a href=\"" thefile "\">" desc "</a>")))))
11932 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell"))
11933 (setq rpl (concat "<i><" type ":"
11934 (save-match-data (org-link-unescape path))
11936 (setq line (replace-match rpl t t line)
11937 start (+ start (length rpl))))
11939 (if (and (string-match org-todo-line-regexp line)
11940 (match-beginning 2))
11941 (if (equal (match-string 2 line) org-done-string)
11942 (setq line (replace-match
11943 "<span class=\"done\">\\2</span>"
11945 (setq line (replace-match "<span class=\"todo\">\\2</span>"
11949 (if (string-match org-deadline-line-regexp line)
11951 (if (save-match-data
11952 (string-match "<a href"
11953 (substring line 0 (match-beginning 0))))
11954 nil ; Don't do the replacement - it is inside a link
11955 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
11956 nil nil line 1)))))
11958 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11959 ;; This is a headline
11960 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
11961 txt (match-string 2 line))
11962 (if (<= level umax) (setq head-count (+ head-count 1)))
11963 (when in-local-list
11964 ;; Close any local lists before inserting a new header line
11965 (while local-list-num
11966 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11967 (pop local-list-num))
11968 (setq local-list-indent nil
11969 in-local-list nil))
11970 (org-html-level-start level txt umax
11971 (and org-export-with-toc (<= level umax))
11974 (when (string-match quote-re line)
11978 ((and org-export-with-tables
11979 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
11980 (if (not table-open)
11981 ;; New table starts
11982 (setq table-open t table-buffer nil table-orig-buffer nil))
11983 ;; Accumulate lines
11984 (setq table-buffer (cons line table-buffer)
11985 table-orig-buffer (cons origline table-orig-buffer))
11986 (when (or (not lines)
11987 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
11989 (setq table-open nil
11990 table-buffer (nreverse table-buffer)
11991 table-orig-buffer (nreverse table-orig-buffer))
11992 (insert (org-format-table-html table-buffer table-orig-buffer))))
11995 (when (and (string-match
11997 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11998 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11999 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
12000 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
12002 (setq ind (org-get-string-indentation line)
12003 start-is-num (match-beginning 4)
12004 starter (if (match-beginning 2) (match-string 2 line))
12005 line (substring line (match-beginning 5)))
12006 (unless (string-match "[^ \t]" line)
12007 ;; empty line. Pretend indentation is large.
12008 (setq ind (1+ (or (car local-list-indent) 1))))
12009 (while (and in-local-list
12010 (or (and (= ind (car local-list-indent))
12012 (< ind (car local-list-indent))))
12013 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
12014 (pop local-list-num) (pop local-list-indent)
12015 (setq in-local-list local-list-indent))
12018 (or (not in-local-list)
12019 (> ind (car local-list-indent))))
12020 ;; Start new (level of ) list
12021 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
12022 (push start-is-num local-list-num)
12023 (push ind local-list-indent)
12024 (setq in-local-list t))
12026 ;; continue current list
12027 (insert "<li>\n"))))
12028 ;; Empty lines start a new paragraph. If hand-formatted lists
12029 ;; are not fully interpreted, lines starting with "-", "+", "*"
12030 ;; also start a new paragraph.
12031 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
12032 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
12034 (if org-export-html-with-timestamp
12035 (insert org-export-html-html-helper-timestamp))
12036 (insert "</body>\n</html>\n")
12039 (goto-char (point-min)))))
12041 (defun org-format-table-html (lines olines)
12042 "Find out which HTML converter to use and return the HTML code."
12043 (if (string-match "^[ \t]*|" (car lines))
12044 ;; A normal org table
12045 (org-format-org-table-html lines)
12046 ;; Table made by table.el - test for spanning
12047 (let* ((hlines (delq nil (mapcar
12049 (if (string-match "^[ \t]*\\+-" x) x
12052 (first (car hlines))
12053 (ll (and (string-match "\\S-+" first)
12054 (match-string 0 first)))
12055 (re (concat "^[ \t]*" (regexp-quote ll)))
12056 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
12058 (if (and (not spanning)
12059 (not org-export-prefer-native-exporter-for-tables))
12060 ;; We can use my own converter with HTML conversions
12061 (org-format-table-table-html lines)
12062 ;; Need to use the code generator in table.el, with the original text.
12063 (org-format-table-table-html-using-table-generate-source olines)))))
12065 (defun org-format-org-table-html (lines)
12066 "Format a table into HTML."
12067 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
12068 (setq lines (nreverse lines))
12069 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
12070 (setq lines (nreverse lines))
12071 (when org-export-table-remove-special-lines
12072 ;; Check if the table has a marking column. If yes remove the
12073 ;; column and the special lines
12079 (or (string-match "^[ \t]*|-" x)
12080 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
12087 (if (string-match "^[ \t]*| *[!_^] *|" x)
12088 nil ; ignore this line
12089 (and (or (string-match "^[ \t]*|-+\\+" x)
12090 (string-match "^[ \t]*|[^|]*|" x))
12091 (replace-match "|" t t x))))
12094 (let ((head (and org-export-highlight-first-table-line
12096 (lambda (x) (string-match "^[ \t]*|-" x))
12099 (setq html (concat org-export-html-table-tag "\n"))
12100 (while (setq line (pop lines))
12102 (if (string-match "^[ \t]*|-" line)
12104 (setq head nil) ;; head ends here, first time around
12105 ;; ignore this line
12106 (throw 'next-line t)))
12107 ;; Break the line into fields
12108 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
12112 (mapconcat (lambda (x)
12114 (concat "<th>" x "</th>")
12115 (concat "<td>" x "</td>")))
12118 (setq html (concat html "</table>\n"))
12121 (defun org-fake-empty-table-line (line)
12122 "Replace everything except \"|\" with spaces."
12123 (let ((i (length line))
12124 (newstr (copy-sequence line)))
12127 (if (not (eq (aref newstr i) ?|))
12128 (aset newstr i ?\ )))
12131 (defun org-format-table-table-html (lines)
12132 "Format a table generated by table.el into HTML.
12133 This conversion does *not* use `table-generate-source' from table.el.
12134 This has the advantage that Org-mode's HTML conversions can be used.
12135 But it has the disadvantage, that no cell- or row-spanning is allowed."
12136 (let (line field-buffer
12137 (head org-export-highlight-first-table-line)
12139 (setq html (concat org-export-html-table-tag "\n"))
12140 (while (setq line (pop lines))
12141 (setq empty " ")
12143 (if (string-match "^[ \t]*\\+-" line)
12152 (if (equal x "") (setq x empty))
12154 (concat "<th>" x "</th>\n")
12155 (concat "<td>" x "</td>\n")))
12159 (setq field-buffer nil)))
12160 ;; Ignore this line
12161 (throw 'next-line t)))
12162 ;; Break the line into fields and store the fields
12163 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
12165 (setq field-buffer (mapcar
12167 (concat x "<br>" (pop fields)))
12169 (setq field-buffer fields))))
12170 (setq html (concat html "</table>\n"))
12173 (defun org-format-table-table-html-using-table-generate-source (lines)
12174 "Format a table into html, using `table-generate-source' from table.el.
12175 This has the advantage that cell- or row-spanning is allowed.
12176 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
12178 (with-current-buffer (get-buffer-create " org-tmp1 ")
12180 (insert (mapconcat 'identity lines "\n"))
12181 (goto-char (point-min))
12182 (if (not (re-search-forward "|[^+]" nil t))
12183 (error "Error processing table"))
12184 (table-recognize-table)
12185 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
12186 (table-generate-source 'html " org-tmp2 ")
12187 (set-buffer " org-tmp2 ")
12188 (buffer-substring (point-min) (point-max))))
12190 (defun org-html-protect (s)
12191 ;; convert & to &, < to < and > to >
12193 (while (string-match "&" s start)
12194 (setq s (replace-match "&" t t s)
12195 start (1+ (match-beginning 0))))
12196 (while (string-match "<" s)
12197 (setq s (replace-match "<" t t s)))
12198 (while (string-match ">" s)
12199 (setq s (replace-match ">" t t s))))
12202 (defun org-html-expand (string)
12203 "Prepare STRING for HTML export. Applies all active conversions.
12204 If there are links in the string, don't modify these."
12206 (while (setq m (string-match org-bracket-link-regexp string))
12207 (setq s (substring string 0 m)
12208 l (match-string 0 string)
12209 string (substring string (match-end 0)))
12210 (push (org-html-do-expand s) res)
12212 (push (org-html-do-expand string) res)
12213 (apply 'concat (nreverse res))))
12215 (defun org-html-do-expand (s)
12216 "Apply all active conversions to translate special ASCII to HTML."
12217 (setq s (org-html-protect s))
12218 (if org-export-html-expand
12219 (while (string-match "@<\\([^&]*\\)>" s)
12220 (setq s (replace-match "<\\1>" nil nil s))))
12221 (if org-export-with-emphasize
12222 (setq s (org-export-html-convert-emphasize s)))
12223 (if org-export-with-sub-superscripts
12224 (setq s (org-export-html-convert-sub-super s)))
12225 (if org-export-with-TeX-macros
12226 (let ((start 0) wd ass)
12227 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
12228 (setq wd (match-string 1 s))
12229 (if (setq ass (assoc wd org-html-entities))
12230 (setq s (replace-match (or (cdr ass)
12231 (concat "&" (car ass) ";"))
12233 (setq start (+ start (length wd)))))))
12236 (defun org-create-multibrace-regexp (left right n)
12237 "Create a regular expression which will match a balanced sexp.
12238 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
12239 as single character strings.
12240 The regexp returned will match the entire expression including the
12241 delimiters. It will also define a single group which contains the
12242 match except for the outermost delimiters. The maximum depth of
12243 stacked delimiters is N. Escaping delimiters is not possible."
12244 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
12247 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
12250 re (concat re or next)
12251 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
12252 (concat left "\\(" re "\\)" right)))
12254 (defvar org-match-substring-regexp
12256 "\\([^\\]\\)\\([_^]\\)\\("
12257 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
12259 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
12261 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
12262 "The regular expression matching a sub- or superscript.")
12264 (defun org-export-html-convert-sub-super (string)
12265 "Convert sub- and superscripts in STRING to HTML."
12267 (while (string-match org-match-substring-regexp string)
12268 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
12269 (setq c (or (match-string 8 string)
12270 (match-string 6 string)
12271 (match-string 5 string)))
12272 (setq string (replace-match
12273 (concat (match-string 1 string)
12274 "<" key ">" c "</" key ">")
12276 (while (string-match "\\\\\\([_^]\\)" string)
12277 (setq string (replace-match (match-string 1 string) t t string))))
12280 ;(defun org-export-html-convert-emphasize (string)
12282 ; (while (string-match "\\(\\W\\|^\\)\\([*/_]\\)\\(\\w+\\)\\2\\(\\W\\|$\\)" string s)
12283 ; (setq c (cdr (assoc (match-string 2 string)
12284 ; '(("*" . "b") ("/" . "i") ("_" . "u"))))
12285 ; s (+ (match-end 0) 3)
12286 ; string (replace-match
12287 ; (concat "\\1<" c ">\\3</" c ">\\4") t nil string)))
12290 (defun org-export-html-convert-emphasize (string)
12291 (while (string-match org-italic-re string)
12292 (setq string (replace-match "\\1<i>\\3</i>\\4" t nil string)))
12293 (while (string-match org-bold-re string)
12294 (setq string (replace-match "\\1<b>\\3</b>\\4" t nil string)))
12295 (while (string-match org-underline-re string)
12296 (setq string (replace-match "\\1<u>\\3</u>\\4" t nil string)))
12299 (defun org-parse-key-lines ()
12300 "Find the special key lines with the information for exporters."
12303 (let ((re (org-make-options-regexp
12304 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
12306 (while (re-search-forward re nil t)
12307 (setq key (match-string 1))
12308 (cond ((string-equal key "TITLE")
12309 (setq title (match-string 2)))
12310 ((string-equal key "AUTHOR")
12311 (setq author (match-string 2)))
12312 ((string-equal key "EMAIL")
12313 (setq email (match-string 2)))
12314 ((string-equal key "LANGUAGE")
12315 (setq language (match-string 2)))
12316 ((string-equal key "TEXT")
12317 (setq text (concat text "\n" (match-string 2))))
12318 ((string-equal key "OPTIONS")
12319 (setq options (match-string 2))))))))
12321 (defun org-parse-export-options (s)
12322 "Parse the export options line."
12323 (let ((op '(("H" . org-export-headline-levels)
12324 ("num" . org-export-with-section-numbers)
12325 ("toc" . org-export-with-toc)
12326 ("\\n" . org-export-preserve-breaks)
12327 ("@" . org-export-html-expand)
12328 (":" . org-export-with-fixed-width)
12329 ("|" . org-export-with-tables)
12330 ("^" . org-export-with-sub-superscripts)
12331 ("*" . org-export-with-emphasize)
12332 ("TeX" . org-export-with-TeX-macros)))
12334 (while (setq o (pop op))
12335 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
12337 (set (make-local-variable (cdr o))
12338 (car (read-from-string (match-string 1 s))))))))
12340 (defun org-html-level-start (level title umax with-toc head-count)
12341 "Insert a new level in HTML export."
12342 (let ((l (1+ (max level umax))))
12343 (while (<= l org-level-max)
12344 (if (aref levels-open (1- l))
12346 (org-html-level-close l)
12347 (aset levels-open (1- l) nil)))
12351 (if (aref levels-open (1- level))
12352 (insert "<li>" title "<p>\n")
12353 (aset levels-open (1- level) t)
12354 (insert "<ul><li>" title "<p>\n")))
12355 (if org-export-with-section-numbers
12356 (setq title (concat (org-section-number level) " " title)))
12357 (setq level (+ level 1))
12359 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
12360 level head-count title level))
12361 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
12363 (defun org-html-level-close (&rest args)
12364 "Terminate one level in HTML export."
12367 ;; Variable holding the vector with section numbers
12368 (defvar org-section-numbers (make-vector org-level-max 0))
12370 (defun org-init-section-numbers ()
12371 "Initialize the vector for the section numbers."
12373 (numbers (nreverse (org-split-string "" "\\.")))
12374 (depth (1- (length org-section-numbers)))
12375 (i depth) number-string)
12378 (aset org-section-numbers i 0)
12379 (setq number-string (or (car numbers) "0"))
12380 (if (string-match "\\`[A-Z]\\'" number-string)
12381 (aset org-section-numbers i
12382 (- (string-to-char number-string) ?A -1))
12383 (aset org-section-numbers i (string-to-number number-string)))
12387 (defun org-section-number (&optional level)
12388 "Return a string with the current section number.
12389 When LEVEL is non-nil, increase section numbers on that level."
12390 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
12393 (aset org-section-numbers
12394 level (1+ (aref org-section-numbers level))))
12395 (setq idx (1+ level))
12396 (while (<= idx depth)
12397 (if (not (= idx 1))
12398 (aset org-section-numbers idx 0))
12399 (setq idx (1+ idx))))
12401 (while (<= idx depth)
12402 (setq n (aref org-section-numbers idx))
12403 (setq string (concat string (if (not (string= string "")) "." "")
12404 (int-to-string n)))
12405 (setq idx (1+ idx)))
12407 (if (string-match "\\`\\([@0]\\.\\)+" string)
12408 (setq string (replace-match "" nil nil string)))
12409 (if (string-match "\\(\\.0\\)+\\'" string)
12410 (setq string (replace-match "" nil nil string))))
12414 (defun org-export-icalendar-this-file ()
12415 "Export current file as an iCalendar file.
12416 The iCalendar file will be located in the same directory as the Org-mode
12417 file, but with extension `.ics'."
12419 (org-export-icalendar nil buffer-file-name))
12421 (defun org-export-as-xml ()
12422 "Export current buffer as XOXO XML buffer."
12424 (cond ((eq org-export-xml-type 'xoxo)
12425 (org-export-as-xoxo (current-buffer)))))
12427 (defun org-export-as-xoxo-insert-into (buffer &rest output)
12428 (with-current-buffer buffer
12429 (apply 'insert output)))
12431 (defun org-export-as-xoxo (&optional buffer)
12432 "Export the org buffer as XOXO.
12433 The XOXO buffer is named *xoxo-<source buffer name>*"
12434 (interactive (list (current-buffer)))
12435 ;; A quickie abstraction
12437 ;; Output everything as XOXO
12438 (with-current-buffer (get-buffer buffer)
12439 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
12440 (let* ((filename (concat (file-name-sans-extension buffer-file-name)
12442 (out (find-file-noselect filename))
12445 ;; Check the output buffer is empty.
12446 (with-current-buffer out (erase-buffer))
12447 ;; Kick off the output
12448 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
12449 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
12450 (let* ((hd (match-string-no-properties 1))
12451 (level (length hd))
12453 (match-string-no-properties 2)
12455 (goto-char (match-end 0))
12460 (if (looking-at "^[ \t]\\(.*\\)")
12461 (setq str (concat str (match-string-no-properties 1)))
12462 (throw 'loop str)))))))))
12464 ;; Handle level rendering
12466 ((> level last-level)
12467 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
12469 ((< level last-level)
12470 (dotimes (- (- last-level level) 1)
12472 (org-export-as-xoxo-insert-into out "</li>\n"))
12473 (org-export-as-xoxo-insert-into out "</ol>\n"))
12475 (org-export-as-xoxo-insert-into out "</li>\n")
12476 (setq hanging-li nil)))
12478 ((equal level last-level)
12480 (org-export-as-xoxo-insert-into out "</li>\n")))
12483 (setq last-level level)
12485 ;; And output the new li
12486 (setq hanging-li 't)
12487 (if (equal ?+ (elt text 0))
12488 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
12489 (org-export-as-xoxo-insert-into out "<li>" text))))
12491 ;; Finally finish off the ol
12492 (dotimes (- last-level 1)
12494 (org-export-as-xoxo-insert-into out "</li>\n"))
12495 (org-export-as-xoxo-insert-into out "</ol>\n"))
12497 ;; Finish the buffer off and clean it up.
12498 (switch-to-buffer-other-window out)
12499 (indent-region (point-min) (point-max))
12501 (goto-char (point-min))
12505 (defun org-export-icalendar-all-agenda-files ()
12506 "Export all files in `org-agenda-files' to iCalendar .ics files.
12507 Each iCalendar file will be located in the same directory as the Org-mode
12508 file, but with extension `.ics'."
12510 (apply 'org-export-icalendar nil (org-agenda-files t)))
12513 (defun org-export-icalendar-combine-agenda-files ()
12514 "Export all files in `org-agenda-files' to a single combined iCalendar file.
12515 The file is stored under the name `org-combined-agenda-icalendar-file'."
12517 (apply 'org-export-icalendar t (org-agenda-files t)))
12519 (defun org-export-icalendar (combine &rest files)
12520 "Create iCalendar files for all elements of FILES.
12521 If COMBINE is non-nil, combine all calendar entries into a single large
12522 file and store it under the name `org-combined-agenda-icalendar-file'."
12524 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
12526 (setq ical-file org-combined-agenda-icalendar-file
12527 ical-buffer (org-get-agenda-file-buffer ical-file))
12528 (set-buffer ical-buffer) (erase-buffer))
12529 (while (setq file (pop files))
12531 (org-check-agenda-file file)
12533 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
12534 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
12535 (set-buffer ical-buffer) (erase-buffer))
12536 (set-buffer (org-get-agenda-file-buffer file))
12537 (setq category (or org-category
12538 (file-name-sans-extension
12539 (file-name-nondirectory buffer-file-name))))
12540 (if (symbolp category) (setq category (symbol-name category)))
12541 (let ((standard-output ical-buffer))
12543 (and (not started) (setq started t)
12544 (org-start-icalendar-file org-icalendar-combined-name))
12545 (org-start-icalendar-file category))
12546 (org-print-icalendar-entries combine category)
12547 (when (or (and combine (not files)) (not combine))
12548 (org-finish-icalendar-file)
12549 (set-buffer ical-buffer)
12551 (run-hooks 'org-after-save-iCalendar-file-hook)))))
12552 (org-release-buffers org-agenda-new-buffers))))
12554 (defvar org-after-save-iCalendar-file-hook nil
12555 "Hook run after an iCalendar file has been saved.
12556 The iCalendar buffer is still current when this hook is run.
12557 A good way to use this is to tell a desktop calenndar application to re-read
12558 the iCalendar file.")
12560 (defun org-print-icalendar-entries (&optional combine category)
12561 "Print iCalendar entries for the current Org-mode file to `standard-output'.
12562 When COMBINE is non nil, add the category to each line."
12563 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
12564 (dts (org-ical-ts-to-string
12565 (format-time-string (cdr org-time-stamp-formats) (current-time))
12567 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
12569 (goto-char (point-min))
12570 (while (re-search-forward org-ts-regexp nil t)
12571 (setq pos (match-beginning 0)
12572 ts (match-string 0)
12574 hd (org-get-heading))
12575 (if (looking-at re2)
12577 (goto-char (match-end 0))
12578 (setq ts2 (match-string 1) inc nil))
12580 tmp (buffer-substring (max (point-min)
12581 (- pos org-ds-keyword-length))
12583 deadlinep (string-match org-deadline-regexp tmp)
12584 scheduledp (string-match org-scheduled-regexp tmp)
12585 ;; donep (org-entry-is-done-p)
12587 (if (or (string-match org-tr-regexp hd)
12588 (string-match org-ts-regexp hd))
12589 (setq hd (replace-match "" t t hd)))
12591 (setq hd (concat hd " (category " category ")")))
12592 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
12593 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
12594 (princ (format "BEGIN:VEVENT
12599 (org-ical-ts-to-string ts "DTSTART")
12600 (org-ical-ts-to-string ts2 "DTEND" inc)
12602 (when org-icalendar-include-todo
12603 (goto-char (point-min))
12604 (while (re-search-forward org-todo-line-regexp nil t)
12605 (setq state (match-string 1))
12606 (unless (equal state org-done-string)
12607 (setq hd (match-string 3))
12608 (if (string-match org-priority-regexp hd)
12609 (setq pri (string-to-char (match-string 2 hd))
12610 hd (concat (substring hd 0 (match-beginning 1))
12611 (substring hd (- (match-end 1)))))
12612 (setq pri org-default-priority))
12613 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
12614 (- org-lowest-priority ?A))))))
12616 (princ (format "BEGIN:VTODO
12624 (defun org-start-icalendar-file (name)
12625 "Start an iCalendar file by inserting the header."
12626 (let ((user user-full-name)
12627 (name (or name "unknown"))
12628 (timezone (cadr (current-time-zone))))
12630 (format "BEGIN:VCALENDAR
12633 PRODID:-//%s//Emacs with Org-mode//EN
12635 CALSCALE:GREGORIAN\n" name user timezone))))
12637 (defun org-finish-icalendar-file ()
12638 "Finish an iCalendar file by inserting the END statement."
12639 (princ "END:VCALENDAR\n"))
12641 (defun org-ical-ts-to-string (s keyword &optional inc)
12642 "Take a time string S and convert it to iCalendar format.
12643 KEYWORD is added in front, to make a complete line like DTSTART....
12644 When INC is non-nil, increase the hour by two (if time string contains
12645 a time), or the day by one (if it does not contain a time)."
12646 (let ((t1 (org-parse-time-string s 'nodefault))
12647 t2 fmt have-time time)
12648 (if (and (car t1) (nth 1 t1) (nth 2 t1))
12649 (setq t2 t1 have-time t)
12650 (setq t2 (org-parse-time-string s)))
12651 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
12652 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
12654 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
12655 (setq time (encode-time s mi h d m y)))
12656 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
12657 (concat keyword (format-time-string fmt time))))
12662 ;; - Bindings in Org-mode map are currently
12663 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
12664 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
12665 ;; e (?) useful from outline-mode
12666 ;; i k @ expendable from outline-mode
12667 ;; 0123456789 % & ()_{} " ` free
12669 ;; Make `C-c C-x' a prefix key
12670 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
12672 ;; TAB key with modifiers
12673 (define-key org-mode-map "\C-i" 'org-cycle)
12674 (define-key org-mode-map [(tab)] 'org-cycle)
12675 (define-key org-mode-map [(meta tab)] 'org-complete)
12676 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
12677 ;; The following line is necessary under Suse GNU/Linux
12678 (unless (featurep 'xemacs)
12679 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
12680 (define-key org-mode-map [(shift tab)] 'org-shifttab)
12682 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
12683 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
12684 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12685 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
12686 (define-key org-mode-map [(meta return)] 'org-meta-return)
12687 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
12688 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
12690 ;; Cursor keys with modifiers
12691 (define-key org-mode-map [(meta left)] 'org-metaleft)
12692 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
12693 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
12694 (define-key org-mode-map [(meta right)] 'org-metaright)
12695 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
12696 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
12697 (define-key org-mode-map [(meta up)] 'org-metaup)
12698 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
12699 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
12700 (define-key org-mode-map [(meta down)] 'org-metadown)
12701 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
12702 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
12704 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12705 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
12706 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
12707 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
12708 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
12709 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
12710 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
12711 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
12712 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
12713 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
12714 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
12715 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
12716 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
12717 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
12718 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
12719 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
12721 ;; All the other keys
12722 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
12723 (define-key org-mode-map "\C-c\C-j" 'org-goto)
12724 (define-key org-mode-map "\C-c\C-t" 'org-todo)
12725 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
12726 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
12727 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
12728 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12729 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
12730 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
12731 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12732 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
12733 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
12734 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
12735 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
12736 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
12737 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
12738 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
12739 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12740 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12741 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12742 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12743 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
12744 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
12745 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12746 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
12747 (define-key org-mode-map "\C-c]" 'org-remove-file)
12748 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
12749 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
12750 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
12751 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12752 (define-key org-mode-map "\C-m" 'org-return)
12753 (define-key org-mode-map "\C-c?" 'org-table-current-column)
12754 (define-key org-mode-map "\C-c " 'org-table-blank-field)
12755 (define-key org-mode-map "\C-c+" 'org-table-sum)
12756 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
12757 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
12758 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
12759 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12760 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
12761 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12762 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
12763 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12764 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
12765 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
12766 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
12767 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
12768 ;; OPML support is only an option for the future
12769 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
12770 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
12771 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
12772 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
12773 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
12774 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
12775 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
12776 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12777 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
12778 (define-key org-mode-map "\C-c\C-xx" 'org-export-as-xml)
12779 (define-key org-mode-map "\C-c\C-x\C-x" 'org-export-as-xml)
12780 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
12781 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
12783 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
12784 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12785 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12786 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12788 (defsubst org-table-p () (org-at-table-p))
12790 (defun org-self-insert-command (N)
12791 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12792 If the cursor is in a table looking at whitespace, the whitespace is
12793 overwritten, and the table is not marked as requiring realignment."
12795 (if (and (org-table-p)
12797 ;; check if we blank the field, and if that triggers align
12798 (and org-table-auto-blank-field
12799 (member last-command
12800 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12801 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12802 ;; got extra space, this field does not determine column width
12803 (let (org-table-may-need-update) (org-table-blank-field))
12804 ;; no extra space, this field may determine column width
12805 (org-table-blank-field)))
12808 (looking-at "[^|\n]* |"))
12809 (let (org-table-may-need-update)
12810 (goto-char (1- (match-end 0)))
12811 (delete-backward-char 1)
12812 (goto-char (match-beginning 0))
12813 (self-insert-command N))
12814 (setq org-table-may-need-update t)
12815 (self-insert-command N)))
12817 (defun org-delete-backward-char (N)
12818 "Like `delete-backward-char', insert whitespace at field end in tables.
12819 When deleting backwards, in tables this function will insert whitespace in
12820 front of the next \"|\" separator, to keep the table aligned. The table will
12821 still be marked for re-alignment if the field did fill the entire column,
12822 because, in this case the deletion might narrow the column."
12824 (if (and (org-table-p)
12826 (string-match "|" (buffer-substring (point-at-bol) (point)))
12827 (looking-at ".*?|"))
12828 (let ((pos (point))
12829 (noalign (looking-at "[^|\n\r]* |"))
12830 (c org-table-may-need-update))
12831 (backward-delete-char N)
12832 (skip-chars-forward "^|")
12834 (goto-char (1- pos))
12835 ;; noalign: if there were two spaces at the end, this field
12836 ;; does not determine the width of the column.
12837 (if noalign (setq org-table-may-need-update c)))
12838 (backward-delete-char N)))
12840 (defun org-delete-char (N)
12841 "Like `delete-char', but insert whitespace at field end in tables.
12842 When deleting characters, in tables this function will insert whitespace in
12843 front of the next \"|\" separator, to keep the table aligned. The table will
12844 still be marked for re-alignment if the field did fill the entire column,
12845 because, in this case the deletion might narrow the column."
12847 (if (and (org-table-p)
12849 (not (= (char-after) ?|))
12851 (if (looking-at ".*?|")
12852 (let ((pos (point))
12853 (noalign (looking-at "[^|\n\r]* |"))
12854 (c org-table-may-need-update))
12855 (replace-match (concat
12856 (substring (match-string 0) 1 -1)
12859 ;; noalign: if there were two spaces at the end, this field
12860 ;; does not determine the width of the column.
12861 (if noalign (setq org-table-may-need-update c))))
12864 ;; How to do this: Measure non-white length of current string
12865 ;; If equal to column width, we should realign.
12867 (defun org-remap (map &rest commands)
12868 "In MAP, remap the functions given in COMMANDS.
12869 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12872 (setq old (pop commands) new (pop commands))
12873 (if (fboundp 'command-remapping)
12874 (define-key map (vector 'remap old) new)
12875 (substitute-key-definition old new map global-map)))))
12877 (when (eq org-enable-table-editor 'optimized)
12878 ;; If the user wants maximum table support, we need to hijack
12879 ;; some standard editing functions
12880 (org-remap org-mode-map
12881 'self-insert-command 'org-self-insert-command
12882 'delete-char 'org-delete-char
12883 'delete-backward-char 'org-delete-backward-char)
12884 (define-key org-mode-map "|" 'org-force-self-insert))
12886 (defun org-shiftcursor-error ()
12887 "Throw an error because Shift-Cursor command was applied in wrong context."
12888 (error "This command is active in special context like tables, headlines or timestamps"))
12890 (defun org-shifttab ()
12891 "Global visibility cycling or move to previous table field.
12892 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
12893 See the individual commands for more information."
12896 ((org-at-table-p) (org-table-previous-field))
12897 (t (org-cycle '(4)))))
12899 (defun org-shiftmetaleft ()
12900 "Promote subtree or delete table column.
12901 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
12902 See the individual commands for more information."
12905 ((org-at-table-p) (org-table-delete-column))
12906 ((org-on-heading-p) (org-promote-subtree))
12907 ((org-at-item-p) (call-interactively 'org-outdent-item))
12908 (t (org-shiftcursor-error))))
12910 (defun org-shiftmetaright ()
12911 "Demote subtree or insert table column.
12912 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
12913 See the individual commands for more information."
12916 ((org-at-table-p) (org-table-insert-column))
12917 ((org-on-heading-p) (org-demote-subtree))
12918 ((org-at-item-p) (call-interactively 'org-indent-item))
12919 (t (org-shiftcursor-error))))
12921 (defun org-shiftmetaup (&optional arg)
12922 "Move subtree up or kill table row.
12923 Calls `org-move-subtree-up' or `org-table-kill-row' or
12924 `org-move-item-up' depending on context. See the individual commands
12925 for more information."
12928 ((org-at-table-p) (org-table-kill-row))
12929 ((org-on-heading-p) (org-move-subtree-up arg))
12930 ((org-at-item-p) (org-move-item-up arg))
12931 (t (org-shiftcursor-error))))
12932 (defun org-shiftmetadown (&optional arg)
12933 "Move subtree down or insert table row.
12934 Calls `org-move-subtree-down' or `org-table-insert-row' or
12935 `org-move-item-down', depending on context. See the individual
12936 commands for more information."
12939 ((org-at-table-p) (org-table-insert-row arg))
12940 ((org-on-heading-p) (org-move-subtree-down arg))
12941 ((org-at-item-p) (org-move-item-down arg))
12942 (t (org-shiftcursor-error))))
12944 (defun org-metaleft (&optional arg)
12945 "Promote heading or move table column to left.
12946 Calls `org-do-promote' or `org-table-move-column', depending on context.
12947 With no specific context, calls the Emacs default `backward-word'.
12948 See the individual commands for more information."
12951 ((org-at-table-p) (org-table-move-column 'left))
12952 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
12953 (t (backward-word (prefix-numeric-value arg)))))
12955 (defun org-metaright (&optional arg)
12956 "Demote subtree or move table column to right.
12957 Calls `org-do-demote' or `org-table-move-column', depending on context.
12958 With no specific context, calls the Emacs default `forward-word'.
12959 See the individual commands for more information."
12962 ((org-at-table-p) (org-table-move-column nil))
12963 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
12964 (t (forward-word (prefix-numeric-value arg)))))
12966 (defun org-metaup (&optional arg)
12967 "Move subtree up or move table row up.
12968 Calls `org-move-subtree-up' or `org-table-move-row' or
12969 `org-move-item-up', depending on context. See the individual commands
12970 for more information."
12973 ((org-at-table-p) (org-table-move-row 'up))
12974 ((org-on-heading-p) (org-move-subtree-up arg))
12975 ((org-at-item-p) (org-move-item-up arg))
12976 (t (org-shiftcursor-error))))
12978 (defun org-metadown (&optional arg)
12979 "Move subtree down or move table row down.
12980 Calls `org-move-subtree-down' or `org-table-move-row' or
12981 `org-move-item-down', depending on context. See the individual
12982 commands for more information."
12985 ((org-at-table-p) (org-table-move-row nil))
12986 ((org-on-heading-p) (org-move-subtree-down arg))
12987 ((org-at-item-p) (org-move-item-down arg))
12988 (t (org-shiftcursor-error))))
12990 (defun org-shiftup (&optional arg)
12991 "Increase item in timestamp or increase priority of current item.
12992 Calls `org-timestamp-up' or `org-priority-up', depending on context.
12993 See the individual commands for more information."
12996 ((org-at-timestamp-p) (org-timestamp-up arg))
12997 (t (org-priority-up))))
12999 (defun org-shiftdown (&optional arg)
13000 "Decrease item in timestamp or decrease priority of current item.
13001 Calls `org-timestamp-down' or `org-priority-down', depending on context.
13002 See the individual commands for more information."
13005 ((org-at-timestamp-p) (org-timestamp-down arg))
13006 (t (org-priority-down))))
13008 (defun org-shiftright ()
13009 "Next TODO keyword or timestamp one day later, depending on context."
13012 ((org-at-timestamp-p) (org-timestamp-up-day))
13013 ((org-on-heading-p) (org-todo 'right))
13014 (t (org-shiftcursor-error))))
13016 (defun org-shiftleft ()
13017 "Previous TODO keyword or timestamp one day earlier, depending on context."
13020 ((org-at-timestamp-p) (org-timestamp-down-day))
13021 ((org-on-heading-p) (org-todo 'left))
13022 (t (org-shiftcursor-error))))
13024 (defun org-copy-special ()
13025 "Copy region in table or copy current subtree.
13026 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13027 See the individual commands for more information."
13029 (call-interactively
13030 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13032 (defun org-cut-special ()
13033 "Cut region in table or cut current subtree.
13034 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13035 See the individual commands for more information."
13037 (call-interactively
13038 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13040 (defun org-paste-special (arg)
13041 "Paste rectangular region into table, or past subtree relative to level.
13042 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13043 See the individual commands for more information."
13045 (if (org-at-table-p)
13046 (org-table-paste-rectangle)
13047 (org-paste-subtree arg)))
13049 (defun org-ctrl-c-ctrl-c (&optional arg)
13050 "Set tags in headline, or update according to changed information at point.
13052 This command does many different things, depending on context:
13054 - If the cursor is in a headline, prompt for tags and insert them
13055 into the current line, aligned to `org-tags-column'. When called
13056 with prefix arg, realign all tags in the current buffer.
13058 - If the cursor is in one of the special #+KEYWORD lines, this
13059 triggers scanning the buffer for these lines and updating the
13062 - If the cursor is inside a table, realign the table. This command
13063 works even if the automatic table editor has been turned off.
13065 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13068 - If the cursor is inside a table created by the table.el package,
13069 activate that table.
13071 - If the current buffer is a remember buffer, close note and file it.
13072 with a prefix argument, file it without further interaction to the default
13075 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13076 links in this buffer.
13078 - If the cursor is on a numbered item in a plain list, renumber the
13081 (let ((org-enable-table-editor t))
13083 ((and (local-variable-p 'org-finish-function (current-buffer))
13084 (fboundp org-finish-function))
13085 (funcall org-finish-function))
13086 ((org-on-target-p) (org-update-radio-target-regexp))
13087 ((org-on-heading-p) (org-set-tags arg))
13088 ((org-at-table.el-p)
13090 (beginning-of-line 1)
13091 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13092 (table-recognize-table))
13094 (org-table-maybe-eval-formula)
13096 (org-table-recalculate t)
13097 (org-table-maybe-recalculate-line))
13100 (org-renumber-ordered-list (prefix-numeric-value arg)))
13101 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13103 ((equal (match-string 1) "TBLFM")
13104 ;; Recalculate the table before this line
13106 (beginning-of-line 1)
13107 (skip-chars-backward " \r\n\t")
13108 (if (org-at-table-p) (org-table-recalculate t))))
13110 (org-mode-restart))))
13111 (t (error "C-c C-c can do nothing useful at this location.")))))
13113 (defun org-mode-restart ()
13114 "Restart Org-mode, to scan again for special lines.
13115 Also updates the keyword regular expressions."
13117 (let ((org-inhibit-startup t)) (org-mode))
13118 (message "Org-mode restarted to refresh keyword and special line setup"))
13120 (defun org-return ()
13121 "Goto next table row or insert a newline.
13122 Calls `org-table-next-row' or `newline', depending on context.
13123 See the individual commands for more information."
13127 (org-table-justify-field-maybe)
13128 (org-table-next-row))
13131 (defun org-meta-return (&optional arg)
13132 "Insert a new heading or wrap a region in a table.
13133 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13134 See the individual commands for more information."
13138 (org-table-wrap-region arg))
13139 (t (org-insert-heading arg))))
13143 ;; Define the Org-mode menus
13144 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13146 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
13147 ["Next Field" org-cycle (org-at-table-p)]
13148 ["Previous Field" org-shifttab (org-at-table-p)]
13149 ["Next Row" org-return (org-at-table-p)]
13151 ["Blank Field" org-table-blank-field (org-at-table-p)]
13152 ["Edit Field" org-table-edit-field (org-at-table-p)]
13153 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13156 ["Move Column Left" org-metaleft (org-at-table-p)]
13157 ["Move Column Right" org-metaright (org-at-table-p)]
13158 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13159 ["Insert Column" org-shiftmetaright (org-at-table-p)]
13161 ["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])
13163 ["Move Row Up" org-metaup (org-at-table-p)]
13164 ["Move Row Down" org-metadown (org-at-table-p)]
13165 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13166 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13167 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13169 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
13171 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13172 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13173 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13174 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13177 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13178 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13179 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
13181 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13182 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13183 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13185 ["Sum Column/Rectangle" org-table-sum
13186 (or (org-at-table-p) (org-region-active-p))]
13187 ["Which Column?" org-table-current-column (org-at-table-p)])
13189 (setq org-table-formula-debug (not org-table-formula-debug))
13190 :style toggle :selected org-table-formula-debug]
13192 ["Create" org-table-create (and (not (org-at-table-p))
13193 org-enable-table-editor)]
13194 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13195 ["Import from File" org-table-import (not (org-at-table-p))]
13196 ["Export to File" org-table-export (org-at-table-p)]
13198 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13200 (easy-menu-define org-org-menu org-mode-map "Org menu"
13202 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
13203 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
13204 ["Sparse Tree" org-occur t]
13205 ["Show All" show-all t]
13207 ["New Heading" org-insert-heading t]
13208 ("Navigate Headings"
13209 ["Up" outline-up-heading t]
13210 ["Next" outline-next-visible-heading t]
13211 ["Previous" outline-previous-visible-heading t]
13212 ["Next Same Level" outline-forward-same-level t]
13213 ["Previous Same Level" outline-backward-same-level t]
13215 ["Jump" org-goto t])
13217 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13218 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13220 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13221 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13222 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13224 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13225 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13226 ["Demote Heading" org-metaright (not (org-at-table-p))]
13227 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13229 ["Archive Subtree" org-archive-subtree t]
13231 ["Convert to odd levels" org-convert-to-odd-levels t]
13232 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13235 ["TODO/DONE/-" org-todo t]
13236 ["Show TODO Tree" org-show-todo-tree t]
13237 ["Global TODO list" org-todo-list t]
13239 ["Set Priority" org-priority t]
13240 ["Priority Up" org-shiftup t]
13241 ["Priority Down" org-shiftdown t])
13242 ("Dates and Scheduling"
13243 ["Timestamp" org-time-stamp t]
13244 ["Timestamp (inactive)" org-time-stamp-inactive t]
13246 ["1 Day Later" org-timestamp-up-day t]
13247 ["1 Day Earlier" org-timestamp-down-day t]
13248 ["1 ... Later" org-shiftup t]
13249 ["1 ... Earlier" org-shiftdown t])
13250 ["Compute Time Range" org-evaluate-time-range t]
13251 ["Schedule Item" org-schedule t]
13252 ["Deadline" org-deadline t]
13254 ["Goto Calendar" org-goto-calendar t]
13255 ["Date from Calendar" org-date-from-calendar t])
13257 ["Agenda Command" org-agenda t]
13258 ("File List for Agenda")
13259 ("Special views current file"
13260 ["TODO Tree" org-show-todo-tree t]
13261 ["Check Deadlines" org-check-deadlines t]
13262 ["Timeline" org-timeline t]
13263 ["Tags Tree" org-tags-sparse-tree t])
13266 ["Store Link (Global)" org-store-link t]
13267 ["Insert Link" org-insert-link t]
13268 ["Follow Link" org-open-at-point t]
13270 ["Descriptive Links"
13271 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13272 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
13275 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13276 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
13278 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
13279 (save-excursion (goto-char (point-min))
13280 (re-search-forward "<[a-z]+:" nil t))])
13283 ["ASCII" org-export-as-ascii t]
13284 ["Extract Visible Text" org-export-copy-visible t]
13285 ["HTML" org-export-as-html t]
13286 ["HTML and Open" org-export-as-html-and-open t]
13287 ["XML (XOXO)" org-export-as-xml t]
13289 ["iCalendar this file" org-export-icalendar-this-file t]
13290 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
13291 :active t :keys "C-c C-x C-i"]
13292 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
13294 ["Option Template" org-insert-export-options-template t]
13295 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
13298 ["Show Version" org-version t]
13299 ["Info Documentation" org-info t])
13301 ["Browse Org Group" org-customize t]
13303 ["Expand This Menu" org-create-customize-menu
13304 (fboundp 'customize-menu-create)])
13306 ["Refresh setup" org-mode-restart t]
13309 (defun org-info (&optional node)
13310 "Read documentation for Org-mode in the info system.
13311 With optional NODE, go directly to that node."
13314 (Info-goto-node (format "(org)%s" (or node ""))))
13316 (defun org-install-agenda-files-menu ()
13317 (let ((bl (buffer-list)))
13320 (set-buffer (pop bl))
13321 (if (eq major-mode 'org-mode) (setq bl nil)))
13322 (when (eq major-mode 'org-mode)
13324 '("Org") "File List for Agenda"
13327 ["Edit File List" (org-edit-agenda-file-list) t]
13328 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13329 ["Remove Current File from List" org-remove-file t]
13330 ["Cycle through agenda files" org-cycle-agenda-files t]
13332 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13336 (defun org-customize ()
13337 "Call the customize function with org as argument."
13339 (customize-browse 'org))
13341 (defun org-create-customize-menu ()
13342 "Create a full customization menu for Org-mode, insert it into the menu."
13344 (if (fboundp 'customize-menu-create)
13347 '("Org") "Customize"
13348 `(["Browse Org group" org-customize t]
13350 ,(customize-menu-create 'org)
13351 ["Set" Custom-set t]
13352 ["Save" Custom-save t]
13353 ["Reset to Current" Custom-reset-current t]
13354 ["Reset to Saved" Custom-reset-saved t]
13355 ["Reset to Standard Settings" Custom-reset-standard t]))
13356 (message "\"Org\"-menu now contains full customization menu"))
13357 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13359 ;;; Miscellaneous stuff
13361 (defun org-move-line-down (arg)
13362 "Move the current line down. With prefix argument, move it past ARG lines."
13364 (let ((col (current-column))
13366 (beginning-of-line 1) (setq beg (point))
13367 (beginning-of-line 2) (setq end (point))
13368 (beginning-of-line (+ 1 arg))
13369 (setq pos (move-marker (make-marker) (point)))
13370 (insert (delete-and-extract-region beg end))
13372 (move-to-column col)))
13374 (defun org-move-line-up (arg)
13375 "Move the current line up. With prefix argument, move it past ARG lines."
13377 (let ((col (current-column))
13379 (beginning-of-line 1) (setq beg (point))
13380 (beginning-of-line 2) (setq end (point))
13381 (beginning-of-line (- arg))
13382 (setq pos (move-marker (make-marker) (point)))
13383 (insert (delete-and-extract-region beg end))
13385 (move-to-column col)))
13387 ;; Paragraph filling stuff.
13388 ;; We want this to be just right, so use the full arsenal.
13389 ;; FIXME: This very likely does not work correctly for XEmacs, because the
13390 ;; filladapt package works slightly differently.
13392 (defun org-set-autofill-regexps ()
13394 ;; In the paragraph separator we include headlines, because filling
13395 ;; text in a line directly attached to a headline would otherwise
13396 ;; fill the headline as well.
13397 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
13398 ;; The paragraph starter includes hand-formatted lists.
13399 (set (make-local-variable 'paragraph-start)
13400 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13401 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13402 ;; But only if the user has not turned off tables or fixed-width regions
13403 (set (make-local-variable 'auto-fill-inhibit-regexp)
13405 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13408 (if org-enable-table-editor "|" "")
13409 (if org-enable-fixed-width-editor ":" "")
13411 ;; We use our own fill-paragraph function, to make sure that tables
13412 ;; and fixed-width regions are not wrapped. That function will pass
13413 ;; through to `fill-paragraph' when appropriate.
13414 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
13415 ;; Adaptive filling: To get full control, first make sure that
13416 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13417 (set (make-local-variable 'adaptive-fill-regexp) "\000")
13418 (set (make-local-variable 'adaptive-fill-function)
13419 'org-adaptive-fill-function))
13421 (defun org-fill-paragraph (&optional justify)
13422 "Re-align a table, pass through to fill-paragraph if no table."
13423 (let ((table-p (org-at-table-p))
13424 (table.el-p (org-at-table.el-p)))
13425 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
13426 (table.el-p t) ; skip table.el tables
13427 (table-p (org-table-align) t) ; align org-mode tables
13428 (t nil)))) ; call paragraph-fill
13430 ;; For reference, this is the default value of adaptive-fill-regexp
13431 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13433 (defun org-adaptive-fill-function ()
13434 "Return a fill prefix for org-mode files.
13435 In particular, this makes sure hanging paragraphs for hand-formatted lists
13437 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
13438 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
13440 ;; Functions needed for Emacs/XEmacs region compatibility
13442 (defun org-add-hook (hook function &optional append local)
13443 "Add-hook, compatible with both Emacsen."
13444 (if (and local (featurep 'xemacs))
13445 (add-local-hook hook function append)
13446 (add-hook hook function append local)))
13448 (defun org-region-active-p ()
13449 "Is `transient-mark-mode' on and the region active?
13450 Works on both Emacs and XEmacs."
13451 (if org-ignore-region
13453 (if (featurep 'xemacs)
13454 (and zmacs-regions (region-active-p))
13455 (and transient-mark-mode mark-active))))
13457 (defun org-add-to-invisibility-spec (arg)
13458 "Add elements to `buffer-invisibility-spec'.
13459 See documentation for `buffer-invisibility-spec' for the kind of elements
13460 that can be added."
13462 ((fboundp 'add-to-invisibility-spec)
13463 (add-to-invisibility-spec arg))
13464 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
13465 (setq buffer-invisibility-spec (list arg)))
13467 (setq buffer-invisibility-spec
13468 (cons arg buffer-invisibility-spec)))))
13470 (defun org-remove-from-invisibility-spec (arg)
13471 "Remove elements from `buffer-invisibility-spec'."
13472 (if (fboundp 'remove-from-invisibility-spec)
13473 (remove-from-invisibility-spec arg)
13474 (if (consp buffer-invisibility-spec)
13475 (setq buffer-invisibility-spec
13476 (delete arg buffer-invisibility-spec)))))
13478 (defun org-in-invisibility-spec-p (arg)
13479 "Is ARG a member of `buffer-invisibility-spec'?"
13480 (if (consp buffer-invisibility-spec)
13481 (member arg buffer-invisibility-spec)
13484 (defun org-image-file-name-regexp ()
13485 "Return regexp matching the file names of images."
13486 (if (fboundp 'image-file-name-regexp)
13487 (image-file-name-regexp)
13488 (let ((image-file-name-extensions
13489 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13490 "xbm" "xpm" "pbm" "pgm" "ppm")))
13492 (regexp-opt (nconc (mapcar 'upcase
13493 image-file-name-extensions)
13494 image-file-name-extensions)
13498 ;; Functions needed for compatibility with old outline.el.
13500 ;; Programming for the old outline.el (that uses selective display
13501 ;; instead of `invisible' text properties) is a nightmare, mostly
13502 ;; because regular expressions can no longer be anchored at
13503 ;; beginning/end of line. Therefore a number of function need special
13504 ;; treatment when the old outline.el is being used.
13506 ;; The following functions capture almost the entire compatibility code
13507 ;; between the different versions of outline-mode. The only other
13508 ;; places where this is important are the font-lock-keywords, and in
13509 ;; `org-export-copy-visible'. Search for `org-noutline-p' to find them.
13511 ;; C-a should go to the beginning of a *visible* line, also in the
13512 ;; new outline.el. I guess this should be patched into Emacs?
13513 (defun org-beginning-of-line ()
13514 "Go to the beginning of the current line. If that is invisible, continue
13515 to a visible line beginning. This makes the function of C-a more intuitive."
13517 (beginning-of-line 1)
13521 (if (org-invisible-p)
13522 (while (and (not (bobp)) (org-invisible-p))
13524 (beginning-of-line 1))
13525 (forward-char 1))))
13527 (when org-noutline-p
13528 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
13529 ;; FIXME: should I use substitute-key-definition to reach other bindings
13530 ;; of beginning-of-line?
13532 (defun org-invisible-p ()
13533 "Check if point is at a character currently not visible."
13535 ;; Early versions of noutline don't have `outline-invisible-p'.
13536 (if (fboundp 'outline-invisible-p)
13537 (outline-invisible-p)
13538 (get-char-property (point) 'invisible))
13540 (skip-chars-backward "^\r\n")
13541 (equal (char-before) ?\r))))
13543 (defun org-invisible-p2 ()
13544 "Check if point is at a character currently not visible."
13548 (if (and (eolp) (not (bobp))) (backward-char 1))
13549 ;; Early versions of noutline don't have `outline-invisible-p'.
13550 (if (fboundp 'outline-invisible-p)
13551 (outline-invisible-p)
13552 (get-char-property (point) 'invisible)))
13553 (skip-chars-backward "^\r\n")
13554 (equal (char-before) ?\r))))
13556 (defun org-back-to-heading (&optional invisible-ok)
13557 "Move to previous heading line, or beg of this line if it's a heading.
13558 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
13560 (outline-back-to-heading invisible-ok)
13561 (if (and (memq (char-before) '(?\n ?\r))
13562 (looking-at outline-regexp))
13564 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
13568 (progn (goto-char (match-end 1))
13569 (looking-at outline-regexp)))
13570 (error "Before first heading")))))
13572 (defun org-on-heading-p (&optional invisible-ok)
13573 "Return t if point is on a (visible) heading line.
13574 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
13576 (outline-on-heading-p 'invisible-ok)
13578 (skip-chars-backward "^\n\r")
13579 (and (looking-at outline-regexp)
13582 (equal (char-before) ?\n))))))
13584 (defun org-on-target-p ()
13585 (let ((pos (point)))
13587 (skip-chars-forward "<")
13588 (and (re-search-backward "<<" nil t)
13589 (or (looking-at org-radio-target-regexp)
13590 (looking-at org-target-regexp))
13591 (<= (match-beginning 0) pos)
13592 (>= (1+ (match-end 0)) pos)))))
13594 (defun org-up-heading-all (arg)
13595 "Move to the heading line of which the present line is a subheading.
13596 This function considers both visible and invisible heading lines.
13597 With argument, move up ARG levels."
13599 (if (fboundp 'outline-up-heading-all)
13600 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13601 (outline-up-heading arg t)) ; emacs 22 version of outline.el
13602 (org-back-to-heading t)
13603 (looking-at outline-regexp)
13604 (if (<= (- (match-end 0) (match-beginning 0)) arg)
13605 (error "Cannot move up %d levels" arg)
13606 (re-search-backward
13607 (concat "[\n\r]" (regexp-quote
13608 (make-string (- (match-end 0) (match-beginning 0) arg)
13611 (forward-char 1))))
13613 (defun org-show-hidden-entry ()
13614 "Show an entry where even the heading is hidden."
13616 (if (not org-noutline-p)
13618 (org-back-to-heading t)
13619 (org-flag-heading nil)))
13622 (defun org-check-occur-regexp (regexp)
13623 "If REGEXP starts with \"^\", modify it to check for \\r as well.
13624 Of course, only for the old outline mode."
13627 (if (string-match "^\\^" regexp)
13628 (concat "[\n\r]" (substring regexp 1))
13631 (defun org-flag-heading (flag &optional entry)
13632 "Flag the current heading. FLAG non-nil means make invisible.
13633 When ENTRY is non-nil, show the entire entry."
13635 (org-back-to-heading t)
13636 (if (not org-noutline-p)
13637 ;; Make the current headline visible
13638 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
13639 ;; Check if we should show the entire entry
13643 (save-excursion ;; FIXME: Is this the fix for points in the -|
13644 ;; middle of text? |
13645 (and (outline-next-heading) ;; |
13646 (org-flag-heading nil)))) ; show the next heading _|
13647 (outline-flag-region (max 1 (1- (point)))
13648 (save-excursion (outline-end-of-heading) (point))
13651 (if flag ?\r ?\n))))))
13653 (defun org-end-of-subtree (&optional invisible-OK)
13654 ;; This is an exact copy of the original function, but it uses
13655 ;; `org-back-to-heading', to make it work also in invisible
13656 ;; trees. And is uses an invisible-OK argument.
13657 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13658 (org-back-to-heading invisible-OK)
13660 (level (funcall outline-level)))
13661 (while (and (not (eobp))
13662 (or first (> (funcall outline-level) level)))
13664 (outline-next-heading))
13665 (if (memq (preceding-char) '(?\n ?\^M))
13667 ;; Go to end of line before heading
13669 (if (memq (preceding-char) '(?\n ?\^M))
13670 ;; leave blank line before heading
13671 (forward-char -1))))))
13673 (defun org-show-subtree ()
13674 "Show everything after this heading at deeper levels."
13675 (outline-flag-region
13678 (outline-end-of-subtree) (outline-next-heading) (point))
13679 (if org-noutline-p nil ?\n)))
13681 (defun org-show-entry ()
13682 "Show the body directly following this heading.
13683 Show the heading too, if it is currently invisible."
13686 (org-back-to-heading t)
13687 (outline-flag-region
13690 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13691 (or (match-beginning 1) (point-max)))
13692 (if org-noutline-p nil ?\n))))
13694 (defun org-make-options-regexp (kwds)
13695 "Make a regular expression for keyword lines."
13697 (if org-noutline-p "^" "[\n\r]")
13699 (mapconcat 'regexp-quote kwds "\\|")
13701 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
13703 ;; Make `bookmark-jump' show the jump location if it was hidden.
13704 (eval-after-load "bookmark"
13705 '(if (boundp 'bookmark-after-jump-hook)
13706 ;; We can use the hook
13707 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13708 ;; Hook not available, use advice
13709 (defadvice bookmark-jump (after org-make-visible activate)
13710 "Make the position visible."
13711 (org-bookmark-jump-unhide))))
13713 (defun org-bookmark-jump-unhide ()
13714 "Unhide the current position, to show the bookmark location."
13715 (and (eq major-mode 'org-mode)
13716 (or (org-invisible-p)
13717 (save-excursion (goto-char (max (point-min) (1- (point))))
13718 (org-invisible-p)))
13719 (org-show-hierarchy-above)))
13725 (run-hooks 'org-load-hook)
13727 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13728 ;;; org.el ends here